zugpferd 0.8.0 → 0.9.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: 05fc84848e61ccfc901d5a22ab7d35ff8032531d543dcd85883073a7d0bd2c43
4
- data.tar.gz: cd37bf998f94dd2be0f9adac19761976145b49f7aace4d22d5af2812df173e1a
3
+ metadata.gz: 5cfc91b900af3d8c0586831fabc3963e99d538383739e298d146d5e9d83714c8
4
+ data.tar.gz: 806154beec1f4525e01745f15c9a9fdd6acc9eb5f74292e521e28667c59119b8
5
5
  SHA512:
6
- metadata.gz: 245cb66ea6b7b151145130747873780113acd36790a66420e23b210ddd1920082e22bd50661cadde218bf15bc1713687ddbc0b5a802bfd0245aa6b72b569fe7c
7
- data.tar.gz: 72af5d37db91aaa59deee1cc9b9ec7aa70347d1dce1f87decc6f5347f5714a077d869533f4bcb23d9bb42b4b52b6db73157904c987c98144c5a888616d7f5f24
6
+ metadata.gz: 753cc63a0cd46279822c2d60a72b5efda5ff21ecc1bca9b098b8b62b3c5197db50f858d922b25c474fab6681e5d40491d17faf2bdeefb271e2cd4cb4d3aabe07
7
+ data.tar.gz: 2d5a186b249dce95d253ab55bfd961af4f0a639de2adf7a15134ec4534c565f08c5098597e8e484c0eb5f5851f68e6f5096f6713a6a1599f2b4c7b480c044913
@@ -51,8 +51,15 @@ module Zugpferd
51
51
  currency_code: "#{SETTLEMENT}/ram:InvoiceCurrencyCode",
52
52
  buyer_reference: "#{AGREEMENT}/ram:BuyerReference",
53
53
  purchase_order_reference: "#{AGREEMENT}/ram:BuyerOrderReferencedDocument/ram:IssuerAssignedID",
54
+ seller_order_reference: "#{AGREEMENT}/ram:SellerOrderReferencedDocument/ram:IssuerAssignedID",
55
+ contract_reference: "#{AGREEMENT}/ram:ContractReferencedDocument/ram:IssuerAssignedID",
56
+ project_reference: "#{AGREEMENT}/ram:SpecifiedProcuringProject/ram:ID",
57
+ buyer_accounting_reference: "#{SETTLEMENT}/ram:ReceivableSpecifiedTradeAccountingAccount/ram:ID",
54
58
  }.freeze
55
59
 
60
+ # Mandatory ram:Name of ram:SpecifiedProcuringProject, no business term in EN 16931
61
+ PROJECT_NAME = "Project reference"
62
+
56
63
  # Seller (BG-4)
57
64
  SELLER = "#{AGREEMENT}/ram:SellerTradeParty"
58
65
  # Buyer (BG-7)
