invoicehn 0.1.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.
@@ -26,6 +26,27 @@ module Invoicehn
26
26
  # rate times the printed subtotal, and that discrepancy is exactly what an
27
27
  # auditor would question. The choice is recorded here because it is a reading
28
28
  # of an open point, not a settled rule.
29
+ #
30
+ # == Prices that already include ISV
31
+ #
32
+ # With +prices_include_isv: true+ the unit prices and discounts of the lines
33
+ # are amounts the consumer pays, ISV included — the shelf price of a shop.
34
+ # Each line's value (quantity × price − discount) is rounded to centavos, and
35
+ # per rate:
36
+ #
37
+ # total = sum of the line values
38
+ # base = total ÷ (1 + rate), rounded under Art. 9
39
+ # ISV = total − base
40
+ #
41
+ # so the invoice total always equals the sum of the prices charged. ISV is
42
+ # the remainder, and it equals the Art. 9 rounding of the tax contained in
43
+ # the price (total × rate ÷ (1 + rate)): test/test_isv_included.rb checks it
44
+ # for every amount up to L 1,000.00. The cost of that guarantee is that the
45
+ # printed ISV can differ by one centavo from the printed rate times the
46
+ # printed base.
47
+ #
48
+ # The bucket's +gross+ and +discount+ are shown without ISV, like +base+, so
49
+ # the printed summary still adds up: Subtotal − Descuentos + ISV = TOTAL.
29
50
  class TaxSummary
30
51
  # One row of the breakdown: everything the document must show for a single
31
52
  # tax treatment.
@@ -49,12 +70,15 @@ module Invoicehn
49
70
 
50
71
  attr_reader :currency, :buckets
51
72
 
52
- def initialize(line_items, currency: "HNL")
73
+ def initialize(line_items, currency: "HNL", prices_include_isv: false)
53
74
  @currency = currency
75
+ @prices_include_isv = prices_include_isv ? true : false
54
76
  @buckets = build_buckets(Array(line_items))
55
77
  freeze
56
78
  end
57
79
 
80
+ def prices_include_isv? = @prices_include_isv
81
+
58
82
  # Only the treatments actually present, in the order the law lists them
59
83
  # (exento, exonerado, gravado 0%, then the taxed rates).
60
84
  def present_buckets = @buckets.reject(&:empty?)
@@ -98,10 +122,11 @@ module Invoicehn
98
122
  "buckets" => present_buckets.map(&:to_h),
99
123
  "gross" => gross.to_h,
100
124
  "discount" => discount.to_h,
125
+ "prices_include_isv" => (true if @prices_include_isv),
101
126
  "subtotal" => subtotal.to_h,
102
127
  "isv_total" => isv_total.to_h,
103
128
  "total" => total.to_h
104
- }
129
+ }.compact
105
130
  end
106
131
 
107
132
  private
@@ -109,6 +134,7 @@ module Invoicehn
109
134
  def build_buckets(line_items)
110
135
  TaxTreatment.all.map do |treatment|
111
136
  lines = line_items.select { |item| item.treatment == treatment }
137
+ next included_bucket(treatment, lines) if @prices_include_isv
112
138
 
113
139
  gross = Money.sum(lines.map(&:gross), currency: @currency).round_statutory
114
140
  discount = Money.sum(lines.map(&:discount), currency: @currency).round_statutory
@@ -122,6 +148,22 @@ module Invoicehn
122
148
  end.freeze
123
149
  end
124
150
 
151
+ # Prices with ISV included: the tax is taken out of the amount paid, never
152
+ # added to it. Every figure stays a BigDecimal; division keeps full
153
+ # precision until #round_statutory.
154
+ def included_bucket(treatment, lines)
155
+ divisor = BigDecimal(1) + treatment.rate
156
+
157
+ total = Money.sum(lines.map { |item| item.taxable_base.round_statutory }, currency: @currency)
158
+ gross_paid = Money.sum(lines.map { |item| item.gross.round_statutory }, currency: @currency)
159
+
160
+ base = (total / divisor).round_statutory
161
+ isv = total - base
162
+ gross = (gross_paid / divisor).round_statutory
163
+
164
+ Bucket.new(treatment: treatment, gross: gross, discount: gross - base, base: base, isv: isv).freeze
165
+ end
166
+
125
167
  def sum_of(field)
