nav_online_invoice 0.2.0 → 0.3.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.
Files changed (62) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +50 -1
  3. data/README.md +28 -22
  4. data/lib/generators/nav_online_invoice/install/install_generator.rb +4 -2
  5. data/lib/generators/nav_online_invoice/install/templates/{nav_online_invoice.rb → nav_online_invoice.rb.tt} +3 -1
  6. data/lib/nav_online_invoice/address.rb +6 -1
  7. data/lib/nav_online_invoice/annulment_items.rb +3 -14
  8. data/lib/nav_online_invoice/audit_data.rb +6 -9
  9. data/lib/nav_online_invoice/business_validation_message.rb +7 -1
  10. data/lib/nav_online_invoice/client.rb +19 -16
  11. data/lib/nav_online_invoice/configuration/builder.rb +43 -0
  12. data/lib/nav_online_invoice/configuration/validation.rb +103 -0
  13. data/lib/nav_online_invoice/configuration.rb +8 -147
  14. data/lib/nav_online_invoice/crypto.rb +5 -2
  15. data/lib/nav_online_invoice/electronic_invoice_hash.rb +11 -0
  16. data/lib/nav_online_invoice/errors.rb +33 -17
  17. data/lib/nav_online_invoice/exchange_token.rb +14 -7
  18. data/lib/nav_online_invoice/invoice_chain_element.rb +4 -8
  19. data/lib/nav_online_invoice/invoice_data_result.rb +8 -8
  20. data/lib/nav_online_invoice/invoice_digest.rb +7 -8
  21. data/lib/nav_online_invoice/invoices.rb +18 -18
  22. data/lib/nav_online_invoice/item_list.rb +26 -0
  23. data/lib/nav_online_invoice/metric.rb +2 -2
  24. data/lib/nav_online_invoice/metric_definition.rb +2 -2
  25. data/lib/nav_online_invoice/metrics.rb +10 -2
  26. data/lib/nav_online_invoice/operations/base.rb +22 -1
  27. data/lib/nav_online_invoice/operations/invoice_number_query.rb +1 -1
  28. data/lib/nav_online_invoice/operations/invoice_query_params.rb +2 -3
  29. data/lib/nav_online_invoice/operations/manage.rb +14 -6
  30. data/lib/nav_online_invoice/operations/manage_invoice.rb +1 -1
  31. data/lib/nav_online_invoice/operations/query_invoice_chain_digest.rb +2 -8
  32. data/lib/nav_online_invoice/operations/query_invoice_data.rb +5 -6
  33. data/lib/nav_online_invoice/operations/query_invoice_digest.rb +2 -8
  34. data/lib/nav_online_invoice/operations/query_taxpayer.rb +5 -3
  35. data/lib/nav_online_invoice/operations/query_transaction_list.rb +1 -7
  36. data/lib/nav_online_invoice/operations/query_transaction_status.rb +4 -4
  37. data/lib/nav_online_invoice/operations/token_exchange.rb +0 -3
  38. data/lib/nav_online_invoice/page.rb +8 -6
  39. data/lib/nav_online_invoice/params.rb +14 -3
  40. data/lib/nav_online_invoice/payload.rb +15 -1
  41. data/lib/nav_online_invoice/processing_result.rb +8 -8
  42. data/lib/nav_online_invoice/railtie.rb +15 -3
  43. data/lib/nav_online_invoice/redacted.rb +15 -0
  44. data/lib/nav_online_invoice/redactor.rb +7 -3
  45. data/lib/nav_online_invoice/request_id.rb +1 -1
  46. data/lib/nav_online_invoice/response_parser.rb +2 -2
  47. data/lib/nav_online_invoice/retry.rb +20 -0
  48. data/lib/nav_online_invoice/schema_validator.rb +3 -2
  49. data/lib/nav_online_invoice/submission.rb +9 -2
  50. data/lib/nav_online_invoice/submission_items.rb +21 -16
  51. data/lib/nav_online_invoice/taxpayer.rb +9 -1
  52. data/lib/nav_online_invoice/taxpayer_result.rb +2 -6
  53. data/lib/nav_online_invoice/technical_validation_message.rb +13 -0
  54. data/lib/nav_online_invoice/throttle.rb +6 -4
  55. data/lib/nav_online_invoice/transaction.rb +8 -9
  56. data/lib/nav_online_invoice/transaction_status.rb +9 -9
  57. data/lib/nav_online_invoice/transactions.rb +37 -20
  58. data/lib/nav_online_invoice/transport.rb +7 -2
  59. data/lib/nav_online_invoice/version.rb +1 -1
  60. data/lib/nav_online_invoice/xml_reader.rb +1 -1
  61. data/lib/nav_online_invoice.rb +8 -0
  62. metadata +17 -9
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8b8b8c3afe0a8d448e09392b80e16facf13d7213697aed1a3ce9b7893b005089
4
- data.tar.gz: 4ac2060931d33810fe1c6437468883c823bc763a14f80e1b4f3338d1c123de19
3
+ metadata.gz: c3c7f3e041d44c8f6f765ba46e8085d04a57a16270520702c9e39b4c2a7abf2e
4
+ data.tar.gz: fa4825716864b51f7cb06a65e9884dc0afdb8bc3505f590c05be8d715a186d35
5
5
  SHA512:
