gamba 2.1.0 → 2.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: 932a1ab720e736e68d99dc4a20f948bee38608632dc178938c2db4d47dbf9d77
4
- data.tar.gz: eb535dfd680f1792e8d651f72c7e8e742e2d65c643cbdbd8a91a9df09449d93a
3
+ metadata.gz: 6655a4d975cae61ca400cdac17500d7d448dc2afafa293a71391f2ed06d2c019
4
+ data.tar.gz: 0c5758306e6ad760436ab97a73294fb8221690d542a536d2bd954a12399bd35a
5
5
  SHA512:
6
- metadata.gz: 1a80a0658e934f8f10a08b6667ba1c46d7846d96470e1ccff3b016ec0430aa5e928dab79718bae2ef807c4df51c16d36a9e64a68dd7e367a26abd0e8691c225f
7
- data.tar.gz: 34805fd6f134b47ba636bc9409cd201e3afb8d1a76da5487b444332d9f8d1573381b10edb5500c4c903b6f5907023dff78f164d04432be000f7fe1996fb0c4e5
6
+ metadata.gz: ab094dc3ea9b9dc2c46741166a87ed188711b15d4c92249c6e61956ef6e7d411205acdd7c2fc52d324984db2c385be482a772d343a567e7bea0138317f19a9d1
7
+ data.tar.gz: cc4254a7747560aa6e36fa213122afb8bed94bbce2d7d5d478d689ccaab4e3cfdcad97c066fab2af70a7afcf072181410d3110175d6fd3a7de0e242b03483d38
data/CHANGELOG.md CHANGED
@@ -2,6 +2,23 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [2.2.0] — 2026-11-27
6
+
7
+ Encrypted documents open in Preview and Safari, and can use AES-256; a watermark takes one option; invoices write their own Factur-X XML.
8
+
9
+ **New**
10
+ - `watermark: "Draft"`, or a hash with its `text`, `font`, `style`, `size`, `angle`, `color` and `opacity`, draws a text along each page's diagonal, beneath its content, on `Prawn::Document` and `Gamba.document`. It is drawn when the document renders, so a font registered later is used, written once per page size, and tagged as a watermark artifact.
11
+ - `encrypt_document(algorithm: :aes_256)` writes the standard security handler's revision 6 in place of 40-bit RC4, which stays the default. Its key, salts and initialization vectors are random, so two renders differ; modification and annotations refused also refuse assembly and form filling, as under RC4.
12
+ - `Gamba::Invoice` holds an invoice as data with exact amounts, computes its totals and VAT breakdown as EN 16931 sets, and writes its EN 16931 XML; `factur_x invoice` embeds it.
13
+ - Writing an invoice's XML checks the EN 16931 business rules its data can break, and with `rules: :fr` the French e-invoicing rules, raising `Gamba::Invoice::RuleViolation` with every broken rule by its id.
14
+ - Released gems carry a Sigstore attestation.
15
+ - The site publishes `llms.txt` and `llms-full.txt`, the guide and API for coding agents.
16
+
17
+ **Fixed**
18
+ - Encrypted documents open in Apple's PDF engine (Preview, Safari on macOS and iOS, Quick Look): their catalog is no longer packed in the object stream, which Core Graphics cannot read once encrypted.
19
+ - Strings in the dictionary of a stream, such as an imported image's indexed palette, are encrypted with the rest of an encrypted document, where they read back as garbage.
20
+ - A date in a time zone with minutes, such as +05:30, keeps them, where Prawn writes +05'00'.
21
+
5
22
  ## [2.1.0] — 2026-11-21
6
23
 
7
24
  Gamba gets an API of its own next to Prawn's, `Gamba.document`: layout described in boxes instead of computed, tables with named columns, barcodes, PDF templates, Rails rendering, test assertions and tagged PDF/UA.
@@ -131,7 +148,8 @@ speed. Same API and same pages as Prawn, pixel for pixel, in lighter files.
131
148
  place of combine_pdf.
132
149
  - `Gamba::VERSION` is the gem's; `Prawn::VERSION` stays 2.5.0, the API reproduced.
133
150
 
134
- [Unreleased]: https://github.com/levups/gamba/compare/v2.1.0...HEAD
151
+ [Unreleased]: https://github.com/levups/gamba/compare/v2.2.0...HEAD
152
+ [2.2.0]: https://github.com/levups/gamba/compare/v2.1.0...v2.2.0
135
153
  [2.1.0]: https://github.com/levups/gamba/compare/v2.0.2...v2.1.0
136
154
  [2.0.2]: https://github.com/levups/gamba/compare/v2.0.1...v2.0.2