@@ -92,6 +99,7 @@ module Zugpferd
92
99
  PAYMENT = {
93
100
  payment_means_code: "ram:TypeCode",
94
101
  account_id: "ram:PayeePartyCreditorFinancialAccount/ram:IBANID",
102
+ account_name: "ram:PayeePartyCreditorFinancialAccount/ram:AccountName",
95
103
  card_account_id: "ram:ApplicableTradeSettlementFinancialCard/ram:ID",
96
104
  card_holder_name: "ram:ApplicableTradeSettlementFinancialCard/ram:CardholderName",
97
105
  debited_account_id: "ram:PayerPartyDebtorFinancialAccount/ram:IBANID",
@@ -56,6 +56,10 @@ module Zugpferd
56
56
  currency_code: text(root, INVOICE_SETTLEMENT[:currency_code]),
57
57
  buyer_reference: text(root, INVOICE_SETTLEMENT[:buyer_reference]),
58
58
  purchase_order_reference: text(root, INVOICE_SETTLEMENT[:purchase_order_reference]),
59
+ seller_order_reference: text(root, INVOICE_SETTLEMENT[:seller_order_reference]),
60
+ contract_reference: text(root, INVOICE_SETTLEMENT[:contract_reference]),
61
+ project_reference: text(root, INVOICE_SETTLEMENT[:project_reference]),
62
+ buyer_accounting_reference: text(root, INVOICE_SETTLEMENT[:buyer_accounting_reference]),
59
63
  customization_id: text(root, INVOICE[:customization_id]),
60
64
  profile_id: text(root, INVOICE[:profile_id]),
61
65
  note: text(root, INVOICE[:note]),
@@ -129,6 +133,7 @@ module Zugpferd
129
133
  payment_means_code: text(means_node, PAYMENT[:payment_means_code]),
130
134
  payment_id: text(settlement_node, PAYMENT_REFERENCE),
131
135
  account_id: text(means_node, PAYMENT[:account_id]),
136
+ account_name: text(means_node, PAYMENT[:account_name]),
132
137
  card_account_id: text(means_node, PAYMENT[:card_account_id]),
133
138
  card_holder_name: text(means_node, PAYMENT[:card_holder_name]),
134
139
  debited_account_id: text(means_node, PAYMENT[:debited_account_id]),
@@ -76,7 +76,27 @@ module Zugpferd
76
76
  xml["ram"].BuyerReference doc.buyer_reference if doc.buyer_reference
77
77
  build_party(xml, "SellerTradeParty", doc.seller, seller: true) if doc.seller
78
78
  build_party(xml, "BuyerTradeParty", doc.buyer) if doc.buyer
79
+
80
+ if doc.seller_order_reference
81
+ xml["ram"].SellerOrderReferencedDocument do
82
+ xml["ram"].IssuerAssignedID doc.seller_order_reference
83
+ end
84
+ end
85
+
79
86
  build_buyer_order_reference(xml, doc) if doc.purchase_order_reference
87
+
88
+ if doc.contract_reference
89
+ xml["ram"].ContractReferencedDocument do
90
+ xml["ram"].IssuerAssignedID doc.contract_reference
91
+ end
92
+ end
93
+
94
+ if doc.project_reference
95
+ xml["ram"].SpecifiedProcuringProject do
96
+ xml["ram"].ID doc.project_reference
97
+ xml["ram"].Name PROJECT_NAME
98
+ end
99
+ end
80
100
  end
81
101
  end
82
102
 
@@ -212,6 +232,12 @@ module Zugpferd
212
232
 
213
233
  # CII allows a single InvoiceReferencedDocument, so only the first BG-3 is written
214
234
  build_preceding_invoice(xml, doc.preceding_invoices.first) if doc.preceding_invoices.any?
235
+
236
+ if doc.buyer_accounting_reference
237
+ xml["ram"].ReceivableSpecifiedTradeAccountingAccount do
238
+ xml["ram"].ID doc.buyer_accounting_reference
239
+ end
240
+ end
215
241
  end
216
242
  end
217
243
 
@@ -258,6 +284,7 @@ module Zugpferd
258
284
  if payment.account_id
259
285
  xml["ram"].PayeePartyCreditorFinancialAccount do
260
286
  xml["ram"].IBANID payment.account_id
287
+ xml["ram"].AccountName payment.account_name if payment.account_name
261
288
  end
262
289
  end
263
290
  end
@@ -35,13 +35,19 @@ module Zugpferd
35
35
  # @return [MonetaryTotals, nil] BG-22 Document totals
36
36
  # @return [PaymentInstructions, nil] BG-16 Payment information
37
37
  # @return [Array<AllowanceCharge>] BG-20/BG-21 Document-level allowances and charges
38
+ # @return [String, nil] BT-11 Project reference
39
+ # @return [String, nil] BT-12 Contract reference
40
+ # @return [String, nil] BT-14 Sales order reference
41
+ # @return [String, nil] BT-19 Buyer accounting reference
38
42
  attr_accessor :number, :issue_date, :due_date, :type_code,
39
43
  :currency_code, :delivery_date, :deliver_to_address,
40
44
  :invoicing_period_start_date, :invoicing_period_end_date,
41
45
  :buyer_reference, :purchase_order_reference,
42
46
  :customization_id, :profile_id, :note, :seller, :buyer,
43
47
  :line_items, :tax_breakdown, :monetary_totals,
44
- :payment_instructions, :allowance_charges, :preceding_invoices
48
+ :payment_instructions, :allowance_charges, :preceding_invoices,
49
+ :contract_reference, :seller_order_reference, :project_reference,
50
+ :buyer_accounting_reference
45
51
 
46
52
  # @param number [String] BT-1 Invoice number
47
53
  # @param issue_date [Date] BT-2 Issue date
@@ -6,6 +6,7 @@ module Zugpferd
6
6
  # @return [String] BT-81 Payment means type code
7
7
  # @return [String, nil] BT-83 Remittance information
8
8
  # @return [String, nil] BT-84 Payment account identifier (IBAN)
9
+ # @return [String, nil] BT-85 Payment account name
9
10
  # @return [String, nil] BT-20 Payment terms
10
11
  # @return [String, nil] BT-87 Payment card primary account number
11
12
  # @return [String, nil] BT-88 Payment card holder name
@@ -13,7 +14,7 @@ module Zugpferd
13
14
  # @return [String, nil] BT-89 Mandate reference identifier
14
15
  # @return [String, nil] BT-90 Bank assigned creditor identifier
15
16
  # @return [String, nil] BT-91 Debited account identifier
16
- attr_accessor :payment_means_code, :payment_id, :account_id, :note,
17
+ attr_accessor :payment_means_code, :payment_id, :account_id, :account_name, :note,
17
18
  :card_account_id, :card_holder_name, :card_network_id,
18
19
  :mandate_reference, :creditor_reference_id,
19
20
  :debited_account_id
@@ -0,0 +1,318 @@
1
+ require "nokogiri"
2
+ require "set"
3
+ require "zlib"
4
+
5
+ module Zugpferd
6
+ module PDF
7
+ # Extracts the embedded invoice XML from a ZUGFeRD / Factur-X / XRechnung
8
+ # hybrid PDF.
9
+ #
10
+ # Needs the pdf-reader gem, which zugpferd does not install for you:
11
+ #
12
+ # gem "pdf-reader", "~> 2.16"
13
+ #
14
+ # @example
15
+ # result = Zugpferd::PDF::Extractor.new.extract(pdf_path: "rechnung.pdf")
16
+ # result.filename # => "factur-x.xml"
17
+ # result.syntax # => :cii
18
+ # invoice = result.read
19
+ class Extractor
20
+ class PdfReaderNotFound < Zugpferd::Error; end
21
+ class ExtractError < Zugpferd::Error; end
22
+ class InvoiceNotFound < ExtractError; end
23
+ class AmbiguousInvoice < ExtractError; end
24
+ class LimitExceeded < ExtractError; end
25
+ class UnsupportedSyntax < ExtractError; end
26
+
27
+ # The names the specifications give the embedded invoice, so that PDFs
28
+ # from any producer are found, not only those of {Embedder}:
29
+ #
30
+ # - factur-x.xml: Factur-X 1.0.06 to 1.08 / ZUGFeRD 2.2 to 2.4, §6.2;
31
+ # ZUGFeRD 2.1.1 Technical Supplement Part A, §2.2
32
+ # - xrechnung.xml: the same Factur-X §6.2 for the XRECHNUNG profile;
33
+ # ZUGFeRD 2.1.1 Technical Supplement Reference Profiles, §3.1
34
+ # - zugferd-invoice.xml: ZUGFeRD 2.0 §5.2; ZUGFeRD 2.1.1 Technical
35
+ # Supplement Part B, §2.2
36
+ # - ZUGFeRD-invoice.xml: ZUGFeRD 1.0 §7.2
37
+ #
38
+ # The specifications do not say whether case matters, so names are
39
+ # matched exactly, as written there.
40
+ INVOICE_FILENAMES = %w[factur-x.xml xrechnung.xml zugferd-invoice.xml ZUGFeRD-invoice.xml].freeze
41
+
42
+ DEFAULT_MAX_XML_BYTES = 10 * 1024 * 1024
43
+ DEFAULT_MAX_NAME_TREE_DEPTH = 32
44
+
45
+ ROOTS = {
46
+ ["urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100", "CrossIndustryInvoice"] => :cii,
47
+ ["urn:oasis:names:specification:ubl:schema:xsd:Invoice-2", "Invoice"] => :ubl,
48
+ ["urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2", "CreditNote"] => :ubl,
49
+ }.freeze
50
+
51
+ # The extracted attachment.
52
+ #
53
+ # @!attribute [r] xml
54
+ # @return [String] the embedded XML, byte for byte
55
+ # @!attribute [r] filename
56
+ # @return [String] the attachment name, e.g. "factur-x.xml"
57
+ # @!attribute [r] syntax
58
+ # @return [Symbol, nil] :cii or :ubl, nil for any other root element
59
+ Result = Struct.new(:xml, :filename, :syntax, keyword_init: true) do
60
+ # Parses the XML with {CII::Reader} or {UBL::Reader}.
61
+ #
62
+ # @return [Model::BillingDocument]
63
+ # @raise [UnsupportedSyntax] for any other root element, e.g. ZUGFeRD 1.0
64
+ def read
65
+ case syntax
66
+ when :cii then CII::Reader.new.read(xml)
67
+ when :ubl then UBL::Reader.new.read(xml)
68
+ else raise UnsupportedSyntax, unsupported_message
69
+ end
70
+ end
71
+
72
+ private
73
+
74
+ def unsupported_message
75
+ root = Nokogiri::XML(xml).root
76
+ if root.nil?
77
+ "#{filename} has no XML root element"
78
+ elsif root.name == "CrossIndustryDocument"
79
+ "#{filename} is a ZUGFeRD 1.0 invoice (CrossIndustryDocument), which zugpferd cannot read"
80
+ else
81
+ "#{filename} has root element #{root.name}; expected CII CrossIndustryInvoice or UBL Invoice/CreditNote"
82
+ end
83
+ end
84
+ end
85
+
86
+ # @param max_xml_bytes [Integer] largest decompressed attachment to accept
87
+ # @param max_name_tree_depth [Integer] deepest EmbeddedFiles name tree level to visit
88
+ def initialize(max_xml_bytes: DEFAULT_MAX_XML_BYTES, max_name_tree_depth: DEFAULT_MAX_NAME_TREE_DEPTH)
89
+ @max_xml_bytes = max_xml_bytes
90
+ @max_name_tree_depth = max_name_tree_depth
91
+ end
92
+
93
+ # @param pdf_path [String]
94
+ # @return [Result]
95
+ # @raise [PdfReaderNotFound] if the pdf-reader gem is not installed
96
+ # @raise [InvoiceNotFound] if no attachment has an invoice file name
97
+ # @raise [AmbiguousInvoice] if more than one has
98
+ # @raise [LimitExceeded] if a limit is hit
99
+ # @raise [ExtractError] if the PDF or the attachment cannot be read
100
+ def extract(pdf_path:)
101
+ raise ArgumentError, "PDF file not found: #{pdf_path}" unless File.exist?(pdf_path)
102
+
103
+ load_pdf_reader!
104
+ filename, xml = read_invoice(pdf_path)
105
+
106
+ Result.new(xml: xml, filename: filename, syntax: detect_syntax(xml))
107
+ end
108
+
109
+ private
110
+
111
+ # Kept apart from #extract: the rescue clause names pdf-reader
112
+ # constants, which only exist once the gem is loaded.
113
+ def read_invoice(pdf_path)
114
+ Document.new(::PDF::Reader::ObjectHash.new(pdf_path), @max_xml_bytes, @max_name_tree_depth).invoice
115
+ rescue ::PDF::Reader::MalformedPDFError, ::PDF::Reader::UnsupportedFeatureError => e
116
+ raise ExtractError, "Cannot read #{pdf_path}: #{e.message}"
117
+ end
118
+
119
+ def load_pdf_reader!
120
+ require "pdf/reader"
121
+ rescue LoadError
122
+ raise PdfReaderNotFound,
123
+ "Zugpferd::PDF::Extractor needs the pdf-reader gem. Add this line to your Gemfile:\n\n" \
124
+ " gem \"pdf-reader\", \"~> 2.16\""
125
+ end
126
+
127
+ def detect_syntax(xml)
128
+ root = Nokogiri::XML(xml).root
129
+ ROOTS[[root.namespace&.href, root.name]] if root
130
+ end
131
+
132
+ # Walks one PDF's object tree. A new one per call keeps Extractor
133
+ # free of per-file state.
134
+ class Document
135
+ # Compressed bytes fed to zlib per step. Deflate expands at most
136
+ # about 1032:1, so one step adds at most about 530 KB past the limit.
137
+ INFLATE_CHUNK_BYTES = 512
138
+ MAX_REFERENCE_HOPS = 16
139
+
140
+ def initialize(objects, max_xml_bytes, max_name_tree_depth)
141
+ @objects = objects
142
+ @max_xml_bytes = max_xml_bytes
143
+ @max_name_tree_depth = max_name_tree_depth
144
+ end
145
+
146
+ # @return [Array(String, String)] file name and XML
147
+ def invoice
148
+ filename, spec = find_invoice
149
+ [filename, read_embedded_file(spec, filename)]
150
+ end
151
+
152
+ private
153
+
154
+ # PDF/A-3 lists associated files in the catalog's /AF array. Only
155
+ # when that holds no invoice is the EmbeddedFiles name tree searched.
156
+ def find_invoice
157
+ catalog = dictionary(@objects.trailer[:Root])
158
+ matches = invoice_specs(pdf_array(catalog[:AF]))
159
+ matches = invoice_specs(name_tree_values(dictionary(catalog[:Names])[:EmbeddedFiles])) if matches.empty?
160
+
161
+ case matches.size
162
+ when 0 then raise InvoiceNotFound, "No invoice attachment (#{INVOICE_FILENAMES.join(", ")}) found"
163
+ when 1 then matches.first
164
+ else raise AmbiguousInvoice, "More than one invoice attachment: #{matches.map(&:first).join(", ")}"
165
+ end
166
+ end
167
+
168
+ def invoice_specs(refs)
169
+ specs = refs.map { |ref| dictionary(ref) }.uniq(&:object_id)
170
+ specs.filter_map do |spec|
171
+ name = file_spec_name(spec)
172
+ [name, spec] if INVOICE_FILENAMES.include?(name)
173
+ end
174
+ end
175
+
176
+ def file_spec_name(spec)
177
+ name = resolve(spec[:UF]) || resolve(spec[:F])
178
+ decode_text_string(name) if name.is_a?(String)
179
+ end
180
+
181
+ # /UF is a text string: UTF-16BE or UTF-8 with a byte order mark,
182
+ # otherwise PDFDocEncoding, which matches ASCII for file names.
183
+ def decode_text_string(string)
184
+ bytes = string.b
185
+ if bytes.start_with?("\xFE\xFF".b)
186
+ bytes.byteslice(2..).force_encoding(Encoding::UTF_16BE).encode(Encoding::UTF_8)
187
+ elsif bytes.start_with?("\xEF\xBB\xBF".b)
188
+ bytes.byteslice(3..).force_encoding(Encoding::UTF_8)
189
+ else
190
+ bytes.force_encoding(Encoding::UTF_8)
191
+ end
192
+ rescue EncodingError
193
+ nil
194
+ end
195
+
196
+ def name_tree_values(root)
197
+ values = []
198
+ visited = Set.new
199
+ pending = [[root, 0]]
200
+
201
+ until pending.empty?
202
+ ref, depth = pending.pop
203
+ next if ref.nil?
204
+
205
+ if depth > @max_name_tree_depth
206
+ raise LimitExceeded, "EmbeddedFiles name tree is deeper than #{@max_name_tree_depth} levels"
207
+ end
208
+ next if ref.is_a?(::PDF::Reader::Reference) && !visited.add?(ref)
209
+
210
+ node = dictionary(ref)
211
+ pdf_array(node[:Names]).each_slice(2) { |_key, value| values << value }
212
+ pdf_array(node[:Kids]).each { |kid| pending << [kid, depth + 1] }
213
+ end
214
+
215
+ values
216
+ end
217
+
218
+ def read_embedded_file(spec, filename)
219
+ embedded = dictionary(spec[:EF])
220
+ stream = resolve(embedded[:UF] || embedded[:F])
221
+ raise ExtractError, "#{filename} has no embedded file stream" unless stream.is_a?(::PDF::Reader::Stream)
222
+
223
+ decode_stream(stream, filename)
224
+ end
225
+
226
+ # pdf-reader inflates a whole stream in one call, so a size limit
227
+ # could only be checked afterwards. The attachment is inflated here
228
+ # in steps instead, to stop as soon as the limit is passed.
229
+ def decode_stream(stream, filename)
230
+ filters = list(stream.hash[:Filter]).map { |f| resolve(f) }
231
+
232
+ case filters
233
+ when []
234
+ check_size!(stream.data.bytesize, filename)
235
+ stream.data.b
236
+ when [:FlateDecode]
237
+ if predictor?(stream.hash[:DecodeParms])
238
+ raise ExtractError, "#{filename} uses a Flate predictor, which is not supported"
239
+ end
240
+
241
+ inflate(stream.data, filename)
242
+ else
243
+ raise ExtractError, "#{filename} uses filter #{filters.join(", ")}; only FlateDecode is supported"
244
+ end
245
+ end
246
+
247
+ def predictor?(decode_parms)
248
+ list(decode_parms).any? { |params| dictionary(params).fetch(:Predictor, 1).to_i > 1 }
249
+ end
250
+
251
+ def inflate(data, filename)
252
+ inflate_with(Zlib::MAX_WBITS + 32, data, filename)
253
+ rescue Zlib::DataError
254
+ # Some producers write raw deflate data without the zlib header.
255
+ begin
256
+ inflate_with(-Zlib::MAX_WBITS, data, filename)
257
+ rescue Zlib::DataError
258
+ raise ExtractError, "#{filename} is not valid Flate data"
259
+ end
260
+ end
261
+
262
+ def inflate_with(window_bits, data, filename)
263
+ zstream = Zlib::Inflate.new(window_bits)
264
+ output = +"".b
265
+ offset = 0
266
+
267
+ while offset < data.bytesize && !zstream.finished?
268
+ output << zstream.inflate(data.byteslice(offset, INFLATE_CHUNK_BYTES))
269
+ offset += INFLATE_CHUNK_BYTES
270
+ check_size!(output.bytesize, filename)
271
+ end
272
+ raise ExtractError, "#{filename} is truncated" unless zstream.finished?
273
+
274
+ output
275
+ ensure
276
+ # Closing a stream stopped early warns unless it is reset first.
277
+ zstream&.reset
278
+ zstream&.close
279
+ end
280
+
281
+ def check_size!(bytesize, filename)
282
+ return if bytesize <= @max_xml_bytes
283
+
284
+ raise LimitExceeded, "#{filename} is larger than #{@max_xml_bytes} bytes"
285
+ end
286
+
287
+ # Follows a reference until it reaches a direct object. Ghostscript,
288
+ # for one, writes /AF entries that point to an object holding
289
+ # another reference.
290
+ def resolve(value)
291
+ MAX_REFERENCE_HOPS.times do
292
+ return value unless value.is_a?(::PDF::Reader::Reference)
293
+
294
+ value = @objects.deref(value)
295
+ end
296
+ raise LimitExceeded, "Reference chain longer than #{MAX_REFERENCE_HOPS} hops"
297
+ end
298
+
299
+ def dictionary(ref)
300
+ value = resolve(ref)
301
+ value.is_a?(Hash) ? value : {}
302
+ end
303
+
304
+ def pdf_array(ref)
305
+ value = resolve(ref)
306
+ value.is_a?(Array) ? value : []
307
+ end
308
+
309
+ # A value that may be a single object or an array of them.
310
+ def list(ref)
311
+ value = resolve(ref)
312
+ value.is_a?(Array) ? value : [value].compact
313
+ end
314
+ end
315
+ private_constant :Document
316
+ end
317
+ end
318
+ end
data/lib/zugpferd/pdf.rb CHANGED
@@ -1 +1,2 @@
1
1
  require_relative "pdf/embedder"
2
+ require_relative "pdf/extractor"
@@ -21,6 +21,7 @@ module Zugpferd
21
21
  type_code: "cbc:InvoiceTypeCode",
22
22
  currency_code: "cbc:DocumentCurrencyCode",
23
23
  buyer_reference: "cbc:BuyerReference",
24
+ buyer_accounting_reference: "cbc:AccountingCost",
24
25
  customization_id: "cbc:CustomizationID",
25
26
  profile_id: "cbc:ProfileID",
26
27
  note: "cbc:Note",
@@ -42,8 +43,20 @@ module Zugpferd
42
43
  end_date: "cbc:EndDate",
43
44
  }.freeze
