enel-ruby-sdk 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: eab8ca3e3db55b2a8e37d6f16bdb0ddd5de50fc5df3cdebed3d5e50247544c7b
4
- data.tar.gz: 3d8bde302a73e43bcc9d91a45c47306160b59136f6fb1f352a6ab56c6ce7b32b
3
+ metadata.gz: 56a90e7bc84616a6e724e2e9fc12aee7ecd99c6b366eca17b1da0c9921a1b2e4
4
+ data.tar.gz: 1266f0221c05749de9741c830bda06771fd1c12fe21b653a5695c3a3a185f829
5
5
  SHA512:
6
- metadata.gz: 3d1780c7bbe75da24c66168e6f2eea77ed714ab85e724b6702bf24773795ecb3d1787ad6fed3b01fbece03e893152b9d00b70ec5a0e80c015bd8d04167c56844
7
- data.tar.gz: 878bb7c511258e5aed6729fda3cc2c5c0c2d8ee3fb50f8df300a509615936e4192cfc6ce18cf85ad81b4d55a5d37ad6846cb8a64c6500e4af2a96d951984460f
6
+ metadata.gz: 2796ebeecdcb5b28beec48a034c2bf281ec29602354889fd12387b98cf27a9cc563d4f62ab94618ab22830b2871735ca64fd4a4fc1193f7ab4b26b4bb9b8c1c1
7
+ data.tar.gz: 950aa50f137d5c7da3a206516ad478b55995c6316842fa97dd22765cb136c6da630286a8cea4bb65c9ad5dd4063a029fff39893ccf91912b6396835b73d61017
data/README.md CHANGED
@@ -8,13 +8,14 @@ venda, alteração de valores, cancelamento e as cinco consultas de histórico.
8
8
 
9
9
  ## Instalação
10
10
 