137
155
  [2.0.1]: https://github.com/levups/gamba/compare/v2.0.0...v2.0.1
data/README.md CHANGED
@@ -11,6 +11,9 @@ from one API to the other one block at a time ([the migration guide](https://lev
11
11
 
12
12
  Website and guide: https://levups.github.io/gamba/
13
13
 
14
+ Coding agents can start from <https://levups.github.io/gamba/llms.txt>, or read this README and the
15
+ website's pages as one Markdown file: <https://levups.github.io/gamba/llms-full.txt>.
16
+
14
17
  ## Installation
15
18
 
16
19
  Gamba needs Ruby 3.3 or later. In your Gemfile, replace `prawn`, `prawn-table` and `prawn-svg` with one line:
@@ -108,16 +111,28 @@ font "Inter.ttf", features: %i[liga kern]
108
111
  ```
109
112
 
110
113
  PDF/A-3b archival files, and Factur-X electronic invoices (the French and German standard that embeds the invoice
111
- data as XML inside the PDF). Gamba embeds the XML your invoicing system produced; it does not build it.
114
+ data as XML inside the PDF). Gamba writes the XML of the EN 16931 profile from a `Gamba::Invoice`, which computes the
115
+ totals and the VAT breakdown with EN 16931's rounding, in exact decimals; or it embeds the XML your invoicing system
116
+ produced, in any profile.
112
117
 
113
118
  ```ruby
119
+ invoice = Gamba::Invoice.new(number: "INV-2026-0001", issued_on: Date.new(2026, 11, 12), due_on: Date.new(2026, 12, 12),
120
+ seller: {name: "Example SAS", vat: "FR32123456789", address: {lines: "1 Example Street", postcode: "75001", city: "Paris", country: "FR"}},
121
+ buyer: {name: "Alice Martin", address: {lines: "2 Example Avenue", postcode: "69001", city: "Lyon", country: "FR"}},
122
+ lines: [{name: "Post", quantity: 2, unit_price: "50.00", vat_rate: 20}])
123
+ invoice.due # => (120/1)
124
+
114
125
  Prawn::Document.new(pdf_a: true, info: {Title: "Invoice INV-2026-0001"}) do
115
126
  font "Inter.ttf" # PDF/A needs embedded fonts: the 14 standard ones raise, and so does encryption
116
127
  # ...
117
- factur_x File.read("factur-x.xml"), profile: :en16931 # or minimum, basic_wl, basic, extended
128
+ factur_x invoice # or File.read("factur-x.xml"), profile: :basic (minimum, basic_wl, basic, en16931, extended)
118
129
  end
119
130
  ```
120
131
 
132
+ The invoice is checked against the EN 16931 business rules first, and with `factur_x invoice, rules: :fr` against those
133
+ of France's e-invoicing reform too; `Gamba::Invoice::RuleViolation` names each rule broken, such as
134
+ `BR-CO-25: an invoice with an amount due needs due_on or payment_terms`.
135
+
121
136
  Tagged PDF for screen readers: `pdf: :ua` (PDF/UA-1) and `pdf_a: :a` (PDF/A-3a) tag the boxes of Gamba's own API
122
137
  from their roles, and raise where a rule is broken (a figure without `alt`, a list item outside a list; under `pdf: :ua`
123
138
  also no `lang`, no title, a skipped heading level).
@@ -147,6 +162,13 @@ Prawn::Document.new(background_pdf: "letterhead.pdf") do
147
162
  end
148
163
  ```
149
164
 
165
+ A watermark across every page, beneath its content, along the page's diagonal unless told otherwise. It is written
166
+ once per page size, and tagged documents mark it as an artifact:
167
+
168
+ ```ruby
169
+ Prawn::Document.new(watermark: {text: "Courtesy translation", opacity: 0.2})
170
+ ```
171
+
150
172
  QR codes, DataMatrix and barcodes (Code 128, EAN-13, EAN-8, Code 39, ITF-14) in pure Ruby, drawn as vectors: one
151
173
  fill per code, read back by zbar and libdmtx in CI:
152
174
 
@@ -209,8 +231,8 @@ Any of it can be built to attack the server that renders it.
209
231
  ignores references that lead back to themselves, so a crafted PDF can't send it into a loop or fill
210
232
  memory.
211
233
  - Text with inline formatting (`inline_format: true`) is parsed in linear time, whatever the markup.
212
- - The `/ID` of an encrypted PDF depends on its passwords, so it reveals nothing about the content to someone
213
- without them.
234
+ - The `/ID` of an encrypted PDF mixes in a secret, its passwords or a random one under AES-256, so it reveals
235
+ nothing about the content to someone without them.
214
236
 
215
237
  Inline formatting still turns `<link href="...">` into a clickable link. Escape user text before you put it inside
216
238
  markup. A word with no space to break at, thousands of characters long, takes time that grows with the square of its
@@ -19,13 +19,13 @@ module Prawn
19
19
 
20
20
  VALID_OPTIONS = %i[
21
21
  page_size page_layout margin left_margin right_margin top_margin bottom_margin skip_page_creation compress
22
- background info text_formatter print_scaling pdf_a pdf lang background_pdf background_pdf_page
22
+ background info text_formatter print_scaling pdf_a pdf lang background_pdf background_pdf_page watermark
23
23
  ].freeze
24
24
 
25
25
  attr_accessor :margin_box, :page_number, :text_formatter
26
26
  # The font used until one is set, Helvetica unless told: PDF/A and PDF/UA documents of Gamba's own API take
27
27
  # their default style's.
28
- attr_writer :default_font_family
28
+ attr_accessor :default_font_family
29
29
  attr_reader :margins, :y
30
30
 
31
31
  # Modules every new document extends itself with: a subclass starts with its parent's.
@@ -54,6 +54,7 @@ module Prawn
54
54
  @background_scale = options[:background_scale] || 1
55
55
  @background_pdf = options[:background_pdf]
56
56
  @background_pdf_page = options[:background_pdf_page] || 1
57
+ @gamba_watermark = Gamba::Watermark.from_option(options[:watermark])
57
58
  @font_size = 12
58
59
  @bounding_box = nil
59
60
  @margin_box = nil
@@ -95,6 +96,7 @@ module Prawn
95
96
  @page_number += 1
96
97
  tag_artifact { canvas { image(@background, scale: @background_scale, at: bounds.top_left) } } if @background
97
98
  draw_background_pdf(options)
99
+ @gamba_watermark&.open_page(self)
98
100
  @y = @bounding_box.absolute_top
99
101
  float { tag_artifact { @on_page_create&.call(self) } }
100
102
  header_blend_mode = page.stack.last&.blend_mode
@@ -154,6 +156,7 @@ module Prawn
154
156
 
155
157
  def render(*arguments)
156
158
  output = arguments.first
159
+ @gamba_watermark&.fill_stamps(self)
157
160
  (1..page_count).each do |page_number|
158
161
  go_to_page(page_number)
159
162
  repeaters.each { _1.run(page_number) }
@@ -0,0 +1,255 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ class Invoice
5
+ # Writes an invoice as UN/CEFACT Cross Industry Invoice D16B, the syntax of Factur-X and ZUGFeRD, in the element
6
+ # order its schema sets.
7
+ class CrossIndustryInvoice
8
+ GUIDELINE_BY_PROFILE = {en16931: "urn:cen.eu:en16931:2017"}.freeze
9
+ NAMESPACES = {
10
+ "rsm" => "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100",
11
+ "ram" => "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100",
12
+ "udt" => "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100",
13
+ "qdt" => "urn:un:unece:uncefact:data:standard:QualifiedDataType:100"
14
+ }.freeze
15
+
16
+ def initialize(invoice, profile)
17
+ @guideline = GUIDELINE_BY_PROFILE.fetch(profile) do
18
+ raise ArgumentError, "Gamba writes the XML of the #{GUIDELINE_BY_PROFILE.keys.map(&:inspect).join(", ")} profile; give the XML of #{profile.inspect} as a String"
19
+ end
20
+ @invoice = invoice
21
+ @xml = +""
22
+ @depth = 0
23
+ end
24
+
25
+ def to_s
26
+ @xml << %(<?xml version="1.0" encoding="UTF-8"?>\n)
27
+ attributes = NAMESPACES.to_h { |prefix, uri| ["xmlns:#{prefix}", uri] }
28
+ element("rsm:CrossIndustryInvoice", **attributes) do
29
+ element("rsm:ExchangedDocumentContext") { element("ram:GuidelineSpecifiedDocumentContextParameter") { element("ram:ID", @guideline) } }
30
+ exchanged_document
31
+ element("rsm:SupplyChainTradeTransaction") do
32
+ @invoice.lines.each_with_index { |line, index| line_item(line, index) }
33
+ header_agreement
34
+ header_delivery
35
+ header_settlement
36
+ end
37
+ end
38
+ @xml
39
+ end
40
+
41
+ private
42
+
43
+ def exchanged_document
44
+ element("rsm:ExchangedDocument") do
45
+ element("ram:ID", @invoice.number)
46
+ element("ram:TypeCode", TYPE_CODE_BY_NAME.fetch(@invoice.type))
47
+ date("ram:IssueDateTime", @invoice.issued_on)
48
+ @invoice.notes.each do |note|
49
+ element("ram:IncludedNote") do
50
+ element("ram:Content", note.text)
51
+ element("ram:SubjectCode", note.subject)
52
+ end
53
+ end
54
+ end
55
+ end
56
+
57
+ def line_item(line, index)
58
+ element("ram:IncludedSupplyChainTradeLineItem") do
59
+ element("ram:AssociatedDocumentLineDocument") { element("ram:LineID", line.id || (index + 1).to_s) }
60
+ element("ram:SpecifiedTradeProduct") do
61
+ element("ram:Name", line.name)
62
+ element("ram:Description", line.description)
63
+ end
64
+ element("ram:SpecifiedLineTradeAgreement") { element("ram:NetPriceProductTradePrice") { element("ram:ChargeAmount", decimal(line.unit_price, 2)) } }
65
+ element("ram:SpecifiedLineTradeDelivery") { element("ram:BilledQuantity", decimal(line.quantity), unitCode: line.unit) }
66
+ element("ram:SpecifiedLineTradeSettlement") do
67
+ tax(line.vat_category, line.vat_rate)
68
+ line.allowances.each { adjustment(_1, charge: false) }
69
+ line.charges.each { adjustment(_1, charge: true) }
70
+ element("ram:SpecifiedTradeSettlementLineMonetarySummation") { element("ram:LineTotalAmount", amount(line.net_amount)) }
71
+ end
72
+ end
73
+ end
74
+
75
+ def header_agreement
76
+ element("ram:ApplicableHeaderTradeAgreement") do
77
+ element("ram:BuyerReference", @invoice.buyer_reference)
78
+ party("ram:SellerTradeParty", @invoice.seller)
79
+ party("ram:BuyerTradeParty", @invoice.buyer)
80
+ element("ram:BuyerOrderReferencedDocument") { element("ram:IssuerAssignedID", @invoice.order_reference) } if @invoice.order_reference
81
+ end
82
+ end
83
+
84
+ def header_delivery
85
+ element("ram:ApplicableHeaderTradeDelivery") do
86
+ if (delivery = @invoice.deliver_to)
87
+ element("ram:ShipToTradeParty") do
88
+ element("ram:Name", delivery.name)
89
+ address(delivery.address)
90
+ end
91
+ end
92
+ element("ram:ActualDeliverySupplyChainEvent") { date("ram:OccurrenceDateTime", @invoice.delivered_on) } if @invoice.delivered_on
93
+ end
94
+ end
95
+
96
+ def header_settlement
97
+ element("ram:ApplicableHeaderTradeSettlement") do
98
+ element("ram:PaymentReference", @invoice.payment&.reference)
99
+ element("ram:InvoiceCurrencyCode", @invoice.currency)
100
+ payment_means
101
+ @invoice.tax_breakdown.each { tax_breakdown(_1) }
102
+ if @invoice.period
103
+ element("ram:BillingSpecifiedPeriod") do
104
+ date("ram:StartDateTime", @invoice.period.begin)
105
+ date("ram:EndDateTime", @invoice.period.end)
106
+ end
107
+ end
108
+ @invoice.allowances.each { adjustment(_1, charge: false) }
109
+ @invoice.charges.each { adjustment(_1, charge: true) }
110
+ if @invoice.payment_terms || @invoice.due_on
111
+ element("ram:SpecifiedTradePaymentTerms") do
112
+ element("ram:Description", @invoice.payment_terms)
113
+ date("ram:DueDateDateTime", @invoice.due_on) if @invoice.due_on
114
+ end
115
+ end
116
+ monetary_summation
117
+ preceding_invoice
118
+ end
119
+ end
120
+
121
+ def preceding_invoice
122
+ reference = @invoice.preceding_invoice
123
+ return unless reference
124
+
125
+ element("ram:InvoiceReferencedDocument") do
126
+ element("ram:IssuerAssignedID", reference.number)
127
+ if reference.issued_on
128
+ element("ram:FormattedIssueDateTime") { element("qdt:DateTimeString", reference.issued_on.strftime("%Y%m%d"), format: "102") }
129
+ end
130
+ end
131
+ end
132
+
133
+ def party(name, party)
134
+ element(name) do
135
+ element("ram:Name", party.name)
136
+ if party.legal_id || party.trading_name
137
+ element("ram:SpecifiedLegalOrganization") do
138
+ element("ram:ID", party.legal_id&.id, schemeID: party.legal_id&.scheme)
139
+ element("ram:TradingBusinessName", party.trading_name)
140
+ end
141
+ end
142
+ address(party.address)
143
+ element("ram:URIUniversalCommunication") { element("ram:URIID", party.electronic_address.id, schemeID: party.electronic_address.scheme) } if party.electronic_address
144
+ element("ram:SpecifiedTaxRegistration") { element("ram:ID", party.vat, schemeID: "VA") } if party.vat
145
+ element("ram:SpecifiedTaxRegistration") { element("ram:ID", party.tax_registration, schemeID: "FC") } if party.tax_registration
146
+ end
147
+ end
148
+
149
+ def address(address)
150
+ element("ram:PostalTradeAddress") do
151
+ element("ram:PostcodeCode", address.postcode)
152
+ %w[ram:LineOne ram:LineTwo ram:LineThree].zip(address.lines) { |line_name, line| element(line_name, line) }
153
+ element("ram:CityName", address.city)
154
+ element("ram:CountryID", address.country)
155
+ element("ram:CountrySubDivisionName", address.subdivision)
156
+ end
157
+ end
158
+
159
+ def payment_means
160
+ payment = @invoice.payment
161
+ return unless payment
162
+
163
+ element("ram:SpecifiedTradeSettlementPaymentMeans") do
164
+ element("ram:TypeCode", PAYMENT_MEANS_CODE_BY_NAME.fetch(payment.means))
165
+ if payment.iban
166
+ element("ram:PayeePartyCreditorFinancialAccount") do
167
+ element("ram:IBANID", payment.iban)
168
+ element("ram:AccountName", payment.account_name)
169
+ end
170
+ end
171
+ element("ram:PayeeSpecifiedCreditorFinancialInstitution") { element("ram:BICID", payment.bic) } if payment.bic
172
+ end
173
+ end
174
+
175
+ def tax(category, rate, name = "ram:ApplicableTradeTax")
176
+ element(name) do
177
+ element("ram:TypeCode", "VAT")
178
+ element("ram:CategoryCode", VAT_CATEGORY_CODE_BY_NAME.fetch(category))
179
+ element("ram:RateApplicablePercent", decimal(rate, 2)) if rate
180
+ end
181
+ end
182
+
183
+ def tax_breakdown(breakdown)
184
+ element("ram:ApplicableTradeTax") do
185
+ element("ram:CalculatedAmount", amount(breakdown.amount))
186
+ element("ram:TypeCode", "VAT")
187
+ element("ram:ExemptionReason", breakdown.exemption&.reason)
188
+ element("ram:BasisAmount", amount(breakdown.basis))
189
+ element("ram:CategoryCode", VAT_CATEGORY_CODE_BY_NAME.fetch(breakdown.vat_category))
190
+ element("ram:ExemptionReasonCode", breakdown.exemption&.code)
191
+ element("ram:RateApplicablePercent", decimal(breakdown.vat_rate, 2)) if breakdown.vat_rate
192
+ end
193
+ end
194
+
195
+ def adjustment(adjustment, charge:)
196
+ element("ram:SpecifiedTradeAllowanceCharge") do
197
+ element("ram:ChargeIndicator") { element("udt:Indicator", charge.to_s) }
198
+ element("ram:ActualAmount", amount(adjustment.amount))
199
+ element("ram:ReasonCode", adjustment.reason_code)
200
+ element("ram:Reason", adjustment.reason)
201
+ tax(adjustment.vat_category, adjustment.vat_rate, "ram:CategoryTradeTax") if adjustment.vat_category
202
+ end
203
+ end
204
+
205
+ def monetary_summation
206
+ element("ram:SpecifiedTradeSettlementHeaderMonetarySummation") do
207
+ element("ram:LineTotalAmount", amount(@invoice.line_total))
208
+ element("ram:ChargeTotalAmount", amount(@invoice.charge_total)) unless @invoice.charges.empty?
209
+ element("ram:AllowanceTotalAmount", amount(@invoice.allowance_total)) unless @invoice.allowances.empty?
210
+ element("ram:TaxBasisTotalAmount", amount(@invoice.tax_basis_total))
211
+ element("ram:TaxTotalAmount", amount(@invoice.tax_total), currencyID: @invoice.currency)
212
+ element("ram:GrandTotalAmount", amount(@invoice.grand_total))
213
+ element("ram:TotalPrepaidAmount", amount(@invoice.paid)) unless @invoice.paid.zero?
214
+ element("ram:DuePayableAmount", amount(@invoice.due))
215
+ end
216
+ end
217
+
218
+ def date(name, date)
219
+ element(name) { element("udt:DateTimeString", date.strftime("%Y%m%d"), format: "102") }
220
+ end
221
+
222
+ # An element with its text, or with the elements its block writes; one without either is left out.
223
+ def element(name, text = nil, **attributes)
224
+ return if text.nil? && !block_given?
225
+
226
+ @xml << (" " * @depth) << "<" << name
227
+ attributes.each { |attribute, value| @xml << " " << attribute.to_s << "=" << value.encode(xml: :attr) if value }
228
+ if block_given?
229
+ @xml << ">\n"
230
+ @depth += 1
231
+ yield
232
+ @depth -= 1
233
+ @xml << (" " * @depth) << "</" << name << ">\n"
234
+ else
235
+ @xml << ">" << text.encode(xml: :text) << "</" << name << ">\n"
236
+ end
237
+ end
238
+
239
+ def amount(value)
240
+ cents = Invoice.cents(value) * 100
241
+ format("%s%d.%02d", cents.negative? ? "-" : "", cents.abs.to_i / 100, cents.abs.to_i % 100)
242
+ end
243
+
244
+ # A quantity, price or rate as it was given, with as many decimals as it needs, at least minimum.
245
+ def decimal(value, minimum = 0)
246
+ places = (minimum..9).find { (value * 10**_1).denominator == 1 } || 9
247
+ scaled = (value * 10**places).round(half: :up)
248
+ return format("%s%d", scaled.negative? ? "-" : "", scaled.abs) if places.zero?
249
+
250
+ digits = scaled.abs.to_s.rjust(places + 1, "0")
251
+ format("%s%s.%s", scaled.negative? ? "-" : "", digits[0...-places], digits[-places..])
252
+ end
253
+ end
254
+ end
255
+ end
@@ -0,0 +1,183 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ class Invoice
5
+ # Raised when an invoice breaks business rules: each violation names its rule, as validators report it.
6
+ class RuleViolation < StandardError
7
+ attr_reader :violations
8
+
9
+ def initialize(violations)
10
+ @violations = violations
11
+ super(violations.map { "#{_1.rule}: #{_1.message}" }.join("\n"))
12
+ end
13
+ end
14
+
15
+ Violation = Data.define(:rule, :message)
16
+
17
+ # The business rules of EN 16931 an invoice built from this data can break, and with :fr those France adds
18
+ # for its e-invoicing reform (XP Z12-012, BR-FR). What Gamba computes, such as totals and the VAT breakdown, holds
19
+ # by construction and is not checked again.
20
+ class Rules
21
+ RULE_SETS = %i[en16931 fr].freeze
22
+ # Categories whose breakdown states why no VAT is due, and those that state none (BR-x-10).
23
+ EXEMPTION_REQUIRED = %i[exempt reverse_charge intra_community export outside_scope].freeze
24
+ # How EN 16931 names its rules on a VAT category, where that is not the category's code.
25
+ RULE_PREFIX_BY_CATEGORY_CODE = {"K" => "IC", "L" => "AF", "M" => "AG"}.freeze
26
+ NOT_IN_FRANCE = %i[canary_islands ceuta_melilla].freeze
27
+ # The rates France accepts (BR-FR-16).
28
+ FRENCH_VAT_RATES = %w[0 10 13 20 8.5 19.6 2.1 5.5 7 20.6 1.05 0.9 1.75 9.2 9.6].map { Rational(_1) }.freeze
29
+ FRENCH_ID = %r{\A[A-Za-z0-9+\-_/]+\z}
30
+ SIREN = /\A\d{9}\z/
31
+ SIREN_SCHEME = "0002"
32
+ FRENCH_LEGAL_NOTES = %w[PMT PMD AAB].freeze
33
+ BILLING_TREATMENTS = %w[B2B B2BINT B2C OUTOFSCOPE ARCHIVEONLY].freeze
34
+
35
+ def self.check(invoice, rules)
36
+ raise ArgumentError, "rules is #{rules.inspect}: #{RULE_SETS.map(&:inspect).join(", ")}, or nil to write without checking" unless rules.nil? || RULE_SETS.include?(rules)
37
+ return [] if rules.nil?
38
+
39
+ rules_set = new(invoice)
40
+ rules_set.en16931
41
+ rules_set.fr if rules == :fr
42
+ rules_set.violations
43
+ end
44
+
45
+ attr_reader :violations
46
+
47
+ def initialize(invoice)
48
+ @invoice = invoice
49
+ @violations = []
50
+ end
51
+
52
+ def en16931
53
+ seller = @invoice.seller
54
+ buyer = @invoice.buyer
55
+ categories = vat_categories
56
+
57
+ @invoice.lines.each { violation("BR-27", "line #{_1.name.inspect} has a negative unit_price") if _1.unit_price.negative? }
58
+ violation("BR-29", "the period ends before it starts") if @invoice.period && @invoice.period.end < @invoice.period.begin
59
+ if %i[credit_transfer sepa_credit_transfer].include?(@invoice.payment&.means) && !@invoice.payment.iban
60
+ violation("BR-61", "payment by #{@invoice.payment.means.to_s.tr("_", " ")} needs the iban")
61
+ end
62
+ {seller:, buyer:}.each do |role, party|
63
+ violation("BR-CO-09", "the #{role}'s vat must start with its country's code, such as FR") if party.vat && !party.vat.match?(/\A[A-Z]{2}/)
64
+ end
65
+ violation("BR-CO-25", "an invoice with an amount due needs due_on or payment_terms") if @invoice.due.positive? && !@invoice.due_on && !@invoice.payment_terms
66
+ violation("BR-CO-26", "the seller needs a legal_id or a vat") unless seller.legal_id || seller.vat
67
+
68
+ seller_taxed = seller.vat || seller.tax_registration
69
+ {standard: "BR-S-02", zero_rated: "BR-Z-02", exempt: "BR-E-02", canary_islands: "BR-AF-02", ceuta_melilla: "BR-AG-02"}.each do |category, rule|
70
+ violation(rule, "#{describe(category)} needs the seller's vat or tax_registration") if categories.include?(category) && !seller_taxed
71
+ end
72
+ taxed_items.each do |item|
73
+ violation("BR-S-05", "standard rated VAT needs a rate above 0") if item.vat_category == :standard && !item.vat_rate.positive?
74
+ end
75
+ if categories.include?(:reverse_charge) && !(seller_taxed && (buyer.vat || buyer.legal_id))
76
+ violation("BR-AE-02", "reverse charge needs the seller's vat or tax_registration, and the buyer's vat or legal_id")
77
+ end
78
+ if categories.include?(:intra_community)
79
+ violation("BR-IC-02", "an intra-community supply needs the seller's and the buyer's vat") unless seller.vat && buyer.vat
80
+ violation("BR-IC-11", "an intra-community supply needs delivered_on or the period") unless @invoice.delivered_on || @invoice.period
81
+ violation("BR-IC-12", "an intra-community supply needs deliver_to, with its country") unless @invoice.deliver_to
82
+ end
83
+ violation("BR-G-02", "an export needs the seller's vat") if categories.include?(:export) && !seller.vat
84
+ if categories.include?(:outside_scope)
85
+ violation("BR-O-02", "an invoice outside the scope of VAT takes neither the seller's nor the buyer's vat") if seller.vat || buyer.vat
86
+ violation("BR-O-11", "an invoice outside the scope of VAT has no other VAT category") if categories.size > 1
87
+ end
88
+ categories.each do |category|
89
+ code = VAT_CATEGORY_CODE_BY_NAME.fetch(category)
90
+ rule = "BR-#{RULE_PREFIX_BY_CATEGORY_CODE.fetch(code, code)}-10"
91
+ if EXEMPTION_REQUIRED.include?(category)
92
+ violation(rule, "#{describe(category)} needs its reason in exemptions") unless @invoice.exemptions[category]
93
+ elsif @invoice.exemptions[category]
94
+ violation(rule, "#{describe(category)} takes no exemption reason")
95
+ end
96
+ end
97
+ end
98
+
99
+ def fr
100
+ seller = @invoice.seller
101
+ buyer = @invoice.buyer
102
+ subjects = @invoice.notes.map(&:subject)
103
+ treatments = @invoice.notes.filter_map { _1.text if _1.subject == "BAR" }
104
+ treatments.uniq!
105
+
106
+ {"invoice number" => @invoice.number, "preceding_invoice number" => @invoice.preceding_invoice&.number}.each do |name, number|
107
+ next unless number
108
+
109
+ violation("BR-FR-01", "the #{name} has more than 35 characters") if number.length > 35
110
+ violation("BR-FR-02", "the #{name} holds characters other than letters, digits, + - _ and /") unless number.match?(FRENCH_ID)
111
+ end
112
+ dates.each { |name, date| violation("BR-FR-03", "#{name} is not between 2000 and 2099") unless (2000..2099).cover?(date.year) }
113
+ FRENCH_LEGAL_NOTES.each { violation("BR-FR-05", "French invoices need a note with subject #{_1}") unless subjects.include?(_1) }
114
+ (FRENCH_LEGAL_NOTES + ["TXD"]).each { violation("BR-FR-06", "a single note may have subject #{_1}") if subjects.count(_1) > 1 }
115
+ violation("BR-FR-10", "the seller needs its SIREN, 9 digits, as legal_id with scheme 0002") unless siren(seller)
116
+ violation("BR-FR-11", "a B2B invoice needs the buyer's SIREN, 9 digits, as legal_id with scheme 0002") if treatments.include?("B2B") && !siren(buyer)
117
+ violation("BR-FR-12", "the buyer needs an electronic_address") unless buyer.electronic_address
118
+ violation("BR-FR-13", "the seller needs an electronic_address") unless seller.electronic_address
119
+ vat_categories.each do |category|
120
+ violation("BR-FR-15", "#{describe(category)} does not apply in France") if NOT_IN_FRANCE.include?(category)
121
+ end
122
+ taxed_items.filter_map(&:vat_rate).uniq.each do |rate|
123
+ violation("BR-FR-16", "#{format("%g", rate)}% is not a French VAT rate") unless FRENCH_VAT_RATES.include?(rate)
124
+ end
125
+ treatments.each { violation("BR-FR-20", "a note with subject BAR reads one of #{BILLING_TREATMENTS.join(", ")}") unless BILLING_TREATMENTS.include?(_1) }
126
+ violation("BR-FR-30", "the notes with subject BAR give one treatment") if treatments.size > 1
127
+ if treatments.include?("B2B") && !(buyer.electronic_address&.scheme == "0225" && siren(buyer) && buyer.electronic_address.id.start_with?(siren(buyer)))
128
+ violation("BR-FR-21", "a B2B invoice addresses the buyer by an electronic_address with scheme 0225 starting with its SIREN")
129
+ end
130
+ {seller:, buyer:}.each do |role, party|
131
+ address = party.electronic_address
132
+ next unless address
133
+
134
+ violation("BR-FR-23", "the #{role}'s electronic_address holds characters other than letters, digits, + - _ and /") if address.scheme == "0225" && !address.id.match?(FRENCH_ID)
135
+ violation("BR-FR-25", "the #{role}'s electronic_address has more than 125 characters") if address.id.length > 125
136
+ end
137
+ if @invoice.type == :credit_note && !@invoice.preceding_invoice&.issued_on
138
+ violation("BR-FR-CO-05", "a credit note needs the preceding_invoice it corrects, with its issued_on")
139
+ end
140
+ violation("BR-FR-CO-07", "due_on is before issued_on") if @invoice.due_on && @invoice.due_on < @invoice.issued_on
141
+ violation("BR-FR-CO-12", "Gamba writes French invoices in EUR only") unless @invoice.currency == "EUR"
142
+ @invoice.lines.each do |line|
143
+ violation("BR-FR-DEC-02", "line #{line.name.inspect} has a quantity with more than 4 decimals") unless (line.quantity * 10**4).denominator == 1
144
+ violation("BR-FR-DEC-03", "line #{line.name.inspect} has a unit_price with more than 6 decimals") unless (line.unit_price * 10**6).denominator == 1
145
+ end
146
+ end
147
+
148
+ private
149
+
150
+ def violation(rule, message)
151
+ @violations << Violation.new(rule:, message:)
152
+ end
153
+
154
+ # What carries a VAT category: the lines, and the invoice's allowances and charges.
155
+ def taxed_items
156
+ @invoice.lines + @invoice.allowances + @invoice.charges
157
+ end
158
+
159
+ def vat_categories
160
+ categories = taxed_items.map(&:vat_category)
161
+ categories.uniq!
162
+ categories
163
+ end
164
+
165
+ def describe(category)
166
+ {standard: "standard rated VAT", zero_rated: "zero rated VAT", exempt: "exemption from VAT", reverse_charge: "reverse charge",
167
+ intra_community: "an intra-community supply", export: "an export", outside_scope: "an invoice outside the scope of VAT",
168
+ canary_islands: "Canary Islands IGIC", ceuta_melilla: "Ceuta and Melilla IPSI"}.fetch(category)
169
+ end
170
+
171
+ def siren(party)
172
+ legal_id = party.legal_id
173
+ legal_id.id if legal_id&.scheme == SIREN_SCHEME && legal_id.id.match?(SIREN)
174
+ end
175
+
176
+ def dates
177
+ {"issued_on" => @invoice.issued_on, "due_on" => @invoice.due_on, "delivered_on" => @invoice.delivered_on,
178
+ "the period's start" => @invoice.period&.begin, "the period's end" => @invoice.period&.end,
179
+ "preceding_invoice issued_on" => @invoice.preceding_invoice&.issued_on}.compact
180
+ end
181
+ end
182
+ end
183
+ end