44
45
 
46
+ # Project reference (BT-11). CreditNote-2 has no cac:ProjectReference,
47
+ # credit notes carry it as additional document reference with type code 50
48
+ PROJECT_REFERENCE = "cac:ProjectReference/cbc:ID"
49
+ PROJECT_REFERENCE_TYPE_CODE = "50"
50
+ CREDIT_NOTE_PROJECT_REFERENCE =
51
+ "cac:AdditionalDocumentReference[cbc:DocumentTypeCode='#{PROJECT_REFERENCE_TYPE_CODE}']/cbc:ID"
52
+ # Contract reference (BT-12)
53
+ CONTRACT_REFERENCE = "cac:ContractDocumentReference/cbc:ID"
45
54
  # Purchase order reference (BT-13)
46
55
  ORDER_REFERENCE = "cac:OrderReference/cbc:ID"
56
+ # Written as BT-13 when only BT-14 is set, because cbc:ID is mandatory
57
+ ORDER_REFERENCE_NOT_APPLICABLE = "NA"
58
+ # Sales order reference (BT-14)
59
+ SALES_ORDER_REFERENCE = "cac:OrderReference/cbc:SalesOrderID"
47
60
 
48
61
  # Preceding invoice reference (BG-3)
49
62
  PRECEDING_INVOICE = "cac:BillingReference/cac:InvoiceDocumentReference"
