correios_api 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d43b602df7c491dc86c8d97c8cd1d3d79301b3387ac7213448202d94e28117ce
4
+ data.tar.gz: 72816d1bf92cc2cc03aaf2598e313a4f3bc78fd744ef0dbcf4fe0f0fe9b13326
5
+ SHA512:
6
+ metadata.gz: c480fc1288acfb2e6d60928c6861c919aa993c7270c5ab8b6966729ff6317ad439dadf6976a61b3ab35cc9e5fb5bb5f020de403fc84f77956f220624f4690ff7
7
+ data.tar.gz: 11b7ef53df6aaef295c61872756ef63ace7d37229cf8b5710cdb3dacfbe4aa7adcdd6f9ebfc274df4461e40f205e2fa2271ab520d161225300200e23c83dcf30
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/standardrb/standard
3
+ ruby_version: 3.0
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-09-23
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 ulysses
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1 @@
1
+ # CorreiosApi
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[test standard]
@@ -0,0 +1,208 @@
1
+ module CorreiosApi
2
+ class Client < Ac::Base
3
+ BASE_URL = "https://api.correios.com.br"
4
+ MAX_RETRIES = 2
5
+
6
+ SERVICES = [
7
+ {
8
+ code: "03220",
9
+ name: "SEDEX CONTRATO AG"
10
+ },
11
+ {
12
+ code: "03298",
13
+ name: "PAC CONTRATO AG"
14
+ },
15
+ {
16
+ code: "04227",
17
+ name: "CORREIOS MINI ENVIOS CTR AG"
18
+ }
19
+ ]
20
+ SERVICE_NAMES = {
21
+ "03220" => "SEDEX CONTRATO AG",
22
+ "03298" => "PAC CONTRATO AG",
23
+ "04227" => "CORREIOS MINI ENVIOS CTR AG"
24
+ }
25
+
26
+ attr_reader :username, :password, :post_card, :contract_number, :access_token, :expires_in
27
+ def initialize username:, password:, post_card:, contract_number: nil, access_token: nil, expires_in: nil
28
+ @username = username
29
+ @password = password
30
+ @post_card = post_card
31
+ @contract_number = contract_number
32
+ if @access_token.nil? || @expires_in < Time.now
33
+ authenticate
34
+ end
35
+ end
36
+
37
+ def authenticate
38
+ body = {
39
+ numero: @post_card
40
+ }
41
+ response = post(
42
+ "/token/v1/autentica/cartaopostagem",
43
+ headers: {
44
+ "Authorization" => "Basic #{Base64.strict_encode64("#{@username}:#{@password}")}",
45
+ "Content-Type" => "application/json"
46
+ },
47
+ body: JSON.dump(body)
48
+ ) { |response| validate_response(response, "token") }
49
+
50
+ @access_token = response.json.dig("token")
51
+ @expires_in = Time.new(response.json.dig("expiraEm"))
52
+ end
53
+
54
+ def create_pre_shipping nome_remet:, cpf_cnpj_remet:, cep_remet:, rua_remet:, numero_remet:, bairro_remet:, cidade_remet:, uf_remet:, nome_dest:, cpf_cnpj_dest:, cep_dest:, rua_dest:, numero_dest:, bairro_dest:, cidade_dest:, uf_dest:, codigo_servico:, preco_pre_postagem:, itens:, peso_gramas:, altura_cm: 15, largura_cm: 15, comprimento_cm: 15
55
+ body = {
56
+ idCorreios: @username,
57
+ remetente: {
58
+ nome: nome_remet,
59
+ cpfCnpj: cpf_cnpj_remet,
60
+ endereco: {
61
+ cep: cep_remet,
62
+ logradouro: rua_remet,
63
+ numero: numero_remet,
64
+ bairro: bairro_remet,
65
+ cidade: cidade_remet,
66
+ uf: uf_remet
67
+ }
68
+ },
69
+ destinatario: {
70
+ nome: nome_dest,
71
+ cpfCnpj: cpf_cnpj_dest,
72
+ endereco: {
73
+ cep: cep_dest,
74
+ logradouro: rua_dest,
75
+ numero: numero_dest,
76
+ bairro: bairro_dest,
77
+ cidade: cidade_dest,
78
+ uf: uf_dest
79
+ }
80
+ },
81
+ codigoServico: codigo_servico,
82
+ precoPrePostagem: preco_pre_postagem,
83
+ numeroCartaoPostagem: @post_card,
84
+ itensDeclaracaoConteudo: itens, # conteudo, quantidade, valor
85
+ pesoInformado: peso_gramas,
86
+ codigoFormatoObjetoInformado: "2",
87
+ alturaInformada: altura_cm,
88
+ larguraInformada: largura_cm,
89
+ comprimentoInformado: comprimento_cm,
90
+ cienteObjetoNaoProibido: "1",
91
+ modalidadePagamento: "2" # 1-à vista, 2-à faturar, 3- à avista e à afaturar e 4- Prestação de contas recebimento ou pagamento
92
+ # solicitarColeta: "N",
93
+ # dataPrevistaPostagem: "20/09/2024"
94
+ }
95
+
96
+ response = post(
97
+ "/prepostagem/v1/prepostagens",
98
+ headers: headers,
99
+ body: JSON.dump(body)
100
+ ) { |response| validate_response(response, "id") }
101
+ PreShipping.new(response.json)
102
+ end
103
+
104
+ def create_label pre_shipping
105
+ body = {
106
+ codigosObjeto: [
107
+ pre_shipping.codigo_objeto
108
+ ],
109
+ idCorreios: @username,
110
+ numeroCartaoPostagem: @post_card,
111
+ tipoRotulo: "P", # P (padrão) ou R (reduzido)
112
+ formatoRotulo: "ET", # ET (Etiqueta) ou EV (Envelope)
113
+ imprimeRemetente: "S", # S (Sim) ou N (não)
114
+ layoutImpressao: "PADRAO" # PADRAO, LINEAR_100_150, LINEAR_100_80, LINEAR_A4, LINEAR_A
115
+ }
116
+
117
+ response = post(
118
+ "/prepostagem/v1/prepostagens/rotulo/assincrono/pdf",
119
+ headers: headers,
120
+ body: JSON.dump(body)
121
+ ) { |response| validate_response(response, "idRecibo") }
122
+ sleep(0.5) # Tem que esperar o PDF ficar pronto
123
+ get_label(response.json.dig("idRecibo"))
124
+ end
125
+
126
+ def get_label id
127
+ response = get(
128
+ "/prepostagem/v1/prepostagens/rotulo/download/assincrono/#{id}",
129
+ headers: headers
130
+ ) { |response| validate_response(response, "nome") }
131
+ Label.new(response.json)
132
+ end
133
+
134
+ def create_rates cep_origem:, cep_destino:, weight_g: 1000, height_cm: 15, width_cm: 15, length_cm: 15
135
+ services_with_time = delivery_time(cep_origem, cep_destino)
136
+ services_with_cost = delivery_cost(cep_origem, cep_destino, weight_g, height_cm, width_cm, length_cm)
137
+
138
+ services_with_time.map do |service_time|
139
+ service_cost = services_with_cost.find { |service| service["coProduto"] == service_time["coProduto"] }
140
+ Rate.new(
141
+ service_name: SERVICE_NAMES[service_time["coProduto"]],
142
+ service_code: service_time["coProduto"],
143
+ price: service_cost["pcFinal"],
144
+ delivery_time_in_days: service_time["prazoEntrega"],
145
+ max_delivery_time: service_time["dataMaxima"],
146
+ message: service_time["msgPrazo"],
147
+ errors: [
148
+ service_cost.dig("txErro"),
149
+ service_time.dig("txErro")
150
+ ].compact
151
+ )
152
+ end
153
+ end
154
+
155
+ def delivery_time cep_origem, cep_destino
156
+ body = {
157
+ idLote: "1",
158
+ parametrosPrazo: SERVICES.map { |service| { coProduto: service[:code], nuRequisicao: 1, cepOrigem: cep_origem, cepDestino: cep_destino } }
159
+ }
160
+ response = post(
161
+ "/prazo/v1/nacional",
162
+ headers: headers,
163
+ body: JSON.dump(body)
164
+ ) { |response| validate_response(response, "coProduto") }
165
+ response.json
166
+ end
167
+
168
+ def delivery_cost cep_origem, cep_destino, weight_g, height_cm, width_cm, length_cm
169
+ params_produto = SERVICES.map do |service|
170
+ {
171
+ coProduto: service[:code],
172
+ nuRequisicao: "1",
173
+ cepOrigem: cep_origem,
174
+ cepDestino: cep_destino,
175
+ psObjeto: weight_g,
176
+ altura: height_cm,
177
+ largura: width_cm,
178
+ comprimento: length_cm,
179
+ tpObjeto: "2"
180
+ }
181
+ end
182
+ body = {
183
+ idLote: "1",
184
+ parametrosProduto: params_produto
185
+ }
186
+ response = post(
187
+ "/preco/v1/nacional",
188
+ headers: headers,
189
+ body: JSON.dump(body)
190
+ ) { |response| validate_response(response, "coProduto") }
191
+ response.json
192
+ end
193
+
194
+ private
195
+
196
+ def headers
197
+ {
198
+ "Authorization" => "Bearer #{@access_token}",
199
+ "Content-Type" => "application/json"
200
+ }
201
+ end
202
+
203
+ def validate_response(response, required_response_key)
204
+ puts response.json unless response.success?
205
+ ![500, 429].include?(response.code) || response.json.dig(*required_response_key)
206
+ end
207
+ end
208
+ end
@@ -0,0 +1,12 @@
1
+ class Label
2
+ attr_reader :response, :name, :data
3
+ def initialize response
4
+ @response = response
5
+ @name = response.dig("nome")
6
+ @data = response.dig("dados")
7
+ end
8
+
9
+ def download_file
10
+ File.write(@name, Base64.decode64(@data))
11
+ end
12
+ end
@@ -0,0 +1,21 @@
1
+ module CorreiosApi
2
+ class PreShipping
3
+
4
+ attr_reader :response, :external_id, :codigo_objeto, :codigo_servico, :modalidade_pagamento, :preco_pre_postagem, :itens_declarados, :data_prevista_postagem, :prazo_postagem, :status, :desc_status, :tipo_rotulo, :tipo_objeto
5
+ def initialize response
6
+ @response = response
7
+ @external_id = response.dig("id")
8
+ @codigo_objeto = response.dig("codigoObjeto")
9
+ @codigo_servico = response.dig("codigoServico")
10
+ @modalidade_pagamento = response.dig("modalidadePagamento")
11
+ @preco_pre_postagem = response.dig("precoPrePostagem")
12
+ @itens_declarados = response.dig("itensDeclaracaoConteudo")
13
+ @data_prevista_postagem = response.dig("dataPrevistaPostagem")
14
+ @prazo_postagem = response.dig("prazoPostagem")
15
+ @status = response.dig("statusAtual")
16
+ @desc_status = response.dig("descStatusAtual")
17
+ @tipo_rotulo = response.dig("tipoRotulo")
18
+ @tipo_objeto = response.dig("tipoObjeto")
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,26 @@
1
+ module CorreiosApi
2
+ class Rate
3
+ attr_reader :service_name, :service_code, :price, :delivery_time_in_days, :max_delivery_time, :message, :errors
4
+ def initialize service_name:, service_code:, price:, delivery_time_in_days:, max_delivery_time:, message: nil, errors: nil
5
+ @service_name = service_name
6
+ @service_code = service_code
7
+ @price = transform_price(price)
8
+ @delivery_time_in_days = delivery_time_in_days
9
+ @max_delivery_time = transform_date(max_delivery_time)
10
+ @message = message
11
+ @errors = errors
12
+ end
13
+
14
+ private
15
+
16
+ def transform_price price
17
+ return nil unless price
18
+ price.gsub(",", ".").to_f
19
+ end
20
+
21
+ def transform_date date
22
+ return nil unless date
23
+ Time.new(date)
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CorreiosApi
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,13 @@
1
+ require_relative "correios_api/version"
2
+
3
+ require "base64"
4
+ require "ac"
5
+
6
+ require "correios_api/client"
7
+ require "correios_api/rate"
8
+ require "correios_api/pre_shipping"
9
+ require "correios_api/label"
10
+
11
+ module CorreiosApi
12
+ class Error < StandardError; end
13
+ end
@@ -0,0 +1,4 @@
1
+ module CorreiosApi
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,87 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: correios_api
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Todas Essas Coisas
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-09-24 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: base64
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: ac
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: ''
42
+ email:
43
+ - ulyssesh.20@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".standard.yml"
49
+ - CHANGELOG.md
50
+ - CODE_OF_CONDUCT.md
51
+ - LICENSE.txt
52
+ - README.md
53
+ - Rakefile
54
+ - lib/correios_api.rb
55
+ - lib/correios_api/client.rb
56
+ - lib/correios_api/label.rb
57
+ - lib/correios_api/pre_shipping.rb
58
+ - lib/correios_api/rate.rb
59
+ - lib/correios_api/version.rb
60
+ - sig/correios_api.rbs
61
+ homepage: https://github.com/todasessascoisas/correios_api
62
+ licenses:
63
+ - MIT
64
+ metadata:
65
+ homepage_uri: https://github.com/todasessascoisas/correios_api
66
+ source_code_uri: https://github.com/todasessascoisas/correios_api
67
+ changelog_uri: https://github.com/todasessascoisas/correios_api
68
+ post_install_message:
69
+ rdoc_options: []
70
+ require_paths:
71
+ - lib
72
+ required_ruby_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: 3.0.0
77
+ required_rubygems_version: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ requirements: []
83
+ rubygems_version: 3.5.11
84
+ signing_key:
85
+ specification_version: 4
86
+ summary: ''
87
+ test_files: []