gamba 2.0.2 → 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.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +47 -1
  3. data/README.md +174 -31
  4. data/lib/gamba/annotations.rb +5 -0
  5. data/lib/gamba/barcodes/data_matrix.rb +204 -0
  6. data/lib/gamba/barcodes/linear.rb +182 -0
  7. data/lib/gamba/barcodes/qr_code.rb +339 -0
  8. data/lib/gamba/barcodes.rb +136 -0
  9. data/lib/gamba/combine.rb +13 -135
  10. data/lib/gamba/copier.rb +107 -0
  11. data/lib/gamba/document/internals.rb +5 -1
  12. data/lib/gamba/document.rb +36 -4
  13. data/lib/gamba/font.rb +7 -3
  14. data/lib/gamba/fonts/afm.rb +3 -2
  15. data/lib/gamba/fonts/ttf.rb +26 -20
  16. data/lib/gamba/images.rb +23 -1
  17. data/lib/gamba/imported_page.rb +137 -0
  18. data/lib/gamba/invoice/cross_industry_invoice.rb +255 -0
  19. data/lib/gamba/invoice/rules.rb +183 -0
  20. data/lib/gamba/invoice.rb +272 -0
  21. data/lib/gamba/minitest.rb +35 -0
  22. data/lib/gamba/native/band.rb +56 -0
  23. data/lib/gamba/native/document.rb +128 -0
  24. data/lib/gamba/native/layout.rb +1063 -0
  25. data/lib/gamba/native/table.rb +189 -0
  26. data/lib/gamba/page_boxes.rb +68 -0
  27. data/lib/gamba/pdf/decryption.rb +1 -20
  28. data/lib/gamba/pdf/reader.rb +8 -2
  29. data/lib/gamba/pdf/writer.rb +34 -5
  30. data/lib/gamba/pdf.rb +15 -1
  31. data/lib/gamba/pdf_a.rb +65 -21
  32. data/lib/gamba/pdf_check.rb +220 -0
  33. data/lib/gamba/railtie.rb +52 -0
  34. data/lib/gamba/rspec.rb +58 -0
  35. data/lib/gamba/security.rb +133 -5
  36. data/lib/gamba/table/cell/kinds.rb +45 -5
  37. data/lib/gamba/table/cell.rb +37 -0
  38. data/lib/gamba/table.rb +7 -0
  39. data/lib/gamba/tagging.rb +302 -0
  40. data/lib/gamba/testing.rb +79 -0
  41. data/lib/gamba/text/formatted/box.rb +5 -0
  42. data/lib/gamba/text/formatted/wrap.rb +1 -1
  43. data/lib/gamba/true_type/open_type_layout.rb +44 -17
  44. data/lib/gamba/true_type/simple_subsets.rb +11 -7
  45. data/lib/gamba/version.rb +1 -1
  46. data/lib/gamba/watermark.rb +108 -0
  47. data/lib/gamba.rb +22 -1
  48. metadata +294 -260
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ # A page of a PDF written elsewhere, drawn like an image: a form XObject showing what a viewer shows of it, its
5
+ # crop box turned by its /Rotate. Placed many times, it is written once; pages of one file share their resources.
6
+ class ImportedPage < Prawn::Images::Image
7
+ include PageBoxes
8
+
9
+ # A file read once per document, its objects copied into it as its pages are used.
10
+ Source = Struct.new(:reader, :copier, :pages)
11
+ # Fonts whose glyphs need no font file: their procedures are in the PDF.
12
+ FONT_PROGRAMS = %i[FontFile FontFile2 FontFile3].freeze
13
+ TYPE3 = PDF::Core::Name.new(value: "Type3")
14
+ FORM = PDF::Core::Name.new(value: "Form")
15
+ MARKED_CONTENT_OPERATOR = %r{(?:\A|[\x00\t\n\f\r >])(?:BDC|BMC)(?:\z|[\x00\t\n\f\r ()<>\[\]{}/%])}
16
+
17
+ attr_reader :width, :height, :form
18
+
19
+ # source: a path, an IO, the bytes of a PDF, or anything answering download, as Active Storage attachments do.
20
+ def self.bytes(source)
21
+ if source.respond_to?(:download) && !source.respond_to?(:read)
22
+ source.download.b
23
+ elsif source.respond_to?(:read)
24
+ source.rewind if source.respond_to?(:rewind)
25
+ source.read.b
26
+ elsif source.is_a?(String) && source.b.start_with?("%PDF-")
27
+ source.b
28
+ else
29
+ path = Pathname.new(source)
30
+ raise ArgumentError, "#{path} not found" unless path.file?
31
+
32
+ path.binread
33
+ end
34
+ end
35
+
36
+ def self.source(document, bytes)
37
+ reader = PDF::Core::Reader.new(bytes)
38
+ document.min_version(reader.version)
39
+ Source.new(reader, Copier.new(reader) { document.ref!(_1) }, reader.pages)
40
+ end
41
+
42
+ def initialize(document, source, number)
43
+ super()
44
+ @reader = source.reader
45
+ raise Prawn::Errors::MalformedPDF, "This PDF has no pages" if source.pages.empty?
46
+ unless number.is_a?(Integer) && number.between?(1, source.pages.size)
47
+ raise ArgumentError, "page is #{number.inspect}: this PDF has pages 1 to #{source.pages.size}"
48
+ end
49
+
50
+ page = source.pages[number - 1].last
51
+ if document.pdf_a? || document.pdf_ua?
52
+ # PDF/A and PDF/UA both embed every font; PDF/UA names the error when both apply, as everywhere else.
53
+ @embedding_violation = document.pdf_ua? ? [Prawn::Errors::PdfUaViolation, "PDF/UA"] : [Prawn::Errors::PdfAViolation, "PDF/A"]
54
+ check_fonts_embedded(page[:Resources], {})
55
+ end
56
+ check_no_marked_content(page[:Contents], document) if document.tagged?
57
+ @form = document.ref!(form_dictionary(page, source.copier))
58
+ @form.stream, filters = content(page[:Contents], source.copier)
59
+ @form.data.merge!(filters)
60
+ source.copier.finish
61
+ end
62
+
63
+ # What draws the page in a box of this width and height, from its lower left corner.
64
+ def placement(width, height, x, y)
65
+ [width / @width.to_f, 0, 0, height / @height.to_f, x, y]
66
+ end
67
+
68
+ private
69
+
70
+ # The form maps the visible box, turned, onto a box from the origin as wide and high as the page is shown.
71
+ def form_dictionary(page, copier)
72
+ left, bottom, right, top = visible_box(page)
73
+ width = right - left
74
+ height = top - bottom
75
+ turn = rotation(page)
76
+ @width, @height = (turn % 180).zero? ? [width, height] : [height, width]
77
+ matrix = [1.0, 0.0, 0.0, 1.0, -left, -bottom]
78
+ matrix = multiply(matrix, ROTATIONS.fetch(turn).call(width, height)) unless turn.zero?
79
+ dictionary = {Type: :XObject, Subtype: :Form, BBox: [left, bottom, right, top], Matrix: matrix, Resources: copier.copy(page[:Resources] || {})}
80
+ dictionary[:Group] = copier.copy(page[:Group]) if page[:Group]
81
+ dictionary
82
+ end
83
+
84
+ # A form holds one stream: a page's only content stream keeps its bytes and filters, several are decoded and
85
+ # joined, as their division may fall between an operator and its operands.
86
+ def content(value, copier)
87
+ streams = Array(@reader.resolve(value)).map { @reader.resolve(_1) }.grep(PDF::Core::Reader::Stream)
88
+ return [+" ", {}] if streams.empty?
89
+ return [+streams.first.data, copier.copy(streams.first.dictionary.slice(:Filter, :DecodeParms))] if streams.one?
90
+
91
+ [streams.map { @reader.decoded(_1) }.join("\n"), {}]
92
+ end
93
+
94
+ # The page is drawn as one figure or artifact: marked content of its own would nest in it, which tagged PDF
95
+ # forbids, and its MCIDs would point at a structure tree left behind. The operator follows whitespace or the >> of
96
+ # its properties, and comes before whitespace, a delimiter or the end: /P<</MCID 0>>BDC(a)Tj is written too.
97
+ def check_no_marked_content(contents, document)
98
+ streams = Array(@reader.resolve(contents)).map { @reader.resolve(_1) }.grep(PDF::Core::Reader::Stream)
99
+ return unless streams.any? { @reader.decoded(_1).match?(MARKED_CONTENT_OPERATOR) }
100
+
101
+ error, standard = document.pdf_ua? ? [Prawn::Errors::PdfUaViolation, "PDF/UA"] : [Prawn::Errors::PdfAViolation, "PDF/A-3a"]
102
+ raise error, "#{standard} cannot import a page that has marked content of its own, a page of a tagged PDF: Gamba does not merge structure trees yet"
103
+ end
104
+
105
+ # PDF/A wants every font's program in the file: a page that leaves one to the viewer raises.
106
+ def check_fonts_embedded(resources, visited)
107
+ resources = @reader.resolve(resources)
108
+ return unless resources.is_a?(Hash)
109
+
110
+ fonts = @reader.resolve(resources[:Font])
111
+ fonts.each_value { |font| check_font_embedded(@reader.resolve(font)) } if fonts.is_a?(Hash)
112
+ xobjects = @reader.resolve(resources[:XObject])
113
+ return unless xobjects.is_a?(Hash)
114
+
115
+ xobjects.each_value do |reference|
116
+ next if !reference.is_a?(PDF::Core::Reader::Ref) || visited[reference.number]
117
+
118
+ visited[reference.number] = true
119
+ xobject = @reader.resolve(reference)
120
+ check_fonts_embedded(xobject.dictionary[:Resources], visited) if xobject.is_a?(PDF::Core::Reader::Stream) && xobject.dictionary[:Subtype] == FORM
121
+ end
122
+ end
123
+
124
+ def check_font_embedded(font)
125
+ return unless font.is_a?(Hash) && font[:Subtype] != TYPE3
126
+
127
+ descendant = @reader.resolve(@reader.resolve(font[:DescendantFonts]).then { _1.is_a?(Array) ? _1.first : nil })
128
+ font = descendant if descendant.is_a?(Hash)
129
+ descriptor = @reader.resolve(font[:FontDescriptor])
130
+ return if descriptor.is_a?(Hash) && FONT_PROGRAMS.any? { descriptor[_1] }
131
+
132
+ name = @reader.resolve(font[:BaseFont])
133
+ error, standard = @embedding_violation
134
+ raise error, "#{standard} embeds every font: the page uses #{name.respond_to?(:value) ? name.value : "a font"} without its font file"
135
+ end
136
+ end
137
+ end
@@ -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