@@ -92,6 +105,7 @@ module Zugpferd
92
105
  payment_means_code: "cbc:PaymentMeansCode",
93
106
  payment_id: "cbc:PaymentID",
94
107
  account_id: "cac:PayeeFinancialAccount/cbc:ID",
108
+ account_name: "cac:PayeeFinancialAccount/cbc:Name",
95
109
  card_account_id: "cac:CardAccount/cbc:PrimaryAccountNumberID",
96
110
  card_network_id: "cac:CardAccount/cbc:NetworkID",
97
111
  card_holder_name: "cac:CardAccount/cbc:HolderName",
@@ -48,7 +48,11 @@ module Zugpferd
48
48
  type_code: text(root, type_code_element),
49
49
  currency_code: text(root, INVOICE[:currency_code]),
50
50
  buyer_reference: text(root, INVOICE[:buyer_reference]),
51
- purchase_order_reference: text(root, ORDER_REFERENCE),
51
+ buyer_accounting_reference: text(root, INVOICE[:buyer_accounting_reference]),
52
+ purchase_order_reference: purchase_order_reference(root),
53
+ seller_order_reference: text(root, SALES_ORDER_REFERENCE),
54
+ contract_reference: text(root, CONTRACT_REFERENCE),
55
+ project_reference: text(root, @credit_note ? CREDIT_NOTE_PROJECT_REFERENCE : PROJECT_REFERENCE),
52
56
  customization_id: text(root, INVOICE[:customization_id]),
