invoicehn 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 97a71a1ec9c4f50865c877824d8e0383eadd0586aafb647e01bc3d42cc160a7c
4
- data.tar.gz: 5f2c1498b2ed86ab1845473badf845aae69ec3061de66c4e9328855e7d6e97ae
3
+ metadata.gz: 4580f834141b2ab9e52b5fec8944ef530c4902ce1bdb8fa381c68ab6b6c9beab
4
+ data.tar.gz: 4741f2bf3fcf275ecff6023cad16ae6aaf2d2c6d5f954359ce3e7e8c1088bb3c
5
5
  SHA512:
6
- metadata.gz: 94039271cdd437cc609cada52de779c80aa55259f7f58cfd6d6247d34832002df9a07f4443c3cdf3ba6d9c2e46824628e9ccb5a9e917acdcdcf87a569ade6f0d
7
- data.tar.gz: 3d96cadbcd9ddbd4463a904e44e134cb8649303de6f1aaa7d09d8f00288879828ab5a33427f89083c18afcc660c2a7cc62bec75d25990a39765bed5bbb72ac6b
6
+ metadata.gz: 11ed78896294af30674a7acdb9472279af545cc44bcb33c5b6179a92896cbc24db5f66980526082be962e064bf34d7bff93bfc9d094868c4a149deb77a61ba54
7
+ data.tar.gz: 43f0b87dbd0575f4206102f298459ce4cde8efabebba60c4d5c1c72f8c9db2cf28a620c58540c10a75859f74c07c02e27ae5523c872eda22db476e6f8788095f
data/CHANGELOG.md CHANGED
@@ -5,6 +5,35 @@ Este proyecto sigue [Versionado Semántico](https://semver.org/lang/es/).
5
5
 
6
6
  ## [Sin publicar]
7
7
 
8
+ ## [0.3.0] — 2026-12-05
9
+
10
+ Precios con ISV incluido, para puntos de venta que trabajan con el precio de
11
+ góndola.
12
+
13
+ ### Agregado
14
+
15
+ - **Precios con ISV incluido** (`prices_include_isv: true` en `Invoice.new`,
16
+ `Issuance#issue` y las notas, y `"prices_include_isv": true` en el JSON de
17
+ `invoicehn issue -f`). Ley del ISV Art. 7 (`doc/fuentes/ley_isv.pdf`): al
18
+ consumidor final *"el impuesto será incluido en el precio final"*. Por tarifa,
19
+ base = total ÷ (1 + tasa) con el redondeo del Art. 9 e ISV = total − base, de
20
+ modo que el total es la suma de los precios cobrados: un producto de L 10.00
21
+ ya no se factura como L 10.01. Cada línea se redondea al centavo antes de
22
+ sumarse. El resumen muestra bruto y descuento sin ISV para que Subtotal −
23
+ Descuentos + ISV = TOTAL, y el detalle lleva una leyenda. Nuevo
24
+ `Invoice#line_value`. Sin la opción, el cálculo y el JSON guardado no cambian.
25
+ - **Las notas usan el modo de la factura.** Una Nota de Crédito o de Débito sin
26
+ `prices_include_isv` hereda el modo de la factura a la que se aplica si está
27
+ en el store; si se indica y no coincide, se rechaza. Sin esto, devolver un
28
+ producto de L 10.00 con precio incluido acreditaría L 11.50.
29
+ - **Contrato del store:** `StoreContract` verifica que un documento con precios
30
+ con ISV incluido vuelva del store con el modo y el mismo total.
31
+
32
+ ### Cambiado
33
+
34
+ - `Issuance#issue` acepta `prices_include_isv:` con valor por omisión `nil`
35
+ (precios sin ISV, o el modo de la factura original en las notas).
36
+
8
37
  ## [0.2.0] — 2026-10-10
9
38
 
10
39
  Notas de Crédito y de Débito, la tabla de códigos reformada, y correcciones
data/README.md CHANGED
@@ -265,7 +265,8 @@ Las firmas exactas:
265
265
  ```ruby
266
266
  Invoicehn::Issuance#issue(customer:, line_items:, identifier: "000-001-01",
267
267
  currency: "HNL", exchange_rate: nil, notes: nil,
268
- issue_date: Invoicehn.today, reference: nil, motivo: nil)
268
+ issue_date: Invoicehn.today, reference: nil, motivo: nil,
269
+ prices_include_isv: nil)
269
270
  Invoicehn::Issuance#issue_credit_note(reference:, motivo:, customer:, line_items:,
270
271
  identifier: "000-001-06", **opciones_de_issue)
271
272
  Invoicehn::Issuance#issue_debit_note(reference:, motivo:, customer:, line_items:,
@@ -346,6 +347,49 @@ La línea de descuentos aparece siempre, con o sin descuento: el Acuerdo 725-201
346
347
  la agregó como **Art. 10 num. 10** ("Descuentos y rebajas otorgados"), es decir
347
348
  como requisito **del formato**, además de los literales l) y j) del Art. 11.
348
349
 
350
+ ### Precios con ISV incluido
351
+
352
+ **Ley del ISV, Artículo 7:** *"Cuando se trate de venta de mercaderías o de
353
+ prestación de servicios al consumidor final, el impuesto será incluido en el
354
+ precio final de bienes y servicios objeto de la venta o transacción."*
355
+
356
+ Un punto de venta trabaja con el precio de góndola, que ya trae el ISV. Si se
357
+ saca la base (L 10.00 ÷ 1.15 = L 8.70) y se vuelve a gravar, la factura cobra
358
+ L 10.01. Con `prices_include_isv: true` los precios y descuentos de las líneas
359
+ son lo que paga el consumidor, y por tarifa:
360
+
361
+ | | |
362
+ |---|---|
363
+ | total | suma de los valores de las líneas, cada uno redondeado al centavo |
364
+ | base | total ÷ (1 + tasa), con el redondeo del Art. 9 |
365
+ | ISV | total − base |
366
+
367
+ ```ruby
368
+ issuance.issue(customer: Invoicehn::Customer::ConsumidorFinal.new,
369
+ line_items: [Invoicehn::LineItem.new(description: "Arroz 5 lb", quantity: 1,
370
+ unit_price: Invoicehn::Money.new("10.00"),
371
+ treatment: :gravado_15)],
372
+ prices_include_isv: true)
373
+ # => base L 8.70, ISV L 1.30, TOTAL L 10.00
374
+ ```
375
+
376
+ El total siempre es la suma de lo cobrado, y el ISV es el redondeo del Art. 9
377
+ del impuesto contenido en el precio (total × tasa ÷ (1 + tasa)); una prueba lo
378
+ recorre para cada monto hasta L 1,000.00 en las dos tasas. El costo: el ISV
379
+ impreso puede diferir en un centavo de la tasa por la base impresa.
380
+
381
+ El detalle muestra los precios con ISV y lo dice en una leyenda; el resumen
382
+ muestra subtotal, descuentos y bases sin ISV, de modo que sigue sumando:
383
+ Subtotal − Descuentos + ISV = TOTAL. `Invoice#line_value(item)` da el valor de
384
+ cada línea tal como se imprime; `LineItem#isv` y `#total` suponen precios sin
385
+ ISV. Los documentos emitidos sin la opción se guardan y se imprimen igual que
386
+ antes.
387
+
388
+ Una nota de crédito o de débito usa el mismo modo que la factura a la que se
389
+ aplica: si se omite `prices_include_isv` y la factura está en el store, lo
390
+ hereda; si se indica y no coincide, se rechaza. Acreditar un precio de góndola
391
+ de L 10.00 como si no incluyera ISV acreditaría L 11.50.
392
+
349
393
  ### El CAI y el RTN se validan con prudencia
350
394
 
351
395
  El Art. 4 num. 7 define el CAI únicamente como *"una serie alfanumérica generada
@@ -26,7 +26,10 @@ module Invoicehn
26
26
  # document in the store, or {correlative, cai, issue_date} for one
27
27
  # issued elsewhere — Arts. 26 and 28 num. 3 and 4.
28
28
  reference: build_reference(data["reference"]),
29
- motivo: data["motivo"]
29
+ motivo: data["motivo"],
30
+ # true when unit_price and discount are shelf prices with ISV included.
31
+ # Notes inherit the original's mode when the key is absent.
32
+ prices_include_isv: (data["prices_include_isv"] == true if data.key?("prices_include_isv"))
30
33
  )
