Repository navigation
Expand file tree
/
Copy pathparse.go
More file actions
518 lines (473 loc) · 17.5 KB
/
Copy pathparse.go
File metadata and controls
518 lines (473 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package einvoice
import (
"bytes"
"encoding/xml"
"fmt"
"strings"
"time"
"github.com/shopspring/decimal"
)
// ParsedInvoice is the result of reading an e-invoice XML. It carries the
// canonical Invoice plus the document-level monetary totals and the VAT
// breakdown as stated in the document — parsing never recomputes amounts,
// so a consumer can compare stated vs. derived values for validation.
type ParsedInvoice struct {
Invoice
Totals Totals
// Taxes is the document-level VAT breakdown (BG-23).
Taxes []TaxBreakdown
// Format is the detected syntax: "cii" (ZUGFeRD / Factur-X / XRechnung
// CII) or "ubl" (XRechnung UBL, Peppol BIS).
Format string
// Guideline is the specification identifier (BT-24): the CII guideline
// URN or the UBL CustomizationID.
Guideline string
}
// Totals are the document-level amounts (BG-22) as stated in the XML.
type Totals struct {
LineTotal decimal.Decimal // BT-106
TaxBasisTotal decimal.Decimal // BT-109
TaxTotal decimal.Decimal // BT-110
GrandTotal decimal.Decimal // BT-112
DuePayable decimal.Decimal // BT-115
}
// TaxBreakdown is one VAT category subtotal (BG-23).
type TaxBreakdown struct {
CategoryCode string
Rate decimal.Decimal
Basis decimal.Decimal
Amount decimal.Decimal
}
// Parse reads an EN 16931 e-invoice XML in either CII or UBL syntax.
// It is lenient: fields absent from the document stay zero — callers that
// need guarantees should check the fields they rely on.
func Parse(data []byte) (*ParsedInvoice, error) {
root, err := rootLocalName(data)
if err != nil {
return nil, fmt.Errorf("einvoice: not an XML document: %w", err)
}
switch root {
case "CrossIndustryInvoice":
return parseCII(data)
case "Invoice", "CreditNote":
return parseUBL(data, root)
default:
return nil, fmt.Errorf("einvoice: unsupported root element %q", root)
}
}
func rootLocalName(data []byte) (string, error) {
dec := xml.NewDecoder(bytes.NewReader(data))
for {
tok, err := dec.Token()
if err != nil {
return "", err
}
if start, ok := tok.(xml.StartElement); ok {
return start.Name.Local, nil
}
}
}
// Decode structs use unqualified names on purpose: encoding/xml then
// matches by local name regardless of namespace prefix, which the
// serializer-side structs (literal "ram:" prefixes) cannot do.
type ciiDoc struct {
Guideline string `xml:"ExchangedDocumentContext>GuidelineSpecifiedDocumentContextParameter>ID"`
Number string `xml:"ExchangedDocument>ID"`
TypeCode string `xml:"ExchangedDocument>TypeCode"`
IssueDate ciiDate `xml:"ExchangedDocument>IssueDateTime>DateTimeString"`
Notes []string `xml:"ExchangedDocument>IncludedNote>Content"`
BuyerReference string `xml:"SupplyChainTradeTransaction>ApplicableHeaderTradeAgreement>BuyerReference"`
Seller ciiParty `xml:"SupplyChainTradeTransaction>ApplicableHeaderTradeAgreement>SellerTradeParty"`
Buyer ciiParty `xml:"SupplyChainTradeTransaction>ApplicableHeaderTradeAgreement>BuyerTradeParty"`
DeliveryDate ciiDate `xml:"SupplyChainTradeTransaction>ApplicableHeaderTradeDelivery>ActualDeliverySupplyChainEvent>OccurrenceDateTime>DateTimeString"`
Lines []ciiLine `xml:"SupplyChainTradeTransaction>IncludedSupplyChainTradeLineItem"`
Currency string `xml:"SupplyChainTradeTransaction>ApplicableHeaderTradeSettlement>InvoiceCurrencyCode"`
PaymentMeans []ciiPaymentMeans `xml:"SupplyChainTradeTransaction>ApplicableHeaderTradeSettlement>SpecifiedTradeSettlementPaymentMeans"`
TradeTaxes []ciiTradeTax `xml:"SupplyChainTradeTransaction>ApplicableHeaderTradeSettlement>ApplicableTradeTax"`
AllowanceCharges []ciiAllowanceCharge `xml:"SupplyChainTradeTransaction>ApplicableHeaderTradeSettlement>SpecifiedTradeAllowanceCharge"`
DueDate ciiDate `xml:"SupplyChainTradeTransaction>ApplicableHeaderTradeSettlement>SpecifiedTradePaymentTerms>DueDateDateTime>DateTimeString"`
Summation ciiSummation `xml:"SupplyChainTradeTransaction>ApplicableHeaderTradeSettlement>SpecifiedTradeSettlementHeaderMonetarySummation"`
}
type ciiAllowanceCharge struct {
IsCharge bool `xml:"ChargeIndicator>Indicator"`
Amount string `xml:"ActualAmount"`
Reason string `xml:"Reason"`
CategoryCode string `xml:"CategoryTradeTax>CategoryCode"`
Rate string `xml:"CategoryTradeTax>RateApplicablePercent"`
}
type ciiDate struct {
Value string `xml:",chardata"`
Format string `xml:"format,attr"`
}
type ciiParty struct {
Name string `xml:"Name"`
ContactPerson string `xml:"DefinedTradeContact>PersonName"`
ContactPhone string `xml:"DefinedTradeContact>TelephoneUniversalCommunication>CompleteNumber"`
ContactEmail string `xml:"DefinedTradeContact>EmailURIUniversalCommunication>URIID"`
Street string `xml:"PostalTradeAddress>LineOne"`
Postcode string `xml:"PostalTradeAddress>PostcodeCode"`
City string `xml:"PostalTradeAddress>CityName"`
Country string `xml:"PostalTradeAddress>CountryID"`
ElectronicURI struct {
Value string `xml:",chardata"`
SchemeID string `xml:"schemeID,attr"`
} `xml:"URIUniversalCommunication>URIID"`
TaxRegistrations []struct {
Value string `xml:",chardata"`
SchemeID string `xml:"schemeID,attr"`
} `xml:"SpecifiedTaxRegistration>ID"`
}
type ciiPaymentMeans struct {
TypeCode string `xml:"TypeCode"`
IBAN string `xml:"PayeePartyCreditorFinancialAccount>IBANID"`
AccountHolder string `xml:"PayeePartyCreditorFinancialAccount>AccountName"`
BIC string `xml:"PayeeSpecifiedCreditorFinancialInstitution>BICID"`
}
type ciiTradeTax struct {
Amount string `xml:"CalculatedAmount"`
Basis string `xml:"BasisAmount"`
CategoryCode string `xml:"CategoryCode"`
Rate string `xml:"RateApplicablePercent"`
}
type ciiSummation struct {
LineTotal string `xml:"LineTotalAmount"`
TaxBasisTotal string `xml:"TaxBasisTotalAmount"`
TaxTotal string `xml:"TaxTotalAmount"`
GrandTotal string `xml:"GrandTotalAmount"`
DuePayable string `xml:"DuePayableAmount"`
}
type ciiLine struct {
Name string `xml:"SpecifiedTradeProduct>Name"`
UnitPrice string `xml:"SpecifiedLineTradeAgreement>NetPriceProductTradePrice>ChargeAmount"`
Quantity ciiQty `xml:"SpecifiedLineTradeDelivery>BilledQuantity"`
TaxCategory string `xml:"SpecifiedLineTradeSettlement>ApplicableTradeTax>CategoryCode"`
TaxRate string `xml:"SpecifiedLineTradeSettlement>ApplicableTradeTax>RateApplicablePercent"`
ExemptionCode string `xml:"SpecifiedLineTradeSettlement>ApplicableTradeTax>ExemptionReasonCode"`
ExemptionReason string `xml:"SpecifiedLineTradeSettlement>ApplicableTradeTax>ExemptionReason"`
}
type ciiQty struct {
Value string `xml:",chardata"`
UnitCode string `xml:"unitCode,attr"`
}
func parseCII(data []byte) (*ParsedInvoice, error) {
var doc ciiDoc
if err := xml.Unmarshal(data, &doc); err != nil {
return nil, fmt.Errorf("einvoice: parse cii: %w", err)
}
p := &ParsedInvoice{Format: "cii", Guideline: strings.TrimSpace(doc.Guideline)}
p.Number = doc.Number
p.TypeCode = doc.TypeCode
p.IssueDate = parseCIIDate(doc.IssueDate)
p.DueDate = parseCIIDate(doc.DueDate)
p.DeliveryDate = parseCIIDate(doc.DeliveryDate)
p.Currency = doc.Currency
p.Note = strings.Join(doc.Notes, "\n")
p.BuyerReference = doc.BuyerReference
p.Seller = ciiPartyToParty(doc.Seller)
p.Buyer = ciiPartyToParty(doc.Buyer)
for _, pm := range doc.PaymentMeans {
applyPaymentMeans(&p.Payment, pm.TypeCode, pm.IBAN, pm.BIC, pm.AccountHolder)
}
for _, tt := range doc.TradeTaxes {
p.Taxes = append(p.Taxes, TaxBreakdown{
CategoryCode: tt.CategoryCode,
Rate: dec(tt.Rate),
Basis: dec(tt.Basis),
Amount: dec(tt.Amount),
})
}
for _, ac := range doc.AllowanceCharges {
p.AllowanceCharges = append(p.AllowanceCharges,
allowanceCharge(ac.Amount, ac.IsCharge, ac.Reason, ac.CategoryCode, ac.Rate))
}
p.Totals = Totals{
LineTotal: dec(doc.Summation.LineTotal),
TaxBasisTotal: dec(doc.Summation.TaxBasisTotal),
TaxTotal: dec(doc.Summation.TaxTotal),
GrandTotal: dec(doc.Summation.GrandTotal),
DuePayable: dec(doc.Summation.DuePayable),
}
for _, l := range doc.Lines {
p.LineItems = append(p.LineItems, LineItem{
Description: l.Name,
Quantity: dec(l.Quantity.Value),
UnitCode: l.Quantity.UnitCode,
UnitPrice: dec(l.UnitPrice),
TaxCategory: TaxCategory(l.TaxCategory),
TaxRate: dec(l.TaxRate),
ExemptionCode: VATExCode(l.ExemptionCode),
ExemptionReason: l.ExemptionReason,
})
}
return p, nil
}
func ciiPartyToParty(cp ciiParty) Party {
party := Party{
Name: cp.Name,
Street: cp.Street,
City: cp.City,
PostalCode: cp.Postcode,
CountryCode: cp.Country,
ElectronicAddress: cp.ElectronicURI.Value,
ElectronicAddressScheme: cp.ElectronicURI.SchemeID,
}
for _, reg := range cp.TaxRegistrations {
// "VA" is the VAT id (BT-31); "FC" (national tax number) is ignored.
if reg.SchemeID == "VA" {
party.VATID = reg.Value
}
}
if cp.ContactPerson != "" || cp.ContactPhone != "" || cp.ContactEmail != "" {
party.Contact = &Contact{Name: cp.ContactPerson, Phone: cp.ContactPhone, Email: cp.ContactEmail}
}
return party
}
// parseCIIDate handles the UNTDID 2379 formats used by EN 16931 ("102" =
// CCYYMMDD) plus ISO dates as a fallback for lenient real-world input.
func parseCIIDate(d ciiDate) time.Time {
v := strings.TrimSpace(d.Value)
if v == "" {
return time.Time{}
}
for _, layout := range []string{"20060102", "2006-01-02"} {
if t, err := time.Parse(layout, v); err == nil {
return t
}
}
return time.Time{}
}
type ublDoc struct {
CustomizationID string `xml:"CustomizationID"`
Number string `xml:"ID"`
IssueDate string `xml:"IssueDate"`
DueDate string `xml:"DueDate"`
InvoiceType string `xml:"InvoiceTypeCode"`
CreditNoteType string `xml:"CreditNoteTypeCode"`
Notes []string `xml:"Note"`
Currency string `xml:"DocumentCurrencyCode"`
BuyerReference string `xml:"BuyerReference"`
DeliveryDate string `xml:"Delivery>ActualDeliveryDate"`
Supplier ublParty `xml:"AccountingSupplierParty>Party"`
Customer ublParty `xml:"AccountingCustomerParty>Party"`
PaymentMeans []ublPaymentMeans `xml:"PaymentMeans"`
AllowanceCharges []ublAllowanceCharge `xml:"AllowanceCharge"`
TaxTotals []ublTaxTotal `xml:"TaxTotal"`
Total ublTotal `xml:"LegalMonetaryTotal"`
InvoiceLines []ublLine `xml:"InvoiceLine"`
CreditLines []ublLine `xml:"CreditNoteLine"`
}
type ublParty struct {
EndpointID struct {
Value string `xml:",chardata"`
SchemeID string `xml:"schemeID,attr"`
} `xml:"EndpointID"`
Name string `xml:"PartyName>Name"`
RegistrationName string `xml:"PartyLegalEntity>RegistrationName"`
Street string `xml:"PostalAddress>StreetName"`
City string `xml:"PostalAddress>CityName"`
Postcode string `xml:"PostalAddress>PostalZone"`
Country string `xml:"PostalAddress>Country>IdentificationCode"`
// A party may carry several PartyTaxScheme entries (VAT id plus the
// national tax number with scheme FC) — collected and filtered in
// ublPartyToParty, since a scalar field would keep the last one.
TaxSchemes []struct {
CompanyID string `xml:"CompanyID"`
Scheme string `xml:"TaxScheme>ID"`
} `xml:"PartyTaxScheme"`
ContactName string `xml:"Contact>Name"`
ContactPhone string `xml:"Contact>Telephone"`
ContactEmail string `xml:"Contact>ElectronicMail"`
}
type ublPaymentMeans struct {
Code string `xml:"PaymentMeansCode"`
// DueDate is the CreditNote location of the due date (UBL CreditNote
// has no top-level DueDate element).
DueDate string `xml:"PaymentDueDate"`
IBAN string `xml:"PayeeFinancialAccount>ID"`
AccountHolder string `xml:"PayeeFinancialAccount>Name"`
BIC string `xml:"PayeeFinancialAccount>FinancialInstitutionBranch>ID"`
}
type ublAllowanceCharge struct {
IsCharge bool `xml:"ChargeIndicator"`
Reason string `xml:"AllowanceChargeReason"`
Amount string `xml:"Amount"`
CategoryCode string `xml:"TaxCategory>ID"`
Rate string `xml:"TaxCategory>Percent"`
}
type ublTaxTotal struct {
Amount string `xml:"TaxAmount"`
Subtotals []struct {
Basis string `xml:"TaxableAmount"`
Amount string `xml:"TaxAmount"`
CategoryCode string `xml:"TaxCategory>ID"`
Rate string `xml:"TaxCategory>Percent"`
} `xml:"TaxSubtotal"`
}
type ublTotal struct {
LineTotal string `xml:"LineExtensionAmount"`
TaxBasisTotal string `xml:"TaxExclusiveAmount"`
GrandTotal string `xml:"TaxInclusiveAmount"`
DuePayable string `xml:"PayableAmount"`
}
type ublLine struct {
Name string `xml:"Item>Name"`
InvoicedQuantity ciiQty `xml:"InvoicedQuantity"`
CreditedQuantity ciiQty `xml:"CreditedQuantity"`
UnitPrice string `xml:"Price>PriceAmount"`
TaxCategory string `xml:"Item>ClassifiedTaxCategory>ID"`
TaxRate string `xml:"Item>ClassifiedTaxCategory>Percent"`
}
func parseUBL(data []byte, root string) (*ParsedInvoice, error) {
var doc ublDoc
if err := xml.Unmarshal(data, &doc); err != nil {
return nil, fmt.Errorf("einvoice: parse ubl: %w", err)
}
p := &ParsedInvoice{Format: "ubl", Guideline: strings.TrimSpace(doc.CustomizationID)}
p.Number = doc.Number
p.TypeCode = doc.InvoiceType
if root == "CreditNote" {
p.TypeCode = doc.CreditNoteType
if p.TypeCode == "" {
p.TypeCode = TypeCreditNote
}
}
if p.TypeCode == "" {
p.TypeCode = TypeCommercialInvoice
}
p.IssueDate = parseISODate(doc.IssueDate)
p.DueDate = parseISODate(doc.DueDate)
p.DeliveryDate = parseISODate(doc.DeliveryDate)
p.Currency = doc.Currency
p.Note = strings.Join(doc.Notes, "\n")
p.BuyerReference = doc.BuyerReference
p.Seller = ublPartyToParty(doc.Supplier)
p.Buyer = ublPartyToParty(doc.Customer)
for _, pm := range doc.PaymentMeans {
if p.DueDate.IsZero() {
p.DueDate = parseISODate(pm.DueDate)
}
applyPaymentMeans(&p.Payment, pm.Code, pm.IBAN, pm.BIC, pm.AccountHolder)
}
for _, ac := range doc.AllowanceCharges {
p.AllowanceCharges = append(p.AllowanceCharges,
allowanceCharge(ac.Amount, ac.IsCharge, ac.Reason, ac.CategoryCode, ac.Rate))
}
var taxTotal decimal.Decimal
for _, tt := range doc.TaxTotals {
// A second TaxTotal only restates the amount in the tax currency
// (BT-111) and never carries subtotals — summing is safe.
for _, sub := range tt.Subtotals {
p.Taxes = append(p.Taxes, TaxBreakdown{
CategoryCode: sub.CategoryCode,
Rate: dec(sub.Rate),
Basis: dec(sub.Basis),
Amount: dec(sub.Amount),
})
}
if taxTotal.IsZero() {
taxTotal = dec(tt.Amount)
}
}
p.Totals = Totals{
LineTotal: dec(doc.Total.LineTotal),
TaxBasisTotal: dec(doc.Total.TaxBasisTotal),
TaxTotal: taxTotal,
GrandTotal: dec(doc.Total.GrandTotal),
DuePayable: dec(doc.Total.DuePayable),
}
lines := doc.InvoiceLines
if root == "CreditNote" {
lines = doc.CreditLines
}
for _, l := range lines {
qty := l.InvoicedQuantity
if qty.Value == "" {
qty = l.CreditedQuantity
}
p.LineItems = append(p.LineItems, LineItem{
Description: l.Name,
Quantity: dec(qty.Value),
UnitCode: qty.UnitCode,
UnitPrice: dec(l.UnitPrice),
TaxCategory: TaxCategory(l.TaxCategory),
TaxRate: dec(l.TaxRate),
})
}
return p, nil
}
func ublPartyToParty(up ublParty) Party {
name := up.Name
if name == "" {
name = up.RegistrationName
}
var vatID string
for _, ts := range up.TaxSchemes {
if ts.Scheme == "VAT" {
vatID = ts.CompanyID
break
}
if vatID == "" {
vatID = ts.CompanyID
}
}
party := Party{
Name: name,
Street: up.Street,
City: up.City,
PostalCode: up.Postcode,
CountryCode: up.Country,
VATID: vatID,
ElectronicAddress: up.EndpointID.Value,
ElectronicAddressScheme: up.EndpointID.SchemeID,
}
if up.ContactName != "" || up.ContactPhone != "" || up.ContactEmail != "" {
party.Contact = &Contact{Name: up.ContactName, Phone: up.ContactPhone, Email: up.ContactEmail}
}
return party
}
func parseISODate(v string) time.Time {
v = strings.TrimSpace(v)
if v == "" {
return time.Time{}
}
t, err := time.Parse("2006-01-02", v)
if err != nil {
return time.Time{}
}
return t
}
// applyPaymentMeans folds one payment-means entry into Payment: the first
// entry with an IBAN becomes the primary account, further ones land in
// AdditionalAccounts (BG-17 is 0..n).
func applyPaymentMeans(p *Payment, code, iban, bic, holder string) {
if p.PaymentMeansCode == "" {
p.PaymentMeansCode = code
}
if iban == "" {
return
}
if p.IBAN == "" {
p.IBAN, p.BIC, p.AccountHolder = iban, bic, holder
return
}
p.AdditionalAccounts = append(p.AdditionalAccounts,
PaymentAccount{IBAN: iban, BIC: bic, AccountHolder: holder})
}
func allowanceCharge(amount string, isCharge bool, reason, category, rate string) AllowanceCharge {
return AllowanceCharge{
Amount: dec(amount),
IsCharge: isCharge,
TaxCategory: TaxCategory(category),
TaxRate: dec(rate),
Reason: reason,
}
}
// dec parses a decimal, mapping empty/malformed input to zero — parse
// leniency over hard failure, stated amounts are validated by consumers.
func dec(v string) decimal.Decimal {
d, err := decimal.NewFromString(strings.TrimSpace(v))
if err != nil {
return decimal.Decimal{}
}
return d
}