53
57
  profile_id: text(root, INVOICE[:profile_id]),
54
58
  note: text(root, INVOICE[:note]),
@@ -125,6 +129,7 @@ module Zugpferd
125
129
  payment_means_code: text(means_node, PAYMENT[:payment_means_code]),
126
130
  payment_id: text(means_node, PAYMENT[:payment_id]),
127
131
  account_id: text(means_node, PAYMENT[:account_id]),
132
+ account_name: text(means_node, PAYMENT[:account_name]),
128
133
  card_account_id: text(means_node, PAYMENT[:card_account_id]),
129
134
  card_network_id: text(means_node, PAYMENT[:card_network_id]),
130
135
  card_holder_name: text(means_node, PAYMENT[:card_holder_name]),
@@ -241,6 +246,11 @@ module Zugpferd
241
246
  )
242
247
  end
243
248
 
249
+ def purchase_order_reference(root)
250
+ ref = text(root, ORDER_REFERENCE)
251
+ ref unless ref == ORDER_REFERENCE_NOT_APPLICABLE
252
+ end
253
+
244
254
  def text(node, xpath)
245
255
  node.at_xpath(xpath, @ns)&.text
246
256
  end
@@ -49,11 +49,20 @@ module Zugpferd
49
49
  end
50
50
  xml["cbc"].Note doc.note if doc.note