126
168
  Money.sum(@buckets.map { |b| b.public_send(field) }, currency: @currency)
127
169
  end
@@ -0,0 +1,269 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "invoicehn" unless defined?(Invoicehn::Issuance)
4
+ require "invoicehn/testing"
5
+
6
+ module Invoicehn
7
+ # Minitest modules a host application includes to run the store, sequence
8
+ # and ledger contracts against its own adapters:
9
+ #
10
+ # require "invoicehn/test_support/contracts"
11
+ #
12
+ # class PostgresStoreContractTest < ActiveSupport::TestCase
13
+ # include Invoicehn::TestSupport::StoreContract
14
+ #
15
+ # # A store holding a complete issuer and a current authorization for
16
+ # # contract_identifier ("000-001-01" unless overridden).
17
+ # def contract_store = Facturacion::InvoicehnStore.new
18
+ # end
19
+ #
20
+ # class PostgresSequenceContractTest < ActiveSupport::TestCase
21
+ # include Invoicehn::TestSupport::SequenceContract
22
+ # def contract_sequence = Facturacion::InvoicehnSequence.new
23
+ # end
24
+ #
25
+ # class LedgerContractTest < ActiveSupport::TestCase
26
+ # include Invoicehn::TestSupport::LedgerContract
27
+ # def contract_ledger = Facturacion::InvoicehnLedger.new
28
+ # end
29
+ #
30
+ # class IssuanceContractTest < ActiveSupport::TestCase
31
+ # include Invoicehn::TestSupport::IssuanceContract
32
+ # def contract_store = Facturacion::InvoicehnStore.new
33
+ # def contract_sequence = Facturacion::InvoicehnSequence.new
34
+ # def contract_ledger = Facturacion::InvoicehnLedger.new
35
+ # end
36
+ #
37
+ # The modules write documents; run them against a test database. They use
38
+ # only Minitest's assertions (assert, assert_equal, assert_raises, ...).
39
+ module TestSupport
40
+ # Fixed sample data, independent of the host's records.
41
+ module Samples
42
+ def contract_identifier = Issuance::DEFAULT_IDENTIFIER
43
+
44
+ def contract_sample_issuer
45
+ Issuer.new(rtn: "08011990123456", legal_name: "Contrato, S. de R.L.", trade_name: "Contrato",
46
+ headquarters_address: "Tegucigalpa, M.D.C.", phone: "2222-3333", email: "contrato@ejemplo.hn")
47
+ end
48
+
49
+ def contract_sample_lines
50
+ [LineItem.new(description: "Prueba de contrato", quantity: 2, unit_price: Money.new("50.00"),
51
+ treatment: :gravado_15)]
52
+ end
53
+
54
+ # A document numbered at the last number of `authorization`'s range, so
55
+ # it does not collide with the next number the host would issue.
56
+ def contract_sample_document(authorization:, issuer: contract_sample_issuer, **extra)
57
+ Invoice.new(correlative: authorization.range_end, issuer: issuer,
58
+ customer: Customer::Taxpayer.new(name: "Cliente de Contrato, S.A.", rtn: "05019005123456"),
59
+ authorization: authorization, line_items: contract_sample_lines,
60
+ issue_date: Invoicehn.today, **extra)
61
+ end
62
+ end
63
+
64
+ # Requires #contract_store.
65
+ module StoreContract
66
+ include Samples
67
+
68
+ def contract_authorization(store = contract_store)
69
+ auth = store.active_authorization(contract_identifier, next_sequence: nil, on: Invoicehn.today)
70
+ assert auth, "contract_store debe tener una autorización vigente para #{contract_identifier}"
71
+ auth
72
+ end
73
+
74
+ def test_store_contract_interface
75
+ assert Testing.assert_store_contract(contract_store)
76
+ end
77
+
78
+ def test_store_contract_issuer_is_complete
79
+ issuer = contract_store.issuer
80
+
81
+ assert_kind_of Issuer, issuer
82
+ assert_empty issuer.missing_fields
83
+ end
84
+
85
+ def test_store_contract_active_authorization_covers_the_number
86
+ store = contract_store
87
+ auth = contract_authorization(store)
88
+
89
+ first = store.active_authorization(contract_identifier, next_sequence: auth.range_start.sequence,
90
+ on: Invoicehn.today)
91
+
92
+ assert_equal auth.to_h, first.to_h
93
+ beyond = auth.range_end.sequence + 1
94
+ covering = store.active_authorization(contract_identifier, next_sequence: beyond, on: Invoicehn.today)
95
+
96
+ assert(covering.nil? || covering.covers?(auth.range_end.with_sequence(beyond)),
97
+ "active_authorization devolvió una autorización que no cubre #{beyond}")
98
+ assert_nil store.active_authorization(contract_identifier, next_sequence: auth.range_start.sequence,
99
+ on: auth.limit_date + 1)
100
+ end
101
+
102
+ def test_store_contract_round_trips_save_find_delete
103
+ store = contract_store
104
+ document = contract_sample_document(authorization: contract_authorization(store))
105
+
106
+ refute store.exists?(document.correlative)
107
+ store.save_document(document)
108
+
109
+ assert store.exists?(document.correlative)
110
+ assert_equal document.to_h, store.find(document.correlative).to_h
111
+ assert_raises(ImmutableDocument) { store.save_document(document) }
112
+
113
+ store.delete_document(document)
114
+
115
+ refute store.exists?(document.correlative)
116
+ assert_raises(DocumentNotFound) { store.find(document.correlative) }
117
+ ensure
118
+ # A failure above must not leave the sample behind for the next test.
119
+ store&.delete_document(document) if document
120
+ end
121
+
122
+ # A document whose prices include ISV must come back with the flag; a
123
+ # store that drops it recomputes the totals with ISV on top.
124
+ def test_store_contract_keeps_prices_that_include_isv
125
+ store = contract_store
126
+ document = contract_sample_document(authorization: contract_authorization(store), prices_include_isv: true)
127
+ store.save_document(document)
128
+
129
+ found = store.find(document.correlative)
130
+
131
+ assert_predicate found, :prices_include_isv?
132
+ assert_equal document.total, found.total
133
+ assert_equal document.to_h, found.to_h
134
+ ensure
135
+ store&.delete_document(document) if document
136
+ end
137
+
138
+ # Art. 41 — the annulled form replaces the record; the number stays.
139
+ def test_store_contract_keeps_the_annulled_form
140
+ store = contract_store
141
+ document = contract_sample_document(authorization: contract_authorization(store))
142
+ store.save_document(document)
143
+ store.save_document(document.annul(reason: "Prueba de contrato"))
144
+
145
+ found = store.find(document.correlative)
146
+
147
+ assert_predicate found, :annulled?
148
+ assert_equal "Prueba de contrato", found.annulment_reason
149
+ ensure
150
+ store&.delete_document(document) if document
151
+ end
152
+
153
+ # A note's reference and motivo (Arts. 26 and 28 num. 3-4) must survive
154
+ # the store. Runs only when the store holds an authorization for
155
+ # contract_note_identifier.
156
+ def test_store_contract_keeps_a_notes_reference_and_motivo
157
+ store = contract_store
158
+ auth = store.active_authorization(contract_note_identifier, next_sequence: nil, on: Invoicehn.today)
159
+ skip "sin autorización para #{contract_note_identifier}" unless auth
160
+
161
+ reference = DocumentReference.new(correlative: "#{contract_identifier}-00000001", cai: "CAI-CONTRATO",
162
+ issue_date: Invoicehn.today)
163
+ note = contract_sample_document(authorization: auth, reference: reference, motivo: "Devolución")
164
+ store.save_document(note)
165
+ found = store.find(note.correlative)
166
+
167
+ assert_equal reference, found.reference
168
+ assert_equal "Devolución", found.motivo
169
+ assert_equal note.to_h, found.to_h
170
+ ensure
171
+ store&.delete_document(note) if note
172
+ end
173
+
174
+ def contract_note_identifier = "#{contract_identifier.split("-")[0, 2].join("-")}-06"
175
+ end
176
+
177
+ # Requires #contract_sequence.
178
+ module SequenceContract
179
+ include Samples
180
+
181
+ def contract_other_identifier = "#{contract_identifier.split("-")[0, 2].join("-")}-07"
182
+
183
+ def test_sequence_contract_interface
184
+ assert Testing.assert_sequence_contract(contract_sequence)
185
+ end
186
+
187
+ def test_sequence_contract_peek_does_not_consume
188
+ sequence = contract_sequence
189
+ before = sequence.issued_count(contract_identifier)
190
+
191
+ assert_equal sequence.peek(contract_identifier), sequence.peek(contract_identifier)
192
+ assert_equal before + 1, sequence.peek(contract_identifier).sequence
193
+ assert_equal before, sequence.issued_count(contract_identifier)
194
+ end
195
+
196
+ def test_sequence_contract_allocate_yields_the_next_number_and_advances
197
+ sequence = contract_sequence
198
+ expected = sequence.peek(contract_identifier)
199
+ yielded = nil
200
+
201
+ result = sequence.allocate(contract_identifier) do |correlative|
202
+ yielded = correlative
203
+ :resultado
204
+ end
205
+
206
+ assert_equal expected, yielded
207
+ assert_equal :resultado, result
208
+ assert_equal expected.sequence, sequence.issued_count(contract_identifier)
209
+ assert_equal expected.succ, sequence.peek(contract_identifier)
210
+ end
211
+
212
+ # The property Issuance's all-or-nothing guarantee rests on.
213
+ def test_sequence_contract_a_failing_block_consumes_nothing
214
+ sequence = contract_sequence
215
+ before = sequence.issued_count(contract_identifier)
216
+
217
+ assert_raises(ArgumentError) { sequence.allocate(contract_identifier) { raise ArgumentError, "fallo" } }
218
+ assert_equal before, sequence.issued_count(contract_identifier)
219
+ end
220
+
221
+ # Each identificador del documento runs its own series (Art. 10 num. 7).
222
+ def test_sequence_contract_identifiers_are_independent
223
+ sequence = contract_sequence
224
+ other = sequence.issued_count(contract_other_identifier)
225
+ sequence.allocate(contract_identifier) { |c| c }
226
+
227
+ assert_equal other, sequence.issued_count(contract_other_identifier)
228
+ end
229
+ end
230
+
231
+ # Requires #contract_ledger.
232
+ module LedgerContract
233
+ include Samples
234
+
235
+ def contract_ledger_document
236
+ auth = Authorization.new(cai: "CAI-CONTRATO", range_start: "#{contract_identifier}-00000001",
237
+ range_end: "#{contract_identifier}-00000010", limit_date: Invoicehn.today + 30)
238
+ contract_sample_document(authorization: auth)
239
+ end
240
+
241
+ def test_ledger_contract_interface
242
+ assert Testing.assert_ledger_contract(contract_ledger)
243
+ end
244
+
245
+ def test_ledger_contract_records_issue_and_annulment
246
+ ledger = contract_ledger
247
+ document = contract_ledger_document
248
+
249
+ ledger.record(document, event: :emision)
250
+ ledger.record(document.annul(reason: "Prueba de contrato"), event: :anulacion)
251
+
252
+ pass
253
+ end
254
+ end
255
+
256
+ # Requires #contract_store, #contract_sequence and #contract_ledger,
257
+ # wired to each other. Issues one real Factura.
258
+ module IssuanceContract
259
+ include Samples
260
+
261
+ def test_issuance_contract_round_trip_and_rollback
262
+ document = Testing.assert_issuance_round_trip(store: contract_store, sequence: contract_sequence,
263
+ ledger: contract_ledger, identifier: contract_identifier)
264
+
265
+ assert_equal contract_identifier, document.correlative.identifier
266
+ end
267
+ end
268
+ end
269
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "monitor"
4
+ require "invoicehn" unless defined?(Invoicehn::Issuance)
5
+
6
+ module Invoicehn
7
+ module TestSupport
8
+ # In-memory store, sequence and ledger. They exist for tests, and as the
9
+ # shortest complete example of the contract a host adapter (Postgres,
10
+ # say) has to meet — each method here is one the README lists. They hold
11
+ # nothing across processes and must never back real fiscal documents.
12
+
13
+ # The store: issuer, authorizations and documents.
14
+ class MemoryStore
15
+ attr_reader :documents, :issuer
16
+
17
+ def initialize(issuer: nil, authorizations: [])
18
+ @issuer = issuer
19
+ @authorizations = authorizations.dup
20
+ @documents = {}
21
+ end
22
+
23
+ def save_issuer(issuer)
24
+ @issuer = issuer
25
+ end
26
+
27
+ def add_authorization(authorization)
28
+ @authorizations << authorization
29
+ authorization
30
+ end
31
+
32
+ def authorizations_for(identifier) = @authorizations.select { |a| a.identifier == identifier }
33
+
34
+ # Unexpired, and — when next_sequence is given — covering that number.
35
+ def active_authorization(identifier, next_sequence: nil, on: Invoicehn.today)
36
+ candidates = authorizations_for(identifier).reject { |a| a.expired?(on) }
37
+ if next_sequence
38
+ correlative = Correlative.parse(format("%<id>s-%<n>08d", id: identifier, n: next_sequence))
39
+ candidates = candidates.select { |a| a.covers?(correlative) }
40
+ end
41
+ candidates.min_by { |a| a.range_start.sequence }
42
+ end
43
+
44
+ # An issued document is immutable; only its annulled form may replace it
45
+ # (Art. 41).
46
+ def save_document(document)
47
+ key = document.correlative.to_s
48
+ if @documents.key?(key) && !document.annulled?
49
+ raise ImmutableDocument, "el documento #{key} ya está registrado y no puede modificarse (Art. 41)"
50
+ end
51
+
52
+ @documents[key] = document.to_h
53
+ document
54
+ end
55
+
56
+ def delete_document(document)
57
+ @documents.delete(document.correlative.to_s)
58
+ document
59
+ end
60
+
61
+ def find(correlative)
62
+ hash = @documents[correlative.to_s]
63
+ raise DocumentNotFound, "no existe el documento #{correlative}" unless hash
64
+
65
+ Invoice.from_h(hash)
66
+ end
67
+
68
+ def exists?(correlative) = @documents.key?(correlative.to_s)
69
+ end
70
+
71
+ # The counter per identifier. The block runs inside the lock and the
72
+ # counter advances only after it returns — the property that keeps a
73
+ # failed issue from burning a number.
74
+ class MemorySequence
75
+ def initialize
76
+ @counters = Hash.new(0)
77
+ @lock = Monitor.new
78
+ end
79
+
80
+ def peek(identifier) = @lock.synchronize { build(identifier, @counters[identifier] + 1) }
81
+
82
+ def issued_count(identifier) = @lock.synchronize { @counters[identifier] }
83
+
84
+ def allocate(identifier)
85
+ @lock.synchronize do
86
+ correlative = build(identifier, @counters[identifier] + 1)
87
+ result = block_given? ? yield(correlative) : correlative
88
+ @counters[identifier] = correlative.sequence
89
+ result
90
+ end
91
+ end
92
+
93
+ private
94
+
95
+ def build(identifier, sequence) = Correlative.parse(format("%<id>s-%<n>08d", id: identifier, n: sequence))
96
+ end
97
+
98
+ # Keeps the entries it is handed.
99
+ class MemoryLedger
100
+ attr_reader :records
101
+
102
+ def initialize
103
+ @records = []
104
+ end
105
+
106
+ def record(document, event: :emision)
107
+ @records << [event, document.correlative.to_s]
108
+ document
109
+ end
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "invoicehn" unless defined?(Invoicehn::Issuance)
4
+
5
+ module Invoicehn
6
+ # Checks a host application's store, sequence and ledger against the
7
+ # contract Invoicehn::Issuance relies on. Not loaded by `require
8
+ # "invoicehn"`; a host's test suite opts in:
9
+ #
10
+ # require "invoicehn/testing"
11
+ #
12
+ # Invoicehn::Testing.assert_store_contract(PostgresStore.new)
13
+ # Invoicehn::Testing.assert_sequence_contract(PostgresSequence.new)
14
+ # Invoicehn::Testing.assert_ledger_contract(AccountingLedger.new)
15
+ # Invoicehn::Testing.assert_issuance_round_trip(store: ..., sequence: ..., ledger: ...)
16
+ #
17
+ # Every check raises Invoicehn::Testing::ContractError listing all the
18
+ # problems it found, and returns the checked object (or, for the round trip,
19
+ # the issued document) otherwise, so it works under minitest, RSpec or a
20
+ # plain script.
21
+ module Testing
22
+ # Raised when an implementation does not satisfy the contract.
23
+ class ContractError < Error; end
24
+
25
+ # name => [positional parameters, keyword parameters]
26
+ STORE_CONTRACT = {
27
+ issuer: [0, []],
28
+ authorizations_for: [1, []],
29
+ active_authorization: [1, %i[next_sequence on]],
30
+ save_document: [1, []],
31
+ delete_document: [1, []],
32
+ find: [1, []],
33
+ exists?: [1, []]
34
+ }.freeze
35
+
36
+ SEQUENCE_CONTRACT = {
37
+ allocate: [1, []],
38
+ peek: [1, []],
39
+ issued_count: [1, []]
40
+ }.freeze
41
+
42
+ LEDGER_CONTRACT = {
43
+ record: [1, %i[event]]
44
+ }.freeze
45
+
46
+ # A ledger that refuses every entry, used to prove the rollback.
47
+ class RefusingLedger
48
+ class Refused < StandardError; end
49
+
50
+ def record(_document, event: :emision)
51
+ raise Refused, "asiento rechazado a propósito (#{event})"
52
+ end
53
+ end
54
+
55
+ class << self
56
+ def assert_store_contract(store) = assert_contract(store, STORE_CONTRACT, "store")
57
+ def assert_sequence_contract(sequence) = assert_contract(sequence, SEQUENCE_CONTRACT, "sequence")
58
+ def assert_ledger_contract(ledger) = assert_contract(ledger, LEDGER_CONTRACT, "ledger")
59
+
60
+ # Behavioural check, against a store that already holds a complete
61
+ # issuer and a current authorization for `identifier`. Issues ONE real
62
+ # Factura, so run it against a test database.
63
+ #
64
+ # 1. With a ledger that refuses the entry, issuing must raise and leave
65
+ # nothing behind: no document at the next number, counter unchanged.
66
+ # This is what a Postgres adapter gets wrong when allocate advances
67
+ # the counter outside the block, or delete_document is a no-op.
68
+ # 2. With the real ledger, the document must come back from find equal
69
+ # to what was issued, and the counter must have advanced by one.
70
+ #
71
+ # @return [Invoice] the document issued in step 2
72
+ def assert_issuance_round_trip(store:, sequence:, ledger:, identifier: Issuance::DEFAULT_IDENTIFIER,
73
+ customer: Customer::ConsumidorFinal.new, line_items: nil)
74
+ line_items ||= [LineItem.new(description: "Prueba de contrato", quantity: 1,
75
+ unit_price: Money.new("1.00"), treatment: :exento)]
76
+ before = sequence.issued_count(identifier)
77
+ upcoming = sequence.peek(identifier)
78
+ problems = []
79
+
80
+ refusing = Issuance.new(store: store, sequence: sequence, ledger: RefusingLedger.new)
81
+ begin
82
+ refusing.issue(customer: customer, line_items: line_items, identifier: identifier)
83
+ problems << "issue no propagó el error del ledger"
84
+ rescue RefusingLedger::Refused
85
+ nil
86
+ end
87
+ problems << "el documento #{upcoming} quedó guardado aunque el ledger lo rechazó" if store.exists?(upcoming)
88
+ if sequence.issued_count(identifier) != before
89
+ problems << "el contador avanzó aunque la emisión falló (allocate debe avanzar sólo si el bloque termina)"
90
+ end
91
+ raise ContractError, problems.join("\n") if problems.any?
92
+
93
+ document = Issuance.new(store: store, sequence: sequence, ledger: ledger)
94
+ .issue(customer: customer, line_items: line_items, identifier: identifier)
95
+
96
+ problems << "se emitió #{document.correlative}, se esperaba #{upcoming}" unless document.correlative == upcoming
97
+ problems << "issued_count no avanzó en uno" unless sequence.issued_count(identifier) == before + 1
98
+ problems << "exists? no encuentra #{document.correlative}" unless store.exists?(document.correlative)
99
+ unless store.find(document.correlative).to_h == document.to_h
100
+ problems << "find(#{document.correlative}) no devuelve el documento tal como se emitió"
101
+ end
102
+ raise ContractError, problems.join("\n") if problems.any?
103
+
104
+ document
105
+ end
106
+
107
+ private
108
+
109
+ def assert_contract(object, contract, role)
110
+ problems = contract.flat_map do |name, (positional, keywords)|
111
+ next ["#{role} debe responder a ##{name}"] unless object.respond_to?(name)
112
+
113
+ signature_problems(object.method(name), role, name, positional, keywords)
114
+ end
115
+ raise ContractError, problems.join("\n") if problems.any?
116
+
117
+ object
118
+ end
119
+
120
+ def signature_problems(method, role, name, positional, keywords)
121
+ params = method.parameters
122
+ problems = []
123
+
124
+ required = params.count { |type, _| type == :req }
125
+ accepts = params.count { |type, _| %i[req opt].include?(type) }
126
+ rest = params.any? { |type, _| type == :rest }
127
+ unless required <= positional && (rest || accepts >= positional)
128
+ problems << "#{role}##{name} debe aceptar #{positional} argumento(s) posicional(es)"
129
+ end
130
+
131
+ keyrest = params.any? { |type, _| type == :keyrest }
132
+ declared = params.filter_map { |type, param| param if %i[key keyreq].include?(type) }
133
+ (keywords - declared).each do |kw|
134
+ problems << "#{role}##{name} debe aceptar la palabra clave #{kw}:" unless keyrest
135
+ end
136
+ problems
137
+ end
138
+ end
139
+ end
140
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Invoicehn
4
- VERSION = "0.1.0"
4
+ VERSION = "0.3.0"
5
5
  end