31
34
  end
32
35
 
@@ -32,7 +32,7 @@ module Invoicehn
32
32
  def initialize(correlative:, issuer:, customer:, authorization:, line_items:,
33
33
  issue_date: nil, currency: "HNL", exchange_rate: nil,
34
34
  status: STATUS_ISSUED, annulment_reason: nil, annulled_at: nil,
35
- notes: nil, reference: nil, motivo: nil)
35
+ notes: nil, reference: nil, motivo: nil, prices_include_isv: false)
36
36
  @correlative = correlative.is_a?(Correlative) ? correlative : Correlative.parse(correlative)
37
37
  @issuer = issuer
38
38
  @customer = customer
@@ -47,6 +47,7 @@ module Invoicehn
47
47
  @notes = notes.to_s.strip
48
48
  @reference = coerce_reference(reference)
49
49
  @motivo = motivo.to_s.strip
50
+ @prices_include_isv = prices_include_isv ? true : false
50
51
 
51
52
  if !note? && (@reference || !@motivo.empty?)
52
53
  raise ValidationError,
@@ -54,13 +55,24 @@ module Invoicehn
54
55
  "(Arts. 26 y 28 num. 3 y 4); #{@correlative} es #{document_name}"
55
56
  end
56
57
 
57
- @summary = TaxSummary.new(@line_items, currency: @currency)
58
+ @summary = TaxSummary.new(@line_items, currency: @currency, prices_include_isv: @prices_include_isv)
58
59
  freeze