11
- Repositório privado, sem publicação no RubyGems por padrão: use a tag git no `Gemfile`.
11
+ A gem é publicada no [RubyGems](https://rubygems.org/gems/enel-ruby-sdk) desde a `0.1.2`. Use a
12
+ versão exata no `Gemfile`:
12
13
 
13
14
  ```ruby
14
- gem 'enel-ruby-sdk', require: 'enel_x', git: 'https://github.com/djosino/enel-ruby-sdk', tag: 'vX.Y.Z'
15
+ gem 'enel-ruby-sdk', 'X.Y.Z', require: 'enel_x'
15
16
  ```
16
17
 
17
- Troque `vX.Y.Z` pela [versão mais recente](https://github.com/djosino/enel-ruby-sdk/releases)
18
+ Troque `X.Y.Z` pela [versão mais recente](https://github.com/djosino/enel-ruby-sdk/releases)
18
19
  e rode `bundle install`.
19
20
 
20
21
  ## Configuração
@@ -32,14 +33,43 @@ client = EnelX::Client.new(
32
33
  client_secret: ENV.fetch('ENEL_CLIENT_SECRET'),
33
34
  client_system: 'BRA-MEUPARCEIRO',
34
35
  partner_code: 'PARC01', # usado como empresaParc nas consultas
36
+ product_code: '12342005', # opcional: codProduto padrão de consultas e pedidos
35
37
  # cache: Rails.cache, # opcional: read/write/delete; padrão em memória
36
38
  # on_request: ->(entry) { ... }, # opcional: chamada já filtrada de segredos e PII
37
39
  )
38
40
  ```
39
41
 
42
+ `partner_code` e `product_code` são padrões: entram como `empresaParc` e `codProduto` só quando
43
+ o pedido não traz o campo (ou o traz `nil`), e o valor do pedido sempre prevalece. Sem
44
+ `product_code`, `codProduto` continua obrigatório na venda, na alteração e no cancelamento.
45
+ A consulta de histórico de adesão por data (`operacao`) não aceita `codProduto` e não o recebe.
46
+ `product_code` precisa ter de 1 a 255 caracteres, senão a criação do cliente levanta
47
+ `EnelX::ConfigurationError`.
48
+
40
49
  Há um cliente por ambiente e nenhum estado global. O cliente não repete chamadas: a política
41
50
  de repetição é do app, guiada por `error.kind` (veja [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md)).
42
51
 
52
+ ### Erros de rede
53
+
54
+ Falha de rede (sem resposta da API) é `EnelX::Error` com `kind` `:retryable` e `reason`
55
+ `:timeout` (tempo de conexão, leitura ou escrita esgotado) ou `:network` (conexão recusada,
56
+ DNS, TLS, conexão encerrada). Use `timeout?` em vez de procurar texto na mensagem:
57
+
58
+ ```ruby
59
+ begin
60
+ client.order_sale(fields)
61
+ rescue EnelX::Error => e
62
+ if e.timeout?
63
+ # a Enel X demorou demais: tente de novo em instantes
64
+ elsif e.kind == :retryable
65
+ # sem resposta ou erro genérico da API: tente de novo
66
+ end
67
+ end
68
+ ```
69
+
70
+ `Gateway Timeout` no corpo da resposta é mensagem da API (tabela 7.3), não falha de rede:
71
+ `timeout?` é falso.
72
+
43
73
  ## Exemplos
44
74
 
45
75
  Os campos usam os nomes do PDF, como Hash ou como argumentos nomeados. Toda validação roda
@@ -66,7 +96,7 @@ result = client.order_sale(
66
96
  'Endereco' => 'Av Lucio Costa', 'EnderecoNumero' => '0123', 'Bairro' => 'Barra da Tijuca',
67
97
  'Cidade' => 'Rio de Janeiro', 'CEP' => '22630-011', 'empresa' => '2005',
68
98
  'numeroCliente' => '123456', 'CPF' => '12345678909', 'numParcelas' => 10,
69
- 'valorParcela' => BigDecimal('32.23'), 'codProduto' => '12342005',
99
+ 'valorParcela' => '32.23', 'codProduto' => '12342005',
70
100
  'dataOcorrencia' => Date.today, 'numeroClienteEmpPar' => 'MD2026ABC',
71
101
  'anexos' => [{ type: 'Termo de Adesão', filename: 'termo.pdf', bytes: File.binread('termo.pdf') }],
72
102
  context: { subscription_id: 7 },
@@ -94,6 +124,60 @@ client.order_disconnect('Nome' => 'John', 'Sobrenome' => 'Doe', 'empresa' => '20
94
124
  'Cidade' => 'Rio de Janeiro', 'CEP' => '00000-000')
95
125
  ```
96
126
 
127
+ ### Montar os campos a partir de valores
128
+
129
+ `EnelX::Orders::Sale.fields` e `EnelX::Orders::Disconnect.fields` recebem valores Ruby e
130
+ devolvem o Hash com os nomes do PDF, pronto para `order_sale`/`order_disconnect`. Eles só
131
+ traduzem nomes e formatos: a validação continua no envio. O Hash com os nomes do PDF continua
132
+ aceito como antes.
133
+
134
+ ```ruby
135
+ fields = EnelX::Orders::Sale.fields(
136
+ first_name: 'Joana', last_name: 'Lima', birth_date: Date.new(1980, 3, 10),
137
+ phone: '85988887777', # email: '' é o padrão (o PDF permite vazio)
138
+ street: 'Rua das Flores', number: '10', neighborhood: 'Centro', city: 'Fortaleza',
139
+ zip_code: '60000-000', company: '2003', utility_account: '1234567', cpf: '12345678909',
140
+ installments: :continuous, # padrão; vira numParcelas -1
141
+ installment_value: '39.90', # ou 3990 (centavos) ou Rational(399, 10) (reais)
142
+ occurred_on: Date.today, # obrigatório: é o início da cobrança
143
+ partner_customer_number: 'MD2026ABC', # product_code: nil usa o da configuração
144
+ attachments: [EnelX::Attachment.new(type: EnelX::Attachment::ADHESION,
145
+ filename: 'termo.pdf', bytes: File.binread('termo.pdf'))],
146
+ )
147
+ client.order_sale(fields, context: { subscription_id: 7 })
148
+
149
+ client.order_disconnect(EnelX::Orders::Disconnect.fields(
150
+ first_name: 'Joana', last_name: 'Lima', company: '2003', utility_account: '1234567',
151
+ installment_value: '39.90', reason_code: '26', occurred_on: Date.today,
152
+ street: 'Rua das Flores', number: '10', neighborhood: 'Centro', city: 'Fortaleza',
153
+ zip_code: '60000-000', partner_customer_number: 'MD2026ABC',
154
+ ))
155
+ ```
156
+
157
+ | Argumento | Campo do PDF | Conversão |
158
+ |---|---|---|
159
+ | `first_name`, `last_name` | `Nome`, `Sobrenome` | nenhuma |
160
+ | `birth_date` | `dtNascimento` | `Date`/`Time` viram `AAAA-MM-DD`; `nil` sai do Hash |
161
+ | `phone`, `email` | `Telefone`, `Email` | `email` é `""` por padrão |
162
+ | `street`, `number`, `neighborhood`, `city`, `zip_code` | `Endereco`, `EnderecoNumero`, `Bairro`, `Cidade`, `CEP` | nenhuma |
163
+ | `company`, `utility_account`, `cpf` | `empresa`, `numeroCliente`, `CPF` | nenhuma |
164
+ | `installments` | `numParcelas` | `:continuous` (padrão) vira `-1`; número passa como veio |
165
+ | `installment_value` | `valorParcela` | veja abaixo |
166
+ | `product_code` | `codProduto` | `nil` sai do Hash e vale o `product_code` da configuração |
167
+ | `occurred_on` | `dataOcorrencia` | obrigatório, sem padrão; `Date`/`Time` viram `AAAA-MM-DD` |
168
+ | `partner_customer_number` | `numeroClienteEmpPar` | `nil` sai do Hash |
169
+ | `attachments` | `anexos` | nenhuma (`EnelX::Attachment` ou Hash) |
170
+ | `reason_code` (cancelamento) | `codOcorr` | texto; motivo validado no envio (22 a 32) |
171
+
172
+ `installment_value` aceita:
173
+
174
+ - `String` com ponto decimal (`'39.90'`), que passa sem alteração;
175
+ - `Integer` em **centavos** (`3990` vira `'39.90'`; atenção, `50` vira `'0.50'`, não R$ 50);
176
+ - `Rational` em reais, exato em centavos (`Rational(399, 10)` vira `'39.90'`).
177
+
178
+ `Float` é recusado com `EnelX::ValidationError`, porque arredonda. A gem não usa `BigDecimal`,
179
+ mas um `BigDecimal` do app passa adiante e é aceito no envio.
180
+
97
181
  ### Consultas de histórico (§5.6 a §5.10)
98
182
 
99
183
  A API não tem webhook: estas consultas são a única forma de saber o que houve com a venda.
@@ -113,13 +197,64 @@ client.collections('empresa' => '2005', 'dataOcorrencia' => Date.today)
113
197
  client.movements('empresa' => '2005', 'numeroCliente' => '123456', 'codProduto' => '12342005')
114
198
  ```
115
199
 
116
- Datas e números voltam como a API enviou; `null` e texto vazio viram `nil`.
200
+ Datas e números voltam como a API enviou; `null` e texto vazio viram `nil`. Para ler uma
201
+ data como `Date`, use os leitores tipados, que nunca levantam erro:
202
+
203
+ ```ruby
204
+ item.dataocorrencia # => "11/05/2026" (texto, como veio)
205
+ item.occurred_on # => #<Date: 2026-11-05> (dataocorrencia)
206
+ item.due_on # datavencimento; item.paid_on: datapagamento
207
+ item.date(:databaixapagamento)
208
+ EnelX::Record.parse_date('2026-11-05T10:20:30') # => #<Date: 2026-11-05>, fora de um registro
209
+ ```
210
+
211
+ A leitura aceita `MM/DD/AAAA` (com mês e dia de um ou dois dígitos) e ISO `AAAA-MM-DD`, com ou
212
+ sem hora. Outro formato, data impossível ou dia antes do mês (`13/01/2026`) vira `nil`. O PDF
213
+ não mostra o formato das respostas: a escolha está na pendência nº 11 de
214
+ [`docs/PENDENCIAS-ENEL.md`](docs/PENDENCIAS-ENEL.md). `occurred_on`, `due_on` e `paid_on` só
215
+ existem nos registros que têm o campo.
117
216
 
118
217
  ### Dados de referência
119
218
 
120
219
  `EnelX::Distributor`, `EnelX::Occurrence` (tabela 7.2, com `stage`), `EnelX::Reference::PartnerCode`
121
220
  (tabela 7.1) e `EnelX::DocumentState` (tabela 7.4).
122
221
 
222
+ Os códigos da tabela 7.2 mais usados têm constantes, com nomes tirados da descrição do PDF:
223
+
224
+ | Constante | Código | Descrição no PDF |
225
+ |---|---|---|
226
+ | `EnelX::Occurrence::PAYMENT` | `901` | Recebido o Pagamento do produto (arrecadação) |
227
+ | `EnelX::Occurrence::BILLING` | `902` | Inclusão de Cobrança na fatura (faturamento) |
228
+ | `EnelX::Occurrence::CANCELED` | `909` | Cancelamento |
229
+ | `EnelX::Occurrence::CHARGE_INCLUDED` | `915` | Cobrança Incluída para o Cliente |
230
+ | `EnelX::Occurrence::INTAKE_OK` | `996` | Retorno OK para novas vendas / Alteração de valores / Cancelamentos |
231
+ | `EnelX::Occurrence::INTAKE_KO` | `997` | Retorno KO para novas vendas / Alteração de valores / Cancelamentos |
232
+ | `EnelX::Occurrence::AUDIT_OK` | `998` | Retorno OK para auditoria |
233
+ | `EnelX::Occurrence::AUDIT_KO` | `999` | Retorno KO para auditoria |
234
+
235
+ ```ruby
236
+ items.any? { |item| item.codocorr == EnelX::Occurrence::AUDIT_OK }
237
+ ```
238
+
239
+ Na ocorrência `909` (cancelamento), a resposta traz só o texto do motivo em `descricaoretorno`.
240
+ `cancellation_reason_for` encontra o motivo da tabela 7.2 por esse texto:
241
+
242
+ ```ruby
243
+ reason = EnelX::Occurrence.cancellation_reason_for(item.descricaoretorno)
244
+ reason&.code # => "26"
245
+ reason&.description # => "Cancelado - Não há interesse"
246
+ reason&.automatic? # => false (pedido do cliente); 02 e 20 são automáticos
247
+ EnelX::Occurrence.cancellation_reason('26') # busca pelo código, como antes
248
+ ```
249
+
250
+ A comparação ignora caixa e espaços nas pontas e casa quando um texto contém o outro,
251
+ devolvendo o primeiro motivo da tabela. Texto vazio ou desconhecido devolve `nil`. Um texto
252
+ genérico como "cancelado" casa com o primeiro motivo que o contém (o `22`). Essa leitura é uma
253
+ suposição: veja a pendência nº 12 de [`docs/PENDENCIAS-ENEL.md`](docs/PENDENCIAS-ENEL.md).
254
+
255
+ O SDK não agrupa códigos (por exemplo, "rejeições") porque o PDF não agrupa. O que cada
256
+ código significa para o negócio (qual libera a ativação, qual é só faturamento) é decisão do app.
257
+
123
258
  ## Documentação
124
259
 
125
260
  - [Índice da documentação](docs/README.md)
data/REVISION CHANGED
@@ -1 +1 @@
1
- 0.1.2
1
+ 0.2.0
@@ -16,11 +16,11 @@ module EnelX
16
16
  DEFAULT_READ_TIMEOUT = 30
17
17
 
18
18
  attr_reader :host, :client_id, :client_secret, :client_system, :partner_code,
19
- :cache, :logger, :on_request, :open_timeout, :read_timeout
19
+ :product_code, :cache, :logger, :on_request, :open_timeout, :read_timeout
20
20
 
21
21
  # rubocop:disable-next Metrics/ParameterLists
22
22
  def initialize(host: nil, client_id: nil, client_secret: nil, client_system: nil,
23
- partner_code: nil, cache: nil, logger: nil, on_request: nil,
23
+ partner_code: nil, product_code: nil, cache: nil, logger: nil, on_request: nil,
24
24
  open_timeout: DEFAULT_OPEN_TIMEOUT,
25
25
  read_timeout: DEFAULT_READ_TIMEOUT)
26
26
  @host = normalize_host(host)
@@ -28,6 +28,7 @@ module EnelX
28
28
  @client_secret = client_secret.to_s
29
29
  @client_system = client_system
30
30
  @partner_code = partner_code
31
+ @product_code = product_code&.to_s
31
32
  @cache = cache || MemoryCache.new
32
33
  @logger = logger || NullLogger.new
33
34
  @on_request = on_request
@@ -57,9 +58,18 @@ module EnelX
57
58
  raise ConfigurationError, "missing configuration: #{missing.join(', ')}"
58
59
  end
59
60
 
61
+ validate_product_code!
60
62
  return if CACHE_METHODS.all? { |name| cache.respond_to?(name) }
61
63
 
62
64
  raise ConfigurationError, 'cache must respond to read, write and delete'
63
65
  end
66
+
67
+ # Same limit as codProduto in the requests (PDF 5.3.2: String(255)).
68
+ def validate_product_code!
69
+ return if product_code.nil?
70
+ return if !product_code.strip.empty? && product_code.length <= 255
71
+
72
+ raise ConfigurationError, 'product_code must have 1 to 255 characters'
73
+ end
64
74
  end
65
75
  end
@@ -81,11 +81,8 @@ module EnelX
81
81
 
82
82
  def build_params(fields)
83
83
  required, optional = @query.forms.fetch(form_for(fields))
84
- unknown = fields.keys - required - optional
85
- unless unknown.empty?
86
- Validators.invalid(unknown.first,
87
- 'not a field of this query')
88
- end
84
+ refuse_unknown(fields, required + optional)
85
+ default_product(fields, required + optional)
89
86
 
90
87
  (required + optional).each_with_object({}) do |name, params|
91
88
  next if optional.include?(name) && !fields.key?(name)
@@ -94,6 +91,22 @@ module EnelX
94
91
  end
95
92
  end
96
93
 
94
+ def refuse_unknown(fields, accepted)
95
+ unknown = fields.keys - accepted
96
+ return if unknown.empty?
97
+
98
+ Validators.invalid(unknown.first, 'not a field of this query')
99
+ end
100
+
101
+ # The configured product_code fills codProduto only in the forms that take it (the
102
+ # subscription history by date does not) and only when the request leaves it out.
103
+ def default_product(fields, accepted)
104
+ product = @client.configuration.product_code
105
+ return if product.nil? || !accepted.include?('codProduto')
106
+
107
+ fields['codProduto'] = product if fields['codProduto'].nil?
108
+ end
109
+
97
110
  def form_for(fields)
98
111
  forms = @query.forms
99
112
  return forms.keys.first if forms.one?
@@ -55,8 +55,11 @@ module EnelX
55
55
  }
56
56
  end
57
57
 
58
+ # The configured product_code fills codProduto only when the request leaves it out.
58
59
  def product(fields)
59
- { 'codProduto' => Validators.text('codProduto', fields['codProduto'], max: 255) }
60
+ value = fields['codProduto']
61
+ value = @client.configuration.product_code if value.nil?
62
+ { 'codProduto' => Validators.text('codProduto', value, max: 255) }
60
63
  end
61
64
 
62
65
  def occurrence_date(fields)
data/lib/enel_x/errors.rb CHANGED
@@ -13,6 +13,9 @@ module EnelX
13
13
  @transaction_id = transaction_id
14
14
  @reason = reason
15
15
  end
16
+
17
+ # Network timeout (open, read or write); an API "Gateway Timeout" message is not.
18
+ def timeout? = reason == :timeout
16
19
  end
17
20
 
18
21
  # Bad credentials, host or persistent 401: the consumer must fix its setup.
data/lib/enel_x/http.rb CHANGED
@@ -31,11 +31,18 @@ module EnelX
31
31
  response = connection(uri).request(request)
32
32
  Response.new(response.code.to_i, response.body.to_s)
33
33
  rescue *NETWORK_ERRORS => e
34
- raise Error.new("network failure: #{e.class}", kind: :retryable)
34
+ raise network_failure(e)
35
35
  end
36
36
 
37
37
  private
38
38
 
39
+ # Errno::ETIMEDOUT is the operating system giving up on connecting: also a timeout.
40
+ def network_failure(error)
41
+ timeout = error.is_a?(Timeout::Error) || error.is_a?(Errno::ETIMEDOUT)
42
+ Error.new("network failure: #{error.class}", kind: :retryable,
43
+ reason: timeout ? :timeout : :network)
44
+ end
45
+
39
46
  def connection(uri)
40
47
  Net::HTTP.new(uri.host, uri.port).tap do |http|
41
48
  http.use_ssl = uri.scheme == 'https'
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+
5
+ require_relative 'validators'
6
+
7
+ module EnelX
8
+ # Builders of the order fields from Ruby values: they only translate names and formats
9
+ # into the PDF fields that Client#order_sale and #order_disconnect take. Limits are
10
+ # still checked by the endpoint, before any network call. No client, no network.
11
+ module Orders
12
+ INFINITE_INSTALLMENTS = -1
13
+
14
+ # Shared translation of values. Integer amounts are cents (4990 => "49.90"); Rational
15
+ # amounts are reais, exact to the cent. Float is refused: binary fractions round.
16
+ # String and anything else (BigDecimal included) go as given to the endpoint check.
17
+ module Format
18
+ module_function
19
+
20
+ def amount(value)
21
+ case value
22
+ when Integer then cents(value)
23
+ when Rational then exact_cents(value)
24
+ when Float then Validators.invalid('valorParcela',
25
+ 'String, Integer cents or Rational, not Float', value)
26
+ else value
27
+ end
28
+ end
29
+
30
+ def date(value)
31
+ value.is_a?(Date) || value.is_a?(Time) ? value.strftime('%Y-%m-%d') : value
32
+ end
33
+
34
+ def installments(value)
35
+ value == :continuous ? INFINITE_INSTALLMENTS : value
36
+ end
37
+
38
+ def cents(number)
39
+ whole, fraction = number.abs.divmod(100)
40
+ format('%<sign>s%<whole>d.%<fraction>02d', sign: number.negative? ? '-' : '',
41
+ whole:, fraction:)
42
+ end
43
+
44
+ def exact_cents(value)
45
+ hundredths = value * 100
46
+ return cents(hundredths.to_i) if hundredths.denominator == 1
47
+
48
+ Validators.invalid('valorParcela', 'at most two decimal places', value)
49
+ end
50
+ end
51
+
52
+ # Fields of Solicitação de Venda (PDF 5.3.2), residential customer. Email defaults to
53
+ # "" (the PDF allows it empty); occurred_on has no default, because it starts the
54
+ # billing (spec "Data de início da cobrança"). Optional nil values are left out, so a
55
+ # nil product_code falls back to the configured product_code.
56
+ module Sale
57
+ module_function
58
+
59
+ # rubocop:disable-next Metrics/ParameterLists -- one keyword per field of the PDF
60
+ def fields(first_name:, last_name:, phone:, street:, number:, neighborhood:, city:,
61
+ zip_code:, company:, utility_account:, cpf:, installment_value:, occurred_on:,
62
+ attachments:, birth_date: nil, email: '', installments: :continuous,
63
+ product_code: nil, partner_customer_number: nil)
64
+ {
65
+ 'Nome' => first_name, 'Sobrenome' => last_name,
66
+ 'dtNascimento' => Format.date(birth_date), 'Telefone' => phone,
67
+ 'Email' => email,
68
+ 'Endereco' => street, 'EnderecoNumero' => number, 'Bairro' => neighborhood,
69
+ 'Cidade' => city, 'CEP' => zip_code,
70
+ 'empresa' => company, 'numeroCliente' => utility_account, 'CPF' => cpf,
71
+ 'numParcelas' => Format.installments(installments),
72
+ 'valorParcela' => Format.amount(installment_value),
73
+ 'codProduto' => product_code, 'dataOcorrencia' => Format.date(occurred_on),
74
+ 'numeroClienteEmpPar' => partner_customer_number,
75
+ 'anexos' => attachments
76
+ }.compact
77
+ end
78
+ end
79
+
80
+ # Fields of Cancelamento (PDF 5.5.2). reason_code is checked against table 7.1 by the
81
+ # endpoint; numParcelas is not sent (see OrderDisconnect).
82
+ module Disconnect
83
+ module_function
84
+
85
+ # rubocop:disable-next Metrics/ParameterLists -- one keyword per field of the PDF
86
+ def fields(first_name:, last_name:, company:, utility_account:, installment_value:,
87
+ reason_code:, occurred_on:, street:, number:, neighborhood:, city:, zip_code:,
88
+ product_code: nil, partner_customer_number: nil)
89
+ {
90
+ 'Nome' => first_name, 'Sobrenome' => last_name,
91
+ 'empresa' => company, 'numeroCliente' => utility_account,
92
+ 'valorParcela' => Format.amount(installment_value),
93
+ 'codProduto' => product_code,
94
+ 'codOcorr' => reason_code&.to_s, 'dataOcorrencia' => Format.date(occurred_on),
95
+ 'Endereco' => street, 'EnderecoNumero' => number, 'Bairro' => neighborhood,
96
+ 'Cidade' => city, 'CEP' => zip_code,
97
+ 'numeroClienteEmpPar' => partner_customer_number
98
+ }.compact
99
+ end
100
+ end
101
+ end
102
+ end
data/lib/enel_x/record.rb CHANGED
@@ -1,13 +1,22 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'date'
4
+
3
5
  require_relative 'reference/document_state'
4
6
  require_relative 'reference/occurrence'
5
7
 
6
8
  module EnelX
7
9
  # Item of a history query (PDF 5.6 to 5.10). Attributes are the lowercase keys of the
8
10
  # PDF; null, absent and empty text become nil. Dates and numbers keep the text the API
9
- # sent, because the PDF does not specify their format.
11
+ # sent, because the PDF does not specify their format; #date reads a date apart.
10
12
  module Record
13
+ # Shortcut => member; each one exists only where the record has the member.
14
+ DATE_SHORTCUTS = {
15
+ occurred_on: :dataocorrencia, due_on: :datavencimento, paid_on: :datapagamento
16
+ }.freeze
17
+ ISO_DATE = /\A(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
18
+ US_DATE = %r{\A(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{4})}
19
+
11
20
  # Class-level builder: keys are matched ignoring case (novaUC => novauc).
12
21
  module Builder
13
22
  def from_hash(hash)
@@ -30,16 +39,46 @@ module EnelX
30
39
  end
31
40
  end
32
41
 
42
+ # Typed reading of any date member; the text attribute stays as received.
43
+ module DateReader
44
+ def date(name)
45
+ unless members.include?(name.to_sym)
46
+ raise ArgumentError, "#{self.class} has no member #{name}"
47
+ end
48
+
49
+ Record.parse_date(self[name.to_sym])
50
+ end
51
+ end
52
+
33
53
  module_function
34
54
 
35
55
  def define(*members)
36
56
  klass = Class.new(Struct.new(*members, keyword_init: true))
37
57
  klass.extend(Builder)
58
+ klass.include(DateReader)
38
59
  klass.include(OccurrenceReader) if members.include?(:codocorr)
39
60
  klass.include(DocumentStateReader) if members.include?(:estadodocumento)
61
+ DATE_SHORTCUTS.each do |shortcut, member|
62
+ klass.define_method(shortcut) { date(member) } if members.include?(member)
63
+ end
40
64
  klass
41
65
  end
42
66
 
67
+ # [ASSUMPTION p.2, p.27-31] the PDF fixes MM/DD/AAAA for the dates sent to the queries
68
+ # (v4.2 note, p.2; send tables, p.27 to 30) but its response examples are empty. The
69
+ # consumer sees MM/DD/AAAA in production; ISO is also read. Anything else, DD/MM
70
+ # included, is nil: never raises, never swaps day and month (PENDENCIAS-ENEL nº 11).
71
+ def parse_date(text)
72
+ value = text.to_s.strip
73
+ if (iso = value.match(ISO_DATE))
74
+ Date.new(iso[:year].to_i, iso[:month].to_i, iso[:day].to_i)
75
+ elsif (us = value.match(US_DATE))
76
+ Date.new(us[:year].to_i, us[:month].to_i, us[:day].to_i)
77
+ end
78
+ rescue Date::Error
79
+ nil
80
+ end
81
+
43
82
  def clean(value)
44
83
  return nil if value.nil?
45
84
 
@@ -12,6 +12,17 @@ module EnelX
12
12
  # Codes the Enel X returns to the partner (PDF 7.2). Read-only table: it does not
13
13
  # decide anything for the consumer.
14
14
  class Occurrence < Data.define(:code, :description, :ok, :legacy_code, :note, :stage)
15
+ # Codes the consumer handles most, named after the PDF 7.2 description. What each one
16
+ # means for the business (e.g. which one allows activation) stays with the consumer.
17
+ PAYMENT = '901' # Recebido o Pagamento do produto (arrecadação)
18
+ BILLING = '902' # Inclusão de Cobrança na fatura (faturamento)
19
+ CANCELED = '909' # Cancelamento
20
+ CHARGE_INCLUDED = '915' # Cobrança Incluída para o Cliente
21
+ INTAKE_OK = '996' # Retorno OK para novas vendas / Alteração / Cancelamentos
22
+ INTAKE_KO = '997' # Retorno KO para novas vendas / Alteração / Cancelamentos
23
+ AUDIT_OK = '998' # Retorno OK para auditoria
24
+ AUDIT_KO = '999' # Retorno KO para auditoria
25
+
15
26
  STAGES = {
16
27
  intake: %w[996 997], audit: %w[998 999],
17
28
  billing: %w[901 902 903 904 905 907 908 909 910 913 914 915 916 917 918 920]
@@ -127,6 +138,20 @@ module EnelX
127
138
  CANCELLATION_REASONS.find { |item| item.code == code.to_s }
128
139
  end
129
140
 
141
+ # [ASSUMPTION p.29, p.36] the occurrence answer (5.7) brings only the reason text
142
+ # in descricaoretorno, not its code: match it against the descriptions of the
143
+ # 909 table, ignoring case, when either text contains the other. First match in
144
+ # table order; blank or unknown text is nil (PENDENCIAS-ENEL nº 12).
145
+ def cancellation_reason_for(text)
146
+ wanted = text.to_s.strip.downcase
147
+ return if wanted.empty?
148
+
149
+ CANCELLATION_REASONS.find do |reason|
150
+ known = reason.description.downcase
151
+ wanted.include?(known) || known.include?(wanted)
152
+ end
153
+ end
154
+
130
155
  # Unknown codes still get an object, so callers can keep the raw code.
131
156
  def fetch(code)
132
157
  find(code) || new(code.to_s, nil, nil, nil, nil, :unknown)
data/lib/enel_x.rb CHANGED
@@ -12,6 +12,7 @@ require_relative 'enel_x/reference'
12
12
  require_relative 'enel_x/validators'
13
13
  require_relative 'enel_x/attachment'
14
14
  require_relative 'enel_x/record'
15
+ require_relative 'enel_x/orders'
15
16
  require_relative 'enel_x/result'
16
17
  require_relative 'enel_x/client'
17
18
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: enel-ruby-sdk
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.2
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Danilo Josino
@@ -36,6 +36,7 @@ files:
36
36
  - lib/enel_x/headers.rb
37
37
  - lib/enel_x/http.rb
38
38
  - lib/enel_x/memory_cache.rb
39
+ - lib/enel_x/orders.rb
39
40
  - lib/enel_x/record.rb
40
41
  - lib/enel_x/reference.rb
41
42
  - lib/enel_x/reference/distributor.rb