data/lib/invoicehn.rb CHANGED
@@ -2,11 +2,13 @@
2
2
 
3
3
  require_relative "invoicehn/version"
4
4
  require_relative "invoicehn/errors"
5
+ require_relative "invoicehn/settings"
5
6
  require_relative "invoicehn/locale"
6
7
  require_relative "invoicehn/money"
7
8
  require_relative "invoicehn/spanish_numerals"
8
9
  require_relative "invoicehn/rtn"
9
10
  require_relative "invoicehn/correlative"
11
+ require_relative "invoicehn/document_reference"
10
12
  require_relative "invoicehn/tax_treatment"
11
13
  require_relative "invoicehn/line_item"
12
14
  require_relative "invoicehn/tax_summary"
@@ -37,4 +39,30 @@ require_relative "invoicehn/renderers/pdf"
37
39
  # límite de emisión (Arts. 59-61) all remain the operator's obligations before
38
40
  # any document produced here is valid.
39
41
  module Invoicehn
42
+ # Invoicehn.configure / Invoicehn.today — see Invoicehn::Settings.
43
+ class << self
44
+ def settings
45
+ @settings ||= Settings.new
46
+ end
47
+
48
+ def configure
49
+ yield settings
50
+ settings
51
+ end
52
+
53
+ # Restores the defaults. Meant for test suites.
54
+ def reset_settings!
55
+ @settings = Settings.new
56
+ end
57
+
58
+ # Today's date in Honduras, as the configured clock reports it. Raises if
59
+ # the clock returns something that is not a Date — a Time or a String here
60
+ # would silently shift fiscal dates.
61
+ def today
62
+ value = settings.today.call
63
+ return value if value.instance_of?(Date)
64
+
65
+ raise Error, "el reloj configurado devolvió #{value.inspect}; se espera un Date"
66
+ end
67
+ end
40
68
  end