59
60
  end
60
61
 
61
62
  # The per-rate breakdown required by Art. 11 num. 1 lit. g) h) i) and l).
62
63
  attr_reader :summary
63
64
 
65
+ # True when the lines' prices and discounts already include ISV (the shelf
66
+ # price a consumer pays). See TaxSummary for how base and tax are derived.
67
+ def prices_include_isv? = @prices_include_isv
68
+
69
+ # The value of one line as printed in the detail: with prices that include
70
+ # ISV, what the consumer pays for it, rounded to centavos; otherwise its
71
+ # taxable base. LineItem#isv and #total assume prices without ISV.
72
+ def line_value(item)
73
+ @prices_include_isv ? item.taxable_base.round_statutory : item.taxable_base
74
+ end
75
+
64
76
  def subtotal = @summary.subtotal
65
77
  def discount = @summary.discount
66
78
  def isv_total = @summary.isv_total
@@ -145,7 +157,8 @@ module Invoicehn
145
157
  "annulled_at" => @annulled_at&.iso8601,
146
158
  "notes" => @notes,
147
159
  "reference" => @reference&.to_h,
148
- "motivo" => (@motivo unless @motivo.empty?)
160
+ "motivo" => (@motivo unless @motivo.empty?),
161
+ "prices_include_isv" => (true if @prices_include_isv)
149
162
  }.compact
150
163
  end
151
164
 
@@ -164,7 +177,8 @@ module Invoicehn
164
177
  annulled_at: hash["annulled_at"],
165
178
  notes: hash["notes"],
166
179
  reference: DocumentReference.from_h(hash["reference"]),
167
- motivo: hash["motivo"]
180
+ motivo: hash["motivo"],
181
+ prices_include_isv: hash["prices_include_isv"] == true
168
182
  )
169
183
  end
170
184
 
@@ -181,7 +195,7 @@ module Invoicehn
181
195
  issue_date: @issue_date, currency: @currency, exchange_rate: @exchange_rate,
182
196
  status: @status, annulment_reason: @annulment_reason,
183
197
  annulled_at: @annulled_at, notes: @notes, reference: @reference,
184
- motivo: @motivo, **changes
198
+ motivo: @motivo, prices_include_isv: @prices_include_isv, **changes
185
199
  )
186
200
  end
187
201
 
@@ -51,11 +51,12 @@ module Invoicehn
51
51
  # documento" (Arts. 26 and 28 num. 4).
52
52
  def issue(customer:, line_items:, identifier: DEFAULT_IDENTIFIER, currency: "HNL",
53
53
  exchange_rate: nil, notes: nil, issue_date: Invoicehn.today,
54
- reference: nil, motivo: nil)
54
+ reference: nil, motivo: nil, prices_include_isv: nil)
55
55
  issuer = @store.issuer
56
56
  raise NoAuthorization, "no se ha configurado el emisor; ejecute «invoicehn setup»" if issuer.nil?
57
57
 
58
- reference = resolve_reference(reference, customer)
58
+ reference, original = resolve_reference(reference, customer)
59
+ prices_include_isv = price_mode(prices_include_isv, original)
59
60
 
60
61
  @sequence.allocate(identifier) do |correlative|
61
62
  authorization = pick_authorization(identifier, correlative, issue_date)
@@ -71,7 +72,8 @@ module Invoicehn
71
72
  exchange_rate: exchange_rate,
72
73
  notes: notes,
73
74
  reference: reference,
74
- motivo: motivo
75
+ motivo: motivo,
76
+ prices_include_isv: prices_include_isv
75
77
  )
76
78
 
77
79
  document.validate!(on: issue_date)
@@ -185,8 +187,9 @@ module Invoicehn
185
187
 
186
188
  # Turns what the caller passed into a DocumentReference, cross-checking it
187
189
  # against the original when the store holds it.
190
+ # Returns the reference and, when the store holds it, the original document.
188
191
  def resolve_reference(reference, customer)
189
- return nil if reference.nil?
192
+ return [nil, nil] if reference.nil?
190
193
 
191
194
  if reference.is_a?(DocumentReference)
192
195
  original = @store.exists?(reference.correlative) ? @store.find(reference.correlative) : nil
