Repository navigation
Expand file tree
/
Copy pathparser_ubl.go
More file actions
994 lines (830 loc) · 35.3 KB
/
Copy pathparser_ubl.go
File metadata and controls
994 lines (830 loc) · 35.3 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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
package einvoice
import (
"encoding/base64"
"fmt"
"strings"
"time"
"github.com/speedata/cxpath"
"github.com/speedata/einvoice/rules"
)
// UBL 2.1 namespace URNs for Invoice and CreditNote documents
const (
nsUBLInvoice = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
nsUBLCreditNote = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2"
nsUBLCAC = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
nsUBLCBC = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
)
// parseTimeUBL parses ISO 8601 date format (YYYY-MM-DD) used in UBL documents.
func parseTimeUBL(ctx *cxpath.Context, path string) (time.Time, error) {
timestring := ctx.Eval(path).String()
if timestring == "" {
return time.Time{}, nil
}
parsedDate, err := time.Parse("2006-01-02", timestring)
if err != nil {
return parsedDate, fmt.Errorf("invalid date %q at %s: %w", timestring, path, err)
}
return parsedDate, nil
}
// parseUBL parses a UBL 2.1 Invoice or CreditNote document into an Invoice struct.
// Both document types are mapped to the same Invoice struct, differentiated by InvoiceTypeCode.
func parseUBL(ctx *cxpath.Context) (*Invoice, error) {
inv := &Invoice{SchemaType: UBL}
// Setup UBL namespaces
ctx.SetNamespace("inv", nsUBLInvoice)
ctx.SetNamespace("cn", nsUBLCreditNote)
ctx.SetNamespace("cac", nsUBLCAC)
ctx.SetNamespace("cbc", nsUBLCBC)
// The syntax-binding rules (rules.UBLSyntaxRules) use "ubl" for the
// Invoice namespace
ctx.SetNamespace("ubl", nsUBLInvoice)
// Get root element after namespace setup
root := ctx.Root()
// Determine document type (Invoice vs CreditNote)
localName := root.Eval("local-name()").String()
// Set namespace prefix based on document type
prefix := "inv:"
if localName == "CreditNote" {
prefix = "cn:"
}
// Parse all components
if err := parseUBLHeader(root, inv, prefix); err != nil {
return nil, fmt.Errorf("parse UBL header: %w", err)
}
if err := parseUBLParties(root, inv, prefix); err != nil {
return nil, fmt.Errorf("parse UBL parties: %w", err)
}
if err := parseUBLAllowanceCharge(root, inv, prefix); err != nil {
return nil, fmt.Errorf("parse UBL allowances/charges: %w", err)
}
if err := parseUBLTaxTotal(root, inv, prefix); err != nil {
return nil, fmt.Errorf("parse UBL tax total: %w", err)
}
if err := parseUBLMonetarySummation(root, inv, prefix); err != nil {
return nil, fmt.Errorf("parse UBL monetary summation: %w", err)
}
if err := parseUBLPaymentMeans(root, inv, prefix); err != nil {
return nil, fmt.Errorf("parse UBL payment means: %w", err)
}
if err := parseUBLPaymentTerms(root, inv, prefix); err != nil {
return nil, fmt.Errorf("parse UBL payment terms: %w", err)
}
if err := parseUBLLines(root, inv, prefix); err != nil {
return nil, fmt.Errorf("parse UBL lines: %w", err)
}
// Stash the tree for the UBL syntax-binding rules (UBL-SR-*, UBL-CR-*,
// UBL-DT-*); the first Validate() call evaluates them and releases the
// tree.
inv.syntaxRoot = root
inv.syntaxRules = rules.UBLSyntaxRules
return inv, nil
}
// parseUBLHeader parses the document header elements (BT-1 to BT-24, BG-1, BG-3, BG-14, BG-24).
func parseUBLHeader(root *cxpath.Context, inv *Invoice, prefix string) error {
// BT-24: CustomizationID (Specification identifier)
inv.GuidelineSpecifiedDocumentContextParameter = root.Eval("cbc:CustomizationID").String()
// BT-23: ProfileID (Business process type)
inv.BPSpecifiedDocumentContextParameter = root.Eval("cbc:ProfileID").String()
// BT-1: Invoice number
inv.InvoiceNumber = root.Eval("cbc:ID").String()
// BT-3: Invoice type code
inv.InvoiceTypeCode = CodeDocument(root.Eval("cbc:InvoiceTypeCode").Int())
if inv.InvoiceTypeCode == 0 {
// Try CreditNoteTypeCode for credit notes
inv.InvoiceTypeCode = CodeDocument(root.Eval("cbc:CreditNoteTypeCode").Int())
}
// If still 0 and this is a CreditNote document, default to 381
if inv.InvoiceTypeCode == 0 && prefix == "cn:" {
inv.InvoiceTypeCode = 381
}
// BT-2: Invoice date
var err error
inv.InvoiceDate, err = parseTimeUBL(root, "cbc:IssueDate")
if err != nil {
return err
}
// BT-72: Actual delivery date (optional, in cac:Delivery)
inv.OccurrenceDateTime, err = parseTimeUBL(root, "cac:Delivery/cbc:ActualDeliveryDate")
if err != nil {
return fmt.Errorf("invalid occurrence date time: %w", err)
}
// BT-5: Invoice currency
inv.InvoiceCurrencyCode = root.Eval("cbc:DocumentCurrencyCode").String()
// BT-6: Tax currency (optional)
inv.TaxCurrencyCode = root.Eval("cbc:TaxCurrencyCode").String()
// BT-10: Buyer reference (optional)
inv.BuyerReference = root.Eval("cbc:BuyerReference").String()
// BT-19: Accounting cost (Buyer accounting reference)
inv.ReceivableSpecifiedTradeAccountingAccount = root.Eval("cbc:AccountingCost").String()
// BT-13: Purchase order reference
inv.BuyerOrderReferencedDocument = root.Eval("cac:OrderReference/cbc:ID").String()
// BT-14: Sales order reference
inv.SellerOrderReferencedDocument = root.Eval("cac:OrderReference/cbc:SalesOrderID").String()
// BT-12: Contract document reference
inv.ContractReferencedDocument = root.Eval("cac:ContractDocumentReference/cbc:ID").String()
// BT-11: Project reference
inv.SpecifiedProcuringProjectID = root.Eval("cac:ProjectReference/cbc:ID").String()
// BT-16: Despatch advice reference
inv.DespatchAdviceReferencedDocument = root.Eval("cac:DespatchDocumentReference/cbc:ID").String()
// BT-15: Receiving advice reference
inv.ReceivingAdviceReferencedDocument = root.Eval("cac:ReceiptDocumentReference/cbc:ID").String()
// BG-1: Process notes
noteCount := root.Eval("count(cbc:Note)").Int()
if noteCount > 0 {
inv.Notes = make([]Note, 0, noteCount)
for note := range root.Each("cbc:Note") {
inv.Notes = append(inv.Notes, Note{
Text: note.String(),
// UBL doesn't typically have subject codes in Note elements
})
}
}
// BG-3: Preceding invoice references
refCount := root.Eval("count(cac:BillingReference/cac:InvoiceDocumentReference)").Int()
if refCount > 0 {
inv.InvoiceReferencedDocument = make([]ReferencedDocument, 0, refCount)
for ref := range root.Each("cac:BillingReference/cac:InvoiceDocumentReference") {
refDoc := ReferencedDocument{
ID: ref.Eval("cbc:ID").String(),
}
refDoc.Date, err = parseTimeUBL(ref, "cbc:IssueDate")
if err != nil {
return fmt.Errorf("invalid referenced document date: %w", err)
}
inv.InvoiceReferencedDocument = append(inv.InvoiceReferencedDocument, refDoc)
}
}
// BG-14: Invoice period (document level)
// BR-CO-19: Track BG-14 (INVOICING PERIOD) presence to validate later
if root.Eval("count(cac:InvoicePeriod)").Int() > 0 {
inv.hasBillingPeriodInXML = true
inv.BillingSpecifiedPeriodStart, err = parseTimeUBL(root, "cac:InvoicePeriod/cbc:StartDate")
if err != nil {
return fmt.Errorf("invalid billing period start date: %w", err)
}
inv.BillingSpecifiedPeriodEnd, err = parseTimeUBL(root, "cac:InvoicePeriod/cbc:EndDate")
if err != nil {
return fmt.Errorf("invalid billing period end date: %w", err)
}
}
// BG-24: Additional supporting documents
docCount := root.Eval("count(cac:AdditionalDocumentReference)").Int()
if docCount > 0 {
inv.AdditionalReferencedDocument = make([]Document, 0, docCount)
for doc := range root.Each("cac:AdditionalDocumentReference") {
// BT-11: In a CreditNote the project reference is an
// AdditionalDocumentReference with DocumentTypeCode 50.
if prefix == "cn:" && doc.Eval("cbc:DocumentTypeCode").String() == "50" {
if inv.SpecifiedProcuringProjectID == "" {
inv.SpecifiedProcuringProjectID = doc.Eval("cbc:ID").String()
}
continue
}
addDoc := Document{
IssuerAssignedID: doc.Eval("cbc:ID").String(),
TypeCode: doc.Eval("cbc:DocumentTypeCode").String(),
Name: doc.Eval("cbc:DocumentDescription").String(),
URIID: doc.Eval("cac:Attachment/cac:ExternalReference/cbc:URI").String(),
}
// BT-18-1: Scheme of the invoiced object identifier
if addDoc.TypeCode == "130" {
addDoc.ReferenceTypeCode = doc.Eval("cbc:ID/@schemeID").String()
}
// UBL has no type code for supporting documents (BG-24); use the
// one of the CII binding
if addDoc.TypeCode == "" {
addDoc.TypeCode = "916"
}
// Handle embedded binary object
binaryData := doc.Eval("cac:Attachment/cbc:EmbeddedDocumentBinaryObject").String()
if binaryData != "" {
addDoc.AttachmentMimeCode = doc.Eval("cac:Attachment/cbc:EmbeddedDocumentBinaryObject/@mimeCode").String()
addDoc.AttachmentFilename = doc.Eval("cac:Attachment/cbc:EmbeddedDocumentBinaryObject/@filename").String()
// Decode base64-encoded attachment data
data, err := base64.StdEncoding.DecodeString(binaryData)
if err != nil {
return fmt.Errorf("cannot decode attachment: %w", err)
}
addDoc.AttachmentBinaryObject = data
}
inv.AdditionalReferencedDocument = append(inv.AdditionalReferencedDocument, addDoc)
}
}
// BT-17: Tender or lot reference, stored like in CII as a referenced
// document with type code 50
if tenderRef := root.Eval("cac:OriginatorDocumentReference/cbc:ID").String(); tenderRef != "" {
inv.AdditionalReferencedDocument = append(inv.AdditionalReferencedDocument, Document{
IssuerAssignedID: tenderRef,
TypeCode: "50",
})
}
return nil
}
// parseUBLParties parses all party elements (BG-4, BG-7, BG-10, BG-11, BG-13).
func parseUBLParties(root *cxpath.Context, inv *Invoice, prefix string) error {
// BG-4: Seller (AccountingSupplierParty)
inv.Seller = parseUBLParty(root.Eval("cac:AccountingSupplierParty/cac:Party"), true)
// BG-7: Buyer (AccountingCustomerParty)
inv.Buyer = parseUBLParty(root.Eval("cac:AccountingCustomerParty/cac:Party"), true)
// BG-10: Payee (optional)
if root.Eval("count(cac:PayeeParty)").Int() > 0 {
payee := parseUBLParty(root.Eval("cac:PayeeParty"), false)
inv.PayeeTradeParty = &payee
}
// BT-90: Bank assigned creditor identifier, a party identifier with
// scheme SEPA of the seller or the payee
inv.CreditorReferenceID = root.Eval("(cac:AccountingSupplierParty/cac:Party/cac:PartyIdentification/cbc:ID[upper-case(@schemeID) = 'SEPA'] | cac:PayeeParty/cac:PartyIdentification/cbc:ID[upper-case(@schemeID) = 'SEPA'])[1]").String()
// BG-11: Seller tax representative (optional)
if root.Eval("count(cac:TaxRepresentativeParty)").Int() > 0 {
taxRep := parseUBLParty(root.Eval("cac:TaxRepresentativeParty"), false)
inv.SellerTaxRepresentativeTradeParty = &taxRep
}
// BG-13: Delivery information (optional)
if root.Eval("count(cac:Delivery)").Int() > 0 {
deliveryCtx := root.Eval("cac:Delivery[1]")
var shipTo Party
hasShipTo := false
// BT-70: Deliver to party name. Documents written by earlier versions
// of this library contain the complete party here, including the
// identifiers and the address.
if deliveryCtx.Eval("count(cac:DeliveryParty)").Int() > 0 {
shipTo = parseUBLParty(deliveryCtx.Eval("cac:DeliveryParty"), false)
hasShipTo = true
}
if deliveryCtx.Eval("count(cac:DeliveryLocation)").Int() > 0 {
locationCtx := deliveryCtx.Eval("cac:DeliveryLocation")
// BT-71: Deliver to location identifier
if id := locationCtx.Eval("cbc:ID").String(); id != "" {
if scheme := locationCtx.Eval("cbc:ID/@schemeID").String(); scheme != "" {
shipTo.GlobalID = append(shipTo.GlobalID, GlobalID{ID: id, Scheme: scheme})
} else {
shipTo.ID = append(shipTo.ID, id)
}
}
// BG-15: Deliver to address
if locationCtx.Eval("count(cac:Address)").Int() > 0 {
shipTo.PostalAddress = parseUBLAddress(locationCtx.Eval("cac:Address"))
}
hasShipTo = true
}
if hasShipTo {
inv.ShipTo = &shipTo
}
}
return nil
}
// parseUBLAddress parses a postal address (BG-5, BG-8, BG-12, BG-15).
// Takes a context already positioned at the address element.
func parseUBLAddress(addrCtx *cxpath.Context) *PostalAddress {
return &PostalAddress{
Line1: addrCtx.Eval("cbc:StreetName").String(),
Line2: addrCtx.Eval("cbc:AdditionalStreetName").String(),
Line3: addrCtx.Eval("cac:AddressLine/cbc:Line").String(),
City: addrCtx.Eval("cbc:CityName").String(),
PostcodeCode: addrCtx.Eval("cbc:PostalZone").String(),
CountrySubDivisionName: addrCtx.Eval("cbc:CountrySubentity").String(),
CountryID: addrCtx.Eval("cac:Country/cbc:IdentificationCode").String(),
}
}
// parseUBLParty parses a single party (reusable for Seller, Buyer, Payee, etc.).
// Takes a context already positioned at the party element. isLegalParty is
// true for the seller and the buyer, whose name (BT-27, BT-44) is the legal
// registration name and whose PartyName is the trading name (BT-28, BT-45).
func parseUBLParty(partyCtx *cxpath.Context, isLegalParty bool) Party {
party := Party{}
// Electronic address (BT-34, BT-49, BT-98)
party.URIUniversalCommunication = partyCtx.Eval("cbc:EndpointID").String()
party.URIUniversalCommunicationScheme = partyCtx.Eval("cbc:EndpointID/@schemeID").String()
// Party identification (BT-29, BT-46, BT-60, BT-71)
idCount := partyCtx.Eval("count(cac:PartyIdentification)").Int()
if idCount > 0 {
party.GlobalID = make([]GlobalID, 0, idCount)
party.ID = make([]string, 0, idCount)
for id := range partyCtx.Each("cac:PartyIdentification") {
idValue := id.Eval("cbc:ID").String()
idScheme := id.Eval("cbc:ID/@schemeID").String()
// BT-90 (bank assigned creditor identifier) is parsed in parseUBLParties
if strings.EqualFold(idScheme, "SEPA") {
continue
}
if idScheme != "" {
party.GlobalID = append(party.GlobalID, GlobalID{
ID: idValue,
Scheme: idScheme,
})
} else {
party.ID = append(party.ID, idValue)
}
}
}
// Party name (BT-27, BT-44, BT-59, BT-62, BT-70) and trading name (BT-28, BT-45)
partyName := partyCtx.Eval("cac:PartyName/cbc:Name").String()
registrationName := partyCtx.Eval("cac:PartyLegalEntity/cbc:RegistrationName").String()
tradingName := ""
if isLegalParty {
party.Name = registrationName
tradingName = partyName
if party.Name == "" {
// Fallback for documents without a registration name
party.Name = partyName
tradingName = ""
}
} else {
party.Name = partyName
if party.Name == "" {
party.Name = registrationName
}
}
// Postal address (BG-5, BG-8, BG-12)
if partyCtx.Eval("count(cac:PostalAddress)").Int() > 0 {
party.PostalAddress = parseUBLAddress(partyCtx.Eval("cac:PostalAddress"))
}
// Legal organization (BT-30, BT-47, BT-61) and trading name (BT-28, BT-45)
legalID := partyCtx.Eval("cac:PartyLegalEntity/cbc:CompanyID").String()
if legalID != "" || tradingName != "" {
party.SpecifiedLegalOrganization = &SpecifiedLegalOrganization{
ID: legalID,
Scheme: partyCtx.Eval("cac:PartyLegalEntity/cbc:CompanyID/@schemeID").String(),
TradingBusinessName: tradingName,
}
}
// Tax registration (BT-31, BT-32, BT-48, BT-63)
for taxScheme := range partyCtx.Each("cac:PartyTaxScheme") {
taxID := taxScheme.Eval("cbc:CompanyID").String()
scheme := taxScheme.Eval("cac:TaxScheme/cbc:ID").String()
switch scheme {
case "VAT":
party.VATaxRegistration = taxID
case "FC":
party.FCTaxRegistration = taxID
}
}
// Contact (BG-6, BG-9)
contactCount := partyCtx.Eval("count(cac:Contact)").Int()
if contactCount > 0 {
party.DefinedTradeContact = make([]DefinedTradeContact, 0, contactCount)
for contact := range partyCtx.Each("cac:Contact") {
dtc := DefinedTradeContact{
PersonName: contact.Eval("cbc:Name").String(),
DepartmentName: contact.Eval("cbc:Department").String(),
PhoneNumber: contact.Eval("cbc:Telephone").String(),
EMail: contact.Eval("cbc:ElectronicMail").String(),
}
party.DefinedTradeContact = append(party.DefinedTradeContact, dtc)
}
}
return party
}
// parseUBLAllowanceCharge parses document-level allowances and charges (BG-20, BG-21).
func parseUBLAllowanceCharge(root *cxpath.Context, inv *Invoice, prefix string) error {
acCount := root.Eval("count(cac:AllowanceCharge)").Int()
if acCount > 0 {
inv.SpecifiedTradeAllowanceCharge = make([]AllowanceCharge, 0, acCount)
for ac := range root.Each("cac:AllowanceCharge") {
chargeIndicator := ac.Eval("string(cbc:ChargeIndicator) = 'true'").Bool()
basisAmount, err := getDecimal(ac, "cbc:BaseAmount")
if err != nil {
return err
}
actualAmount, err := getDecimal(ac, "cbc:Amount")
if err != nil {
return err
}
calculationPercent, err := getDecimal(ac, "cbc:MultiplierFactorNumeric")
if err != nil {
return err
}
categoryTaxRate, err := getDecimal(ac, "cac:TaxCategory/cbc:Percent")
if err != nil {
return err
}
allowanceCharge := AllowanceCharge{
ChargeIndicator: chargeIndicator,
BasisAmount: basisAmount,
ActualAmount: actualAmount,
CalculationPercent: calculationPercent,
ReasonCode: ac.Eval("cbc:AllowanceChargeReasonCode").String(),
Reason: ac.Eval("cbc:AllowanceChargeReason").String(),
CategoryTradeTaxType: ac.Eval("cac:TaxCategory/cac:TaxScheme/cbc:ID").String(),
CategoryTradeTaxCategoryCode: ac.Eval("cac:TaxCategory/cbc:ID").String(),
CategoryTradeTaxRateApplicablePercent: categoryTaxRate,
hasCategoryTradeTaxRateApplicablePercent: ac.Eval("count(cac:TaxCategory/cbc:Percent)").Int() > 0,
}
inv.SpecifiedTradeAllowanceCharge = append(inv.SpecifiedTradeAllowanceCharge, allowanceCharge)
}
}
return nil
}
// parseUBLTaxTotal parses the tax breakdown (BG-23).
func parseUBLTaxTotal(root *cxpath.Context, inv *Invoice, prefix string) error {
var err error
// BT-110 and BT-111: Parse TaxTotal by matching currencyID (not position)
// EN 16931 specifies which currency each total must be in, regardless of XML order
for taxTotal := range root.Each("cac:TaxTotal") {
currency := taxTotal.Eval("cbc:TaxAmount/@currencyID").String()
if currency == "" {
currency = inv.InvoiceCurrencyCode // Default if missing
}
amount, err := getDecimal(taxTotal, "cbc:TaxAmount")
if err != nil {
return fmt.Errorf("invalid TaxAmount with currency %s: %w", currency, err)
}
// BT-110: Tax total in invoice currency (must match BT-5)
switch {
case currency == inv.InvoiceCurrencyCode:
inv.TaxTotalCurrency = currency
inv.TaxTotal = amount
case inv.TaxCurrencyCode != "" && currency == inv.TaxCurrencyCode:
// BT-111: Tax total in accounting currency (must match BT-6)
inv.TaxTotalAccountingCurrency = currency
inv.TaxTotalAccounting = amount
default:
// Track unexpected TaxTotal currencies for validation
inv.unexpectedTaxCurrencies = append(inv.unexpectedTaxCurrencies, currency)
}
}
// BG-23: VAT breakdown (TaxSubtotal elements)
taxSubtotalCount := root.Eval("count(cac:TaxTotal/cac:TaxSubtotal)").Int()
if taxSubtotalCount > 0 {
inv.TradeTaxes = make([]TradeTax, 0, taxSubtotalCount)
for subtotal := range root.Each("cac:TaxTotal/cac:TaxSubtotal") {
tradeTax := TradeTax{}
tradeTax.BasisAmount, err = getDecimal(subtotal, "cbc:TaxableAmount")
if err != nil {
return err
}
tradeTax.CalculatedAmount, err = getDecimal(subtotal, "cbc:TaxAmount")
if err != nil {
return err
}
tradeTax.TypeCode = subtotal.Eval("cac:TaxCategory/cac:TaxScheme/cbc:ID").String()
if tradeTax.TypeCode == "" {
tradeTax.TypeCode = "VAT" // Default to VAT
}
tradeTax.CategoryCode = subtotal.Eval("cac:TaxCategory/cbc:ID").String()
tradeTax.Percent, err = getDecimal(subtotal, "cac:TaxCategory/cbc:Percent")
if err != nil {
return err
}
tradeTax.ExemptionReason = subtotal.Eval("cac:TaxCategory/cbc:TaxExemptionReason").String()
tradeTax.ExemptionReasonCode = subtotal.Eval("cac:TaxCategory/cbc:TaxExemptionReasonCode").String()
inv.TradeTaxes = append(inv.TradeTaxes, tradeTax)
}
}
return nil
}
// parseUBLMonetarySummation parses the monetary totals (BT-106 to BT-115).
func parseUBLMonetarySummation(root *cxpath.Context, inv *Invoice, prefix string) error {
legalMonetaryTotal := root.Eval("cac:LegalMonetaryTotal")
// Track XML element presence for BR-12 through BR-15 validation
inv.hasLineTotalInXML = legalMonetaryTotal.Eval("count(cbc:LineExtensionAmount)").Int() > 0
inv.hasTaxBasisTotalInXML = legalMonetaryTotal.Eval("count(cbc:TaxExclusiveAmount)").Int() > 0
inv.hasGrandTotalInXML = legalMonetaryTotal.Eval("count(cbc:TaxInclusiveAmount)").Int() > 0
inv.hasDuePayableAmountInXML = legalMonetaryTotal.Eval("count(cbc:PayableAmount)").Int() > 0
var err error
// BT-106: Sum of Invoice line net amount
inv.LineTotal, err = getDecimal(legalMonetaryTotal, "cbc:LineExtensionAmount")
if err != nil {
return err
}
// BT-107: Sum of allowances on document level
inv.AllowanceTotal, err = getDecimal(legalMonetaryTotal, "cbc:AllowanceTotalAmount")
if err != nil {
return err
}
// BT-108: Sum of charges on document level
inv.ChargeTotal, err = getDecimal(legalMonetaryTotal, "cbc:ChargeTotalAmount")
if err != nil {
return err
}
// BT-109: Invoice total amount without VAT
inv.TaxBasisTotal, err = getDecimal(legalMonetaryTotal, "cbc:TaxExclusiveAmount")
if err != nil {
return err
}
// BT-112: Invoice total amount with VAT
inv.GrandTotal, err = getDecimal(legalMonetaryTotal, "cbc:TaxInclusiveAmount")
if err != nil {
return err
}
// BT-113: Paid amount
inv.TotalPrepaid, err = getDecimal(legalMonetaryTotal, "cbc:PrepaidAmount")
if err != nil {
return err
}
// BT-114: Rounding amount
inv.RoundingAmount, err = getDecimal(legalMonetaryTotal, "cbc:PayableRoundingAmount")
if err != nil {
return err
}
// BT-115: Amount due for payment
inv.DuePayableAmount, err = getDecimal(legalMonetaryTotal, "cbc:PayableAmount")
if err != nil {
return err
}
return nil
}
// parseUBLPaymentMeans parses payment means elements (BG-16, BG-17, BG-18, BG-19).
func parseUBLPaymentMeans(root *cxpath.Context, inv *Invoice, prefix string) error {
pmCount := root.Eval("count(cac:PaymentMeans)").Int()
if pmCount > 0 {
inv.PaymentMeans = make([]PaymentMeans, 0, pmCount)
for pm := range root.Each("cac:PaymentMeans") {
paymentMeans := PaymentMeans{
TypeCode: pm.Eval("cbc:PaymentMeansCode").Int(),
Information: pm.Eval("cbc:PaymentMeansCode/@name").String(),
}
// BT-82: Older documents written by this library used InstructionNote
if paymentMeans.Information == "" {
paymentMeans.Information = pm.Eval("cbc:InstructionNote").String()
}
// BT-83: Remittance information
inv.PaymentReference = pm.Eval("cbc:PaymentID").String()
// BG-17: Credit transfer (IBAN/BIC)
if pm.Eval("count(cac:PayeeFinancialAccount)").Int() > 0 {
paymentMeans.PayeePartyCreditorFinancialAccountIBAN = pm.Eval("cac:PayeeFinancialAccount/cbc:ID").String()
paymentMeans.PayeePartyCreditorFinancialAccountName = pm.Eval("cac:PayeeFinancialAccount/cbc:Name").String()
paymentMeans.PayeePartyCreditorFinancialAccountProprietaryID = pm.Eval("cac:PayeeFinancialAccount/cac:ID").String()
paymentMeans.PayeeSpecifiedCreditorFinancialInstitutionBIC = pm.Eval("cac:PayeeFinancialAccount/cac:FinancialInstitutionBranch/cbc:ID").String()
// BR-61: Track XML element presence to validate later.
// Per EN 16931 schematron, BR-61 test is "(ram:IBANID) or (ram:ProprietaryID)"
// which checks for element PRESENCE, not value. An empty element <cbc:ID/>
// satisfies the test because the element exists.
paymentMeans.hasPayeeAccountInXML = true
paymentMeans.hasPayeeIBANInXML = pm.Eval("count(cac:PayeeFinancialAccount/cbc:ID)").Int() > 0
paymentMeans.hasPayeeProprietaryIDInXML = pm.Eval("count(cac:PayeeFinancialAccount/cac:ID)").Int() > 0
}
// BG-18: Payment card information
if pm.Eval("count(cac:CardAccount)").Int() > 0 {
paymentMeans.ApplicableTradeSettlementFinancialCardID = pm.Eval("cac:CardAccount/cbc:PrimaryAccountNumberID").String()
paymentMeans.ApplicableTradeSettlementFinancialCardCardholderName = pm.Eval("cac:CardAccount/cbc:HolderName").String()
}
// BG-19: Direct debit
if pm.Eval("count(cac:PaymentMandate)").Int() > 0 {
paymentMeans.PayerPartyDebtorFinancialAccountIBAN = pm.Eval("cac:PaymentMandate/cac:PayerFinancialAccount/cbc:ID").String()
}
inv.PaymentMeans = append(inv.PaymentMeans, paymentMeans)
}
}
return nil
}
// parseUBLPaymentTerms parses payment terms (BT-20, BT-9, BT-89).
func parseUBLPaymentTerms(root *cxpath.Context, inv *Invoice, prefix string) error {
// BT-9: Payment due date at document level. An Invoice has cbc:DueDate,
// a CreditNote has cac:PaymentMeans/cbc:PaymentDueDate.
rootDueDate, err := parseTimeUBL(root, "cbc:DueDate")
if err != nil {
return err
}
if rootDueDate.IsZero() {
rootDueDate, err = parseTimeUBL(root, "(cac:PaymentMeans/cbc:PaymentDueDate)[1]")
if err != nil {
return err
}
}
// BT-89: Mandate reference identifier
mandateID := root.Eval("(cac:PaymentMeans/cac:PaymentMandate/cbc:ID[normalize-space(.) != ''])[1]").String()
ptCount := root.Eval("count(cac:PaymentTerms)").Int()
if ptCount > 0 {
inv.SpecifiedTradePaymentTerms = make([]SpecifiedTradePaymentTerms, 0, ptCount)
for pt := range root.Each("cac:PaymentTerms") {
paymentTerm := SpecifiedTradePaymentTerms{
Description: pt.Eval("cbc:Note").String(),
}
// BT-9: Payment due date (prefer element-level DueDate if present)
paymentTerm.DueDate, err = parseTimeUBL(pt, "cbc:PaymentDueDate")
if err != nil {
return err
}
// If not in PaymentTerms, use root-level DueDate
if paymentTerm.DueDate.IsZero() && !rootDueDate.IsZero() {
paymentTerm.DueDate = rootDueDate
}
// BT-89: Direct debit mandate identifier (older documents
// written by this library used PaymentTerms/PaymentMeansID)
paymentTerm.DirectDebitMandateID = pt.Eval("cbc:PaymentMeansID").String()
if len(inv.SpecifiedTradePaymentTerms) == 0 && mandateID != "" {
paymentTerm.DirectDebitMandateID = mandateID
}
inv.SpecifiedTradePaymentTerms = append(inv.SpecifiedTradePaymentTerms, paymentTerm)
}
} else if !rootDueDate.IsZero() || mandateID != "" {
// If there are no PaymentTerms elements but there's a document-level
// due date or mandate, create a single PaymentTerms entry for them
inv.SpecifiedTradePaymentTerms = []SpecifiedTradePaymentTerms{
{DueDate: rootDueDate, DirectDebitMandateID: mandateID},
}
}
return nil
}
// parseUBLLines parses all invoice line items (BG-25).
func parseUBLLines(root *cxpath.Context, inv *Invoice, prefix string) error {
// Determine line element and quantity element names based on document type
lineElementName := "cac:InvoiceLine"
quantityElementName := "cbc:InvoicedQuantity"
if prefix == "cn:" {
lineElementName = "cac:CreditNoteLine"
quantityElementName = "cbc:CreditedQuantity"
}
lineCount := root.Eval("count(" + lineElementName + ")").Int()
if lineCount > 0 {
inv.InvoiceLines = make([]InvoiceLine, 0, lineCount)
}
for lineItem := range root.Each(lineElementName) {
invoiceLine := InvoiceLine{}
var err error
// BT-126: Invoice line identifier
invoiceLine.LineID = lineItem.Eval("cbc:ID").String()
// BT-127: Invoice line note
invoiceLine.Note = lineItem.Eval("cbc:Note").String()
// BG-26: Invoice line period
// BR-CO-20: Track BG-26 (INVOICE LINE PERIOD) presence to validate later
if lineItem.Eval("count(cac:InvoicePeriod)").Int() > 0 {
invoiceLine.linePeriodPresent = true
invoiceLine.BillingSpecifiedPeriodStart, err = parseTimeUBL(lineItem, "cac:InvoicePeriod/cbc:StartDate")
if err != nil {
return fmt.Errorf("invalid line billing period start date for line %s: %w", invoiceLine.LineID, err)
}
invoiceLine.BillingSpecifiedPeriodEnd, err = parseTimeUBL(lineItem, "cac:InvoicePeriod/cbc:EndDate")
if err != nil {
return fmt.Errorf("invalid line billing period end date for line %s: %w", invoiceLine.LineID, err)
}
}
// BT-128: Invoice line object identifier
invoiceLine.AdditionalReferencedDocumentID = lineItem.Eval("cac:DocumentReference/cbc:ID").String()
invoiceLine.AdditionalReferencedDocumentTypeCode = lineItem.Eval("cac:DocumentReference/cbc:DocumentTypeCode").String()
// BT-132: Referenced purchase order line
invoiceLine.BuyerOrderReferencedDocument = lineItem.Eval("cac:OrderLineReference/cbc:LineID").String()
// BT-133: Invoice line Buyer accounting reference
invoiceLine.ReceivableSpecifiedTradeAccountingAccount = lineItem.Eval("cbc:AccountingCost").String()
// BT-129: Invoiced quantity (or Credited quantity for credit notes)
invoiceLine.BilledQuantity, err = getDecimal(lineItem, quantityElementName)
if err != nil {
return err
}
// BT-130: Invoiced quantity unit of measure
invoiceLine.BilledQuantityUnit = lineItem.Eval(quantityElementName + "/@unitCode").String()
// BT-131: Invoice line net amount
// Track XML element presence for BR-24 validation
invoiceLine.hasLineTotalInXML = lineItem.Eval("count(cbc:LineExtensionAmount)").Int() > 0
invoiceLine.Total, err = getDecimal(lineItem, "cbc:LineExtensionAmount")
if err != nil {
return err
}
// Parse item information
if err := parseUBLLineItem(lineItem, &invoiceLine); err != nil {
return err
}
// Parse price information
if err := parseUBLLinePrice(lineItem, &invoiceLine); err != nil {
return err
}
// BG-27: Line level allowances
// BG-28: Line level charges
lineACCount := lineItem.Eval("count(cac:AllowanceCharge)").Int()
if lineACCount > 0 {
// Pre-allocate both slices with full capacity since we don't know the split
invoiceLine.InvoiceLineAllowances = make([]AllowanceCharge, 0, lineACCount)
invoiceLine.InvoiceLineCharges = make([]AllowanceCharge, 0, lineACCount)
for ac := range lineItem.Each("cac:AllowanceCharge") {
chargeIndicator := ac.Eval("string(cbc:ChargeIndicator) = 'true'").Bool()
basisAmount, err := getDecimal(ac, "cbc:BaseAmount")
if err != nil {
return err
}
actualAmount, err := getDecimal(ac, "cbc:Amount")
if err != nil {
return err
}
calculationPercent, err := getDecimal(ac, "cbc:MultiplierFactorNumeric")
if err != nil {
return err
}
alc := AllowanceCharge{
ChargeIndicator: chargeIndicator,
BasisAmount: basisAmount,
ActualAmount: actualAmount,
CalculationPercent: calculationPercent,
ReasonCode: ac.Eval("cbc:AllowanceChargeReasonCode").String(),
Reason: ac.Eval("cbc:AllowanceChargeReason").String(),
}
if chargeIndicator {
invoiceLine.InvoiceLineCharges = append(invoiceLine.InvoiceLineCharges, alc)
} else {
invoiceLine.InvoiceLineAllowances = append(invoiceLine.InvoiceLineAllowances, alc)
}
}
}
// Parse line tax information
taxInfo := lineItem.Eval("cac:Item/cac:ClassifiedTaxCategory")
invoiceLine.TaxTypeCode = taxInfo.Eval("cac:TaxScheme/cbc:ID").String()
if invoiceLine.TaxTypeCode == "" {
invoiceLine.TaxTypeCode = "VAT" // Default to VAT
}
invoiceLine.TaxCategoryCode = taxInfo.Eval("cbc:ID").String()
invoiceLine.TaxRateApplicablePercent, err = getDecimal(taxInfo, "cbc:Percent")
if err != nil {
return err
}
invoiceLine.hasTaxRateApplicablePercent = taxInfo.Eval("count(cbc:Percent)").Int() > 0
inv.InvoiceLines = append(inv.InvoiceLines, invoiceLine)
}
return nil
}
// parseUBLLineItem parses item-specific information within a line.
func parseUBLLineItem(lineItem *cxpath.Context, invoiceLine *InvoiceLine) error {
item := lineItem.Eval("cac:Item")
// BT-153: Item name
invoiceLine.ItemName = item.Eval("cbc:Name").String()
// BT-154: Item description
invoiceLine.Description = item.Eval("cbc:Description").String()
// BT-155: Item Seller's identifier
invoiceLine.ArticleNumber = item.Eval("cac:SellersItemIdentification/cbc:ID").String()
// BT-156: Item Buyer's identifier
invoiceLine.ArticleNumberBuyer = item.Eval("cac:BuyersItemIdentification/cbc:ID").String()
// BT-157: Item standard identifier
invoiceLine.GlobalID = item.Eval("cac:StandardItemIdentification/cbc:ID").String()
invoiceLine.GlobalIDType = item.Eval("cac:StandardItemIdentification/cbc:ID/@schemeID").String()
// BT-158: Item classification identifier
classCount := item.Eval("count(cac:CommodityClassification)").Int()
if classCount > 0 {
invoiceLine.ProductClassification = make([]Classification, 0, classCount)
for class := range item.Each("cac:CommodityClassification") {
classification := Classification{
ClassCode: class.Eval("cbc:ItemClassificationCode").String(),
ListID: class.Eval("cbc:ItemClassificationCode/@listID").String(),
ListVersionID: class.Eval("cbc:ItemClassificationCode/@listVersionID").String(),
}
invoiceLine.ProductClassification = append(invoiceLine.ProductClassification, classification)
}
}
// BT-159: Item country of origin
invoiceLine.OriginTradeCountry = item.Eval("cac:OriginCountry/cbc:IdentificationCode").String()
// BG-32: Item attributes
attrCount := item.Eval("count(cac:AdditionalItemProperty)").Int()
if attrCount > 0 {
invoiceLine.Characteristics = make([]Characteristic, 0, attrCount)
for attr := range item.Each("cac:AdditionalItemProperty") {
characteristic := Characteristic{
Description: attr.Eval("cbc:Name").String(),
Value: attr.Eval("cbc:Value").String(),
}
invoiceLine.Characteristics = append(invoiceLine.Characteristics, characteristic)
}
}
return nil
}
// parseUBLLinePrice parses price information within a line.
func parseUBLLinePrice(lineItem *cxpath.Context, invoiceLine *InvoiceLine) error {
price := lineItem.Eval("cac:Price")
var err error
// BT-146: Item net price
// Track XML element presence for BR-26 validation
invoiceLine.hasNetPriceInXML = price.Eval("count(cbc:PriceAmount)").Int() > 0
invoiceLine.NetPrice, err = getDecimal(price, "cbc:PriceAmount")
if err != nil {
return err
}
// BT-149: Item price base quantity with unit code
invoiceLine.BasisQuantity, err = getDecimal(price, "cbc:BaseQuantity")
if err != nil {
return err
}
invoiceLine.BasisQuantityUnit = price.Eval("cbc:BaseQuantity/@unitCode").String()
// BT-148: Item gross price (price before allowances)
// UBL doesn't have a direct gross price field, but may have allowances on price
// For now, calculate from net price if allowances exist on price
priceACCount := price.Eval("count(cac:AllowanceCharge)").Int()
if priceACCount > 0 {
invoiceLine.AppliedTradeAllowanceCharge = make([]AllowanceCharge, 0, priceACCount)
for ac := range price.Each("cac:AllowanceCharge") {
chargeIndicator := ac.Eval("string(cbc:ChargeIndicator) = 'true'").Bool()
basisAmount, err := getDecimal(ac, "cbc:BaseAmount")
if err != nil {
return err
}
actualAmount, err := getDecimal(ac, "cbc:Amount")
if err != nil {
return err
}
calculationPercent, err := getDecimal(ac, "cbc:MultiplierFactorNumeric")
if err != nil {
return err
}
allowanceCharge := AllowanceCharge{
ChargeIndicator: chargeIndicator,
BasisAmount: basisAmount,
ActualAmount: actualAmount,
CalculationPercent: calculationPercent,
ReasonCode: ac.Eval("cbc:AllowanceChargeReasonCode").String(),
Reason: ac.Eval("cbc:AllowanceChargeReason").String(),
}
invoiceLine.AppliedTradeAllowanceCharge = append(invoiceLine.AppliedTradeAllowanceCharge, allowanceCharge)
// Calculate gross price if we have basis amount
if !basisAmount.IsZero() && invoiceLine.GrossPrice.IsZero() {
invoiceLine.GrossPrice = basisAmount
}
}
}
return nil
}