51
51
  xml["cbc"].DocumentCurrencyCode doc.currency_code
52
+ xml["cbc"].AccountingCost doc.buyer_accounting_reference if doc.buyer_accounting_reference
52
53
  xml["cbc"].BuyerReference doc.buyer_reference if doc.buyer_reference
53
54
  build_invoice_period(xml, doc) if doc.invoicing_period_start_date || doc.invoicing_period_end_date
54
- build_order_reference(xml, doc) if doc.purchase_order_reference
55
+ build_order_reference(xml, doc) if doc.purchase_order_reference || doc.seller_order_reference
55
56
  doc.preceding_invoices.each { |pi| build_preceding_invoice(xml, pi) }
56
57
 
58
+ if doc.contract_reference
59
+ xml["cac"].ContractDocumentReference do
60
+ xml["cbc"].ID doc.contract_reference
61
+ end
62
+ end
63
+
64
+ build_project_reference(xml, doc.project_reference) if doc.project_reference
65
+
57
66
  build_supplier(xml, doc.seller, doc.payment_instructions) if doc.seller
58
67
  build_customer(xml, doc.buyer) if doc.buyer
59
68
  build_delivery(xml, doc) if doc.delivery_date || doc.deliver_to_address
@@ -165,9 +174,23 @@ module Zugpferd
165
174
  end