@@ -197,7 +200,22 @@ module Invoicehn
197
200
  end
198
201
 
199
202
  check_original!(original, customer) if original
200
- reference
203
+ [reference, original]
204
+ end
205
+
206
+ # A note adjusts the amounts of the document it applies to, so it uses the
207
+ # same kind of prices: crediting a L 10.00 shelf price as if it excluded ISV
208
+ # would credit L 11.50. Left unspecified, a note inherits the original's
209
+ # mode; stated, it must match it. Without an original in the store, the
210
+ # caller's choice stands (default: prices without ISV).
211
+ def price_mode(requested, original)
212
+ return requested ? true : false if original.nil?
213
+ return original.prices_include_isv? if requested.nil?
214
+ return requested if requested == original.prices_include_isv?
215
+
216
+ raise ValidationError,
217
+ "#{original.correlative} se emitió con precios #{original.prices_include_isv? ? "con" : "sin"} ISV " \
218
+ "incluido; la nota debe usar el mismo modo"
201
219
  end
202
220
 
203
221
  def check_reference_matches!(reference, original)
@@ -47,6 +47,10 @@ module Invoicehn
47
47
  # it rounds once per rate on the summed base, so that the printed ISV equals
48
48
  # the printed rate times the printed subtotal. This is offered for line-level
49
49
  # display and reconciliation only.
50
+ #
51
+ # Valid only when unit prices exclude ISV. On an invoice whose prices
52
+ # include it (Invoice#prices_include_isv?), the line's value is
53
+ # #taxable_base and its tax is part of it; use Invoice#line_value.
50
54
  def isv = (taxable_base * @treatment.rate).round_statutory
51
55
 
52
56
  def total = taxable_base + isv
@@ -142,6 +142,8 @@ module Invoicehn
142
142
 
143
143
  # Art. 11 num. 1 lit. d) e) f) and l).
144
144
  def line_items_section(pdf)
145
+ pdf.text(e(Text::INCLUDED_LEGEND), size: BODY_SIZE) if @invoice.prices_include_isv?
146
+
145
147
  header = ["Descripción", "Cant.", "V. unitario", "Descuento", "Tratamiento", "Valor"].map { |h| e(h) }
146
148
  rows = @invoice.line_items.map do |item|
147
149
  [
@@ -150,7 +152,7 @@ module Invoicehn
150
152
  item.unit_price.to_fixed,
151
153
  item.discount.to_fixed,
152
154
  e(item.treatment.label),
153
- item.taxable_base.to_fixed
155
+ @invoice.line_value(item).to_fixed
154
156
  ]
155
157
  end
156
158
 
@@ -38,6 +38,11 @@ module Invoicehn
38
38
  RECEIVER_FIELDS = ["Recibido por (nombres y apellidos)", "Identidad o documento de identificación",
39
39
  "Firma"].freeze
40
40
 
41
+ # Printed above the detail when the prices include ISV, so a reader knows
42
+ # why the detail and the summary (which shows bases) differ.
43
+ INCLUDED_LEGEND = "Precios y descuentos del detalle con ISV incluido; " \
44
+ "el resumen muestra los importes sin ISV."
45
+
41
46
  def self.title_for(invoice) = TITLES.fetch(invoice.document_type, invoice.document_name.upcase)
42
47
 
43
48
  def self.copy_legend(invoice, copy)
@@ -174,7 +179,9 @@ module Invoicehn
174
179
 
175
180
  # Art. 11 num. 1 lit. d), e), f) and l).
176
181
  def line_items_block
177
- lines = [header_row, rule("·")]
182
+ lines = []
183
+ lines += wrap(INCLUDED_LEGEND) if @invoice.prices_include_isv?
184
+ lines += [header_row, rule("·")]
178
185
 
179
186
  @invoice.line_items.each do |item|
180
187
  lines += item_rows(item)
@@ -202,7 +209,7 @@ module Invoicehn
202
209
  trim_quantity(item.quantity),
203
210
  item.unit_price.to_fixed,
204
211
  item.discount.to_fixed,
205
- item.taxable_base.to_fixed)]
212
+ @invoice.line_value(item).to_fixed)]
206
213
 
207
214
  rows += rest.map { |line| " #{line}" }
208
215
  rows << " (#{item.treatment.label})"
@@ -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
@@ -119,6 +119,22 @@ module Invoicehn
119
119
  store&.delete_document(document) if document
120
120
  end
121
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
+
122
138
  # Art. 41 — the annulled form replaces the record; the number stays.
123
139
  def test_store_contract_keeps_the_annulled_form
124
140
  store = contract_store
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Invoicehn
4
- VERSION = "0.2.0"
4
+ VERSION = "0.3.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: invoicehn
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jorge Padilla