6
- metadata.gz: f61b5bd781664cff78e41cd250a4f49170376a8939f638ea1b178a1a5561b6f799614b56a702162ea18fb92c4baaf0e6c6ba362acf4fac25c94a9cf337e9182d
7
- data.tar.gz: ea98155c5178f1bed3eddc44d3178d8a0f577cec1e93814734b0a9a6583f9537f89ba7c998615118089cec8b570d5b4a7bfcc893f9b70e951c84b55088dac70f
6
+ metadata.gz: 9a4f402079d5ac704f972641ef3cd0ff8d42b83de10d7e89675d1743e1cdabe8870c79a2d713da2316d6914d66198d696ad316da0ea27f65b6d754354fc55dc1
7
+ data.tar.gz: 87ad7196f8a8acc941891b38e61c6aac3e5a64315c1816851e60f3f4516e5141ebd3eb51306ed0fcdf4a05f911f3544e9ecd6ac5b3fadf4c388cb5d9298e9822
data/CHANGELOG.md CHANGED
@@ -6,6 +6,47 @@ and the project adheres to [Semantic Versioning](https://semver.org/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.3.0] - 2026-11-18
10
+
11
+ ### Fixed
12
+
13
+ - `transactions.reconcile` searches by NAV's clock: `UnknownOutcomeError#sent_at` is NAV's time of sending, worked
14
+ out from the exchange token, and the window runs from five minutes before to ten minutes after it (spec 1.9.2).
15
+ A wrong local clock or a long throttle wait could hide the transaction and lead to a duplicate submission.
16
+ - `reconcile` no longer counts an annulment, or a submission NAV aborted, as an arrived invoice; it refuses to run
17
+ on a `with_predecessor` client, whose list shows the predecessor's submissions.
18
+ - An invoice with `completenessIndicator` written as `1` gets its `electronicInvoiceHash`.
19
+ - A submission answered with a 4xx that is not a NAV answer raises the `TransportError` (rejected) instead of
20
+ `UnknownOutcomeError`.
21
+ - `TransactionStatus#accepted?` is false while there are no results.
22
+ - `transactions.each_transaction` checks its parameters before the first request.
23
+ - `NOT_ALLOWED_EXCEPTION` raises `RequestError`, not `PermissionError`.
24
+ - The generated Rails initializer leaves the gem unconfigured instead of stopping the boot when the credentials
25
+ have no `nav` entry.
26
+
27
+ ### Changed
28
+
29
+ - **Breaking:** `ExchangeTokenError` inherits from `ApiError`, not `RequestError`, since submitting again is safe.
30
+ - **Breaking:** electronic invoice hashes are `NavOnlineInvoice::ElectronicInvoiceHash` values in
31
+ `Submission#electronic_invoice_hashes` and `InvoiceDataResult#electronic_invoice_hash`;
32
+ `InvoiceDataResult#electronic_invoice_hash_type` is gone. `submit` takes a Hash or an `ElectronicInvoiceHash`.
33
+ - **Breaking:** `reconcile` returns `{ invoice_number => [transaction_id, ...] }` and takes `annulment: true` for
34
+ annulments.
35
+ - `TechnicalValidationMessage` is a top-level class; `ApiError::TechnicalValidationMessage` still refers to it.
36
+ - `Submission#compressed?`, `Transaction#technical_annulment?` and `InvoiceDigest#complete?`.
37
+ - Queries retry a bare 503 from a network device; NAV's own `MAINTENANCE_MODE` is still not retried.
38
+ - `nokogiri` 1.19.5 or later.
39
+
40
+ ### Security
41
+
42
+ - Schema validation messages leave the rejected values out (`SchemaValidationError#message`); the full messages
43
+ stay in `#errors`. `ArgumentError` messages no longer quote free text or tax numbers.
44
+ - `Taxpayer` and `Address` leave the name and the address out of `inspect`; `pp` of every result and of every
45
+ operation shows the same redacted text; `to_h` of the exchange token and of a submitted item hides their data.
46
+ - The Railtie hides the login, the password and the keys in `config.nav_online_invoice` once applied.
47
+ - Unpacking gzip data stops at 20 MB; requests go only over https with a verified certificate and TLS 1.2 or later;
48
+ the log redactor also covers CDATA, comments and prefixes with dots or hyphens.
49
+
9
50
  ## [0.2.0] - 2026-11-18
10
51
 
11
52
  ### Added
@@ -32,6 +73,8 @@ and the project adheres to [Semantic Versioning](https://semver.org/).
32
73
  - Rails integration: a Railtie that uses `Rails.logger` by default and turns `config.nav_online_invoice` into the
33
74
  global configuration, and `rails generate nav_online_invoice:install`.
34
75
  - `NavOnlineInvoice.default_logger` for configurations that set no logger.
76
+ - `Client#predecessor_tax_number`, `UnknownOutcomeError#reconcile_window`, `Crypto.index_hash`,
77
+ `Crypto.electronic_invoice_hash` and `Crypto.decrypt_token`; the log line has a `bytes=` field.
35
78
 
36
79
  ### Changed
37
80
 
@@ -41,6 +84,11 @@ and the project adheres to [Semantic Versioning](https://semver.org/).
41
84
  - New runtime dependency: `bigdecimal` (any version shipped with Ruby 3.3 or later).
42
85
  - `INVALID_EXCHANGE_TOKEN` raises `ExchangeTokenError` (a `RequestError`).
43
86
 
87
+ ### Security
88
+
89
+ - 0.1.0 logged NAV's answers at `debug` level without hiding anything; 0.2.0 logs no XML unless `log_payloads` is
90
+ set, and hides credentials and invoice data even then.
91
+
44
92
  ## [0.1.0] - 2026-11-17
45
93
 
46
94
  ### Added
@@ -63,7 +111,8 @@ and the project adheres to [Semantic Versioning](https://semver.org/).
63
111
 
64
112
  - Project skeleton: gemspec, RSpec, RuboCop, GitHub Actions CI. No public API yet.
65
113
 
66
- [Unreleased]: https://github.com/kilozdazolik/nav-online-invoice/compare/v0.2.0...HEAD
114
+ [Unreleased]: https://github.com/kilozdazolik/nav-online-invoice/compare/v0.3.0...HEAD
115
+ [0.3.0]: https://github.com/kilozdazolik/nav-online-invoice/compare/v0.2.0...v0.3.0
67
116
  [0.2.0]: https://github.com/kilozdazolik/nav-online-invoice/compare/v0.1.0...v0.2.0
68
117
  [0.1.0]: https://github.com/kilozdazolik/nav-online-invoice/compare/v0.0.1...v0.1.0
69
118
  [0.0.1]: https://github.com/kilozdazolik/nav-online-invoice/releases/tag/v0.0.1
data/README.md CHANGED
@@ -21,7 +21,7 @@ Ruby client for the Hungarian Tax Authority's (NAV) **Online Invoice API v3.0**
21
21
 
22
22
  ## Requirements
23
23
 
24
- - Ruby 3.3 or newer (CRuby; tested on 3.3, 3.4 and 4.0, on Linux and Windows)
24
+ - Ruby 3.3 or newer (CRuby; tested on 3.3, 3.4 and 4.0 on Linux, and on 4.0 on Windows)
25
25
  - A NAV Online Invoice technical user: login, password and signature key. Test and production users are separate;
26
26
  register a test user at <https://onlineszamla-test.nav.gov.hu>.
27
27
 
@@ -71,14 +71,14 @@ result.matches?("12345678-2-42") # => true if the VAT and county codes matc
71
71
  result.taxpayer.name # => "EXAMPLE KFT."
72
72
  result.taxpayer.tax_number # => "12345678-2-42"
73
73
  result.taxpayer.incorporation # => :organization, :self_employed or :taxable_person
74
- result.taxpayer.headquarters.city # addresses: :hq, :site or :branch
74
+ result.taxpayer.headquarters&.city # addresses: :hq, :site or :branch
75
75
  result.request_id # for your logs
76
76
  ```
77
77
 
78
78
  An unknown tax number is not an error: `valid?` is `false` and `taxpayer` is `nil`. NAV checks only the first 8
79
79
  digits, so `valid?` is also true for `12345678-9-99`; use `matches?` to check a full tax number.
80
80
 
81
- The gem never reads environment variables or Rails credentials; pass the values in. Keep one `Client` per technical
81
+ The gem itself never reads environment variables or Rails credentials; pass the values in. Keep one `Client` per technical
82
82
  user and reuse it; it is thread-safe.
83
83
 
84
84
  ### Querying invoices
@@ -110,7 +110,8 @@ single value or a range with both ends (`10_000..500_000`); NAV accepts no open
110
110
 
111
111
  Parameters are checked before sending; a bad one raises `ArgumentError`. `data` returns `nil` when NAV has no such
112
112
  invoice for you. A long `each_digest` can walk many pages, and NAV's data can change while it does: set
113
- `max_pages` or narrow the filters.
113
+ `max_pages` or narrow the filters. Every paged query has an `each_` method named after its items: `digest` and
114
+ `each_digest`, `chain_digest` and `each_chain_element`, `transactions.list` and `each_transaction`.
114
115
 
115
116
  ### Transactions
116
117
 
@@ -141,26 +142,30 @@ submission.transaction_id # NAV received the request; proces
141
142
  status = client.transactions.wait(submission.transaction_id, timeout: 120)
142
143
  status.finished? # NAV finished with every invoice
143
144
  status.accepted? # ... and all of them are DONE without errors
144
- status.results.reject(&:done?).map(&:index) # positions (from 1) to fix and submit again
145
+ status.results.reject { |r| r.done? && !r.errors? }.map(&:index) # positions (from 1) to fix and submit again
145
146
  ```
146
147
 
147
- - **Sent once, never retried.** A NAV error answer (`ApiError`) means nothing was stored, so the invoices can be
148
- sent again. `UnknownOutcomeError` means the request was sent but no answer arrived: the invoices may be at NAV.
149
- Do not resend them blindly; after five minutes, ask NAV:
148
+ - **Sent once, never retried.** A NAV error answer (`ApiError`), or a 4xx without one, means nothing was stored, so
149
+ the invoices can be sent again. `UnknownOutcomeError` means the request was sent but no answer arrived: the
150
+ invoices may be at NAV. Do not resend them blindly; after five minutes, ask NAV:
150
151
 
151
152
  ```ruby
152
153
  rescue NavOnlineInvoice::UnknownOutcomeError => e
153
154
  # five minutes later, e.g. from a background job:
154
155
  found = client.transactions.reconcile(sent_at: e.sent_at, invoice_numbers: numbers)
155
- # => { "INV-2026-0001" => "4Q8O2ZCTX1J8WGZ2" }; submit the rest again
156
+ # => { "INV-2026-0001" => ["4Q8O2ZCTX1J8WGZ2"] }; submit the rest again
156
157
  ```
157
158
 
159
+ `e.sent_at` is NAV's time of sending, worked out from the exchange token, so a wrong local clock does not hide the
160
+ transaction. Aborted submissions do not count as arrived; for annulments pass `annulment: true`.
161
+
158
162
  - **Partial failures.** Each invoice is processed on its own. Submit only the aborted ones again, in a new call.
159
163
  - **Size.** NAV accepts at most 10 MB per request and 15 MB per invoice. With `compress: :auto` (the default) the
160
164
  invoices are gzipped only when the request would be too large; `compress: true` or `false` decides yourself.
161
165
  - **Electronic invoices.** When the XML itself is the electronic invoice (`completenessIndicator` true), the gem
162
166
  computes its `electronicInvoiceHash`. Otherwise pass the hash of your own electronic invoice file:
163
- `electronic_invoice_hash: { value: "...", crypto_type: "SHA-256" }` (or `"SHA3-512"`).
167
+ `electronic_invoice_hash: { value: "...", crypto_type: "SHA-256" }` (or `"SHA3-512"`). The submission returns the
168
+ hashes it sent as `NavOnlineInvoice::ElectronicInvoiceHash` values.
164
169
  - `wait` returns the last status at the timeout instead of raising; store it and ask again later with `status`.
165
170
 
166
171
  ### Technical annulment
@@ -211,7 +216,8 @@ metrics.definitions # names a
211
216
 
212
217
  Dates are `Date`, timestamps `Time` in UTC, amounts `BigDecimal`, NAV's codes lowercase symbols (`:outbound`,
213
218
  `:storno`, `:done`). Paged queries return a `NavOnlineInvoice::Page` with `items`, `current_page` and
214
- `total_pages`. `inspect` and `pp` of the results leave out names, addresses, amounts and invoice contents.
219
+ `total_pages` (and `last_page?`). `inspect` and `pp` of the results leave out names, addresses, amounts and invoice
220
+ contents.
215
221
 
216
222
  ### Global configuration
217
223
 
@@ -252,8 +258,8 @@ config.nav_online_invoice.login = Rails.application.credentials.dig(:nav, :login
252
258
 
253
259
  - `Rails.logger` is the default logger, unless a configuration sets its own.
254
260
  - An unknown or invalid setting stops the application at boot with a `ConfigurationError`.
255
- - Rails' default `filter_parameters` (`:passw`, `:_key`, `:token`, `:secret`) already hide the password and the
256
- keys in the Rails log.
261
+ - The gem logs none of its settings. Rails' default `filter_parameters` (`:passw`, `:_key`, `:token`, `:secret`)
262
+ cover the password and the keys if your own code passes them as request parameters; the login is not secret.
257
263
  - For several companies, skip the global configuration and keep one `Client` per company.
258
264
 
259
265
  The gem ships no background jobs; follow submissions from your own:
@@ -280,10 +286,10 @@ end
280
286
  | `retry_base_delay` | `1.0` | seconds before the first retry; doubles on each retry |
281
287
  | `throttle` | shared `Throttle` | at most one request per second per process; `nil` turns it off |
282
288
  | `validate_requests` | `true` | check each request against NAV's schema before sending |
283
- | `logger` | `nil` | one line per request at `info`, without any content |
289
+ | `logger` | `NavOnlineInvoice.default_logger` (`Rails.logger` under Rails) | one line per request at `info`, without any content; `nil` for none |
284
290
  | `log_payloads` | `false` | also log the XML at `debug`; never in production, see below |
285
291
  | `request_id_generator` | `NavOnlineInvoice::RequestId` | any object with `call` |
286
- | `exchange_key` | `nil` | only needed to submit invoices (not supported yet) |
292
+ | `exchange_key` | `nil` | 16 characters; only needed to submit invoices and annulments |
287
293
  | `clock` | `Time.method(:now)` | any object with `call` returning a `Time`; for tests |
288
294
 
289
295
  For an interactive lookup, e.g. on a form, use a shorter `read_timeout` and fewer retries:
@@ -306,7 +312,7 @@ can succeed.
306
312
  | `CustomerError` | `NOT_REGISTERED_CUSTOMER`, `INVALID_CUSTOMER`, `INVALID_USER_RELATION`, ... | no |
307
313
  | `RequestError` | `INVALID_REQUEST`, `INVALID_TIMESTAMP`, `BAD_QUERY_PARAM_*`, ... | no |
308
314
  | `ExchangeTokenError` | `INVALID_EXCHANGE_TOKEN`: wrong exchange key, or the token expired; nothing was stored | no (`retryable?` is true) |
309
- | `MaintenanceError` | NAV is under maintenance | no (`retryable?` is true: try again later) |
315
+ | `MaintenanceError` | NAV is under maintenance, or a network device answered 503 | only a query's bare 503 (`retryable?` is true: try again later) |
310
316
  | `TemporaryError` | `OPERATION_FAILED`, `REQUEST_ID_NOT_UNIQUE` | yes, except submissions |
311
317
  | `DecodeError` | NAV sent invoice data that is not valid base64, gzip or UTF-8, or a token the exchange key does not decrypt | no |
312
318
 
@@ -331,9 +337,9 @@ end
331
337
  ID of a request it refused with `FORBIDDEN` or `INVALID_REQUEST_SIGNATURE`.
332
338
  - Only temporary failures of queries and token requests are retried. Submissions (`submit`, `annul`) are never
333
339
  retried. In the worst case one call takes about `(max_retries + 1) × read_timeout`.
334
- - NAV allows **one request per second per IP address** on `queryTaxpayer`, `queryInvoiceData` and
335
- `queryTransactionStatus`, `tokenExchange`, `manageInvoice` and `manageAnnulment`, and delays the rest. The default throttle keeps one such
336
- request per second within a process; the other queries are not throttled. If several processes share an
340
+ - NAV allows **one request per second per IP address** on `queryTaxpayer`, `queryInvoiceData`,
341
+ `queryTransactionStatus`, `tokenExchange`, `manageInvoice` and `manageAnnulment`, and delays the rest. The default
342
+ throttle keeps one such request per second within a process; the other queries are not throttled. If several processes share an
337
343
  IP address, pass a shared `throttle`: any object with `wait(operation_name)`, e.g. one using a database lock.
338
344
 
339
345
  ### Logging and personal data
@@ -351,7 +357,7 @@ environment only.
351
357
  The gem needs no compiler: `nokogiri` ships precompiled, and `bigdecimal` comes with Ruby. Keep your lock file on
352
358
  the `bigdecimal` version your Ruby ships with (`gem list bigdecimal`), because there is no precompiled Windows build
353
359
  of newer versions. To check an installation on a machine without a compiler, run
354
- [script/windows_smoke.rb](script/windows_smoke.rb) after `gem install --local nav_online_invoice-X.Y.Z.gem`.
360
+ [script/windows_smoke.rb](https://github.com/kilozdazolik/nav-online-invoice/blob/main/script/windows_smoke.rb) after `gem install --local nav_online_invoice-X.Y.Z.gem`.
355
361
 
356
362
  ## Development
357
363
 
@@ -382,8 +388,8 @@ to update them.
382
388
 
383
389
  1. Update `VERSION` in `lib/nav_online_invoice/version.rb` and add a matching section to `CHANGELOG.md`.
384
390
  2. Run `bin/dev bundle exec rake release:check`.
385
- 3. Commit (`Release 0.1.0`), push and wait for CI.
386
- 4. Tag and push: `git tag -a v0.1.0 -m "Version 0.1.0" && git push origin v0.1.0`. GitHub Actions publishes the
391
+ 3. Commit (`Release X.Y.Z`), push and wait for CI.
392
+ 4. Tag and push: `git tag -a vX.Y.Z -m "Version X.Y.Z" && git push origin vX.Y.Z`. GitHub Actions publishes the
387
393
  gem to RubyGems via trusted publishing and creates the GitHub release from the CHANGELOG section.
388
394
 
389
395
  ## Changelog
@@ -3,15 +3,17 @@
3
3
  require "rails/generators"
4
4
 
5
5
  module NavOnlineInvoice
6
+ # Rails generators of the gem.
6
7
  module Generators
7
- # +rails generate nav_online_invoice:install+: creates config/initializers/nav_online_invoice.rb.
8
+ # `rails generate nav_online_invoice:install`: creates config/initializers/nav_online_invoice.rb.
8
9
  class InstallGenerator < ::Rails::Generators::Base
9
10
  source_root File.expand_path("templates", __dir__)
10
11
 
11
12
  desc "Creates config/initializers/nav_online_invoice.rb with the settings NAV needs."
12
13
 
14
+ # Writes the initializer; asks before replacing an existing one.
13
15
  def create_initializer
14
- copy_file "nav_online_invoice.rb", "config/initializers/nav_online_invoice.rb"
16
+ template "nav_online_invoice.rb.tt", "config/initializers/nav_online_invoice.rb"
15
17
  end
16
18
  end
17
19
  end
@@ -10,7 +10,9 @@
10
10
  # tax_number: "12345678"
11
11
  #
12
12
  # The test and the production environment need separate technical users.
13
- nav = Rails.application.credentials.nav || {}
13
+ # Without them (e.g. in CI or during assets:precompile) the gem stays unconfigured instead of stopping the boot.
14
+ nav = Rails.application.credentials.nav
15
+ return if nav.blank?
14
16
 
15
17
  NavOnlineInvoice.configure do |config|
16
18
  config.environment = Rails.env.production? ? :production : :test
@@ -7,13 +7,18 @@ module NavOnlineInvoice
7
7
  # An address of a taxpayer, as NAV stores it.
8
8
  #
9
9
  # @!attribute type
10
- # @return [Symbol] +:hq+ (registered office), +:site+ or +:branch+
10
+ # @return [Symbol] `:hq` (registered office), `:site` or `:branch`
11
11
  # @!attribute public_place_category
12
12
  # @return [String] e.g. "UTCA" or "ÚT"
13
13
  class Address
14
+ include Redacted
15
+
14
16
  def initialize(type:, country_code:, postal_code:, city:, street_name:, public_place_category:, region: nil,
15
17
  number: nil, building: nil, staircase: nil, floor: nil, door: nil, lot_number: nil)
16
18
  super
17
19
  end
20
+
21
+ # Leaves out the address itself: for a sole trader it is personal data.
22
+ def inspect = "#<data #{self.class.name} type=#{type.inspect}, country_code=#{country_code.inspect}>"
18
23
  end
19
24
  end
@@ -16,11 +16,7 @@ module NavOnlineInvoice
16
16
  # @return [Array<Operations::Manage::Item>]
17
17
  # @raise [ArgumentError, SchemaValidationError]
18
18
  def prepare(items, time:, validate:)
19
- unless items.is_a?(Array) && items.all?(Hash) && items.size.between?(1, Operations::Manage::MAX_ITEMS)
20
- raise ArgumentError, "items must be an Array of 1-#{Operations::Manage::MAX_ITEMS} Hashes"
21
- end
22
-
23
- items.map.with_index(1) do |item, index|
19
+ ItemList.check(items).map.with_index(1) do |item, index|
24
20
  xml = xml(item, "items[#{index}]", time)
25
21
  SchemaValidator.validate!(xml, schema: :annulment) if validate
26
22
  Operations::Manage::Item.new(operation: "ANNUL", data: Payload.encode(xml, compressed: false))
@@ -39,21 +35,14 @@ module NavOnlineInvoice
39
35
 
40
36
  # @return [Hash{Symbol => String}] the elements in schema order
41
37
  def values(item, name, time)
42
- unknown = item.keys - KEYS
43
- raise ArgumentError, "#{name} has unknown keys: #{unknown.inspect}" unless unknown.empty?
38
+ ItemList.known_keys!(name, item, KEYS)
44
39
 
45
40
  {
46
41
  annulmentReference: Params.text(:"#{name}[:reference]", item[:reference], max: 50),
47
- annulmentTimestamp: Params.timestamp(timestamp(item[:timestamp] || time, name)),
42
+ annulmentTimestamp: Params.timestamp(Params.time(:"#{name}[:timestamp]", item[:timestamp] || time)),
48
43
  annulmentCode: Params.enum(:"#{name}[:code]", item[:code], CODES),
49
44
  annulmentReason: Params.text(:"#{name}[:reason]", item[:reason], max: 1024)
50
45
  }
51
46
  end
52
-
53
- def timestamp(value, name)
54
- return value if value.respond_to?(:getutc) && !value.is_a?(Date)
55
-
56
- raise ArgumentError, "#{name}[:timestamp] must be a Time, got #{value.inspect}"
57
- end
58
47
  end
59
48
  end
@@ -11,20 +11,17 @@ module NavOnlineInvoice
11
11
  # @!attribute ins_cus_user
12
12
  # @return [String] login of the technical user who sent it
13
13
  # @!attribute source
14
- # @return [Symbol] e.g. +:xml+ or +:web+
14
+ # @return [Symbol] e.g. `:xml` or `:web`
15
15
  # @!attribute original_request_version
16
16
  # @return [String] the format of the invoice, e.g. "3.0"
17
17
  class AuditData
18
+ include Redacted
19
+
18
20
  # Hides the technical user's login.
19
21
  def inspect
20
- "#<data #{self.class.name} ins_date=#{ins_date.inspect}, ins_cus_user=[FILTERED], source=#{source.inspect}, " \
21
- "transaction_id=#{transaction_id.inspect}, original_request_version=#{original_request_version.inspect}>"
22
- end
23
- alias to_s inspect
24
-
25
- # Used by +pp+, IRB and the Rails console.
26
- def pretty_print(printer)
27
- printer.text(inspect)
22
+ "#<data #{self.class.name} ins_date=#{ins_date.inspect}, ins_cus_user=#{Redactor::FILTERED}, " \
23
+ "source=#{source.inspect}, transaction_id=#{transaction_id.inspect}, " \
24
+ "original_request_version=#{original_request_version.inspect}>"
28
25
  end
29
26
  end
30
27
  end
@@ -4,13 +4,19 @@ module NavOnlineInvoice
4
4
  # A business rule finding of NAV on a submitted invoice.
5
5
  #
6
6
  # @!attribute result_code
7
- # @return [Symbol] +:error+ (the invoice is rejected), +:warn+ or +:info+
7
+ # @return [Symbol] `:error` (the invoice is rejected), `:warn` or `:info`
8
8
  # @!attribute error_code
9
9
  # @return [String, nil] NAV's code, e.g. "INVOICE_LINE_MISSING"
10
+ # @!attribute message
11
+ # @return [String, nil] NAV's explanation, in Hungarian
10
12
  # @!attribute tag
11
13
  # @return [String, nil] the element NAV points to
12
14
  # @!attribute line
13
15
  # @return [Integer, nil] the invoice line NAV points to
16
+ # @!attribute value
17
+ # @return [String, nil] the value NAV found
18
+ # @!attribute original_invoice_number
19
+ # @return [String, nil] the invoice a modification refers to
14
20
  BusinessValidationMessage = Data.define(:result_code, :error_code, :message, :tag, :value, :line,
15
21
  :original_invoice_number)
16
22
  end
@@ -73,17 +73,25 @@ module NavOnlineInvoice
73
73
  begin
74
74
  attempt += 1
75
75
  perform(operation, attempt)
76
- rescue TransportError, TemporaryError => e
77
- raise unless e.retryable? && operation.auto_retry? && attempt <= config.max_retries
76
+ rescue TransportError, TemporaryError, MaintenanceError => e
77
+ raise unless retry?(e, operation, attempt)
78
78
 
79
- log(:warn) { "NAV #{operation.name} attempt #{attempt} failed, retrying: #{e.message}" }
80
- pause(retry_delay(attempt))
79
+ Retry.wait(attempt, base_delay: config.retry_base_delay, logger: config.logger,
80
+ message: "#{operation.name}: #{e.message}")
81
81
  retry
82
82
  end
83
83
  end
84
84
 
85
85
  private
86
86
 
87
+ # Temporary failures of operations that may repeat. A MaintenanceError only when it came without NAV's
88
+ # MAINTENANCE_MODE code, i.e. from a network device: NAV's own maintenance takes longer than a retry.
89
+ def retry?(error, operation, attempt)
90
+ return false if error.is_a?(MaintenanceError) && error.code
91
+
92
+ error.retryable? && operation.auto_retry? && attempt <= config.max_retries
93
+ end
94
+
87
95
  def perform(operation, attempt)
88
96
  request_id, time, xml = build_request(operation)
89
97
  config.throttle&.wait(operation.name) if operation.rate_limited?
@@ -104,14 +112,17 @@ module NavOnlineInvoice
104
112
  def unknown_outcome(operation, error, request_id, time)
105
113
  return error unless operation.submission? && outcome_unknown?(error)
106
114
 
107
- UnknownOutcomeError.new(operation: operation.name, request_id:, sent_at: time,
115
+ UnknownOutcomeError.new(operation: operation.name, request_id:, sent_at: operation.sent_at || time,
108
116
  item_count: operation.index_hashes.size)
109
117
  end
110
118
 
111
- # A NAV error answer means the submission was rejected. Without one, it may have arrived: a 503 without a
112
- # NAV body can come from a network device while NAV is still processing.
119
+ # A NAV error answer means the submission was rejected, and so does a 4xx without one: the server answered
120
+ # without processing it. Otherwise it may have arrived: a 502, 503 or 504 can come from a network device while
121
+ # NAV is still processing.
113
122
  def outcome_unknown?(error)
114
- error.is_a?(TransportError) ? error.request_sent? : error.code.nil?
123
+ return error.code.nil? unless error.is_a?(TransportError)
124
+
125
+ error.request_sent? && !(400..499).cover?(error.http_status)
115
126
  end
116
127
 
117
128
  def build_request(operation)
@@ -157,14 +168,6 @@ module NavOnlineInvoice
157
168
  [result, ((Monotonic.now - started) * 1000).round]
158
169
  end
159
170
 
160
- def retry_delay(attempt)
161
- config.retry_base_delay * (2**(attempt - 1)) * rand(0.8..1.2)
162
- end
163
-
164
- def pause(seconds)
165
- sleep(seconds) if seconds.positive?
166
- end
167
-
168
171
  def log(level, &)
169
172
  config.logger&.public_send(level, &)
170
173
  end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NavOnlineInvoice
4
+ class Configuration
5
+ # Collects settings for {NavOnlineInvoice.configure}.
6
+ #
7
+ # Only the settings that were assigned are passed on, so `throttle = nil` turns the throttle off.
8
+ class Builder
9
+ include Redacted
10
+
11
+ # The settings that can be assigned.
12
+ ATTRIBUTES = %i[
13
+ environment login password password_hash signature_key exchange_key tax_number software logger log_payloads
14
+ throttle validate_requests max_retries retry_base_delay open_timeout read_timeout write_timeout clock
15
+ request_id_generator
16
+ ].freeze
17
+
18
+ def initialize
19
+ @values = {}
20
+ end
21
+
22
+ ATTRIBUTES.each do |name|
23
+ define_method(name) { @values[name] }
24
+ define_method(:"#{name}=") { |value| @values[name] = value }
25
+ end
26
+
27
+ # Creates the configuration from the assigned settings.
28
+ #
29
+ # @return [Configuration]
30
+ # @raise [ConfigurationError] if a setting is missing or invalid
31
+ def build
32
+ Configuration.new(**@values)
33
+ rescue ArgumentError => e
34
+ raise ConfigurationError, e.message
35
+ end
36
+
37
+ # Shows the assigned setting names only, never their values.
38
+ def inspect
39
+ "#<#{self.class.name} assigned=#{@values.keys.inspect}>"
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NavOnlineInvoice
4
+ class Configuration
5
+ # Checks and normalizes the settings.
6
+ #
7
+ # @api private
8
+ module Validation
9
+ module_function
10
+
11
+ def environment(value)
12
+ return value if ENDPOINTS.key?(value)
13
+
14
+ raise ConfigurationError, "environment must be :test or :production, got #{value.inspect}"
15
+ end
16
+
17
+ def login(value)
18
+ return value if value.is_a?(String) && value.match?(/\A[a-zA-Z0-9]{6,15}\z/)
19
+
20
+ raise ConfigurationError, "login must be 6-15 letters or digits"
21
+ end
22
+
23
+ def password_hash(password, hash)
24
+ raise ConfigurationError, "give either password or password_hash, not both" if password && hash
25
+ return Crypto.password_hash(required(:password, password)) if password
26
+
27
+ hash = required(:password_hash, hash).upcase
28
+ return hash if hash.match?(/\A[0-9A-F]{128}\z/)
29
+
30
+ raise ConfigurationError, "password_hash must be a SHA-512 hex digest"
31
+ end
32
+
33
+ def exchange_key(value)
34
+ return value if value.nil? || (value.is_a?(String) && value.bytesize == 16 && !value.strip.empty?)
35
+
36
+ raise ConfigurationError, "exchange_key must be 16 characters"
37
+ end
38
+
39
+ def tax_number(value)
40
+ TaxNumber.normalize(value)
41
+ rescue ArgumentError
42
+ raise ConfigurationError, "tax_number must have 8 or 11 digits, got #{value.inspect}"
43
+ end
44
+
45
+ def software(value)
46
+ software = value.is_a?(Hash) ? Software.new(**value) : value
47
+ raise ConfigurationError, "software must be a Hash or Configuration::Software" unless software.is_a?(Software)
48
+
49
+ software_id(software.id)
50
+ software_operation(software.operation)
51
+ %i[name main_version dev_name dev_contact].each do |key|
52
+ required(:"software.#{key}", software.public_send(key))
53
+ end
54
+ software
55
+ rescue ArgumentError => e
56
+ raise ConfigurationError, "software: #{e.message}"
57
+ end
58
+
59
+ def software_id(value)
60
+ return if value.is_a?(String) && value.match?(/\A[0-9A-Z-]{18}\z/)
61
+
62
+ raise ConfigurationError, "software.id must be exactly 18 characters of 0-9, A-Z and -"
63
+ end
64
+
65
+ def software_operation(value)
66
+ return if %i[local_software online_service].include?(value)
67
+
68
+ raise ConfigurationError, "software.operation must be :local_software or :online_service"
69
+ end
70
+
71
+ def required(name, value)
72
+ return value if value.is_a?(String) && !value.strip.empty?
73
+
74
+ raise ConfigurationError, "#{name} is required"
75
+ end
76
+
77
+ def non_negative_integer(name, value)
78
+ return value if value.is_a?(Integer) && !value.negative?
79
+
80
+ raise ConfigurationError, "#{name} must be an integer of 0 or more"
81
+ end
82
+
83
+ def non_negative_number(name, value)
84
+ return value if value.is_a?(Numeric) && !value.negative?
85
+
86
+ raise ConfigurationError, "#{name} must be a number of 0 or more"
87
+ end
88
+
89
+ def positive_number(name, value)
90
+ return value if value.is_a?(Numeric) && value.positive?
91
+
92
+ raise ConfigurationError, "#{name} must be a positive number"
93
+ end
94
+
95
+ def callable(name, value)
96
+ return value if value.respond_to?(:call)
97
+
98
+ raise ConfigurationError, "#{name} must respond to call"
99
+ end
100
+ end
101
+ private_constant :Validation
102
+ end
103
+ end