166
175
  end
167
176
 
177
+ def build_project_reference(xml, project_reference)
178
+ if @credit_note
179
+ xml["cac"].AdditionalDocumentReference do
180
+ xml["cbc"].ID project_reference
181
+ xml["cbc"].DocumentTypeCode PROJECT_REFERENCE_TYPE_CODE
182
+ end
183
+ else
184
+ xml["cac"].ProjectReference do
185
+ xml["cbc"].ID project_reference
186
+ end
187
+ end
188
+ end
189
+
168
190
  def build_order_reference(xml, doc)
169
191
  xml["cac"].OrderReference do
170
- xml["cbc"].ID doc.purchase_order_reference
192
+ xml["cbc"].ID doc.purchase_order_reference || ORDER_REFERENCE_NOT_APPLICABLE
193
+ xml["cbc"].SalesOrderID doc.seller_order_reference if doc.seller_order_reference
171
194
  end
172
195
  end
173
196
 
@@ -209,6 +232,7 @@ module Zugpferd
209
232
  if payment.account_id
210
233
  xml["cac"].PayeeFinancialAccount do
211
234
  xml["cbc"].ID payment.account_id
235
+ xml["cbc"].Name payment.account_name if payment.account_name
212
236
  end
213
237
  end
214
238
  if payment.mandate_reference
@@ -35,10 +35,10 @@ module Zugpferd
35
35
 
36
36
  def load_schema(key)
37
37
  @schema_cache[key] ||= begin
38
- path = File.join(@schemas_path, XSD_PATHS.fetch(key))
39
- Dir.chdir(File.dirname(path)) do
40
- Nokogiri::XML::Schema(File.read(File.basename(path)))
41
- end
38
+ # The document URL lets Nokogiri resolve relative imports without
39
+ # changing the working directory of the whole process.
40
+ path = File.expand_path(XSD_PATHS.fetch(key), @schemas_path)
41
+ Nokogiri::XML::Schema.from_document(Nokogiri::XML(File.read(path), path))
42
42
  end
43
43
  end
44
44
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: zugpferd
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.0
4
+ version: 0.9.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Alexander Zeitler
@@ -99,6 +99,7 @@ files:
99
99
  - lib/zugpferd/model/trade_party.rb
100
100
  - lib/zugpferd/pdf.rb
101
101
  - lib/zugpferd/pdf/embedder.rb
102
+ - lib/zugpferd/pdf/extractor.rb
102
103
  - lib/zugpferd/ubl/mapping.rb
103
104
  - lib/zugpferd/ubl/reader.rb
104
105
  - lib/zugpferd/ubl/writer.rb