@financica/ubl 0.9.0 → 0.11.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.
package/README.md CHANGED
@@ -139,7 +139,23 @@ const xml = serializeUblDocument(doc);
139
139
  ```
140
140
 
141
141
  Set `documentType: "creditNote"` (with `precedingInvoiceId` referencing the
142
- original invoice) to emit a `CreditNote` instead. The build subpath also exports
142
+ original invoice) to emit a `CreditNote` instead.
143
+
144
+ For a document that is already paid, pass the settled gross amount as
145
+ `prepaidAmount` (BT-113) so `payableAmount` (BT-115) reports what is actually
146
+ outstanding rather than the full gross total:
147
+
148
+ ```ts
149
+ const { taxTotal, monetaryTotal } = buildTaxTotals(lines, { prepaidAmount: 121 });
150
+ // monetaryTotal.payableAmount => 0
151
+ ```
152
+
153
+ `buildTaxTotals` derives `payableAmount` as
154
+ `taxInclusiveAmount - prepaidAmount + payableRoundingAmount` (BR-CO-16) and does
155
+ not clamp it, so an overpayment shows up as a negative figure instead of being
156
+ silently hidden.
157
+
158
+ The build subpath also exports
143
159
  helpers such as `buildSupplierParty`, `buildTaxTotals`, `buildCompanyId`,
144
160
  `buildPdfAttachment`, and Peppol identifier utilities (`resolveVatEndpoint`,
145
161
  `parsePeppolEndpoint`, `listPeppolReceiverIdentifierCandidates`).
@@ -95,6 +95,13 @@ interface UblLine {
95
95
  lineExtensionAmount: number;
96
96
  /** `cac:Price/cbc:PriceAmount` (BT-146) — net unit price. */
97
97
  priceAmount: number;
98
+ /**
99
+ * `cac:Price/cbc:BaseQuantity` (BT-149) — the number of units `priceAmount`
100
+ * covers. Omitted means 1. Set it when the net doesn't divide evenly into
101
+ * cents, so `quantity × (priceAmount ÷ baseQuantity)` reproduces the line
102
+ * net exactly (PEPPOL-EN16931-R120); see `deriveUnitPrice`.
103
+ */
104
+ baseQuantity?: number;
98
105
  taxCategory: UblTaxCategory;
99
106
  }
100
107
  interface UblTaxSubtotal {
@@ -116,7 +123,17 @@ interface UblMonetaryTotal {
116
123
  taxExclusiveAmount: number;
117
124
  /** BT-112 — total with VAT. */
118
125
  taxInclusiveAmount: number;
119
- /** BT-115 — amount due for payment. */
126
+ /**
127
+ * BT-113 — sum of amounts paid in advance. **Gross (VAT-inclusive)**, since
128
+ * BR-CO-16 subtracts it directly from BT-112. Omitted when absent or zero.
129
+ */
130
+ prepaidAmount?: number;
131
+ /** BT-114 — rounding applied to the payable amount. Omitted when absent or zero. */
132
+ payableRoundingAmount?: number;
133
+ /**
134
+ * BT-115 — amount due for payment, i.e. the *outstanding* amount.
135
+ * BR-CO-16: `BT-115 = BT-112 − BT-113 + BT-114`.
136
+ */
120
137
  payableAmount: number;
121
138
  }
122
139
  /** An embedded supporting document (BG-24), e.g. the rendered PDF. */
@@ -367,6 +384,30 @@ declare const listPeppolReceiverIdentifierCandidates: (customer: {
367
384
  declare const roundCurrency: (value: number) => number;
368
385
  /** Convert an integer cent amount into a 2-decimal currency value. */
369
386
  declare const centsToDecimal: (cents: number) => number;
387
+ /** The `cac:Price` pair for a line: BT-146 and the optional BT-149. */
388
+ interface UnitPrice {
389
+ /** `cbc:PriceAmount` (BT-146). */
390
+ priceAmount: number;
391
+ /** `cbc:BaseQuantity` (BT-149) — the units `priceAmount` covers. Omitted = 1. */
392
+ baseQuantity?: number;
393
+ }
394
+ /**
395
+ * Derive the `cac:Price` for a line whose net total is authoritative.
396
+ *
397
+ * Peppol rule PEPPOL-EN16931-R120 checks
398
+ * `quantity × (priceAmount ÷ baseQuantity)` against the line net amount within
399
+ * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that
400
+ * whenever the division doesn't land on a cent: 940.00 over 14 units gives
401
+ * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and
402
+ * rejected as a fatal validation error.
403
+ *
404
+ * So the cent-rounded unit price is only used when it reproduces the net
405
+ * exactly. Otherwise the line is priced as a whole via BT-149 (`priceAmount` =
406
+ * the net, `baseQuantity` = the quantity), which is exact at any magnitude
407
+ * instead of merely within tolerance — the residual of a rounded unit price
408
+ * grows with quantity and would eventually breach 0.02 at any fixed precision.
409
+ */
410
+ declare const deriveUnitPrice: (netTotal: number, quantity: number) => UnitPrice;
370
411
  //#endregion
371
412
  //#region src/build/tax-category.d.ts
372
413
  /**
@@ -419,6 +460,16 @@ interface BuildTaxTotalsResult {
419
460
  taxTotal: UblTaxTotal;
420
461
  monetaryTotal: UblMonetaryTotal;
421
462
  }
463
+ interface BuildTaxTotalsOptions {
464
+ /**
465
+ * BT-113 — amount already paid, **gross (VAT-inclusive)**. Subtracted from
466
+ * BT-112 to derive the outstanding `payableAmount` (BR-CO-16). Pass the full
467
+ * gross total for a settled document so it reports a payable amount of 0.
468
+ */
469
+ prepaidAmount?: number;
470
+ /** BT-114 — rounding applied to the payable amount. */
471
+ payableRoundingAmount?: number;
472
+ }
422
473
  /**
423
474
  * Group lines by `(category, percent)` into a VAT breakdown and compute the
424
475
  * document monetary totals.
@@ -429,8 +480,13 @@ interface BuildTaxTotalsResult {
429
480
  * consistent and passes validation; it can differ by a cent from the figure a
430
481
  * payment processor reported, which is an unavoidable artifact of representing
431
482
  * a cents-rounded system as a rate-based VAT breakdown.
483
+ *
484
+ * `payableAmount` is derived per BR-CO-16 (`BT-112 − BT-113 + BT-114`) so the
485
+ * invariant holds by construction. The result is *not* clamped: a prepayment
486
+ * exceeding the total yields a negative payable amount, surfacing the upstream
487
+ * overpayment rather than hiding it.
432
488
  */
433
- declare const buildTaxTotals: (lines: UblLine[]) => BuildTaxTotalsResult;
489
+ declare const buildTaxTotals: (lines: UblLine[], options?: BuildTaxTotalsOptions) => BuildTaxTotalsResult;
434
490
  //#endregion
435
491
  //#region src/build/xml.d.ts
436
492
  /**
@@ -463,5 +519,5 @@ declare const el: (name: string, attrs?: XmlAttrs | null, content?: string | num
463
519
  /** Serialize a root element into a UTF-8 XML document string. */
464
520
  declare const serializeDocument: (root: XmlElement) => string;
465
521
  //#endregion
466
- export { type BuildTaxTotalsResult, COUNTRY_CODE_LIST_ID, CREDIT_NOTE_TYPE_CODE, type CustomerTaxIdentifiers, DEFAULT_UNIT_CODE, EXEMPT_TAXABILITY_REASONS, INVOICE_TYPE_CODE, NS_CAC, NS_CBC, NS_CREDIT_NOTE, NS_INVOICE, type SupplierVatStatus, type TaxAmountInfo, UBL_CUSTOMIZATION_ID, UBL_PROFILE_ID, type UblAddress, type UblAttachment, type UblCompanyId, type UblCustomer, type UblDocument, type UblEndpoint, type UblLine, type UblMonetaryTotal, type UblParty, type UblSupplier, type UblTaxCategory, type UblTaxSubtotal, type UblTaxTotal, VAT_TAX_SCHEME_ID, type XmlAttrs, type XmlElement, buildCompanyId, buildCustomerParty, buildPdfAttachment, buildSupplierParty, buildTaxTotals, centsToDecimal, el, extractCustomerTaxIdentifiers, listPeppolReceiverIdentifierCandidates, normalizeAddress, normalizeCompanyNumberForCountry, parsePeppolEndpoint, reconcileLinesToExclTotal, resolveCompanyIdScheme, resolveTaxCategoryFromTaxAmounts, resolveVatEndpoint, roundCurrency, sanitizeUblDocumentForAudit, serializeDocument, serializeUblDocument, taxCategoryFromReasonOrRate };
522
+ export { type BuildTaxTotalsOptions, type BuildTaxTotalsResult, COUNTRY_CODE_LIST_ID, CREDIT_NOTE_TYPE_CODE, type CustomerTaxIdentifiers, DEFAULT_UNIT_CODE, EXEMPT_TAXABILITY_REASONS, INVOICE_TYPE_CODE, NS_CAC, NS_CBC, NS_CREDIT_NOTE, NS_INVOICE, type SupplierVatStatus, type TaxAmountInfo, UBL_CUSTOMIZATION_ID, UBL_PROFILE_ID, type UblAddress, type UblAttachment, type UblCompanyId, type UblCustomer, type UblDocument, type UblEndpoint, type UblLine, type UblMonetaryTotal, type UblParty, type UblSupplier, type UblTaxCategory, type UblTaxSubtotal, type UblTaxTotal, type UnitPrice, VAT_TAX_SCHEME_ID, type XmlAttrs, type XmlElement, buildCompanyId, buildCustomerParty, buildPdfAttachment, buildSupplierParty, buildTaxTotals, centsToDecimal, deriveUnitPrice, el, extractCustomerTaxIdentifiers, listPeppolReceiverIdentifierCandidates, normalizeAddress, normalizeCompanyNumberForCountry, parsePeppolEndpoint, reconcileLinesToExclTotal, resolveCompanyIdScheme, resolveTaxCategoryFromTaxAmounts, resolveVatEndpoint, roundCurrency, sanitizeUblDocumentForAudit, serializeDocument, serializeUblDocument, taxCategoryFromReasonOrRate };
467
523
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/build/ubl/constants.ts","../../src/build/ubl/types.ts","../../src/build/ubl/serialize.ts","../../src/build/party.ts","../../src/build/address.ts","../../src/build/attachment.ts","../../src/build/identifiers.ts","../../src/build/numeric.ts","../../src/build/tax-category.ts","../../src/build/tax-totals.ts","../../src/build/xml.ts"],"mappings":";;;cAGa;;cAIA;;cAGA;;cAEA;;cAGA;;cAGA;;cAGA;cAEA;cACA;cAEA;cAEA;;;;;;;;;;;UCnBI;;EAEhB;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;UAIgB;EAChB;EACA;;;UAIgB;EAChB;;EAEA;;UAGgB;;EAEhB,UAAU;;EAEV;EACA,SAAS;;EAET;;EAEA;;EAEA,WAAW;;;;;;;;;;;;UAaK;EAChB;EACA;;EAEA;;UAGgB;;EAEhB;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA,aAAa;;UAGG;;EAEhB;;EAEA;EACA,UAAU;;UAGM;;EAEhB;EACA,WAAW;;UAGK;;EAEhB;;EAEA;;EAEA;;EAEA;;;UAIgB;;EAEhB;;EAEA;;EAEA;;EAEA;;UAGgB;EAChB;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA,UAAU;EACV,UAAU;EACV,OAAO;EACP,UAAU;EACV,eAAe;EACf,aAAa;;;;;cCaD,uBAAoB,KAAS;;;;;;;;;;;;;;KC3I9B;;;;;;;UAQK;;EAEhB;;EAEA;;;;;EAKA;;EAEA;;EAEA;;EAEA,WAAW;;EAEX;;;cAIY,qBAAkB,UAAc,gBAAc;;;;;;;;UAsB1C;;EAEhB;;EAEA,SAAS;;;;;;;EAOT;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;cAcY,qBAAkB,UACpB,aAAW,mBACF,uBACjB;;;;;;;;;;;;cCrFU,mBAAgB,kBACZ,oCACkB,iCAEhC;;;;;;;;cCfU,qBAAkB;EAC9B;EACA,OAAO;;EAEP;MACG;;;;;cAWS,8BAA2B,KAAS,gBAAc;;;;;;;cCLlD,mCAAgC,wCACN;;;;;;;;;;;;;cAqB1B,yBAAsB;EAClC;EACA;;;;;;;cA0BY,iBAAc;EAC1B;EACA;MACG;;;;;;;;;;;cAkFS,qBAAkB;EAC9B;EACA;MACG;;;;;;;;cA2BS,sBAAmB,wCAE7B;UAWc;EAChB;EACA;EACA;EACA;;;;;;;;;cAaY,gCAA6B,oBAEvC;;;;;;;;;;;;;;;;;;;;cAwDU,yCAAsC;EAEjD;EACA;EACA;EACA;GACA;;;;cCpRW,gBAAa;;cAIb,iBAAc;;;;;;;cCCd,2BAAyB;UAsBrB;EAChB;EACA;EACA;;;;;;;;;;;;;cAoBY,8BAA2B;EACvC;EACA;EACA;MACG;;;;;;;cA6CS,mCAAgC,YAChC,iBAAe,iBAEzB;;;;;;;;;;;;;cCpFU,4BAAyB,OAC9B,WAAS,sCAEd;UA8Bc;EAChB,UAAU;EACV,eAAe;;;;;;;;;;;;;cAcH,iBAAc,OAAW,cAAY;;;;;;;;;;;KC3DtC,WAAW;UAEN;EAChB;EACA,QAAQ;;EAER;;EAEA,WAAW;;;KAIP,YAAY;;;;;;;;cASJ,KAAE,cACF,QACJ,iBAAe,mCACY,gBACjC;;cA4CU,oBAAiB,MAAU"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/build/ubl/constants.ts","../../src/build/ubl/types.ts","../../src/build/ubl/serialize.ts","../../src/build/party.ts","../../src/build/address.ts","../../src/build/attachment.ts","../../src/build/identifiers.ts","../../src/build/num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AAc;EAC1B;EACA;MACG;;;;;;;;;;;cAkFS,qBAAkB;EAC9B;EACA;MACG;;;;;;;;cA2BS,sBAAmB,wCAE7B;UAWc;EAChB;EACA;EACA;EACA;;;;;;;;;cAaY,gCAA6B,oBAEvC;;;;;;;;;;;;;;;;;;;;cAwDU,yCAAsC;EAEjD;EACA;EACA;EACA;GACA;;;;cCpRW,gBAAa;;cAIb,iBAAc;;UAGV;;EAEhB;;EAEA;;;;;;;;;;;;;;;;;;cAmBY,kBAAe,kBAAoB,qBAAqB;;;;;;;cCzBxD,2BAAyB;UAsBrB;EAChB;EACA;EACA;;;;;;;;;;;;;cAoBY,8BAA2B;EACvC;EACA;EACA;MACG;;;;;;;cA6CS,mCAAgC,YAChC,iBAAe,iBAEzB;;;;;;;;;;;;;cCpFU,4BAAyB,OAC9B,WAAS,sCAEd;UAoCc;EAChB,UAAU;EACV,eAAe;;UAGC;;;;;;EAMhB;;EAEA;;;;;;;;;;;;;;;;;;cAmBY,iBAAc,OACnB,WAAS,UACN,0BACR;;;;;;;;;;;KCpFS,WAAW;UAEN;EAChB;EACA,QAAQ;;EAER;;EAEA,WAAW;;;KAIP,YAAY;;;;;;;;cASJ,KAAE,cACF,QACJ,iBAAe,mCACY,gBACjC;;cA4CU,oBAAiB,MAAU"}
@@ -98,6 +98,22 @@ const taxSubtotal = (subtotal, currency) => el("cac:TaxSubtotal", null, [
98
98
  money("cbc:TaxAmount", subtotal.taxAmount, currency),
99
99
  taxCategory("cac:TaxCategory", subtotal.category)
100
100
  ]);
101
+ /**
102
+ * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`
103
+ * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`
104
+ * — emitting them after it produces schema-invalid XML.
105
+ */
106
+ const legalMonetaryTotalChildren = (doc) => {
107
+ const { currency, monetaryTotal: total } = doc;
108
+ return [
109
+ money("cbc:LineExtensionAmount", total.lineExtensionAmount, currency),
110
+ money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount, currency),
111
+ money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount, currency),
112
+ total.prepaidAmount ? money("cbc:PrepaidAmount", total.prepaidAmount, currency) : null,
113
+ total.payableRoundingAmount ? money("cbc:PayableRoundingAmount", total.payableRoundingAmount, currency) : null,
114
+ money("cbc:PayableAmount", total.payableAmount, currency)
115
+ ].filter((child) => Boolean(child));
116
+ };
101
117
  const line = (source, currency, documentType) => {
102
118
  const lineElementName = documentType === "creditNote" ? "cac:CreditNoteLine" : "cac:InvoiceLine";
103
119
  const quantityElementName = documentType === "creditNote" ? "cbc:CreditedQuantity" : "cbc:InvoicedQuantity";
@@ -106,7 +122,7 @@ const line = (source, currency, documentType) => {
106
122
  el(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),
107
123
  money("cbc:LineExtensionAmount", source.lineExtensionAmount, currency),
108
124
  el("cac:Item", null, [el("cbc:Name", null, source.name), taxCategory("cac:ClassifiedTaxCategory", source.taxCategory)]),
109
- el("cac:Price", null, [money("cbc:PriceAmount", source.priceAmount, currency)])
125
+ el("cac:Price", null, [money("cbc:PriceAmount", source.priceAmount, currency), source.baseQuantity != null ? el("cbc:BaseQuantity", { unitCode: source.unitCode }, String(source.baseQuantity)) : null])
110
126
  ]);
111
127
  };
112
128
  const attachmentReference = (attachment) => el("cac:AdditionalDocumentReference", null, [el("cbc:ID", null, attachment.id), el("cac:Attachment", null, [el("cbc:EmbeddedDocumentBinaryObject", {
@@ -135,12 +151,7 @@ const serializeUblDocument = (doc) => {
135
151
  el("cac:AccountingSupplierParty", null, [party(doc.supplier)]),
136
152
  el("cac:AccountingCustomerParty", null, [party(doc.customer)]),
137
153
  el("cac:TaxTotal", null, [money("cbc:TaxAmount", doc.taxTotal.taxAmount, doc.currency), ...doc.taxTotal.subtotals.map((subtotal) => taxSubtotal(subtotal, doc.currency))]),
138
- el("cac:LegalMonetaryTotal", null, [
139
- money("cbc:LineExtensionAmount", doc.monetaryTotal.lineExtensionAmount, doc.currency),
140
- money("cbc:TaxExclusiveAmount", doc.monetaryTotal.taxExclusiveAmount, doc.currency),
141
- money("cbc:TaxInclusiveAmount", doc.monetaryTotal.taxInclusiveAmount, doc.currency),
142
- money("cbc:PayableAmount", doc.monetaryTotal.payableAmount, doc.currency)
143
- ]),
154
+ el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
144
155
  ...doc.lines.map((source) => line(source, doc.currency, doc.documentType))
145
156
  ];
146
157
  return serializeDocument(el(rootName, {
@@ -517,6 +528,31 @@ const sanitizeUblDocumentForAudit = (doc) => {
517
528
  const roundCurrency = (value) => Math.round((value + Number.EPSILON) * 100) / 100;
518
529
  /** Convert an integer cent amount into a 2-decimal currency value. */
519
530
  const centsToDecimal = (cents) => roundCurrency(cents / 100);
531
+ /**
532
+ * Derive the `cac:Price` for a line whose net total is authoritative.
533
+ *
534
+ * Peppol rule PEPPOL-EN16931-R120 checks
535
+ * `quantity × (priceAmount ÷ baseQuantity)` against the line net amount within
536
+ * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that
537
+ * whenever the division doesn't land on a cent: 940.00 over 14 units gives
538
+ * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and
539
+ * rejected as a fatal validation error.
540
+ *
541
+ * So the cent-rounded unit price is only used when it reproduces the net
542
+ * exactly. Otherwise the line is priced as a whole via BT-149 (`priceAmount` =
543
+ * the net, `baseQuantity` = the quantity), which is exact at any magnitude
544
+ * instead of merely within tolerance — the residual of a rounded unit price
545
+ * grows with quantity and would eventually breach 0.02 at any fixed precision.
546
+ */
547
+ const deriveUnitPrice = (netTotal, quantity) => {
548
+ const units = quantity > 0 ? quantity : 1;
549
+ const perUnit = roundCurrency(netTotal / units);
550
+ if (roundCurrency(perUnit * units) === roundCurrency(netTotal)) return { priceAmount: perUnit };
551
+ return {
552
+ priceAmount: roundCurrency(netTotal),
553
+ baseQuantity: units
554
+ };
555
+ };
520
556
  //#endregion
521
557
  //#region src/build/tax-category.ts
522
558
  /**
@@ -638,10 +674,12 @@ const reconcileLinesToExclTotal = (lines, authoritativeTotalExclVat) => {
638
674
  return lines.map((line, idx) => {
639
675
  if (idx !== largestIdx) return line;
640
676
  const adjusted = roundCurrency(line.lineExtensionAmount + diff);
677
+ const { priceAmount, baseQuantity } = deriveUnitPrice(adjusted, line.quantity);
641
678
  return {
642
679
  ...line,
643
680
  lineExtensionAmount: adjusted,
644
- priceAmount: roundCurrency(adjusted / Math.max(line.quantity, 1))
681
+ priceAmount,
682
+ baseQuantity
645
683
  };
646
684
  });
647
685
  };
@@ -656,8 +694,13 @@ const categoryKey = (category) => `${category.id}:${category.percent}`;
656
694
  * consistent and passes validation; it can differ by a cent from the figure a
657
695
  * payment processor reported, which is an unavoidable artifact of representing
658
696
  * a cents-rounded system as a rate-based VAT breakdown.
697
+ *
698
+ * `payableAmount` is derived per BR-CO-16 (`BT-112 − BT-113 + BT-114`) so the
699
+ * invariant holds by construction. The result is *not* clamped: a prepayment
700
+ * exceeding the total yields a negative payable amount, surfacing the upstream
701
+ * overpayment rather than hiding it.
659
702
  */
660
- const buildTaxTotals = (lines) => {
703
+ const buildTaxTotals = (lines, options) => {
661
704
  const groups = /* @__PURE__ */ new Map();
662
705
  for (const line of lines) {
663
706
  const key = categoryKey(line.taxCategory);
@@ -676,6 +719,9 @@ const buildTaxTotals = (lines) => {
676
719
  const lineExtensionAmount = roundCurrency(lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0));
677
720
  const taxAmount = roundCurrency(subtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0));
678
721
  const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
722
+ const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
723
+ const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
724
+ const payableAmount = roundCurrency(taxInclusiveAmount - prepaidAmount + payableRoundingAmount);
679
725
  return {
680
726
  taxTotal: {
681
727
  taxAmount,
@@ -685,11 +731,13 @@ const buildTaxTotals = (lines) => {
685
731
  lineExtensionAmount,
686
732
  taxExclusiveAmount: lineExtensionAmount,
687
733
  taxInclusiveAmount,
688
- payableAmount: taxInclusiveAmount
734
+ ...prepaidAmount ? { prepaidAmount } : {},
735
+ ...payableRoundingAmount ? { payableRoundingAmount } : {},
736
+ payableAmount
689
737
  }
690
738
  };
691
739
  };
692
740
  //#endregion
693
- export { COUNTRY_CODE_LIST_ID, CREDIT_NOTE_TYPE_CODE, DEFAULT_UNIT_CODE, EXEMPT_TAXABILITY_REASONS, INVOICE_TYPE_CODE, NS_CAC, NS_CBC, NS_CREDIT_NOTE, NS_INVOICE, UBL_CUSTOMIZATION_ID, UBL_PROFILE_ID, VAT_TAX_SCHEME_ID, buildCompanyId, buildCustomerParty, buildPdfAttachment, buildSupplierParty, buildTaxTotals, centsToDecimal, el, extractCustomerTaxIdentifiers, listPeppolReceiverIdentifierCandidates, normalizeAddress, normalizeCompanyNumberForCountry, parsePeppolEndpoint, reconcileLinesToExclTotal, resolveCompanyIdScheme, resolveTaxCategoryFromTaxAmounts, resolveVatEndpoint, roundCurrency, sanitizeUblDocumentForAudit, serializeDocument, serializeUblDocument, taxCategoryFromReasonOrRate };
741
+ export { COUNTRY_CODE_LIST_ID, CREDIT_NOTE_TYPE_CODE, DEFAULT_UNIT_CODE, EXEMPT_TAXABILITY_REASONS, INVOICE_TYPE_CODE, NS_CAC, NS_CBC, NS_CREDIT_NOTE, NS_INVOICE, UBL_CUSTOMIZATION_ID, UBL_PROFILE_ID, VAT_TAX_SCHEME_ID, buildCompanyId, buildCustomerParty, buildPdfAttachment, buildSupplierParty, buildTaxTotals, centsToDecimal, deriveUnitPrice, el, extractCustomerTaxIdentifiers, listPeppolReceiverIdentifierCandidates, normalizeAddress, normalizeCompanyNumberForCountry, parsePeppolEndpoint, reconcileLinesToExclTotal, resolveCompanyIdScheme, resolveTaxCategoryFromTaxAmounts, resolveVatEndpoint, roundCurrency, sanitizeUblDocumentForAudit, serializeDocument, serializeUblDocument, taxCategoryFromReasonOrRate };
694
742
 
695
743
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/build/ubl/constants.ts","../../src/build/xml.ts","../../src/build/ubl/serialize.ts","../../src/build/utils.ts","../../src/build/address.ts","../../src/build/identifiers.ts","../../src/build/party.ts","../../src/build/attachment.ts","../../src/build/numeric.ts","../../src/build/tax-category.ts","../../src/build/tax-totals.ts"],"sourcesContent":["/** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */\n\n/** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */\nexport const UBL_CUSTOMIZATION_ID =\n\t\"urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0\";\n\n/** Peppol BIS Billing 3.0 process (BT-23). */\nexport const UBL_PROFILE_ID = \"urn:fdc:peppol.eu:2017:poacc:billing:01:1.0\";\n\n/** UNTDID 1001 — commercial invoice. */\nexport const INVOICE_TYPE_CODE = \"380\";\n/** UNTDID 1001 — credit note. */\nexport const CREDIT_NOTE_TYPE_CODE = \"381\";\n\n/** UN/ECE Recommendation 20 — \"one / piece\" (the default line unit). */\nexport const DEFAULT_UNIT_CODE = \"C62\";\n\n/** UNCL5153 — the VAT tax scheme identifier. */\nexport const VAT_TAX_SCHEME_ID = \"VAT\";\n\n/** ISO 3166-1 alpha-2 list identifier for `cbc:IdentificationCode`. */\nexport const COUNTRY_CODE_LIST_ID = \"ISO3166-1:Alpha2\";\n\nexport const NS_INVOICE = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nexport const NS_CREDIT_NOTE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\nexport const NS_CAC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\nexport const NS_CBC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\n","/**\n * Minimal, dependency-free XML builder + serializer.\n *\n * UBL is order-sensitive (every element sequence is fixed by the schema), so\n * children are always explicit, ordered arrays. There is no attribute or text\n * coercion magic beyond escaping — the UBL layer is responsible for emitting\n * elements in the right order.\n */\n\nexport type XmlAttrs = Record<string, string | number | null | undefined>;\n\nexport interface XmlElement {\n\tname: string;\n\tattrs?: XmlAttrs;\n\t/** Leaf text content. Mutually exclusive with `children`. */\n\ttext?: string | number | null;\n\t/** Child elements. Mutually exclusive with `text`. */\n\tchildren?: XmlElement[];\n}\n\n/** Falsy children are dropped, so callers can write `cond && el(...)`. */\ntype ChildSpec = XmlElement | null | undefined | false;\n\n/**\n * Build an XML element.\n *\n * el(\"cbc:ID\", null, \"INV-1\") → <cbc:ID>INV-1</cbc:ID>\n * el(\"cbc:Amount\", { currencyID: \"EUR\" }, \"10.00\") → <cbc:Amount currencyID=\"EUR\">10.00</cbc:Amount>\n * el(\"cac:Party\", null, [child, cond && child2]) → nested element\n */\nexport const el = (\n\tname: string,\n\tattrs?: XmlAttrs | null,\n\tcontent?: string | number | null | ChildSpec[],\n): XmlElement => {\n\tif (Array.isArray(content)) {\n\t\treturn {\n\t\t\tname,\n\t\t\tattrs: attrs ?? undefined,\n\t\t\tchildren: content.filter((c): c is XmlElement => Boolean(c)),\n\t\t};\n\t}\n\treturn { name, attrs: attrs ?? undefined, text: content ?? undefined };\n};\n\nconst escapeText = (value: string): string =>\n\tvalue.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\nconst escapeAttr = (value: string): string => escapeText(value).replace(/\"/g, \"&quot;\");\n\nconst serializeAttrs = (attrs: XmlAttrs | undefined): string => {\n\tif (!attrs) return \"\";\n\treturn Object.entries(attrs)\n\t\t.filter(([, value]) => value !== null && value !== undefined)\n\t\t.map(([key, value]) => ` ${key}=\"${escapeAttr(String(value))}\"`)\n\t\t.join(\"\");\n};\n\nconst serializeElement = (node: XmlElement, indentLevel: number): string => {\n\tconst pad = \" \".repeat(indentLevel);\n\tconst attrs = serializeAttrs(node.attrs);\n\n\tif (node.text !== undefined && node.text !== null) {\n\t\treturn `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;\n\t}\n\n\tconst children = node.children ?? [];\n\tif (children.length === 0) {\n\t\treturn `${pad}<${node.name}${attrs}/>`;\n\t}\n\n\tconst inner = children\n\t\t.map((child) => serializeElement(child, indentLevel + 1))\n\t\t.join(\"\\n\");\n\treturn `${pad}<${node.name}${attrs}>\\n${inner}\\n${pad}</${node.name}>`;\n};\n\n/** Serialize a root element into a UTF-8 XML document string. */\nexport const serializeDocument = (root: XmlElement): string =>\n\t`<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${serializeElement(root, 0)}\\n`;\n","import { el, serializeDocument, type XmlElement } from \"../xml\";\nimport {\n\tCOUNTRY_CODE_LIST_ID,\n\tCREDIT_NOTE_TYPE_CODE,\n\tINVOICE_TYPE_CODE,\n\tNS_CAC,\n\tNS_CBC,\n\tNS_CREDIT_NOTE,\n\tNS_INVOICE,\n\tUBL_CUSTOMIZATION_ID,\n\tUBL_PROFILE_ID,\n\tVAT_TAX_SCHEME_ID,\n} from \"./constants\";\nimport type {\n\tUblAddress,\n\tUblAttachment,\n\tUblDocument,\n\tUblLine,\n\tUblParty,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n} from \"./types\";\n\n/** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */\nconst amount = (value: number): string => value.toFixed(2);\n\n/** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */\nconst percent = (value: number): string => {\n\tconst rounded = Math.round(value * 100) / 100;\n\treturn Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);\n};\n\nconst money = (name: string, value: number, currency: string): XmlElement =>\n\tel(name, { currencyID: currency }, amount(value));\n\nconst vatTaxScheme = (): XmlElement =>\n\tel(\"cac:TaxScheme\", null, [el(\"cbc:ID\", null, VAT_TAX_SCHEME_ID)]);\n\n/**\n * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)\n * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption\n * reason for the non-charging categories (E/AE/O/K/G).\n */\nconst taxCategory = (name: string, category: UblTaxCategory): XmlElement =>\n\tel(name, null, [\n\t\tel(\"cbc:ID\", null, category.id),\n\t\tel(\"cbc:Percent\", null, percent(category.percent)),\n\t\tcategory.exemptionReason\n\t\t\t? el(\"cbc:TaxExemptionReason\", null, category.exemptionReason)\n\t\t\t: null,\n\t\tvatTaxScheme(),\n\t]);\n\nconst postalAddress = (address: UblAddress): XmlElement =>\n\tel(\"cac:PostalAddress\", null, [\n\t\taddress.street ? el(\"cbc:StreetName\", null, address.street) : null,\n\t\taddress.additionalStreet\n\t\t\t? el(\"cbc:AdditionalStreetName\", null, address.additionalStreet)\n\t\t\t: null,\n\t\taddress.city ? el(\"cbc:CityName\", null, address.city) : null,\n\t\taddress.postalZone ? el(\"cbc:PostalZone\", null, address.postalZone) : null,\n\t\taddress.countrySubentity\n\t\t\t? el(\"cbc:CountrySubentity\", null, address.countrySubentity)\n\t\t\t: null,\n\t\taddress.countryCode\n\t\t\t? el(\"cac:Country\", null, [\n\t\t\t\t\tel(\n\t\t\t\t\t\t\"cbc:IdentificationCode\",\n\t\t\t\t\t\t{ listID: COUNTRY_CODE_LIST_ID },\n\t\t\t\t\t\taddress.countryCode,\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t: null,\n\t]);\n\nconst party = (source: UblParty): XmlElement =>\n\tel(\"cac:Party\", null, [\n\t\tsource.endpoint\n\t\t\t? el(\n\t\t\t\t\t\"cbc:EndpointID\",\n\t\t\t\t\t{ schemeID: source.endpoint.scheme },\n\t\t\t\t\tsource.endpoint.value,\n\t\t\t\t)\n\t\t\t: null,\n\t\tel(\"cac:PartyName\", null, [el(\"cbc:Name\", null, source.name)]),\n\t\tpostalAddress(source.address),\n\t\tsource.vatNumber\n\t\t\t? el(\"cac:PartyTaxScheme\", null, [\n\t\t\t\t\tel(\"cbc:CompanyID\", null, source.vatNumber),\n\t\t\t\t\tvatTaxScheme(),\n\t\t\t\t])\n\t\t\t: null,\n\t\tel(\"cac:PartyLegalEntity\", null, [\n\t\t\tel(\"cbc:RegistrationName\", null, source.legalName ?? source.name),\n\t\t\tsource.companyId\n\t\t\t\t? el(\n\t\t\t\t\t\t\"cbc:CompanyID\",\n\t\t\t\t\t\tsource.companyId.scheme\n\t\t\t\t\t\t\t? { schemeID: source.companyId.scheme }\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\tsource.companyId.value,\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t]),\n\t]);\n\nconst taxSubtotal = (subtotal: UblTaxSubtotal, currency: string): XmlElement =>\n\tel(\"cac:TaxSubtotal\", null, [\n\t\tmoney(\"cbc:TaxableAmount\", subtotal.taxableAmount, currency),\n\t\tmoney(\"cbc:TaxAmount\", subtotal.taxAmount, currency),\n\t\ttaxCategory(\"cac:TaxCategory\", subtotal.category),\n\t]);\n\nconst line = (\n\tsource: UblLine,\n\tcurrency: string,\n\tdocumentType: UblDocument[\"documentType\"],\n): XmlElement => {\n\tconst lineElementName =\n\t\tdocumentType === \"creditNote\" ? \"cac:CreditNoteLine\" : \"cac:InvoiceLine\";\n\tconst quantityElementName =\n\t\tdocumentType === \"creditNote\" ? \"cbc:CreditedQuantity\" : \"cbc:InvoicedQuantity\";\n\n\treturn el(lineElementName, null, [\n\t\tel(\"cbc:ID\", null, source.id),\n\t\tel(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),\n\t\tmoney(\"cbc:LineExtensionAmount\", source.lineExtensionAmount, currency),\n\t\tel(\"cac:Item\", null, [\n\t\t\tel(\"cbc:Name\", null, source.name),\n\t\t\ttaxCategory(\"cac:ClassifiedTaxCategory\", source.taxCategory),\n\t\t]),\n\t\tel(\"cac:Price\", null, [money(\"cbc:PriceAmount\", source.priceAmount, currency)]),\n\t]);\n};\n\nconst attachmentReference = (attachment: UblAttachment): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tel(\"cbc:ID\", null, attachment.id),\n\t\tel(\"cac:Attachment\", null, [\n\t\t\tel(\n\t\t\t\t\"cbc:EmbeddedDocumentBinaryObject\",\n\t\t\t\t{ mimeCode: attachment.mimeCode, filename: attachment.filename },\n\t\t\t\tattachment.base64,\n\t\t\t),\n\t\t]),\n\t]);\n\nconst billingReference = (precedingInvoiceId: string): XmlElement =>\n\tel(\"cac:BillingReference\", null, [\n\t\tel(\"cac:InvoiceDocumentReference\", null, [\n\t\t\tel(\"cbc:ID\", null, precedingInvoiceId),\n\t\t]),\n\t]);\n\n/** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */\nexport const serializeUblDocument = (doc: UblDocument): string => {\n\tconst isCreditNote = doc.documentType === \"creditNote\";\n\tconst rootName = isCreditNote ? \"CreditNote\" : \"Invoice\";\n\tconst rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;\n\tconst typeCodeElement = isCreditNote\n\t\t? el(\"cbc:CreditNoteTypeCode\", null, CREDIT_NOTE_TYPE_CODE)\n\t\t: el(\"cbc:InvoiceTypeCode\", null, INVOICE_TYPE_CODE);\n\n\tconst children: (XmlElement | null | false)[] = [\n\t\tel(\"cbc:CustomizationID\", null, UBL_CUSTOMIZATION_ID),\n\t\tel(\"cbc:ProfileID\", null, UBL_PROFILE_ID),\n\t\tel(\"cbc:ID\", null, doc.id),\n\t\tel(\"cbc:IssueDate\", null, doc.issueDate),\n\t\t// CreditNote has no DueDate element in the UBL sequence.\n\t\t!isCreditNote && doc.dueDate ? el(\"cbc:DueDate\", null, doc.dueDate) : null,\n\t\ttypeCodeElement,\n\t\tdoc.note ? el(\"cbc:Note\", null, doc.note) : null,\n\t\tel(\"cbc:DocumentCurrencyCode\", null, doc.currency),\n\t\tdoc.buyerReference ? el(\"cbc:BuyerReference\", null, doc.buyerReference) : null,\n\t\tdoc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,\n\t\t...doc.attachments.map(attachmentReference),\n\t\tel(\"cac:AccountingSupplierParty\", null, [party(doc.supplier)]),\n\t\tel(\"cac:AccountingCustomerParty\", null, [party(doc.customer)]),\n\t\tel(\"cac:TaxTotal\", null, [\n\t\t\tmoney(\"cbc:TaxAmount\", doc.taxTotal.taxAmount, doc.currency),\n\t\t\t...doc.taxTotal.subtotals.map((subtotal) =>\n\t\t\t\ttaxSubtotal(subtotal, doc.currency),\n\t\t\t),\n\t\t]),\n\t\tel(\"cac:LegalMonetaryTotal\", null, [\n\t\t\tmoney(\n\t\t\t\t\"cbc:LineExtensionAmount\",\n\t\t\t\tdoc.monetaryTotal.lineExtensionAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\n\t\t\t\t\"cbc:TaxExclusiveAmount\",\n\t\t\t\tdoc.monetaryTotal.taxExclusiveAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\n\t\t\t\t\"cbc:TaxInclusiveAmount\",\n\t\t\t\tdoc.monetaryTotal.taxInclusiveAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\"cbc:PayableAmount\", doc.monetaryTotal.payableAmount, doc.currency),\n\t\t]),\n\t\t...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),\n\t];\n\n\tconst root = el(\n\t\trootName,\n\t\t{\n\t\t\txmlns: rootNamespace,\n\t\t\t\"xmlns:cac\": NS_CAC,\n\t\t\t\"xmlns:cbc\": NS_CBC,\n\t\t},\n\t\tchildren.filter((child): child is XmlElement => Boolean(child)),\n\t);\n\n\treturn serializeDocument(root);\n};\n","export const isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const normalizeString = (value: unknown): string | null => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\nexport const toNumber = (value: unknown): number => {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\tif (typeof value === \"string\") {\n\t\tconst parsed = Number(value);\n\t\tif (Number.isFinite(parsed)) return parsed;\n\t}\n\treturn 0;\n};\n","import type { UblAddress } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst normalizeCountryCode = (value: string | null | undefined): string | null => {\n\tconst trimmed = normalizeString(value);\n\tif (!trimmed) return null;\n\treturn trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;\n};\n\n/**\n * Normalize a free-form address (Stripe shape, custom shape, or an internal\n * shape) into a {@link UblAddress}.\n *\n * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`\n * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address\n * has no country, but never silently substitutes a caller's country — pass\n * `null` when \"no country\" is the right answer.\n */\nexport const normalizeAddress = (\n\taddress: unknown,\n\tfallbackCountryCode: string | null,\n\tfallbackLine?: string | null,\n): UblAddress => {\n\tconst record = isRecord(address) ? address : {};\n\tconst countryCode =\n\t\tnormalizeCountryCode(normalizeString(record.country)) ??\n\t\tnormalizeCountryCode(normalizeString(record.country_code)) ??\n\t\tnormalizeCountryCode(fallbackCountryCode);\n\treturn {\n\t\tstreet:\n\t\t\tnormalizeString(record.line1) ??\n\t\t\tnormalizeString(record.street) ??\n\t\t\tfallbackLine ??\n\t\t\tnull,\n\t\tadditionalStreet: normalizeString(record.line2),\n\t\tcity: normalizeString(record.city),\n\t\tpostalZone:\n\t\t\tnormalizeString(record.postal_code) ?? normalizeString(record.zip_code),\n\t\tcountrySubentity:\n\t\t\tnormalizeString(record.state) ?? normalizeString(record.country_subentity),\n\t\tcountryCode,\n\t};\n};\n","import type { UblCompanyId, UblEndpoint } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst cleanIdentifierValue = (value: string) =>\n\tvalue\n\t\t.trim()\n\t\t.replace(/\\s+/g, \"\")\n\t\t.replace(/[^A-Za-z0-9]/g, \"\");\n\nconst normalizeBelgianCompanyNumber = (value: string | null | undefined) => {\n\tif (!value) return \"\";\n\treturn cleanIdentifierValue(value).toUpperCase().replace(/^BE/, \"\");\n};\n\n/**\n * Strip whitespace/punctuation from a country-specific company number.\n * For Belgium, also strips an optional `BE` prefix.\n */\nexport const normalizeCompanyNumberForCountry = (\n\tcountryCode: string | null | undefined,\n\tcompanyNumber: string | null | undefined,\n) => {\n\tif (!companyNumber) return \"\";\n\tconst upper = countryCode?.trim().toUpperCase() ?? \"\";\n\tif (upper === \"BE\") return normalizeBelgianCompanyNumber(companyNumber);\n\treturn companyNumber.trim();\n};\n\n/**\n * Country code → Peppol/ISO 6523 ICD scheme for a legal registration number\n * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`).\n *\n * BE → 0208 (Belgian enterprise number, CBE/KBO/BCE)\n * NL → 0106 (Netherlands KvK)\n * FR → 0002 (France SIRENE)\n *\n * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).\n * Returns `null` when the scheme can't be determined, in which case the\n * CompanyID is emitted without a `schemeID` attribute.\n */\nexport const resolveCompanyIdScheme = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): string | null => {\n\tconst companyNumber = normalizeString(params.companyNumber);\n\tif (!companyNumber) return null;\n\n\tconst TABLE: Record<string, string> = {\n\t\tBE: \"0208\",\n\t\tNL: \"0106\",\n\t\tFR: \"0002\",\n\t};\n\n\tconst normalizedCountry =\n\t\tnormalizeString(params.countryCode)?.toUpperCase() ?? null;\n\tif (normalizedCountry && normalizedCountry in TABLE) {\n\t\treturn TABLE[normalizedCountry] ?? null;\n\t}\n\n\tconst countryPrefix = cleanIdentifierValue(companyNumber).toUpperCase().slice(0, 2);\n\treturn countryPrefix in TABLE ? (TABLE[countryPrefix] ?? null) : null;\n};\n\n/**\n * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the\n * country-appropriate ICD scheme when known. Returns `null` when there is no\n * company number.\n */\nexport const buildCompanyId = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): UblCompanyId | null => {\n\tconst normalized = normalizeString(\n\t\tnormalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),\n\t);\n\tif (!normalized) return null;\n\treturn {\n\t\tvalue: normalized,\n\t\tscheme: resolveCompanyIdScheme({\n\t\t\tcountryCode: params.countryCode,\n\t\t\tcompanyNumber: normalized,\n\t\t}),\n\t};\n};\n\n/**\n * Country code → Peppol EAS scheme for a *VAT* identifier, keyed by ISO 3166-1\n * alpha-2. Source: Peppol Code Lists – Participant Identifier Schemes (EAS),\n * Peppol BIS Billing 3.0 (November 2025 release).\n *\n * Only countries that publish a VAT-based EAS scheme appear here. Some (e.g.\n * SE/DK/NO) address Peppol participants by organisation number rather than VAT\n * and are intentionally absent — see {@link resolveCompanyIdScheme}.\n */\nconst VAT_SCHEME_BY_COUNTRY: Record<string, string> = {\n\tAD: \"9922\", // Andorra\n\tAL: \"9923\", // Albania\n\tAT: \"9914\", // Austria\n\tBA: \"9924\", // Bosnia and Herzegovina\n\tBE: \"9925\", // Belgium\n\tBG: \"9926\", // Bulgaria\n\tCH: \"9927\", // Switzerland\n\tCY: \"9928\", // Cyprus\n\tCZ: \"9929\", // Czech Republic\n\tDE: \"9930\", // Germany\n\tEE: \"9931\", // Estonia\n\tES: \"9920\", // Spain (Spanish Tax Administration)\n\tFI: \"0213\", // Finland (Finnish VAT Identifier)\n\tFR: \"9957\", // France\n\tGB: \"9932\", // United Kingdom\n\tGR: \"9933\", // Greece (VAT prefix \"EL\")\n\tHR: \"9934\", // Croatia\n\tHU: \"9910\", // Hungary\n\tIE: \"9935\", // Ireland\n\tLI: \"9936\", // Liechtenstein\n\tLT: \"9937\", // Lithuania\n\tLU: \"9938\", // Luxembourg\n\tLV: \"9939\", // Latvia\n\tMC: \"9940\", // Monaco\n\tME: \"9941\", // Montenegro\n\tMK: \"9942\", // North Macedonia\n\tMT: \"9943\", // Malta\n\tNL: \"9944\", // Netherlands\n\tPL: \"9945\", // Poland\n\tPT: \"9946\", // Portugal\n\tRO: \"9947\", // Romania\n\tRS: \"9948\", // Serbia\n\tSI: \"9949\", // Slovenia\n\tSK: \"9950\", // Slovakia\n\tSM: \"9951\", // San Marino\n\tTR: \"9952\", // Turkey\n\tVA: \"9953\", // Holy See / Vatican City\n};\n\n/**\n * VAT registration prefixes that differ from the ISO 3166-1 alpha-2 country\n * code, so a VAT number's leading two letters still resolve to the right scheme.\n */\nconst VAT_PREFIX_TO_COUNTRY: Record<string, string> = {\n\tEL: \"GR\", // Greece issues VAT numbers with the \"EL\" prefix\n\tXI: \"GB\", // Northern Ireland VAT is issued under the UK scheme\n};\n\n/**\n * Resolve the Peppol participant identifier for a VAT number, deriving the EAS\n * scheme from the number's own country prefix (falling back to `countryCode`).\n *\n * `BE0206582284` → `{ scheme: \"9925\", value: \"BE0206582284\" }`\n *\n * The value keeps its country prefix, matching how participants register (the\n * Peppol directory lists this party as `9925:be0206582284`). Returns `null`\n * when the country has no VAT EAS scheme or the input is empty.\n */\nexport const resolveVatEndpoint = (params: {\n\tvatNumber: string | null | undefined;\n\tcountryCode?: string | null;\n}): UblEndpoint | null => {\n\tconst value = normalizeString(params.vatNumber);\n\tif (!value) return null;\n\tconst cleaned = cleanIdentifierValue(value).toUpperCase();\n\tif (!cleaned) return null;\n\n\tconst prefix = cleaned.slice(0, 2);\n\tconst fromPrefix = /^[A-Z]{2}$/.test(prefix)\n\t\t? (VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix)\n\t\t: null;\n\tconst fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;\n\n\tconst country =\n\t\tfromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;\n\tconst scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : undefined;\n\tif (!scheme) return null;\n\n\treturn { scheme, value: cleaned };\n};\n\n/**\n * Parse a Peppol participant identifier into a {@link UblEndpoint}.\n *\n * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns\n * `null` for values without an explicit scheme, since `cbc:EndpointID` requires\n * a `schemeID` and guessing one would mis-route the document.\n */\nexport const parsePeppolEndpoint = (\n\tpeppolId: string | null | undefined,\n): UblEndpoint | null => {\n\tconst normalized = normalizeString(peppolId);\n\tif (!normalized) return null;\n\tconst separatorIndex = normalized.indexOf(\":\");\n\tif (separatorIndex <= 0) return null;\n\tconst scheme = normalized.slice(0, separatorIndex).trim();\n\tconst value = normalized.slice(separatorIndex + 1).trim();\n\tif (!scheme || !value) return null;\n\treturn { scheme, value };\n};\n\nexport interface CustomerTaxIdentifiers {\n\tpeppolID: string | null;\n\tglnNumber: string | null;\n\ttaxNumber: string | null;\n\tvatNumber: string | null;\n}\n\nconst normalizeIdentifierType = (value: string | null) =>\n\tvalue?.toLowerCase().replace(/[^a-z0-9]+/g, \"_\") ?? null;\n\n/**\n * Pick the first usable Peppol identifier, GLN, VAT number, and tax number\n * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).\n *\n * Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.\n * Peppol IDs are typically stored as a custom `peppol_id` type.\n */\nexport const extractCustomerTaxIdentifiers = (\n\ttaxIds: unknown,\n): CustomerTaxIdentifiers => {\n\tlet peppolID: string | null = null;\n\tlet glnNumber: string | null = null;\n\tlet taxNumber: string | null = null;\n\tlet vatNumber: string | null = null;\n\n\tif (!Array.isArray(taxIds)) {\n\t\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n\t}\n\n\tfor (const entry of taxIds) {\n\t\tif (!isRecord(entry)) continue;\n\n\t\tconst type = normalizeIdentifierType(normalizeString(entry.type));\n\t\tconst value = normalizeString(entry.value);\n\t\tif (!type || !value) continue;\n\n\t\tif (!peppolID && type.includes(\"peppol\")) {\n\t\t\tpeppolID = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!glnNumber && type.includes(\"gln\")) {\n\t\t\tglnNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!vatNumber && type.includes(\"vat\")) {\n\t\t\tvatNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!taxNumber && type.includes(\"tax\")) {\n\t\t\ttaxNumber = value;\n\t\t}\n\t}\n\n\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n};\n\n/**\n * Build the fully-qualified Peppol participant identifiers (`scheme:value`) a\n * receiver lookup will accept, in priority order, de-duplicated.\n *\n * Stripe stores a customer's VAT number without a Peppol scheme (e.g.\n * `BE0206582284`), but a participant lookup needs the qualified identifier\n * (`9925:BE0206582284`). This attaches the right scheme:\n *\n * 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;\n * 2. a GLN under EAS `0088`;\n * 3. the VAT number under its country's VAT EAS scheme (see\n * {@link resolveVatEndpoint});\n * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)\n * under EAS `0208` — many Belgian entities register only under that;\n * 5. a generic tax/registration number under its country's company-ID scheme.\n *\n * `countryCode` (the customer's country, when known) disambiguates schemes for\n * identifiers that don't carry a country prefix (GLN, plain tax numbers).\n */\nexport const listPeppolReceiverIdentifierCandidates = (\n\tcustomer: {\n\t\tpeppolID?: string | null;\n\t\tglnNumber?: string | null;\n\t\ttaxNumber?: string | null;\n\t\tvatNumber?: string | null;\n\t},\n\tcountryCode?: string | null,\n): string[] => {\n\tconst candidates: string[] = [];\n\tconst add = (id: { scheme?: string | null; value: string } | null) => {\n\t\tif (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);\n\t};\n\n\t// 1. An explicit Peppol ID already carries its own scheme.\n\tconst peppol = normalizeString(customer.peppolID);\n\tif (peppol) candidates.push(peppol);\n\n\t// 2. GLN → EAS 0088 (Global Location Number).\n\tconst gln = normalizeString(customer.glnNumber);\n\tif (gln) add({ scheme: \"0088\", value: cleanIdentifierValue(gln) });\n\n\t// 3. VAT number → the country's VAT EAS scheme (e.g. BE → 9925).\n\tconst vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\tadd(vat);\n\n\t// 4. Belgium also reaches parties by enterprise number under EAS 0208; it is\n\t// the VAT digits without the `BE` prefix, and some entities register only so.\n\tif (vat?.scheme === \"9925\") {\n\t\tadd(\n\t\t\tbuildCompanyId({\n\t\t\t\tcountryCode: \"BE\",\n\t\t\t\tcompanyNumber: customer.vatNumber ?? null,\n\t\t\t}),\n\t\t);\n\t}\n\n\t// 5. A generic tax/registration number → its country's company-ID scheme.\n\tconst tax = normalizeString(customer.taxNumber);\n\tif (tax)\n\t\tadd(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));\n\n\treturn Array.from(new Set(candidates));\n};\n","import { normalizeAddress } from \"./address\";\nimport { buildCompanyId, parsePeppolEndpoint, resolveVatEndpoint } from \"./identifiers\";\nimport type { UblAddress, UblEndpoint, UblParty } from \"./ubl/types\";\nimport { normalizeString } from \"./utils\";\n\n/**\n * Supplier (seller) VAT status. Drives how zero-VAT lines are reported when the\n * seller does not charge VAT:\n *\n * 1 — Subject to VAT (the normal case): line categories come from the data.\n * 2 — Not subject to VAT.\n * 3 — Small business / franchise exemption (e.g. Belgian Article 56bis).\n *\n * For statuses 2 and 3, {@link ../build.ts} coerces all line categories to a\n * non-charging exempt category so no VAT is reported.\n */\nexport type SupplierVatStatus = 1 | 2 | 3;\n\n/**\n * Caller-provided supplier data, normalized into a stable shape.\n *\n * Each consumer builds this from its own data store. Once a `UblSupplier`\n * exists, the party builder no longer needs to know where it came from.\n */\nexport interface UblSupplier {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** ISO 3166-1 alpha-2 country code (e.g. `\"BE\"`). */\n\tcountryCode: string;\n\t/**\n\t * Free-form address. Stripe-style fields (`line1`, `postal_code`, `country`)\n\t * and legacy/internal fields (`street`, `zip_code`) are both accepted.\n\t */\n\taddress: unknown;\n\t/** Country-specific company/registration number (e.g. BE enterprise number). */\n\tcompanyNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n\t/** Whether the supplier charges VAT. See {@link SupplierVatStatus}. */\n\tvatStatus: SupplierVatStatus;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n}\n\n/** Convert a {@link UblSupplier} into the supplier (seller) party. */\nexport const buildSupplierParty = (supplier: UblSupplier): UblParty => {\n\tconst address = normalizeAddress(supplier.address, supplier.countryCode);\n\treturn {\n\t\tendpoint: parsePeppolEndpoint(supplier.peppolID),\n\t\tname: supplier.name,\n\t\taddress,\n\t\tvatNumber: normalizeString(supplier.vatNumber),\n\t\tlegalName: supplier.name,\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode: supplier.countryCode,\n\t\t\tcompanyNumber: supplier.companyNumber ?? null,\n\t\t}),\n\t};\n};\n\n/**\n * Caller-provided customer (buyer) data, normalized into a stable shape.\n *\n * Each consumer (the Stripe adapter, app-specific row builders) resolves its\n * own identifiers and address, then hands this generic shape to\n * {@link buildCustomerParty}, so the Peppol routing logic lives in one place.\n */\nexport interface UblCustomer {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** Customer address, already normalized by the caller. */\n\taddress: UblAddress;\n\t/**\n\t * The customer's ISO 3166-1 alpha-2 country, used to resolve VAT/registration\n\t * schemes for identifiers that don't carry a country prefix. Pass the\n\t * customer's *own* country (never the supplier's) so the document is not\n\t * mis-routed; falls back to the address country when omitted.\n\t */\n\tcountryCode?: string | null;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n\t/** Global Location Number (resolved under EAS `0088`). */\n\tglnNumber?: string | null;\n\t/** Generic tax/registration number (no VAT prefix). */\n\ttaxNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n}\n\n/**\n * Convert a {@link UblCustomer} into the customer (buyer) party.\n *\n * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in\n * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered\n * identifier), then an explicit Peppol ID, then a GLN (scheme `0088`), then the\n * VAT number mapped to its country's VAT EAS scheme (e.g. BE → `9925`). That\n * last step matters because most data stores hold a customer's VAT without a\n * scheme, so without it a VAT-only customer would have no endpoint and the\n * document would be unroutable.\n */\nexport const buildCustomerParty = (\n\tcustomer: UblCustomer,\n\tendpointOverride?: UblEndpoint | null,\n): UblParty => {\n\tconst countryCode =\n\t\tnormalizeString(customer.countryCode) ?? customer.address.countryCode;\n\tconst endpoint =\n\t\tendpointOverride ??\n\t\tparsePeppolEndpoint(customer.peppolID) ??\n\t\t(customer.glnNumber ? { scheme: \"0088\", value: customer.glnNumber } : null) ??\n\t\tresolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\n\treturn {\n\t\tendpoint,\n\t\tname: customer.name,\n\t\taddress: customer.address,\n\t\tvatNumber: normalizeString(customer.vatNumber),\n\t\tlegalName: customer.name,\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode,\n\t\t\tcompanyNumber: customer.taxNumber ?? null,\n\t\t}),\n\t};\n};\n","import type { UblAttachment, UblDocument } from \"./ubl/types\";\n\n/**\n * Build a UBL embedded-document attachment (BG-24) from raw bytes — e.g. the\n * rendered PDF of the invoice. Emitted as a `cac:AdditionalDocumentReference`\n * with an inline base64 `cbc:EmbeddedDocumentBinaryObject`.\n */\nexport const buildPdfAttachment = (params: {\n\tfilename: string;\n\tbytes: Uint8Array;\n\t/** Document reference ID (BT-122). Defaults to the filename. */\n\tid?: string;\n}): UblAttachment => ({\n\tid: params.id ?? params.filename,\n\tfilename: params.filename,\n\tmimeCode: \"application/pdf\",\n\tbase64: Buffer.from(params.bytes).toString(\"base64\"),\n});\n\n/**\n * Replace each attachment's base64 payload with `[omitted]` plus a length, so a\n * {@link UblDocument} is safe to log or persist for audit.\n */\nexport const sanitizeUblDocumentForAudit = (doc: UblDocument): UblDocument => {\n\tif (doc.attachments.length === 0) return doc;\n\treturn {\n\t\t...doc,\n\t\tattachments: doc.attachments.map((attachment) => ({\n\t\t\t...attachment,\n\t\t\tbase64: `[omitted ${attachment.base64.length} chars]`,\n\t\t})),\n\t};\n};\n","/** Round a number to 2 decimal places (cents). */\nexport const roundCurrency = (value: number) =>\n\tMath.round((value + Number.EPSILON) * 100) / 100;\n\n/** Convert an integer cent amount into a 2-decimal currency value. */\nexport const centsToDecimal = (cents: number) => roundCurrency(cents / 100);\n","import type { UblTaxCategory } from \"./ubl/types\";\n\n/**\n * Stripe Tax `taxability_reason` values that map to a VAT-exempt UBL category\n * (`E`). Reverse charge is handled separately (category `AE`).\n */\nexport const EXEMPT_TAXABILITY_REASONS = new Set([\n\t\"customer_exempt\",\n\t\"product_exempt\",\n\t\"not_subject_to_tax\",\n\t\"not_collecting\",\n\t\"not_supported\",\n\t\"portion_product_exempt\",\n]);\n\n/** Human-readable EN 16931 exemption reasons (BR-E-10 / BR-AE-10 / …). */\nconst EXEMPTION_REASON_TEXT: Record<string, string> = {\n\treverse_charge: \"Reverse charge\",\n\tintra_community: \"Intra-community supply\",\n\texport: \"Export outside the EU\",\n\tcustomer_exempt: \"Exempt based on customer status\",\n\tproduct_exempt: \"Exempt based on the supplied goods or services\",\n\tportion_product_exempt: \"Exempt based on the supplied goods or services\",\n\tnot_subject_to_tax: \"Not subject to VAT\",\n\tnot_collecting: \"VAT not collected\",\n\tnot_supported: \"VAT not applicable\",\n};\n\nexport interface TaxAmountInfo {\n\tamount: number;\n\ttaxability_reason?: string | null;\n\ttax_rate_percentage?: number | null;\n}\n\nconst normalizeTaxCategoryId = (value: unknown) => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim().toUpperCase();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\n/**\n * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a\n * numeric rate into a {@link UblTaxCategory}.\n *\n * - Reverse charge → `AE` (0%, with exemption reason)\n * - Intra-community supply → `K` (0%, with exemption reason)\n * - Export outside the EU → `G` (0%, with exemption reason)\n * - Any other exempt reason → `E` (0%, with exemption reason)\n * - Category `Z` / rate ≤ 0 → `Z` (zero-rated, 0%)\n * - Otherwise → `S` (standard, the line's rate)\n */\nexport const taxCategoryFromReasonOrRate = (params: {\n\ttaxCategoryId?: string | null;\n\ttaxabilityReason: string | null;\n\trate: number;\n}): UblTaxCategory => {\n\tconst categoryHint = normalizeTaxCategoryId(params.taxCategoryId);\n\tconst reason = params.taxabilityReason;\n\n\tif (categoryHint === \"AE\" || reason === \"reverse_charge\") {\n\t\treturn {\n\t\t\tid: \"AE\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.reverse_charge,\n\t\t};\n\t}\n\tif (categoryHint === \"K\" || reason === \"intra_community\") {\n\t\treturn {\n\t\t\tid: \"K\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.intra_community,\n\t\t};\n\t}\n\tif (categoryHint === \"G\" || reason === \"export\") {\n\t\treturn {\n\t\t\tid: \"G\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.export,\n\t\t};\n\t}\n\tif (categoryHint === \"E\" || (reason && EXEMPT_TAXABILITY_REASONS.has(reason))) {\n\t\treturn {\n\t\t\tid: \"E\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason:\n\t\t\t\t(reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? \"Exempt from VAT\",\n\t\t};\n\t}\n\tif (categoryHint === \"Z\" || reason === \"zero_rated\" || params.rate <= 0) {\n\t\treturn { id: \"Z\", percent: 0 };\n\t}\n\treturn { id: \"S\", percent: params.rate };\n};\n\n/**\n * Resolve a {@link UblTaxCategory} from a line's Stripe tax info.\n *\n * Exempt / reverse-charge / zero-rated reasons take precedence over the rate;\n * otherwise the rate decides standard (`S`) vs zero-rated (`Z`).\n */\nexport const resolveTaxCategoryFromTaxAmounts = (\n\ttaxAmounts: TaxAmountInfo[],\n\trate: number,\n): UblTaxCategory => {\n\tfor (const ta of taxAmounts) {\n\t\tif (!ta.taxability_reason) continue;\n\t\tif (ta.taxability_reason === \"reverse_charge\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"reverse_charge\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: ta.taxability_reason,\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (ta.taxability_reason === \"zero_rated\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"zero_rated\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t}\n\treturn taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });\n};\n","import { roundCurrency } from \"./numeric\";\nimport type {\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"./ubl/types\";\n\n/**\n * Adjust the largest line's net amount so the line nets sum to the\n * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).\n *\n * Reconciling at the *line* level — rather than directly on the VAT breakdown —\n * keeps the document consistent bottom-up: the VAT category taxable amounts\n * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the\n * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level\n * coupon; larger ones indicate a real upstream data problem.\n */\nexport const reconcileLinesToExclTotal = (\n\tlines: UblLine[],\n\tauthoritativeTotalExclVat: number,\n): UblLine[] => {\n\tif (lines.length === 0) return lines;\n\tconst computed = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst diff = roundCurrency(authoritativeTotalExclVat - computed);\n\tif (diff === 0) return lines;\n\n\tconst largestIdx = lines.reduce(\n\t\t(maxIdx, line, idx, arr) =>\n\t\t\tline.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0)\n\t\t\t\t? idx\n\t\t\t\t: maxIdx,\n\t\t0,\n\t);\n\n\treturn lines.map((line, idx) => {\n\t\tif (idx !== largestIdx) return line;\n\t\tconst adjusted = roundCurrency(line.lineExtensionAmount + diff);\n\t\treturn {\n\t\t\t...line,\n\t\t\tlineExtensionAmount: adjusted,\n\t\t\tpriceAmount: roundCurrency(adjusted / Math.max(line.quantity, 1)),\n\t\t};\n\t});\n};\n\nconst categoryKey = (category: UblTaxCategory): string =>\n\t`${category.id}:${category.percent}`;\n\nexport interface BuildTaxTotalsResult {\n\ttaxTotal: UblTaxTotal;\n\tmonetaryTotal: UblMonetaryTotal;\n}\n\n/**\n * Group lines by `(category, percent)` into a VAT breakdown and compute the\n * document monetary totals.\n *\n * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,\n * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the\n * upstream per-line tax cents. This guarantees the breakdown is internally\n * consistent and passes validation; it can differ by a cent from the figure a\n * payment processor reported, which is an unavoidable artifact of representing\n * a cents-rounded system as a rate-based VAT breakdown.\n */\nexport const buildTaxTotals = (lines: UblLine[]): BuildTaxTotalsResult => {\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ category: UblTaxCategory; taxableAmount: number }\n\t>();\n\n\tfor (const line of lines) {\n\t\tconst key = categoryKey(line.taxCategory);\n\t\tconst current = groups.get(key) ?? {\n\t\t\tcategory: line.taxCategory,\n\t\t\ttaxableAmount: 0,\n\t\t};\n\t\tcurrent.taxableAmount = roundCurrency(\n\t\t\tcurrent.taxableAmount + line.lineExtensionAmount,\n\t\t);\n\t\tgroups.set(key, current);\n\t}\n\n\tconst subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({\n\t\ttaxableAmount: group.taxableAmount,\n\t\ttaxAmount: roundCurrency((group.taxableAmount * group.category.percent) / 100),\n\t\tcategory: group.category,\n\t}));\n\n\tconst lineExtensionAmount = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst taxAmount = roundCurrency(\n\t\tsubtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0),\n\t);\n\tconst taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);\n\n\treturn {\n\t\ttaxTotal: { taxAmount, subtotals },\n\t\tmonetaryTotal: {\n\t\t\tlineExtensionAmount,\n\t\t\ttaxExclusiveAmount: lineExtensionAmount,\n\t\t\ttaxInclusiveAmount,\n\t\t\tpayableAmount: taxInclusiveAmount,\n\t\t},\n\t};\n};\n"],"mappings":";;;AAGA,MAAa,uBACZ;;AAGD,MAAa,iBAAiB;;AAG9B,MAAa,oBAAoB;;AAEjC,MAAa,wBAAwB;;AAGrC,MAAa,oBAAoB;;AAGjC,MAAa,oBAAoB;;AAGjC,MAAa,uBAAuB;AAEpC,MAAa,aAAa;AAC1B,MAAa,iBACZ;AACD,MAAa,SACZ;AACD,MAAa,SACZ;;;;;;;;;;ACCD,MAAa,MACZ,MACA,OACA,YACgB;CAChB,IAAI,MAAM,QAAQ,OAAO,GACxB,OAAO;EACN;EACA,OAAO,SAAS,KAAA;EAChB,UAAU,QAAQ,QAAQ,MAAuB,QAAQ,CAAC,CAAC;CAC5D;CAED,OAAO;EAAE;EAAM,OAAO,SAAS,KAAA;EAAW,MAAM,WAAW,KAAA;CAAU;AACtE;AAEA,MAAM,cAAc,UACnB,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM;AAExE,MAAM,cAAc,UAA0B,WAAW,KAAK,CAAC,CAAC,QAAQ,MAAM,QAAQ;AAEtF,MAAM,kBAAkB,UAAwC;CAC/D,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,OAAO,QAAQ,KAAK,CAAC,CAC1B,QAAQ,GAAG,WAAW,UAAU,QAAQ,UAAU,KAAA,CAAS,CAAC,CAC5D,KAAK,CAAC,KAAK,WAAW,IAAI,IAAI,IAAI,WAAW,OAAO,KAAK,CAAC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Q,KAAK,SAAS,MAAM,KAAK,qBAAqB,CAAC,CAC9D;CACA,MAAM,YAAY,cACjB,UAAU,QAAQ,KAAK,aAAa,MAAM,SAAS,WAAW,CAAC,CAChE;CACA,MAAM,qBAAqB,cAAc,sBAAsB,SAAS;CAExE,OAAO;EACN,UAAU;GAAE;GAAW;EAAU;EACjC,eAAe;GACd;GACA,oBAAoB;GACpB;GACA,eAAe;EAChB;CACD;AACD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/build/ubl/constants.ts","../../src/build/xml.ts","../../src/build/ubl/serialize.ts","../../src/build/utils.ts","../../src/build/address.ts","../../src/build/identifiers.ts","../../src/build/party.ts","../../src/build/attachment.ts","../../src/build/numeric.ts","../../src/build/tax-category.ts","../../src/build/tax-totals.ts"],"sourcesContent":["/** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */\n\n/** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */\nexport const UBL_CUSTOMIZATION_ID =\n\t\"urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0\";\n\n/** Peppol BIS Billing 3.0 process (BT-23). */\nexport const UBL_PROFILE_ID = \"urn:fdc:peppol.eu:2017:poacc:billing:01:1.0\";\n\n/** UNTDID 1001 — commercial invoice. */\nexport const INVOICE_TYPE_CODE = \"380\";\n/** UNTDID 1001 — credit note. */\nexport const CREDIT_NOTE_TYPE_CODE = \"381\";\n\n/** UN/ECE Recommendation 20 — \"one / piece\" (the default line unit). */\nexport const DEFAULT_UNIT_CODE = \"C62\";\n\n/** UNCL5153 — the VAT tax scheme identifier. */\nexport const VAT_TAX_SCHEME_ID = \"VAT\";\n\n/** ISO 3166-1 alpha-2 list identifier for `cbc:IdentificationCode`. */\nexport const COUNTRY_CODE_LIST_ID = \"ISO3166-1:Alpha2\";\n\nexport const NS_INVOICE = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nexport const NS_CREDIT_NOTE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\nexport const NS_CAC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\nexport const NS_CBC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\n","/**\n * Minimal, dependency-free XML builder + serializer.\n *\n * UBL is order-sensitive (every element sequence is fixed by the schema), so\n * children are always explicit, ordered arrays. There is no attribute or text\n * coercion magic beyond escaping — the UBL layer is responsible for emitting\n * elements in the right order.\n */\n\nexport type XmlAttrs = Record<string, string | number | null | undefined>;\n\nexport interface XmlElement {\n\tname: string;\n\tattrs?: XmlAttrs;\n\t/** Leaf text content. Mutually exclusive with `children`. */\n\ttext?: string | number | null;\n\t/** Child elements. Mutually exclusive with `text`. */\n\tchildren?: XmlElement[];\n}\n\n/** Falsy children are dropped, so callers can write `cond && el(...)`. */\ntype ChildSpec = XmlElement | null | undefined | false;\n\n/**\n * Build an XML element.\n *\n * el(\"cbc:ID\", null, \"INV-1\") → <cbc:ID>INV-1</cbc:ID>\n * el(\"cbc:Amount\", { currencyID: \"EUR\" }, \"10.00\") → <cbc:Amount currencyID=\"EUR\">10.00</cbc:Amount>\n * el(\"cac:Party\", null, [child, cond && child2]) → nested element\n */\nexport const el = (\n\tname: string,\n\tattrs?: XmlAttrs | null,\n\tcontent?: string | number | null | ChildSpec[],\n): XmlElement => {\n\tif (Array.isArray(content)) {\n\t\treturn {\n\t\t\tname,\n\t\t\tattrs: attrs ?? undefined,\n\t\t\tchildren: content.filter((c): c is XmlElement => Boolean(c)),\n\t\t};\n\t}\n\treturn { name, attrs: attrs ?? undefined, text: content ?? undefined };\n};\n\nconst escapeText = (value: string): string =>\n\tvalue.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\nconst escapeAttr = (value: string): string => escapeText(value).replace(/\"/g, \"&quot;\");\n\nconst serializeAttrs = (attrs: XmlAttrs | undefined): string => {\n\tif (!attrs) return \"\";\n\treturn Object.entries(attrs)\n\t\t.filter(([, value]) => value !== null && value !== undefined)\n\t\t.map(([key, value]) => ` ${key}=\"${escapeAttr(String(value))}\"`)\n\t\t.join(\"\");\n};\n\nconst serializeElement = (node: XmlElement, indentLevel: number): string => {\n\tconst pad = \" \".repeat(indentLevel);\n\tconst attrs = serializeAttrs(node.attrs);\n\n\tif (node.text !== undefined && node.text !== null) {\n\t\treturn `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;\n\t}\n\n\tconst children = node.children ?? [];\n\tif (children.length === 0) {\n\t\treturn `${pad}<${node.name}${attrs}/>`;\n\t}\n\n\tconst inner = children\n\t\t.map((child) => serializeElement(child, indentLevel + 1))\n\t\t.join(\"\\n\");\n\treturn `${pad}<${node.name}${attrs}>\\n${inner}\\n${pad}</${node.name}>`;\n};\n\n/** Serialize a root element into a UTF-8 XML document string. */\nexport const serializeDocument = (root: XmlElement): string =>\n\t`<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${serializeElement(root, 0)}\\n`;\n","import { el, serializeDocument, type XmlElement } from \"../xml\";\nimport {\n\tCOUNTRY_CODE_LIST_ID,\n\tCREDIT_NOTE_TYPE_CODE,\n\tINVOICE_TYPE_CODE,\n\tNS_CAC,\n\tNS_CBC,\n\tNS_CREDIT_NOTE,\n\tNS_INVOICE,\n\tUBL_CUSTOMIZATION_ID,\n\tUBL_PROFILE_ID,\n\tVAT_TAX_SCHEME_ID,\n} from \"./constants\";\nimport type {\n\tUblAddress,\n\tUblAttachment,\n\tUblDocument,\n\tUblLine,\n\tUblParty,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n} from \"./types\";\n\n/** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */\nconst amount = (value: number): string => value.toFixed(2);\n\n/** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */\nconst percent = (value: number): string => {\n\tconst rounded = Math.round(value * 100) / 100;\n\treturn Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);\n};\n\nconst money = (name: string, value: number, currency: string): XmlElement =>\n\tel(name, { currencyID: currency }, amount(value));\n\nconst vatTaxScheme = (): XmlElement =>\n\tel(\"cac:TaxScheme\", null, [el(\"cbc:ID\", null, VAT_TAX_SCHEME_ID)]);\n\n/**\n * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)\n * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption\n * reason for the non-charging categories (E/AE/O/K/G).\n */\nconst taxCategory = (name: string, category: UblTaxCategory): XmlElement =>\n\tel(name, null, [\n\t\tel(\"cbc:ID\", null, category.id),\n\t\tel(\"cbc:Percent\", null, percent(category.percent)),\n\t\tcategory.exemptionReason\n\t\t\t? el(\"cbc:TaxExemptionReason\", null, category.exemptionReason)\n\t\t\t: null,\n\t\tvatTaxScheme(),\n\t]);\n\nconst postalAddress = (address: UblAddress): XmlElement =>\n\tel(\"cac:PostalAddress\", null, [\n\t\taddress.street ? el(\"cbc:StreetName\", null, address.street) : null,\n\t\taddress.additionalStreet\n\t\t\t? el(\"cbc:AdditionalStreetName\", null, address.additionalStreet)\n\t\t\t: null,\n\t\taddress.city ? el(\"cbc:CityName\", null, address.city) : null,\n\t\taddress.postalZone ? el(\"cbc:PostalZone\", null, address.postalZone) : null,\n\t\taddress.countrySubentity\n\t\t\t? el(\"cbc:CountrySubentity\", null, address.countrySubentity)\n\t\t\t: null,\n\t\taddress.countryCode\n\t\t\t? el(\"cac:Country\", null, [\n\t\t\t\t\tel(\n\t\t\t\t\t\t\"cbc:IdentificationCode\",\n\t\t\t\t\t\t{ listID: COUNTRY_CODE_LIST_ID },\n\t\t\t\t\t\taddress.countryCode,\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t: null,\n\t]);\n\nconst party = (source: UblParty): XmlElement =>\n\tel(\"cac:Party\", null, [\n\t\tsource.endpoint\n\t\t\t? el(\n\t\t\t\t\t\"cbc:EndpointID\",\n\t\t\t\t\t{ schemeID: source.endpoint.scheme },\n\t\t\t\t\tsource.endpoint.value,\n\t\t\t\t)\n\t\t\t: null,\n\t\tel(\"cac:PartyName\", null, [el(\"cbc:Name\", null, source.name)]),\n\t\tpostalAddress(source.address),\n\t\tsource.vatNumber\n\t\t\t? el(\"cac:PartyTaxScheme\", null, [\n\t\t\t\t\tel(\"cbc:CompanyID\", null, source.vatNumber),\n\t\t\t\t\tvatTaxScheme(),\n\t\t\t\t])\n\t\t\t: null,\n\t\tel(\"cac:PartyLegalEntity\", null, [\n\t\t\tel(\"cbc:RegistrationName\", null, source.legalName ?? source.name),\n\t\t\tsource.companyId\n\t\t\t\t? el(\n\t\t\t\t\t\t\"cbc:CompanyID\",\n\t\t\t\t\t\tsource.companyId.scheme\n\t\t\t\t\t\t\t? { schemeID: source.companyId.scheme }\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\tsource.companyId.value,\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t]),\n\t]);\n\nconst taxSubtotal = (subtotal: UblTaxSubtotal, currency: string): XmlElement =>\n\tel(\"cac:TaxSubtotal\", null, [\n\t\tmoney(\"cbc:TaxableAmount\", subtotal.taxableAmount, currency),\n\t\tmoney(\"cbc:TaxAmount\", subtotal.taxAmount, currency),\n\t\ttaxCategory(\"cac:TaxCategory\", subtotal.category),\n\t]);\n\n/**\n * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`\n * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`\n * — emitting them after it produces schema-invalid XML.\n */\nconst legalMonetaryTotalChildren = (doc: UblDocument): XmlElement[] => {\n\tconst { currency, monetaryTotal: total } = doc;\n\tconst children: (XmlElement | null)[] = [\n\t\tmoney(\"cbc:LineExtensionAmount\", total.lineExtensionAmount, currency),\n\t\tmoney(\"cbc:TaxExclusiveAmount\", total.taxExclusiveAmount, currency),\n\t\tmoney(\"cbc:TaxInclusiveAmount\", total.taxInclusiveAmount, currency),\n\t\ttotal.prepaidAmount\n\t\t\t? money(\"cbc:PrepaidAmount\", total.prepaidAmount, currency)\n\t\t\t: null,\n\t\ttotal.payableRoundingAmount\n\t\t\t? money(\"cbc:PayableRoundingAmount\", total.payableRoundingAmount, currency)\n\t\t\t: null,\n\t\tmoney(\"cbc:PayableAmount\", total.payableAmount, currency),\n\t];\n\treturn children.filter((child): child is XmlElement => Boolean(child));\n};\n\nconst line = (\n\tsource: UblLine,\n\tcurrency: string,\n\tdocumentType: UblDocument[\"documentType\"],\n): XmlElement => {\n\tconst lineElementName =\n\t\tdocumentType === \"creditNote\" ? \"cac:CreditNoteLine\" : \"cac:InvoiceLine\";\n\tconst quantityElementName =\n\t\tdocumentType === \"creditNote\" ? \"cbc:CreditedQuantity\" : \"cbc:InvoicedQuantity\";\n\n\treturn el(lineElementName, null, [\n\t\tel(\"cbc:ID\", null, source.id),\n\t\tel(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),\n\t\tmoney(\"cbc:LineExtensionAmount\", source.lineExtensionAmount, currency),\n\t\tel(\"cac:Item\", null, [\n\t\t\tel(\"cbc:Name\", null, source.name),\n\t\t\ttaxCategory(\"cac:ClassifiedTaxCategory\", source.taxCategory),\n\t\t]),\n\t\t// BT-149's unit code must match the invoiced/credited quantity's\n\t\t// (PEPPOL-EN16931-R130).\n\t\tel(\"cac:Price\", null, [\n\t\t\tmoney(\"cbc:PriceAmount\", source.priceAmount, currency),\n\t\t\tsource.baseQuantity != null\n\t\t\t\t? el(\n\t\t\t\t\t\t\"cbc:BaseQuantity\",\n\t\t\t\t\t\t{ unitCode: source.unitCode },\n\t\t\t\t\t\tString(source.baseQuantity),\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t]),\n\t]);\n};\n\nconst attachmentReference = (attachment: UblAttachment): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tel(\"cbc:ID\", null, attachment.id),\n\t\tel(\"cac:Attachment\", null, [\n\t\t\tel(\n\t\t\t\t\"cbc:EmbeddedDocumentBinaryObject\",\n\t\t\t\t{ mimeCode: attachment.mimeCode, filename: attachment.filename },\n\t\t\t\tattachment.base64,\n\t\t\t),\n\t\t]),\n\t]);\n\nconst billingReference = (precedingInvoiceId: string): XmlElement =>\n\tel(\"cac:BillingReference\", null, [\n\t\tel(\"cac:InvoiceDocumentReference\", null, [\n\t\t\tel(\"cbc:ID\", null, precedingInvoiceId),\n\t\t]),\n\t]);\n\n/** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */\nexport const serializeUblDocument = (doc: UblDocument): string => {\n\tconst isCreditNote = doc.documentType === \"creditNote\";\n\tconst rootName = isCreditNote ? \"CreditNote\" : \"Invoice\";\n\tconst rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;\n\tconst typeCodeElement = isCreditNote\n\t\t? el(\"cbc:CreditNoteTypeCode\", null, CREDIT_NOTE_TYPE_CODE)\n\t\t: el(\"cbc:InvoiceTypeCode\", null, INVOICE_TYPE_CODE);\n\n\tconst children: (XmlElement | null | false)[] = [\n\t\tel(\"cbc:CustomizationID\", null, UBL_CUSTOMIZATION_ID),\n\t\tel(\"cbc:ProfileID\", null, UBL_PROFILE_ID),\n\t\tel(\"cbc:ID\", null, doc.id),\n\t\tel(\"cbc:IssueDate\", null, doc.issueDate),\n\t\t// CreditNote has no DueDate element in the UBL sequence.\n\t\t!isCreditNote && doc.dueDate ? el(\"cbc:DueDate\", null, doc.dueDate) : null,\n\t\ttypeCodeElement,\n\t\tdoc.note ? el(\"cbc:Note\", null, doc.note) : null,\n\t\tel(\"cbc:DocumentCurrencyCode\", null, doc.currency),\n\t\tdoc.buyerReference ? el(\"cbc:BuyerReference\", null, doc.buyerReference) : null,\n\t\tdoc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,\n\t\t...doc.attachments.map(attachmentReference),\n\t\tel(\"cac:AccountingSupplierParty\", null, [party(doc.supplier)]),\n\t\tel(\"cac:AccountingCustomerParty\", null, [party(doc.customer)]),\n\t\tel(\"cac:TaxTotal\", null, [\n\t\t\tmoney(\"cbc:TaxAmount\", doc.taxTotal.taxAmount, doc.currency),\n\t\t\t...doc.taxTotal.subtotals.map((subtotal) =>\n\t\t\t\ttaxSubtotal(subtotal, doc.currency),\n\t\t\t),\n\t\t]),\n\t\tel(\"cac:LegalMonetaryTotal\", null, legalMonetaryTotalChildren(doc)),\n\t\t...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),\n\t];\n\n\tconst root = el(\n\t\trootName,\n\t\t{\n\t\t\txmlns: rootNamespace,\n\t\t\t\"xmlns:cac\": NS_CAC,\n\t\t\t\"xmlns:cbc\": NS_CBC,\n\t\t},\n\t\tchildren.filter((child): child is XmlElement => Boolean(child)),\n\t);\n\n\treturn serializeDocument(root);\n};\n","export const isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const normalizeString = (value: unknown): string | null => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\nexport const toNumber = (value: unknown): number => {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\tif (typeof value === \"string\") {\n\t\tconst parsed = Number(value);\n\t\tif (Number.isFinite(parsed)) return parsed;\n\t}\n\treturn 0;\n};\n","import type { UblAddress } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst normalizeCountryCode = (value: string | null | undefined): string | null => {\n\tconst trimmed = normalizeString(value);\n\tif (!trimmed) return null;\n\treturn trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;\n};\n\n/**\n * Normalize a free-form address (Stripe shape, custom shape, or an internal\n * shape) into a {@link UblAddress}.\n *\n * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`\n * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address\n * has no country, but never silently substitutes a caller's country — pass\n * `null` when \"no country\" is the right answer.\n */\nexport const normalizeAddress = (\n\taddress: unknown,\n\tfallbackCountryCode: string | null,\n\tfallbackLine?: string | null,\n): UblAddress => {\n\tconst record = isRecord(address) ? address : {};\n\tconst countryCode =\n\t\tnormalizeCountryCode(normalizeString(record.country)) ??\n\t\tnormalizeCountryCode(normalizeString(record.country_code)) ??\n\t\tnormalizeCountryCode(fallbackCountryCode);\n\treturn {\n\t\tstreet:\n\t\t\tnormalizeString(record.line1) ??\n\t\t\tnormalizeString(record.street) ??\n\t\t\tfallbackLine ??\n\t\t\tnull,\n\t\tadditionalStreet: normalizeString(record.line2),\n\t\tcity: normalizeString(record.city),\n\t\tpostalZone:\n\t\t\tnormalizeString(record.postal_code) ?? normalizeString(record.zip_code),\n\t\tcountrySubentity:\n\t\t\tnormalizeString(record.state) ?? normalizeString(record.country_subentity),\n\t\tcountryCode,\n\t};\n};\n","import type { UblCompanyId, UblEndpoint } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst cleanIdentifierValue = (value: string) =>\n\tvalue\n\t\t.trim()\n\t\t.replace(/\\s+/g, \"\")\n\t\t.replace(/[^A-Za-z0-9]/g, \"\");\n\nconst normalizeBelgianCompanyNumber = (value: string | null | undefined) => {\n\tif (!value) return \"\";\n\treturn cleanIdentifierValue(value).toUpperCase().replace(/^BE/, \"\");\n};\n\n/**\n * Strip whitespace/punctuation from a country-specific company number.\n * For Belgium, also strips an optional `BE` prefix.\n */\nexport const normalizeCompanyNumberForCountry = (\n\tcountryCode: string | null | undefined,\n\tcompanyNumber: string | null | undefined,\n) => {\n\tif (!companyNumber) return \"\";\n\tconst upper = countryCode?.trim().toUpperCase() ?? \"\";\n\tif (upper === \"BE\") return normalizeBelgianCompanyNumber(companyNumber);\n\treturn companyNumber.trim();\n};\n\n/**\n * Country code → Peppol/ISO 6523 ICD scheme for a legal registration number\n * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`).\n *\n * BE → 0208 (Belgian enterprise number, CBE/KBO/BCE)\n * NL → 0106 (Netherlands KvK)\n * FR → 0002 (France SIRENE)\n *\n * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).\n * Returns `null` when the scheme can't be determined, in which case the\n * CompanyID is emitted without a `schemeID` attribute.\n */\nexport const resolveCompanyIdScheme = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): string | null => {\n\tconst companyNumber = normalizeString(params.companyNumber);\n\tif (!companyNumber) return null;\n\n\tconst TABLE: Record<string, string> = {\n\t\tBE: \"0208\",\n\t\tNL: \"0106\",\n\t\tFR: \"0002\",\n\t};\n\n\tconst normalizedCountry =\n\t\tnormalizeString(params.countryCode)?.toUpperCase() ?? null;\n\tif (normalizedCountry && normalizedCountry in TABLE) {\n\t\treturn TABLE[normalizedCountry] ?? null;\n\t}\n\n\tconst countryPrefix = cleanIdentifierValue(companyNumber).toUpperCase().slice(0, 2);\n\treturn countryPrefix in TABLE ? (TABLE[countryPrefix] ?? null) : null;\n};\n\n/**\n * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the\n * country-appropriate ICD scheme when known. Returns `null` when there is no\n * company number.\n */\nexport const buildCompanyId = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): UblCompanyId | null => {\n\tconst normalized = normalizeString(\n\t\tnormalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),\n\t);\n\tif (!normalized) return null;\n\treturn {\n\t\tvalue: normalized,\n\t\tscheme: resolveCompanyIdScheme({\n\t\t\tcountryCode: params.countryCode,\n\t\t\tcompanyNumber: normalized,\n\t\t}),\n\t};\n};\n\n/**\n * Country code → Peppol EAS scheme for a *VAT* identifier, keyed by ISO 3166-1\n * alpha-2. Source: Peppol Code Lists – Participant Identifier Schemes (EAS),\n * Peppol BIS Billing 3.0 (November 2025 release).\n *\n * Only countries that publish a VAT-based EAS scheme appear here. Some (e.g.\n * SE/DK/NO) address Peppol participants by organisation number rather than VAT\n * and are intentionally absent — see {@link resolveCompanyIdScheme}.\n */\nconst VAT_SCHEME_BY_COUNTRY: Record<string, string> = {\n\tAD: \"9922\", // Andorra\n\tAL: \"9923\", // Albania\n\tAT: \"9914\", // Austria\n\tBA: \"9924\", // Bosnia and Herzegovina\n\tBE: \"9925\", // Belgium\n\tBG: \"9926\", // Bulgaria\n\tCH: \"9927\", // Switzerland\n\tCY: \"9928\", // Cyprus\n\tCZ: \"9929\", // Czech Republic\n\tDE: \"9930\", // Germany\n\tEE: \"9931\", // Estonia\n\tES: \"9920\", // Spain (Spanish Tax Administration)\n\tFI: \"0213\", // Finland (Finnish VAT Identifier)\n\tFR: \"9957\", // France\n\tGB: \"9932\", // United Kingdom\n\tGR: \"9933\", // Greece (VAT prefix \"EL\")\n\tHR: \"9934\", // Croatia\n\tHU: \"9910\", // Hungary\n\tIE: \"9935\", // Ireland\n\tLI: \"9936\", // Liechtenstein\n\tLT: \"9937\", // Lithuania\n\tLU: \"9938\", // Luxembourg\n\tLV: \"9939\", // Latvia\n\tMC: \"9940\", // Monaco\n\tME: \"9941\", // Montenegro\n\tMK: \"9942\", // North Macedonia\n\tMT: \"9943\", // Malta\n\tNL: \"9944\", // Netherlands\n\tPL: \"9945\", // Poland\n\tPT: \"9946\", // Portugal\n\tRO: \"9947\", // Romania\n\tRS: \"9948\", // Serbia\n\tSI: \"9949\", // Slovenia\n\tSK: \"9950\", // Slovakia\n\tSM: \"9951\", // San Marino\n\tTR: \"9952\", // Turkey\n\tVA: \"9953\", // Holy See / Vatican City\n};\n\n/**\n * VAT registration prefixes that differ from the ISO 3166-1 alpha-2 country\n * code, so a VAT number's leading two letters still resolve to the right scheme.\n */\nconst VAT_PREFIX_TO_COUNTRY: Record<string, string> = {\n\tEL: \"GR\", // Greece issues VAT numbers with the \"EL\" prefix\n\tXI: \"GB\", // Northern Ireland VAT is issued under the UK scheme\n};\n\n/**\n * Resolve the Peppol participant identifier for a VAT number, deriving the EAS\n * scheme from the number's own country prefix (falling back to `countryCode`).\n *\n * `BE0206582284` → `{ scheme: \"9925\", value: \"BE0206582284\" }`\n *\n * The value keeps its country prefix, matching how participants register (the\n * Peppol directory lists this party as `9925:be0206582284`). Returns `null`\n * when the country has no VAT EAS scheme or the input is empty.\n */\nexport const resolveVatEndpoint = (params: {\n\tvatNumber: string | null | undefined;\n\tcountryCode?: string | null;\n}): UblEndpoint | null => {\n\tconst value = normalizeString(params.vatNumber);\n\tif (!value) return null;\n\tconst cleaned = cleanIdentifierValue(value).toUpperCase();\n\tif (!cleaned) return null;\n\n\tconst prefix = cleaned.slice(0, 2);\n\tconst fromPrefix = /^[A-Z]{2}$/.test(prefix)\n\t\t? (VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix)\n\t\t: null;\n\tconst fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;\n\n\tconst country =\n\t\tfromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;\n\tconst scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : undefined;\n\tif (!scheme) return null;\n\n\treturn { scheme, value: cleaned };\n};\n\n/**\n * Parse a Peppol participant identifier into a {@link UblEndpoint}.\n *\n * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns\n * `null` for values without an explicit scheme, since `cbc:EndpointID` requires\n * a `schemeID` and guessing one would mis-route the document.\n */\nexport const parsePeppolEndpoint = (\n\tpeppolId: string | null | undefined,\n): UblEndpoint | null => {\n\tconst normalized = normalizeString(peppolId);\n\tif (!normalized) return null;\n\tconst separatorIndex = normalized.indexOf(\":\");\n\tif (separatorIndex <= 0) return null;\n\tconst scheme = normalized.slice(0, separatorIndex).trim();\n\tconst value = normalized.slice(separatorIndex + 1).trim();\n\tif (!scheme || !value) return null;\n\treturn { scheme, value };\n};\n\nexport interface CustomerTaxIdentifiers {\n\tpeppolID: string | null;\n\tglnNumber: string | null;\n\ttaxNumber: string | null;\n\tvatNumber: string | null;\n}\n\nconst normalizeIdentifierType = (value: string | null) =>\n\tvalue?.toLowerCase().replace(/[^a-z0-9]+/g, \"_\") ?? null;\n\n/**\n * Pick the first usable Peppol identifier, GLN, VAT number, and tax number\n * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).\n *\n * Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.\n * Peppol IDs are typically stored as a custom `peppol_id` type.\n */\nexport const extractCustomerTaxIdentifiers = (\n\ttaxIds: unknown,\n): CustomerTaxIdentifiers => {\n\tlet peppolID: string | null = null;\n\tlet glnNumber: string | null = null;\n\tlet taxNumber: string | null = null;\n\tlet vatNumber: string | null = null;\n\n\tif (!Array.isArray(taxIds)) {\n\t\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n\t}\n\n\tfor (const entry of taxIds) {\n\t\tif (!isRecord(entry)) continue;\n\n\t\tconst type = normalizeIdentifierType(normalizeString(entry.type));\n\t\tconst value = normalizeString(entry.value);\n\t\tif (!type || !value) continue;\n\n\t\tif (!peppolID && type.includes(\"peppol\")) {\n\t\t\tpeppolID = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!glnNumber && type.includes(\"gln\")) {\n\t\t\tglnNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!vatNumber && type.includes(\"vat\")) {\n\t\t\tvatNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!taxNumber && type.includes(\"tax\")) {\n\t\t\ttaxNumber = value;\n\t\t}\n\t}\n\n\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n};\n\n/**\n * Build the fully-qualified Peppol participant identifiers (`scheme:value`) a\n * receiver lookup will accept, in priority order, de-duplicated.\n *\n * Stripe stores a customer's VAT number without a Peppol scheme (e.g.\n * `BE0206582284`), but a participant lookup needs the qualified identifier\n * (`9925:BE0206582284`). This attaches the right scheme:\n *\n * 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;\n * 2. a GLN under EAS `0088`;\n * 3. the VAT number under its country's VAT EAS scheme (see\n * {@link resolveVatEndpoint});\n * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)\n * under EAS `0208` — many Belgian entities register only under that;\n * 5. a generic tax/registration number under its country's company-ID scheme.\n *\n * `countryCode` (the customer's country, when known) disambiguates schemes for\n * identifiers that don't carry a country prefix (GLN, plain tax numbers).\n */\nexport const listPeppolReceiverIdentifierCandidates = (\n\tcustomer: {\n\t\tpeppolID?: string | null;\n\t\tglnNumber?: string | null;\n\t\ttaxNumber?: string | null;\n\t\tvatNumber?: string | null;\n\t},\n\tcountryCode?: string | null,\n): string[] => {\n\tconst candidates: string[] = [];\n\tconst add = (id: { scheme?: string | null; value: string } | null) => {\n\t\tif (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);\n\t};\n\n\t// 1. An explicit Peppol ID already carries its own scheme.\n\tconst peppol = normalizeString(customer.peppolID);\n\tif (peppol) candidates.push(peppol);\n\n\t// 2. GLN → EAS 0088 (Global Location Number).\n\tconst gln = normalizeString(customer.glnNumber);\n\tif (gln) add({ scheme: \"0088\", value: cleanIdentifierValue(gln) });\n\n\t// 3. VAT number → the country's VAT EAS scheme (e.g. BE → 9925).\n\tconst vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\tadd(vat);\n\n\t// 4. Belgium also reaches parties by enterprise number under EAS 0208; it is\n\t// the VAT digits without the `BE` prefix, and some entities register only so.\n\tif (vat?.scheme === \"9925\") {\n\t\tadd(\n\t\t\tbuildCompanyId({\n\t\t\t\tcountryCode: \"BE\",\n\t\t\t\tcompanyNumber: customer.vatNumber ?? null,\n\t\t\t}),\n\t\t);\n\t}\n\n\t// 5. A generic tax/registration number → its country's company-ID scheme.\n\tconst tax = normalizeString(customer.taxNumber);\n\tif (tax)\n\t\tadd(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));\n\n\treturn Array.from(new Set(candidates));\n};\n","import { normalizeAddress } from \"./address\";\nimport { buildCompanyId, parsePeppolEndpoint, resolveVatEndpoint } from \"./identifiers\";\nimport type { UblAddress, UblEndpoint, UblParty } from \"./ubl/types\";\nimport { normalizeString } from \"./utils\";\n\n/**\n * Supplier (seller) VAT status. Drives how zero-VAT lines are reported when the\n * seller does not charge VAT:\n *\n * 1 — Subject to VAT (the normal case): line categories come from the data.\n * 2 — Not subject to VAT.\n * 3 — Small business / franchise exemption (e.g. Belgian Article 56bis).\n *\n * For statuses 2 and 3, {@link ../build.ts} coerces all line categories to a\n * non-charging exempt category so no VAT is reported.\n */\nexport type SupplierVatStatus = 1 | 2 | 3;\n\n/**\n * Caller-provided supplier data, normalized into a stable shape.\n *\n * Each consumer builds this from its own data store. Once a `UblSupplier`\n * exists, the party builder no longer needs to know where it came from.\n */\nexport interface UblSupplier {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** ISO 3166-1 alpha-2 country code (e.g. `\"BE\"`). */\n\tcountryCode: string;\n\t/**\n\t * Free-form address. Stripe-style fields (`line1`, `postal_code`, `country`)\n\t * and legacy/internal fields (`street`, `zip_code`) are both accepted.\n\t */\n\taddress: unknown;\n\t/** Country-specific company/registration number (e.g. BE enterprise number). */\n\tcompanyNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n\t/** Whether the supplier charges VAT. See {@link SupplierVatStatus}. */\n\tvatStatus: SupplierVatStatus;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n}\n\n/** Convert a {@link UblSupplier} into the supplier (seller) party. */\nexport const buildSupplierParty = (supplier: UblSupplier): UblParty => {\n\tconst address = normalizeAddress(supplier.address, supplier.countryCode);\n\treturn {\n\t\tendpoint: parsePeppolEndpoint(supplier.peppolID),\n\t\tname: supplier.name,\n\t\taddress,\n\t\tvatNumber: normalizeString(supplier.vatNumber),\n\t\tlegalName: supplier.name,\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode: supplier.countryCode,\n\t\t\tcompanyNumber: supplier.companyNumber ?? null,\n\t\t}),\n\t};\n};\n\n/**\n * Caller-provided customer (buyer) data, normalized into a stable shape.\n *\n * Each consumer (the Stripe adapter, app-specific row builders) resolves its\n * own identifiers and address, then hands this generic shape to\n * {@link buildCustomerParty}, so the Peppol routing logic lives in one place.\n */\nexport interface UblCustomer {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** Customer address, already normalized by the caller. */\n\taddress: UblAddress;\n\t/**\n\t * The customer's ISO 3166-1 alpha-2 country, used to resolve VAT/registration\n\t * schemes for identifiers that don't carry a country prefix. Pass the\n\t * customer's *own* country (never the supplier's) so the document is not\n\t * mis-routed; falls back to the address country when omitted.\n\t */\n\tcountryCode?: string | null;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n\t/** Global Location Number (resolved under EAS `0088`). */\n\tglnNumber?: string | null;\n\t/** Generic tax/registration number (no VAT prefix). */\n\ttaxNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n}\n\n/**\n * Convert a {@link UblCustomer} into the customer (buyer) party.\n *\n * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in\n * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered\n * identifier), then an explicit Peppol ID, then a GLN (scheme `0088`), then the\n * VAT number mapped to its country's VAT EAS scheme (e.g. BE → `9925`). That\n * last step matters because most data stores hold a customer's VAT without a\n * scheme, so without it a VAT-only customer would have no endpoint and the\n * document would be unroutable.\n */\nexport const buildCustomerParty = (\n\tcustomer: UblCustomer,\n\tendpointOverride?: UblEndpoint | null,\n): UblParty => {\n\tconst countryCode =\n\t\tnormalizeString(customer.countryCode) ?? customer.address.countryCode;\n\tconst endpoint =\n\t\tendpointOverride ??\n\t\tparsePeppolEndpoint(customer.peppolID) ??\n\t\t(customer.glnNumber ? { scheme: \"0088\", value: customer.glnNumber } : null) ??\n\t\tresolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\n\treturn {\n\t\tendpoint,\n\t\tname: customer.name,\n\t\taddress: customer.address,\n\t\tvatNumber: normalizeString(customer.vatNumber),\n\t\tlegalName: customer.name,\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode,\n\t\t\tcompanyNumber: customer.taxNumber ?? null,\n\t\t}),\n\t};\n};\n","import type { UblAttachment, UblDocument } from \"./ubl/types\";\n\n/**\n * Build a UBL embedded-document attachment (BG-24) from raw bytes — e.g. the\n * rendered PDF of the invoice. Emitted as a `cac:AdditionalDocumentReference`\n * with an inline base64 `cbc:EmbeddedDocumentBinaryObject`.\n */\nexport const buildPdfAttachment = (params: {\n\tfilename: string;\n\tbytes: Uint8Array;\n\t/** Document reference ID (BT-122). Defaults to the filename. */\n\tid?: string;\n}): UblAttachment => ({\n\tid: params.id ?? params.filename,\n\tfilename: params.filename,\n\tmimeCode: \"application/pdf\",\n\tbase64: Buffer.from(params.bytes).toString(\"base64\"),\n});\n\n/**\n * Replace each attachment's base64 payload with `[omitted]` plus a length, so a\n * {@link UblDocument} is safe to log or persist for audit.\n */\nexport const sanitizeUblDocumentForAudit = (doc: UblDocument): UblDocument => {\n\tif (doc.attachments.length === 0) return doc;\n\treturn {\n\t\t...doc,\n\t\tattachments: doc.attachments.map((attachment) => ({\n\t\t\t...attachment,\n\t\t\tbase64: `[omitted ${attachment.base64.length} chars]`,\n\t\t})),\n\t};\n};\n","/** Round a number to 2 decimal places (cents). */\nexport const roundCurrency = (value: number) =>\n\tMath.round((value + Number.EPSILON) * 100) / 100;\n\n/** Convert an integer cent amount into a 2-decimal currency value. */\nexport const centsToDecimal = (cents: number) => roundCurrency(cents / 100);\n\n/** The `cac:Price` pair for a line: BT-146 and the optional BT-149. */\nexport interface UnitPrice {\n\t/** `cbc:PriceAmount` (BT-146). */\n\tpriceAmount: number;\n\t/** `cbc:BaseQuantity` (BT-149) — the units `priceAmount` covers. Omitted = 1. */\n\tbaseQuantity?: number;\n}\n\n/**\n * Derive the `cac:Price` for a line whose net total is authoritative.\n *\n * Peppol rule PEPPOL-EN16931-R120 checks\n * `quantity × (priceAmount ÷ baseQuantity)` against the line net amount within\n * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that\n * whenever the division doesn't land on a cent: 940.00 over 14 units gives\n * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and\n * rejected as a fatal validation error.\n *\n * So the cent-rounded unit price is only used when it reproduces the net\n * exactly. Otherwise the line is priced as a whole via BT-149 (`priceAmount` =\n * the net, `baseQuantity` = the quantity), which is exact at any magnitude\n * instead of merely within tolerance — the residual of a rounded unit price\n * grows with quantity and would eventually breach 0.02 at any fixed precision.\n */\nexport const deriveUnitPrice = (netTotal: number, quantity: number): UnitPrice => {\n\t// A zero or fractional-to-zero quantity still has to price something; BT-149\n\t// must be a positive number (PEPPOL-EN16931-R121), so floor the divisor at 1.\n\tconst units = quantity > 0 ? quantity : 1;\n\tconst perUnit = roundCurrency(netTotal / units);\n\tif (roundCurrency(perUnit * units) === roundCurrency(netTotal)) {\n\t\treturn { priceAmount: perUnit };\n\t}\n\treturn { priceAmount: roundCurrency(netTotal), baseQuantity: units };\n};\n","import type { UblTaxCategory } from \"./ubl/types\";\n\n/**\n * Stripe Tax `taxability_reason` values that map to a VAT-exempt UBL category\n * (`E`). Reverse charge is handled separately (category `AE`).\n */\nexport const EXEMPT_TAXABILITY_REASONS = new Set([\n\t\"customer_exempt\",\n\t\"product_exempt\",\n\t\"not_subject_to_tax\",\n\t\"not_collecting\",\n\t\"not_supported\",\n\t\"portion_product_exempt\",\n]);\n\n/** Human-readable EN 16931 exemption reasons (BR-E-10 / BR-AE-10 / …). */\nconst EXEMPTION_REASON_TEXT: Record<string, string> = {\n\treverse_charge: \"Reverse charge\",\n\tintra_community: \"Intra-community supply\",\n\texport: \"Export outside the EU\",\n\tcustomer_exempt: \"Exempt based on customer status\",\n\tproduct_exempt: \"Exempt based on the supplied goods or services\",\n\tportion_product_exempt: \"Exempt based on the supplied goods or services\",\n\tnot_subject_to_tax: \"Not subject to VAT\",\n\tnot_collecting: \"VAT not collected\",\n\tnot_supported: \"VAT not applicable\",\n};\n\nexport interface TaxAmountInfo {\n\tamount: number;\n\ttaxability_reason?: string | null;\n\ttax_rate_percentage?: number | null;\n}\n\nconst normalizeTaxCategoryId = (value: unknown) => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim().toUpperCase();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\n/**\n * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a\n * numeric rate into a {@link UblTaxCategory}.\n *\n * - Reverse charge → `AE` (0%, with exemption reason)\n * - Intra-community supply → `K` (0%, with exemption reason)\n * - Export outside the EU → `G` (0%, with exemption reason)\n * - Any other exempt reason → `E` (0%, with exemption reason)\n * - Category `Z` / rate ≤ 0 → `Z` (zero-rated, 0%)\n * - Otherwise → `S` (standard, the line's rate)\n */\nexport const taxCategoryFromReasonOrRate = (params: {\n\ttaxCategoryId?: string | null;\n\ttaxabilityReason: string | null;\n\trate: number;\n}): UblTaxCategory => {\n\tconst categoryHint = normalizeTaxCategoryId(params.taxCategoryId);\n\tconst reason = params.taxabilityReason;\n\n\tif (categoryHint === \"AE\" || reason === \"reverse_charge\") {\n\t\treturn {\n\t\t\tid: \"AE\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.reverse_charge,\n\t\t};\n\t}\n\tif (categoryHint === \"K\" || reason === \"intra_community\") {\n\t\treturn {\n\t\t\tid: \"K\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.intra_community,\n\t\t};\n\t}\n\tif (categoryHint === \"G\" || reason === \"export\") {\n\t\treturn {\n\t\t\tid: \"G\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.export,\n\t\t};\n\t}\n\tif (categoryHint === \"E\" || (reason && EXEMPT_TAXABILITY_REASONS.has(reason))) {\n\t\treturn {\n\t\t\tid: \"E\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason:\n\t\t\t\t(reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? \"Exempt from VAT\",\n\t\t};\n\t}\n\tif (categoryHint === \"Z\" || reason === \"zero_rated\" || params.rate <= 0) {\n\t\treturn { id: \"Z\", percent: 0 };\n\t}\n\treturn { id: \"S\", percent: params.rate };\n};\n\n/**\n * Resolve a {@link UblTaxCategory} from a line's Stripe tax info.\n *\n * Exempt / reverse-charge / zero-rated reasons take precedence over the rate;\n * otherwise the rate decides standard (`S`) vs zero-rated (`Z`).\n */\nexport const resolveTaxCategoryFromTaxAmounts = (\n\ttaxAmounts: TaxAmountInfo[],\n\trate: number,\n): UblTaxCategory => {\n\tfor (const ta of taxAmounts) {\n\t\tif (!ta.taxability_reason) continue;\n\t\tif (ta.taxability_reason === \"reverse_charge\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"reverse_charge\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: ta.taxability_reason,\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (ta.taxability_reason === \"zero_rated\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"zero_rated\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t}\n\treturn taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });\n};\n","import { deriveUnitPrice, roundCurrency } from \"./numeric\";\nimport type {\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"./ubl/types\";\n\n/**\n * Adjust the largest line's net amount so the line nets sum to the\n * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).\n *\n * Reconciling at the *line* level — rather than directly on the VAT breakdown —\n * keeps the document consistent bottom-up: the VAT category taxable amounts\n * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the\n * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level\n * coupon; larger ones indicate a real upstream data problem.\n */\nexport const reconcileLinesToExclTotal = (\n\tlines: UblLine[],\n\tauthoritativeTotalExclVat: number,\n): UblLine[] => {\n\tif (lines.length === 0) return lines;\n\tconst computed = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst diff = roundCurrency(authoritativeTotalExclVat - computed);\n\tif (diff === 0) return lines;\n\n\tconst largestIdx = lines.reduce(\n\t\t(maxIdx, line, idx, arr) =>\n\t\t\tline.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0)\n\t\t\t\t? idx\n\t\t\t\t: maxIdx,\n\t\t0,\n\t);\n\n\treturn lines.map((line, idx) => {\n\t\tif (idx !== largestIdx) return line;\n\t\tconst adjusted = roundCurrency(line.lineExtensionAmount + diff);\n\t\t// Re-derive the price from the adjusted net through the shared helper —\n\t\t// nudging the net without re-deriving BT-146/BT-149 to match is exactly\n\t\t// what PEPPOL-EN16931-R120 rejects. Assign `baseQuantity` unconditionally\n\t\t// so a line that no longer needs one doesn't keep a stale value.\n\t\tconst { priceAmount, baseQuantity } = deriveUnitPrice(adjusted, line.quantity);\n\t\treturn {\n\t\t\t...line,\n\t\t\tlineExtensionAmount: adjusted,\n\t\t\tpriceAmount,\n\t\t\tbaseQuantity,\n\t\t};\n\t});\n};\n\nconst categoryKey = (category: UblTaxCategory): string =>\n\t`${category.id}:${category.percent}`;\n\nexport interface BuildTaxTotalsResult {\n\ttaxTotal: UblTaxTotal;\n\tmonetaryTotal: UblMonetaryTotal;\n}\n\nexport interface BuildTaxTotalsOptions {\n\t/**\n\t * BT-113 — amount already paid, **gross (VAT-inclusive)**. Subtracted from\n\t * BT-112 to derive the outstanding `payableAmount` (BR-CO-16). Pass the full\n\t * gross total for a settled document so it reports a payable amount of 0.\n\t */\n\tprepaidAmount?: number;\n\t/** BT-114 — rounding applied to the payable amount. */\n\tpayableRoundingAmount?: number;\n}\n\n/**\n * Group lines by `(category, percent)` into a VAT breakdown and compute the\n * document monetary totals.\n *\n * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,\n * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the\n * upstream per-line tax cents. This guarantees the breakdown is internally\n * consistent and passes validation; it can differ by a cent from the figure a\n * payment processor reported, which is an unavoidable artifact of representing\n * a cents-rounded system as a rate-based VAT breakdown.\n *\n * `payableAmount` is derived per BR-CO-16 (`BT-112 − BT-113 + BT-114`) so the\n * invariant holds by construction. The result is *not* clamped: a prepayment\n * exceeding the total yields a negative payable amount, surfacing the upstream\n * overpayment rather than hiding it.\n */\nexport const buildTaxTotals = (\n\tlines: UblLine[],\n\toptions?: BuildTaxTotalsOptions,\n): BuildTaxTotalsResult => {\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ category: UblTaxCategory; taxableAmount: number }\n\t>();\n\n\tfor (const line of lines) {\n\t\tconst key = categoryKey(line.taxCategory);\n\t\tconst current = groups.get(key) ?? {\n\t\t\tcategory: line.taxCategory,\n\t\t\ttaxableAmount: 0,\n\t\t};\n\t\tcurrent.taxableAmount = roundCurrency(\n\t\t\tcurrent.taxableAmount + line.lineExtensionAmount,\n\t\t);\n\t\tgroups.set(key, current);\n\t}\n\n\tconst subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({\n\t\ttaxableAmount: group.taxableAmount,\n\t\ttaxAmount: roundCurrency((group.taxableAmount * group.category.percent) / 100),\n\t\tcategory: group.category,\n\t}));\n\n\tconst lineExtensionAmount = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst taxAmount = roundCurrency(\n\t\tsubtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0),\n\t);\n\tconst taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);\n\n\tconst prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);\n\tconst payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);\n\tconst payableAmount = roundCurrency(\n\t\ttaxInclusiveAmount - prepaidAmount + payableRoundingAmount,\n\t);\n\n\treturn {\n\t\ttaxTotal: { taxAmount, subtotals },\n\t\tmonetaryTotal: {\n\t\t\tlineExtensionAmount,\n\t\t\ttaxExclusiveAmount: lineExtensionAmount,\n\t\t\ttaxInclusiveAmount,\n\t\t\t...(prepaidAmount ? { prepaidAmount } : {}),\n\t\t\t...(payableRoundingAmount ? { payableRoundingAmount } : {}),\n\t\t\tpayableAmount,\n\t\t},\n\t};\n};\n"],"mappings":";;;AAGA,MAAa,uBACZ;;AAGD,MAAa,iBAAiB;;AAG9B,MAAa,oBAAoB;;AAEjC,MAAa,wBAAwB;;AAGrC,MAAa,oBAAoB;;AAGjC,MAAa,oBAAoB;;AAGjC,MAAa,uBAAuB;AAEpC,MAAa,aAAa;AAC1B,MAAa,iBACZ;AACD,MAAa,SACZ;AACD,MAAa,SACZ;;;;;;;;;;ACCD,MAAa,MACZ,MACA,OACA,YACgB;CAChB,IAAI,MAAM,QAAQ,OAAO,GACxB,OAAO;EACN;EACA,OAAO,SAAS,KAAA;EAChB,UAAU,QAAQ,QAAQ,MAAuB,QAAQ,CAAC,CAAC;CAC5D;CAED,OAAO;EAAE;EAAM,OAAO,SAAS,KAAA;EAAW,MAAM,WAAW,KAAA;CAAU;AACtE;AAEA,MAAM,cAAc,UACnB,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM;AAExE,MAAM,cAAc,UAA0B,WAAW,KAAK,CAAC,CAAC,QAAQ,MAAM,QAAQ;AAEtF,MAAM,kBAAkB,UAAwC;CAC/D,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,OAAO,QAAQ,KAAK,CAAC,CAC1B,QAAQ,GAAG,WAAW,UAAU,QAAQ,UAAU,KAAA,CAAS,CAAC,CAC5D,KAAK,CAAC,KAAK,WAAW,IAAI,IAAI,IAAI,WAAW,OAAO,KAAK,CAAC,E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ts","../src/normalize.ts"],"mappings":";UAEiB;EAChB;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;EACA;;UAGgB;EAChB;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,uBAAuB;EACvB,UAAU;EACV,UAAU;;UAGM;EAChB;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,eAAe;EACf,mBAAmB;EACnB;EACA;EACA;EACA;EACA;EACA,2BAA2B;;UAGX;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;;UAGgB;EAChB;EACA,UAAU;;UAGM;EAChB;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,mBAAmB;EACnB,QAAQ;EACR,OAAO;EACP,WAAW;EACX,OAAO;EACP,cAAc;EACd,eAAe;EACf,eAAe;EACf,mBAAmB;EACnB,gBAAgB;EAChB;EACA;EACA,cAAc;EACd,qBAAqB;EACrB,mBAAmB;;UAKH;EAChB;EACA;EACA;IACC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;MACC;MACA;MACA;MACA;MACA;;IAED;MACC;MACA;MACA;;IAED,OAAO;;EAER,YAAY;IACX;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,OAAO;;EAER;IACC;IACA,QAAQ;;;;;;;;;;UC9MO;EAChB;EACA;EACA;EACA;;EAEA;EACA;;;;;;;;cAYY,gCAA6B,gBAAkB;;;;;cAwB/C,sBAAmB,YACnB,KAAK;;;iBCmcF,gBAAgB,cAAc;;;;;;;cCzejC;;cAIA;;;;;UAMI;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;;;;;;;cA8FY,+BAA4B;EACxC;EACA;EACA;;;;;;;cAgBY,kCAA+B,gBAEzC;;;cC9HU,oBAAiB;cAOjB,YAAS;;;;cAmHT,iBAAc,OAAW;;;;;cASzB,uBAAoB,aACrB;EAGX,WAAW;EACX,YAAY;;;;;cA8NA,0BAAuB;EACnC,OAAO;EACP;EACA;;;;;aAFO"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/attachments.ts","../src/parser.ts","../src/mlr.ts","../src/normalize.ts"],"mappings":";UAEiB;EAChB;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;EACA;;UAGgB;EAChB;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,uBAAuB;EACvB,UAAU;EACV,UAAU;;UAGM;EAChB;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,eAAe;EACf,mBAAmB;EACnB;EACA;EACA;EACA;EACA;EACA,2BAA2B;;UAGX;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;;UAGgB;EAChB;EACA;;UAGgB;EAChB;EACA,UAAU;;UAGM;EAChB;EACA;;UAGgB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,mBAAmB;EACnB,QAAQ;EACR,OAAO;EACP,WAAW;EACX,OAAO;EACP,cAAc;EACd,eAAe;EACf,eAAe;EACf,mBAAmB;EACnB,gBAAgB;EAChB;EACA;EACA,cAAc;EACd,qBAAqB;EACrB,mBAAmB;;UAKH;EAChB;EACA;EACA;IACC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;MACC;MACA;MACA;MACA;MACA;;IAED;MACC;MACA;MACA;;IAED,OAAO;;EAER,YAAY;IACX;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,OAAO;;EAER;IACC;IACA,QAAQ;;;;;;;;;;UC9MO;EAChB;EACA;EACA;EACA;;EAEA;EACA;;;;;;;;cAYY,gCAA6B,gBAAkB;;;;;cAwB/C,sBAAmB,YACnB,KAAK;;;iBCmcF,gBAAgB,cAAc;;;;;;;cC7ejC;;cAIA;;;;;UAMI;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;;;;;;;cA8FY,+BAA4B;EACxC;EACA;EACA;;;;;;;cAgBY,kCAA+B,gBAEzC;;;cC1HU,oBAAiB;cAOjB,YAAS;;;;cAmHT,iBAAc,OAAW;;;;;cASzB,uBAAoB,aACrB;EAGX,WAAW;EACX,YAAY;;;;;cA8NA,0BAAuB;EACnC,OAAO;EACP;EACA;;;;;aAFO"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["CBC_NS","CAC_NS","cbcText","cacElement","cbcDirectText","stripDoctype","XmlDomParser","XmlDomParser"],"sources":["../src/parser.ts","../src/attachments.ts","../src/mlr.ts","../src/normalize.ts"],"sourcesContent":["import { DOMParser as XmlDomParser, type Element } from \"@xmldom/xmldom\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\n\tUblDelivery,\n\tUblDocumentReference,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblItemProperty,\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblParty,\n\tUblPartyIdentification,\n\tUblPaymentMeans,\n\tUblTaxSubtotal,\n} from \"./types.js\";\n\nconst CBC_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nconst CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n// --- DOM helpers ---\n\nfunction cbcText(parent: Element, tag: string): string {\n\tconst el = parent.getElementsByTagNameNS(CBC_NS, tag)[0];\n\treturn el?.textContent?.trim() ?? \"\";\n}\n\nfunction cacElement(parent: Element, tag: string): Element | null {\n\treturn parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacElements(parent: Element, tag: string): Element[] {\n\treturn Array.from(parent.getElementsByTagNameNS(CAC_NS, tag));\n}\n\nfunction cbcNumber(parent: Element, tag: string): number {\n\tconst n = Number.parseFloat(cbcText(parent, tag));\n\treturn Number.isNaN(n) ? 0 : n;\n}\n\nfunction childElementsByTagNs(\n\tparent: Element,\n\tnamespace: string,\n\ttag: string,\n): Element[] {\n\tconst elements: Element[] = [];\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst element = node as Element;\n\t\tif (element.namespaceURI === namespace && element.localName === tag) {\n\t\t\telements.push(element);\n\t\t}\n\t}\n\treturn elements;\n}\n\nfunction cbcDirectText(parent: Element, tag: string): string {\n\tconst el = childElementsByTagNs(parent, CBC_NS, tag)[0];\n\treturn el?.textContent?.trim() ?? \"\";\n}\n\nfunction cbcDirectNumber(parent: Element, tag: string): number | null {\n\tconst value = cbcDirectText(parent, tag);\n\tif (!value) return null;\n\tconst parsed = Number.parseFloat(value);\n\treturn Number.isNaN(parsed) ? null : parsed;\n}\n\nfunction cacDirectElement(parent: Element, tag: string): Element | null {\n\treturn childElementsByTagNs(parent, CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacDirectElements(parent: Element, tag: string): Element[] {\n\treturn childElementsByTagNs(parent, CAC_NS, tag);\n}\n\n// --- Section parsers ---\n\nfunction parseAddressFromElement(address: Element | null): UblAddress | undefined {\n\tif (!address) return undefined;\n\tconst country = cacElement(address, \"Country\");\n\treturn {\n\t\tstreet: cbcText(address, \"StreetName\"),\n\t\tadditionalStreet: cbcText(address, \"AdditionalStreetName\") || undefined,\n\t\tcity: cbcText(address, \"CityName\"),\n\t\tpostalZone: cbcText(address, \"PostalZone\"),\n\t\tcountrySubentity: cbcText(address, \"CountrySubentity\") || undefined,\n\t\tcountryCode: country ? cbcText(country, \"IdentificationCode\") : \"\",\n\t};\n}\n\nfunction parseAddress(party: Element): UblAddress | undefined {\n\tconst postal = cacElement(party, \"PostalAddress\");\n\treturn parseAddressFromElement(postal);\n}\n\nfunction parseTaxSchemeId(parent: Element | null): string | undefined {\n\tif (!parent) return undefined;\n\tconst taxScheme = cacElement(parent, \"TaxScheme\");\n\tif (!taxScheme) return undefined;\n\treturn cbcText(taxScheme, \"ID\") || undefined;\n}\n\nfunction parseContact(party: Element): import(\"./types.js\").UblContact | undefined {\n\tconst contact = cacElement(party, \"Contact\");\n\tif (!contact) return undefined;\n\tconst name = cbcText(contact, \"Name\");\n\tconst phone = cbcText(contact, \"Telephone\");\n\tconst email = cbcText(contact, \"ElectronicMail\");\n\tif (!name && !phone && !email) return undefined;\n\treturn {\n\t\tname: name || undefined,\n\t\tphone: phone || undefined,\n\t\temail: email || undefined,\n\t};\n}\n\nfunction parsePartyIdentifications(party: Element): UblPartyIdentification[] {\n\tconst ids = cacElements(party, \"PartyIdentification\");\n\tconst result: UblPartyIdentification[] = [];\n\tfor (const idEl of ids) {\n\t\tconst idValue = cbcText(idEl, \"ID\");\n\t\tif (!idValue) continue;\n\t\tconst schemeIdAttr = idEl\n\t\t\t.getElementsByTagNameNS(CBC_NS, \"ID\")[0]\n\t\t\t?.getAttribute(\"schemeID\");\n\t\tresult.push({\n\t\t\tid: idValue,\n\t\t\tschemeId: schemeIdAttr || undefined,\n\t\t});\n\t}\n\treturn result;\n}\n\nfunction parseParty(root: Element, role: string): UblParty {\n\tconst wrapper = cacElement(root, role);\n\tconst party = wrapper ? cacElement(wrapper, \"Party\") : null;\n\tif (!party) return { name: \"Unknown\" };\n\n\tconst partyName = cacElement(party, \"PartyName\");\n\tconst legalEntity = cacElement(party, \"PartyLegalEntity\");\n\tconst taxScheme = cacElement(party, \"PartyTaxScheme\");\n\tconst partyId = cacElement(party, \"PartyIdentification\");\n\tconst endpointEl = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tconst partyIdentifications = parsePartyIdentifications(party);\n\tconst companyIdEl = legalEntity\n\t\t? legalEntity.getElementsByTagNameNS(CBC_NS, \"CompanyID\")[0]\n\t\t: null;\n\n\treturn {\n\t\tname: partyName ? cbcText(partyName, \"Name\") : \"\",\n\t\tregistrationName: legalEntity\n\t\t\t? cbcText(legalEntity, \"RegistrationName\") || undefined\n\t\t\t: undefined,\n\t\tcompanyLegalForm: legalEntity\n\t\t\t? cbcText(legalEntity, \"CompanyLegalForm\") || undefined\n\t\t\t: undefined,\n\t\tvatId: taxScheme ? cbcText(taxScheme, \"CompanyID\") || undefined : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxScheme),\n\t\tcompanyId: companyIdEl\n\t\t\t? companyIdEl.textContent?.trim() || undefined\n\t\t\t: partyId\n\t\t\t\t? cbcText(partyId, \"ID\") || undefined\n\t\t\t\t: undefined,\n\t\tcompanyIdSchemeId: companyIdEl?.getAttribute(\"schemeID\") || undefined,\n\t\tendpointId: endpointEl?.textContent?.trim() || undefined,\n\t\tendpointSchemeId: endpointEl?.getAttribute(\"schemeID\") || undefined,\n\t\tpartyIdentifications:\n\t\t\tpartyIdentifications.length > 0 ? partyIdentifications : undefined,\n\t\taddress: parseAddress(party),\n\t\tcontact: parseContact(party),\n\t};\n}\n\nfunction parseTaxSubtotal(sub: Element): UblTaxSubtotal {\n\tconst cat = cacElement(sub, \"TaxCategory\");\n\treturn {\n\t\ttaxableAmount: cbcNumber(sub, \"TaxableAmount\"),\n\t\ttaxAmount: cbcNumber(sub, \"TaxAmount\"),\n\t\ttaxPercent: (cat ? cbcNumber(cat, \"Percent\") : 0) || cbcNumber(sub, \"Percent\"),\n\t\ttaxCategoryId: cat ? cbcText(cat, \"ID\") || undefined : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(cat),\n\t\ttaxExemptionReason: cat\n\t\t\t? cbcText(cat, \"TaxExemptionReason\") || undefined\n\t\t\t: undefined,\n\t};\n}\n\nfunction parseTaxSubtotalsFromTaxTotal(taxTotal: Element): UblTaxSubtotal[] {\n\treturn cacDirectElements(taxTotal, \"TaxSubtotal\").map(parseTaxSubtotal);\n}\n\nfunction parseTaxSubtotals(root: Element): UblTaxSubtotal[] {\n\tconst taxTotals = cacDirectElements(root, \"TaxTotal\");\n\tif (taxTotals.length === 0) return [];\n\treturn taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal);\n}\n\nfunction parseAllowanceCharge(charge: Element): UblAllowanceCharge {\n\tconst taxCategory = cacElement(charge, \"TaxCategory\");\n\tconst indicatorRaw = cbcDirectText(charge, \"ChargeIndicator\").toLowerCase();\n\tconst chargeIndicator = indicatorRaw === \"true\" || indicatorRaw === \"1\";\n\treturn {\n\t\tchargeIndicator,\n\t\tamount: cbcNumber(charge, \"Amount\"),\n\t\tbaseAmount: cbcDirectNumber(charge, \"BaseAmount\") ?? undefined,\n\t\tmultiplierFactorNumeric:\n\t\t\tcbcDirectNumber(charge, \"MultiplierFactorNumeric\") ?? undefined,\n\t\treason: cbcText(charge, \"AllowanceChargeReason\") || undefined,\n\t\treasonCode: cbcText(charge, \"AllowanceChargeReasonCode\") || undefined,\n\t\ttaxPercent: taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined,\n\t\ttaxCategoryId: taxCategory\n\t\t\t? cbcText(taxCategory, \"ID\") || undefined\n\t\t\t: undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxCategory),\n\t};\n}\n\nfunction parseAllowanceCharges(parent: Element): UblAllowanceCharge[] {\n\treturn cacDirectElements(parent, \"AllowanceCharge\").map(parseAllowanceCharge);\n}\n\nfunction parseLines(root: Element, isCreditNote: boolean): UblLine[] {\n\tconst qtyTag = isCreditNote ? \"CreditedQuantity\" : \"InvoicedQuantity\";\n\tconst lineTag = isCreditNote ? \"CreditNoteLine\" : \"InvoiceLine\";\n\n\treturn cacElements(root, lineTag).map((line) => {\n\t\tconst item = cacElement(line, \"Item\");\n\t\tconst price = cacElement(line, \"Price\");\n\t\tconst taxCategory = item ? cacElement(item, \"ClassifiedTaxCategory\") : null;\n\t\tconst sellersId = item ? cacElement(item, \"SellersItemIdentification\") : null;\n\t\tconst buyersId = item ? cacElement(item, \"BuyersItemIdentification\") : null;\n\t\tconst qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];\n\t\tconst lineExtensionAmount = cbcNumber(line, \"LineExtensionAmount\");\n\t\tconst lineTaxTotal = cacDirectElement(line, \"TaxTotal\");\n\t\tconst lineTaxSubtotals = lineTaxTotal\n\t\t\t? parseTaxSubtotalsFromTaxTotal(lineTaxTotal)\n\t\t\t: [];\n\t\tconst taxAmountFromSubtotals = lineTaxSubtotals.reduce(\n\t\t\t(sum, subtotal) => sum + subtotal.taxAmount,\n\t\t\t0,\n\t\t);\n\t\tconst taxAmountFromLineTotal = lineTaxTotal\n\t\t\t? cbcDirectNumber(lineTaxTotal, \"TaxAmount\")\n\t\t\t: null;\n\t\tconst taxPercent =\n\t\t\tlineTaxSubtotals[0]?.taxPercent ??\n\t\t\t(taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined);\n\t\tconst computedTaxAmount =\n\t\t\ttaxPercent !== undefined\n\t\t\t\t? Number(((lineExtensionAmount * taxPercent) / 100).toFixed(2))\n\t\t\t\t: undefined;\n\t\tconst lineAllowanceCharges = parseAllowanceCharges(line);\n\t\tconst priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];\n\t\tconst allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];\n\t\tconst discountAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum : sum + Math.abs(charge.amount),\n\t\t\t0,\n\t\t);\n\t\tconst chargeAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum + Math.abs(charge.amount) : sum,\n\t\t\t0,\n\t\t);\n\n\t\tconst additionalItemProperties: UblItemProperty[] = [];\n\t\tif (item) {\n\t\t\tfor (const prop of cacElements(item, \"AdditionalItemProperty\")) {\n\t\t\t\tconst propName = cbcText(prop, \"Name\");\n\t\t\t\tconst propValue = cbcText(prop, \"Value\");\n\t\t\t\tif (propName) {\n\t\t\t\t\tadditionalItemProperties.push({\n\t\t\t\t\t\tname: propName,\n\t\t\t\t\t\tvalue: propValue,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// EN16931 BT-146 (PriceAmount) is the price for BT-149 (BaseQuantity) units\n\t\t// of the item, not necessarily for one unit. Effective unit price is\n\t\t// PriceAmount / BaseQuantity, with BaseQuantity defaulting to 1 when absent.\n\t\tconst priceAmount = price ? cbcNumber(price, \"PriceAmount\") : 0;\n\t\tconst priceBaseQuantity = price ? cbcDirectNumber(price, \"BaseQuantity\") : null;\n\t\tconst unitPrice =\n\t\t\tpriceBaseQuantity && priceBaseQuantity > 0\n\t\t\t\t? priceAmount / priceBaseQuantity\n\t\t\t\t: priceAmount;\n\n\t\treturn {\n\t\t\tid: cbcText(line, \"ID\"),\n\t\t\tdescription: item ? cbcText(item, \"Description\") : \"\",\n\t\t\tquantity: cbcNumber(line, qtyTag),\n\t\t\tunitCode: qtyEl?.getAttribute(\"unitCode\") ?? \"\",\n\t\t\tunitPrice,\n\t\t\tlineExtensionAmount,\n\t\t\ttaxPercent,\n\t\t\ttaxAmount:\n\t\t\t\ttaxAmountFromLineTotal ??\n\t\t\t\t(lineTaxSubtotals.length > 0\n\t\t\t\t\t? taxAmountFromSubtotals\n\t\t\t\t\t: computedTaxAmount),\n\t\t\ttaxCategoryId:\n\t\t\t\tlineTaxSubtotals[0]?.taxCategoryId ??\n\t\t\t\t(taxCategory ? cbcText(taxCategory, \"ID\") || undefined : undefined),\n\t\t\ttaxSchemeId:\n\t\t\t\tlineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),\n\t\t\ttaxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : undefined,\n\t\t\tallowanceCharges:\n\t\t\t\tallowanceCharges.length > 0 ? allowanceCharges : undefined,\n\t\t\tdiscountAmount: discountAmount > 0 ? discountAmount : undefined,\n\t\t\tchargeAmount: chargeAmount > 0 ? chargeAmount : undefined,\n\t\t\titemName: item ? cbcText(item, \"Name\") || undefined : undefined,\n\t\t\tsellersItemId: sellersId\n\t\t\t\t? cbcText(sellersId, \"ID\") || undefined\n\t\t\t\t: undefined,\n\t\t\tbuyersItemId: buyersId ? cbcText(buyersId, \"ID\") || undefined : undefined,\n\t\t\tadditionalItemProperties:\n\t\t\t\tadditionalItemProperties.length > 0\n\t\t\t\t\t? additionalItemProperties\n\t\t\t\t\t: undefined,\n\t\t};\n\t});\n}\n\nfunction parseMonetaryTotal(root: Element): UblMonetaryTotal {\n\tconst total = cacDirectElement(root, \"LegalMonetaryTotal\");\n\tif (!total) {\n\t\treturn {\n\t\t\tlineExtensionAmount: 0,\n\t\t\ttaxExclusiveAmount: 0,\n\t\t\ttaxInclusiveAmount: 0,\n\t\t\tpayableAmount: 0,\n\t\t};\n\t}\n\treturn {\n\t\tlineExtensionAmount: cbcNumber(total, \"LineExtensionAmount\"),\n\t\ttaxExclusiveAmount: cbcNumber(total, \"TaxExclusiveAmount\"),\n\t\ttaxInclusiveAmount: cbcNumber(total, \"TaxInclusiveAmount\"),\n\t\tallowanceTotalAmount: cbcNumber(total, \"AllowanceTotalAmount\") || undefined,\n\t\tchargeTotalAmount: cbcNumber(total, \"ChargeTotalAmount\") || undefined,\n\t\tprepaidAmount: cbcNumber(total, \"PrepaidAmount\") || undefined,\n\t\tpayableRoundingAmount: cbcNumber(total, \"PayableRoundingAmount\") || undefined,\n\t\tpayableAmount: cbcNumber(total, \"PayableAmount\"),\n\t};\n}\n\nfunction parsePaymentMeansElement(pm: Element): UblPaymentMeans {\n\tconst account = cacElement(pm, \"PayeeFinancialAccount\");\n\tconst branch = account ? cacElement(account, \"FinancialInstitutionBranch\") : null;\n\tconst paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, \"PaymentMeansCode\")[0];\n\tconst mandate = cacElement(pm, \"PaymentMandate\");\n\n\treturn {\n\t\tcode: cbcText(pm, \"PaymentMeansCode\"),\n\t\tcodeName: paymentMeansCodeEl?.getAttribute(\"name\") || undefined,\n\t\tpaymentId: cbcText(pm, \"PaymentID\") || undefined,\n\t\tiban: account ? cbcText(account, \"ID\") || undefined : undefined,\n\t\tbic: branch ? cbcText(branch, \"ID\") || undefined : undefined,\n\t\taccountName: (account && cbcText(account, \"Name\")) || undefined,\n\t\tmandateId: mandate ? cbcText(mandate, \"ID\") || undefined : undefined,\n\t};\n}\n\nfunction parsePaymentMeansList(root: Element): UblPaymentMeans[] | undefined {\n\tconst list = cacElements(root, \"PaymentMeans\").map(parsePaymentMeansElement);\n\treturn list.length > 0 ? list : undefined;\n}\n\nfunction parseInvoicePeriod(root: Element): UblInvoicePeriod | undefined {\n\tconst period = cacElement(root, \"InvoicePeriod\");\n\tif (!period) return undefined;\n\n\tconst start = cbcText(period, \"StartDate\");\n\tconst end = cbcText(period, \"EndDate\");\n\tif (!start && !end) return undefined;\n\n\treturn {\n\t\tstartDate: start || undefined,\n\t\tendDate: end || undefined,\n\t\tdescriptionCode: cbcText(period, \"DescriptionCode\") || undefined,\n\t};\n}\n\nfunction parseDelivery(root: Element): UblDelivery | undefined {\n\tconst delivery = cacElement(root, \"Delivery\");\n\tif (!delivery) return undefined;\n\tconst actualDeliveryDate = cbcText(delivery, \"ActualDeliveryDate\") || undefined;\n\tconst deliveryLocation = cacElement(delivery, \"DeliveryLocation\");\n\tconst address = parseAddressFromElement(\n\t\tdeliveryLocation ? cacElement(deliveryLocation, \"Address\") : null,\n\t);\n\tif (!actualDeliveryDate && !address) return undefined;\n\treturn {\n\t\tactualDeliveryDate,\n\t\taddress,\n\t};\n}\n\nfunction parsePaymentTermsNote(root: Element): string | undefined {\n\tconst paymentTerms = cacElement(root, \"PaymentTerms\");\n\tif (!paymentTerms) return undefined;\n\tconst note = cbcText(paymentTerms, \"Note\");\n\treturn note || undefined;\n}\n\nfunction parseNotes(root: Element): string | undefined {\n\tconst noteEls = root.getElementsByTagNameNS(CBC_NS, \"Note\");\n\tconst notes: string[] = [];\n\tfor (let i = 0; i < noteEls.length; i++) {\n\t\tconst el = noteEls[i];\n\t\tif (!el) continue;\n\t\tif (el.parentElement === root || el.parentNode === root) {\n\t\t\tconst text = el.textContent?.trim();\n\t\t\tif (text) notes.push(text);\n\t\t}\n\t}\n\treturn notes.length > 0 ? notes.join(\"\\n\") : undefined;\n}\n\nfunction parseAttachments(root: Element): {\n\tattachments: UblAttachment[] | undefined;\n\tdocumentReferences: UblDocumentReference[] | undefined;\n} {\n\tconst refs = cacElements(root, \"AdditionalDocumentReference\");\n\tconst attachments: UblAttachment[] = [];\n\tconst documentReferences: UblDocumentReference[] = [];\n\n\tfor (const ref of refs) {\n\t\tconst attachment = cacElement(ref, \"Attachment\");\n\t\tconst refId = cbcText(ref, \"ID\");\n\t\tconst description = cbcText(ref, \"DocumentDescription\") || undefined;\n\n\t\tif (!attachment) {\n\t\t\t// Text-only document reference (e.g. terms & conditions, notices)\n\t\t\tif (refId || description) {\n\t\t\t\tdocumentReferences.push({ id: refId, description });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst binaryEl = attachment.getElementsByTagNameNS(\n\t\t\tCBC_NS,\n\t\t\t\"EmbeddedDocumentBinaryObject\",\n\t\t)[0];\n\t\tconst externalRef = cacElement(attachment, \"ExternalReference\");\n\n\t\tif (binaryEl) {\n\t\t\tconst content = binaryEl.textContent?.trim();\n\t\t\tif (content) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tfilename: binaryEl.getAttribute(\"filename\") || undefined,\n\t\t\t\t\tmimeCode: binaryEl.getAttribute(\"mimeCode\") || undefined,\n\t\t\t\t\tdescription,\n\t\t\t\t\tbase64Content: content,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (externalRef) {\n\t\t\tconst uri = cbcText(externalRef, \"URI\");\n\t\t\tif (uri) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tdescription,\n\t\t\t\t\texternalUri: uri,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tattachments: attachments.length > 0 ? attachments : undefined,\n\t\tdocumentReferences:\n\t\t\tdocumentReferences.length > 0 ? documentReferences : undefined,\n\t};\n}\n\nfunction parseBillingReference(root: Element): UblBillingReference | undefined {\n\tconst billingRef = cacElement(root, \"BillingReference\");\n\tif (!billingRef) return undefined;\n\tconst invoiceRef = cacElement(billingRef, \"InvoiceDocumentReference\");\n\tif (!invoiceRef) return undefined;\n\tconst invoiceId = cbcText(invoiceRef, \"ID\") || undefined;\n\tconst invoiceIssueDate = cbcText(invoiceRef, \"IssueDate\") || undefined;\n\tif (!invoiceId && !invoiceIssueDate) return undefined;\n\treturn { invoiceId, invoiceIssueDate };\n}\n\n// --- Main parser ---\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove\n * DOCTYPE blocks (including inline DTD subsets) before parsing.\n */\nconst stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\nexport function parseUblInvoice(xml: string): UblInvoice | null {\n\ttry {\n\t\tconst safeXml = stripDoctype(xml);\n\t\tconst BrowserDomParser = (globalThis as { DOMParser?: typeof XmlDomParser })\n\t\t\t.DOMParser;\n\t\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\t\tconst doc = parser.parseFromString(safeXml, \"text/xml\");\n\t\tif (doc.getElementsByTagName(\"parsererror\").length > 0) return null;\n\n\t\tconst root = doc.documentElement;\n\t\tif (!root) return null;\n\t\tconst localName = root.localName;\n\n\t\tlet documentType: \"Invoice\" | \"CreditNote\";\n\t\tif (localName === \"Invoice\") {\n\t\t\tdocumentType = \"Invoice\";\n\t\t} else if (localName === \"CreditNote\") {\n\t\t\tdocumentType = \"CreditNote\";\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst isCreditNote = documentType === \"CreditNote\";\n\t\tconst id = cbcText(root, \"ID\");\n\t\tif (!id) return null;\n\t\tconst paymentMeansList = parsePaymentMeansList(root);\n\t\tconst orderReference = cacElement(root, \"OrderReference\");\n\t\tconst contractReference = cacElement(root, \"ContractDocumentReference\");\n\t\tconst projectReference = cacElement(root, \"ProjectReference\");\n\t\tconst { attachments, documentReferences } = parseAttachments(root);\n\n\t\treturn {\n\t\t\tdocumentType,\n\t\t\tcustomizationId: cbcText(root, \"CustomizationID\") || undefined,\n\t\t\tprofileId: cbcText(root, \"ProfileID\") || undefined,\n\t\t\tid,\n\t\t\tinvoiceTypeCode:\n\t\t\t\tcbcText(root, \"InvoiceTypeCode\") ||\n\t\t\t\tcbcText(root, \"CreditNoteTypeCode\") ||\n\t\t\t\tundefined,\n\t\t\tissueDate: cbcText(root, \"IssueDate\"),\n\t\t\tdueDate: cbcText(root, \"DueDate\") || undefined,\n\t\t\ttaxPointDate: cbcText(root, \"TaxPointDate\") || undefined,\n\t\t\tcurrency: cbcText(root, \"DocumentCurrencyCode\"),\n\t\t\tbuyerReference: cbcText(root, \"BuyerReference\") || undefined,\n\t\t\torderReference: orderReference ? cbcText(orderReference, \"ID\") : undefined,\n\t\t\tsalesOrderId: orderReference\n\t\t\t\t? cbcText(orderReference, \"SalesOrderID\") || undefined\n\t\t\t\t: undefined,\n\t\t\tcontractReference: contractReference\n\t\t\t\t? cbcText(contractReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tprojectReference: projectReference\n\t\t\t\t? cbcText(projectReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tbillingReference: parseBillingReference(root),\n\t\t\tseller: parseParty(root, \"AccountingSupplierParty\"),\n\t\t\tbuyer: parseParty(root, \"AccountingCustomerParty\"),\n\t\t\tdelivery: parseDelivery(root),\n\t\t\tlines: parseLines(root, isCreditNote),\n\t\t\ttaxSubtotals: parseTaxSubtotals(root),\n\t\t\tmonetaryTotal: parseMonetaryTotal(root),\n\t\t\tpaymentMeansList,\n\t\t\tpaymentMeans: paymentMeansList?.[0],\n\t\t\tinvoicePeriod: parseInvoicePeriod(root),\n\t\t\tnote: parseNotes(root),\n\t\t\tpaymentTermsNote: parsePaymentTermsNote(root),\n\t\t\tattachments,\n\t\t\tdocumentReferences,\n\t\t\tallowanceCharges: parseAllowanceCharges(root),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import { parseUblInvoice } from \"./parser.js\";\nimport type { UblAttachment } from \"./types.js\";\n\n/**\n * An embedded attachment extracted from a UBL document's\n * `AdditionalDocumentReference` entries, with its binary content still\n * base64-encoded. `sizeBytes` is the approximate decoded size.\n */\nexport interface UblEmbeddedAttachment {\n\tid: string | null;\n\tfilename: string;\n\tmimeCode: string;\n\tsizeBytes: number;\n\t/** Zero-based position among the document's embedded attachments. */\n\tlineOrder: number;\n\tbase64Content: string;\n}\n\n/** Approximate decoded byte length of a base64 string. */\nconst base64DecodedSize = (base64: string) => Math.round((base64.length * 3) / 4);\n\n/**\n * Extract the embedded attachments (typically the human-readable PDF) from a\n * UBL invoice or credit note XML. Attachments referenced only by external URI\n * (no `EmbeddedDocumentBinaryObject`) are skipped; use {@link parseUblInvoice}\n * directly when those matter.\n */\nexport const extractUblEmbeddedAttachments = (xml: string): UblEmbeddedAttachment[] => {\n\tconst parsed = parseUblInvoice(xml);\n\tif (!parsed?.attachments || parsed.attachments.length === 0) return [];\n\n\treturn parsed.attachments\n\t\t.map((attachment, index): UblEmbeddedAttachment | null => {\n\t\t\tconst base64Content = attachment.base64Content?.trim();\n\t\t\tif (!base64Content) return null;\n\t\t\treturn {\n\t\t\t\tid: attachment.id || null,\n\t\t\t\tfilename: attachment.filename || `attachment-${index + 1}`,\n\t\t\t\tmimeCode: attachment.mimeCode || \"application/octet-stream\",\n\t\t\t\tsizeBytes: base64DecodedSize(base64Content),\n\t\t\t\tlineOrder: index,\n\t\t\t\tbase64Content,\n\t\t\t};\n\t\t})\n\t\t.filter((entry): entry is UblEmbeddedAttachment => entry !== null);\n};\n\n/**\n * Whether an attachment looks like a PDF, by MIME type first and filename\n * extension as a fallback.\n */\nexport const isPdfLikeAttachment = (\n\tattachment: Pick<UblAttachment, \"filename\" | \"mimeCode\">,\n): boolean => {\n\tconst mimeCode = attachment.mimeCode?.toLowerCase() ?? \"\";\n\tif (mimeCode === \"application/pdf\" || mimeCode.endsWith(\"/pdf\")) return true;\n\treturn attachment.filename?.toLowerCase().endsWith(\".pdf\") ?? false;\n};\n","import {\n\ttype Document,\n\tDOMParser as XmlDomParser,\n\ttype Element,\n} from \"@xmldom/xmldom\";\n\nconst CBC_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nconst CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n/**\n * Peppol BIS MLR (Message Level Response) document-type identifier value\n * (Peppol `busdox-docid-qns` scheme).\n */\nexport const PEPPOL_MLR_DOCUMENT_TYPE_VALUE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1\";\n\n/** Peppol BIS MLR process identifier value. */\nexport const PEPPOL_MLR_PROCESS_VALUE = \"urn:fdc:peppol.eu:poacc:bis:mlr:3\";\n\n/**\n * A parsed Peppol Message Level Response (a UBL `ApplicationResponse`). Every\n * field is nullable: a given MLR may omit any of them.\n */\nexport interface PeppolMessageLevelResponse {\n\tcustomizationId: string | null;\n\tprofileId: string | null;\n\tresponseId: string | null;\n\tissueDate: string | null;\n\tissueTime: string | null;\n\treferencedDocumentId: string | null;\n\tresponseCode: string | null;\n\tdescription: string | null;\n\t/** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */\n\tsenderIdentifier: string | null;\n\t/** Receiver participant id as `schemeID:value`. */\n\treceiverIdentifier: string | null;\n}\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove DOCTYPE\n * blocks (including inline DTD subsets) before parsing.\n */\nconst stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\nconst parseXmlDocument = (xml: string): Document | null => {\n\tconst safeXml = stripDoctype(xml);\n\tconst BrowserDomParser = (globalThis as { DOMParser?: typeof XmlDomParser })\n\t\t.DOMParser;\n\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\tconst doc = parser.parseFromString(safeXml, \"text/xml\");\n\tif (doc.getElementsByTagName(\"parsererror\").length > 0) return null;\n\treturn doc;\n};\n\nconst trimmed = (value: string | null | undefined): string | null => {\n\tconst text = value?.trim();\n\treturn text ? text : null;\n};\n\n/** First descendant CBC element's trimmed text, or null. */\nconst cbcText = (parent: Element, tag: string): string | null =>\n\ttrimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);\n\n/**\n * First direct-child CBC element's trimmed text, or null. Used for the\n * top-level scalars so a nested `cbc:ID` (e.g. inside DocumentReference) cannot\n * shadow the ApplicationResponse's own id.\n */\nconst cbcDirectText = (parent: Element, tag: string): string | null => {\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst el = node as Element;\n\t\tif (el.namespaceURI === CBC_NS && el.localName === tag) {\n\t\t\treturn trimmed(el.textContent);\n\t\t}\n\t}\n\treturn null;\n};\n\n/** First descendant CAC element, or null. */\nconst cacElement = (parent: Element, tag: string): Element | null =>\n\tparent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n\n/**\n * The Peppol participant identifier of a SenderParty / ReceiverParty, rendered\n * as `schemeID:value` when the EndpointID carries a scheme and the value does\n * not already include one, otherwise the raw value.\n */\nconst endpointIdentifier = (party: Element | null): string | null => {\n\tif (!party) return null;\n\tconst endpoint = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tif (!endpoint) return null;\n\tconst id = trimmed(endpoint.textContent);\n\tconst scheme = endpoint.getAttribute(\"schemeID\");\n\tif (scheme && id && !id.includes(\":\")) return `${scheme}:${id}`;\n\treturn id;\n};\n\n/**\n * Locate the `ApplicationResponse` element, unwrapping a Standard Business\n * Document (SBDH) envelope when present. Returns null when the XML is not\n * parseable or contains no ApplicationResponse.\n */\nconst findApplicationResponse = (xml: string): Element | null => {\n\tlet doc: Document | null;\n\ttry {\n\t\tdoc = parseXmlDocument(xml);\n\t} catch {\n\t\treturn null;\n\t}\n\tconst root = doc?.documentElement;\n\tif (!root) return null;\n\tif (root.localName === \"ApplicationResponse\") return root;\n\tconst candidates = root.getElementsByTagName(\"*\");\n\tfor (let i = 0; i < candidates.length; i++) {\n\t\tconst el = candidates[i];\n\t\tif (el?.localName === \"ApplicationResponse\") return el;\n\t}\n\treturn null;\n};\n\n/**\n * Whether an inbound document is a Peppol Message Level Response, identified by\n * its document-type value, its process value, or by parsing the XML and finding\n * an `ApplicationResponse` root (SBDH-wrapped or not).\n */\nexport const isPeppolMessageLevelResponse = (params: {\n\tdocumentTypeValue?: string | null;\n\tprocessValue?: string | null;\n\txml?: string | null;\n}): boolean => {\n\tif (trimmed(params.documentTypeValue) === PEPPOL_MLR_DOCUMENT_TYPE_VALUE) {\n\t\treturn true;\n\t}\n\tif (trimmed(params.processValue) === PEPPOL_MLR_PROCESS_VALUE) return true;\n\tconst xml = trimmed(params.xml);\n\tif (!xml) return false;\n\treturn findApplicationResponse(xml) !== null;\n};\n\n/**\n * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping\n * an SBDH envelope when present. Throws when the XML is not an\n * ApplicationResponse.\n */\nexport const parsePeppolMessageLevelResponse = (\n\txml: string,\n): PeppolMessageLevelResponse => {\n\tconst root = findApplicationResponse(xml);\n\tif (!root) {\n\t\tthrow new Error(\"Document is not a Peppol Message Level Response\");\n\t}\n\n\tconst documentResponse = cacElement(root, \"DocumentResponse\");\n\tconst response = documentResponse ? cacElement(documentResponse, \"Response\") : null;\n\tconst documentReference = documentResponse\n\t\t? cacElement(documentResponse, \"DocumentReference\")\n\t\t: null;\n\n\treturn {\n\t\tcustomizationId: cbcDirectText(root, \"CustomizationID\"),\n\t\tprofileId: cbcDirectText(root, \"ProfileID\"),\n\t\tresponseId: cbcDirectText(root, \"ID\"),\n\t\tissueDate: cbcDirectText(root, \"IssueDate\"),\n\t\tissueTime: cbcDirectText(root, \"IssueTime\"),\n\t\treferencedDocumentId: documentReference\n\t\t\t? cbcText(documentReference, \"ID\")\n\t\t\t: null,\n\t\tresponseCode: response ? cbcText(response, \"ResponseCode\") : null,\n\t\tdescription: response ? cbcText(response, \"Description\") : null,\n\t\tsenderIdentifier: endpointIdentifier(cacElement(root, \"SenderParty\")),\n\t\treceiverIdentifier: endpointIdentifier(cacElement(root, \"ReceiverParty\")),\n\t};\n};\n","import { parseUblInvoice } from \"./parser.js\";\nimport type {\n\tInvoiceExtractionDTO,\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblInvoice,\n} from \"./types.js\";\n\n// --- Utility helpers ---\n\nconst UTF8_BOM = 0xfeff;\n\nconst normalizeText = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst upper = trimmed.toUpperCase();\n\tif (upper === \"NA\" || upper === \"N/A\") return null;\n\treturn trimmed;\n};\n\nconst toNumberOrNull = (value: number | null | undefined): number | null =>\n\tNumber.isFinite(value ?? Number.NaN) ? (value as number) : null;\n\nexport const normalizeCurrency = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\treturn trimmed.toUpperCase();\n};\n\nexport const parseDate = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst timestamp = Date.parse(trimmed);\n\tif (Number.isNaN(timestamp)) return null;\n\tconst iso = new Date(timestamp).toISOString();\n\treturn iso.slice(0, 10);\n};\n\n// --- Address helpers ---\n\nconst addressToString = (address?: UblAddress): string | null => {\n\tif (!address) return null;\n\tconst street = [address.street, address.additionalStreet]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst cityLine = [address.postalZone, address.city]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst countryLine = [address.countrySubentity, address.countryCode]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst lines = [street, cityLine, countryLine].filter((line) => line.length > 0);\n\treturn lines.length > 0 ? lines.join(\"\\n\") : null;\n};\n\nconst addressToStructured = (address?: UblAddress) => {\n\tif (!address) return null;\n\tconst line1 = [address.street, address.additionalStreet]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst result = {\n\t\tline1: normalizeText(line1),\n\t\tline2: null as string | null,\n\t\tcity: normalizeText(address.city),\n\t\tstate: normalizeText(address.countrySubentity),\n\t\tpostal_code: normalizeText(address.postalZone),\n\t\tcountry: normalizeText(address.countryCode),\n\t};\n\tconst hasValue = Object.values(result).some((value) => value);\n\treturn hasValue ? result : null;\n};\n\n// --- Attachment & charge sanitizers ---\n\nconst base64ByteLength = (content: string) => {\n\tconst sanitized = content.replace(/\\s+/g, \"\");\n\tif (!sanitized) return 0;\n\tconst paddingLength = sanitized.endsWith(\"==\")\n\t\t? 2\n\t\t: sanitized.endsWith(\"=\")\n\t\t\t? 1\n\t\t\t: 0;\n\treturn Math.floor((sanitized.length * 3) / 4) - paddingLength;\n};\n\nconst sanitizeAttachments = (attachments?: UblAttachment[]) =>\n\t(attachments ?? []).map((attachment) => ({\n\t\tid: normalizeText(attachment.id),\n\t\tfilename: normalizeText(attachment.filename),\n\t\tmime_code: normalizeText(attachment.mimeCode),\n\t\tdescription: normalizeText(attachment.description),\n\t\tsize_bytes: attachment.base64Content\n\t\t\t? base64ByteLength(attachment.base64Content)\n\t\t\t: null,\n\t\texternal_uri: normalizeText(attachment.externalUri),\n\t}));\n\nconst sanitizeAllowanceCharges = (charges?: UblAllowanceCharge[]) =>\n\t(charges ?? []).map((charge) => ({\n\t\tcharge_indicator: charge.chargeIndicator,\n\t\tamount: toNumberOrNull(charge.amount),\n\t\tbase_amount: toNumberOrNull(charge.baseAmount),\n\t\tmultiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),\n\t\treason: normalizeText(charge.reason),\n\t\treason_code: normalizeText(charge.reasonCode),\n\t\ttax_percent: toNumberOrNull(charge.taxPercent),\n\t\ttax_category_id: normalizeText(charge.taxCategoryId),\n\t\ttax_scheme_id: normalizeText(charge.taxSchemeId),\n\t}));\n\nconst sanitizeRawUbl = (ubl: UblInvoice) => ({\n\t...ubl,\n\tattachments: sanitizeAttachments(ubl.attachments),\n\tdocumentReferences: ubl.documentReferences ?? [],\n});\n\n// --- Summation helpers ---\n\nconst sumTaxTotal = (ubl: UblInvoice) => {\n\tconst subtotalSum = ubl.taxSubtotals.reduce(\n\t\t(sum, subtotal) => sum + subtotal.taxAmount,\n\t\t0,\n\t);\n\tif (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) {\n\t\treturn subtotalSum;\n\t}\n\treturn ubl.monetaryTotal.taxInclusiveAmount - ubl.monetaryTotal.taxExclusiveAmount;\n};\n\nconst sumAllowanceChargesByType = (\n\tcharges: UblAllowanceCharge[] | undefined,\n\tchargeIndicator: boolean,\n) =>\n\t(charges ?? []).reduce((sum, charge) => {\n\t\tif (charge.chargeIndicator !== chargeIndicator) return sum;\n\t\treturn sum + Math.abs(charge.amount);\n\t}, 0);\n\n// --- Public API ---\n\n/**\n * Decode raw XML bytes, stripping an optional UTF-8 BOM.\n */\nexport const decodeXmlBytes = (bytes: Uint8Array): string => {\n\tconst text = new TextDecoder(\"utf-8\").decode(bytes);\n\treturn text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;\n};\n\n/**\n * Parse a UBL XML string and normalize it into a flat DTO suitable for\n * database storage or API responses.\n */\nexport const normalizeUblResponse = (\n\txml: string,\n\tdocumentId: string,\n): {\n\textracted: InvoiceExtractionDTO;\n\trawPayload: Record<string, unknown>;\n} => {\n\tconst ubl = parseUblInvoice(xml);\n\tif (!ubl) {\n\t\tthrow new Error(\"Failed to parse UBL invoice XML\");\n\t}\n\n\tconst subtotal =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);\n\tconst total =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst prepaidAmount = toNumberOrNull(ubl.monetaryTotal.prepaidAmount);\n\tconst amountPaid =\n\t\tprepaidAmount ??\n\t\t(total !== null && amountDue !== null && total > amountDue\n\t\t\t? toNumberOrNull(total - amountDue)\n\t\t\t: null);\n\tconst taxTotal = toNumberOrNull(sumTaxTotal(ubl));\n\tconst hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;\n\tconst headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);\n\tconst headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);\n\tconst currency = normalizeCurrency(ubl.currency);\n\tconst paymentTerms = normalizeText(ubl.paymentTermsNote);\n\tconst poNumber =\n\t\tnormalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);\n\n\tconst lineItems = ubl.lines.map((line) => ({\n\t\tdescription:\n\t\t\tnormalizeText(line.description) ??\n\t\t\tnormalizeText(line.itemName) ??\n\t\t\t\"Line item\",\n\t\tquantity: toNumberOrNull(line.quantity),\n\t\tunit: normalizeText(line.unitCode),\n\t\tunit_price: toNumberOrNull(line.unitPrice),\n\t\tamount: toNumberOrNull(line.lineExtensionAmount),\n\t\ttax_amount: toNumberOrNull(line.taxAmount),\n\t\ttax_rate: toNumberOrNull(line.taxPercent),\n\t\tproduct_code:\n\t\t\tnormalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),\n\t\tdiscount_amount: toNumberOrNull(line.discountAmount),\n\t\textra: {\n\t\t\tubl_line_id: normalizeText(line.id),\n\t\t\titem_name: normalizeText(line.itemName),\n\t\t\tsellers_item_id: normalizeText(line.sellersItemId),\n\t\t\tbuyers_item_id: normalizeText(line.buyersItemId),\n\t\t\ttax_category_id: normalizeText(line.taxCategoryId),\n\t\t\ttax_scheme_id: normalizeText(line.taxSchemeId),\n\t\t\ttax_subtotals: line.taxSubtotals ?? [],\n\t\t\tallowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),\n\t\t\tcharge_amount: toNumberOrNull(line.chargeAmount),\n\t\t\tmetadata: line.additionalItemProperties\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tline.additionalItemProperties.map((p) => [p.name, p.value]),\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t},\n\t}));\n\n\tconst supplierAddress = addressToString(ubl.seller.address);\n\tconst receiverAddress = addressToString(ubl.buyer.address);\n\tconst supplierAddressStructured = addressToStructured(ubl.seller.address);\n\tconst receiverAddressStructured = addressToStructured(ubl.buyer.address);\n\tconst attachmentMetadata = sanitizeAttachments(ubl.attachments);\n\tconst paymentMeansList =\n\t\tubl.paymentMeansList && ubl.paymentMeansList.length > 0\n\t\t\t? ubl.paymentMeansList\n\t\t\t: ubl.paymentMeans\n\t\t\t\t? [ubl.paymentMeans]\n\t\t\t\t: [];\n\n\tconst extracted: InvoiceExtractionDTO = {\n\t\tprovider: \"ubl_xml\",\n\t\tdocument_id: documentId,\n\t\tinvoice: {\n\t\t\tinvoice_number: normalizeText(ubl.id),\n\t\t\tinvoice_date: parseDate(ubl.issueDate),\n\t\t\tdue_date: parseDate(ubl.dueDate),\n\t\t\tcurrency,\n\t\t\tsubtotal,\n\t\t\ttax_total: taxTotal,\n\t\t\ttotal,\n\t\t\tamount_due: amountDue,\n\t\t\tamount_paid: amountPaid,\n\t\t\tdiscount_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges\n\t\t\t\t\t? toNumberOrNull(headerDiscountTotal)\n\t\t\t\t\t: null),\n\t\t\tshipping_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),\n\t\t\tpayment_terms: paymentTerms,\n\t\t\tpo_number: poNumber,\n\t\t\tsupplier: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.seller.name) ??\n\t\t\t\t\tnormalizeText(ubl.seller.registrationName),\n\t\t\t\taddress: supplierAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.seller.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.seller.companyId),\n\t\t\t\tiban: normalizeText(ubl.paymentMeans?.iban),\n\t\t\t\tbic: normalizeText(ubl.paymentMeans?.bic),\n\t\t\t},\n\t\t\treceiver: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.buyer.name) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.registrationName),\n\t\t\t\taddress: receiverAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.buyer.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.companyId),\n\t\t\t},\n\t\t\textra: {\n\t\t\t\tdocument_type: ubl.documentType,\n\t\t\t\tcustomization_id: normalizeText(ubl.customizationId),\n\t\t\t\tprofile_id: normalizeText(ubl.profileId),\n\t\t\t\tinvoice_type_code: normalizeText(ubl.invoiceTypeCode),\n\t\t\t\tbuyer_reference: normalizeText(ubl.buyerReference),\n\t\t\t\torder_reference_id: normalizeText(ubl.orderReference),\n\t\t\t\tsales_order_id: normalizeText(ubl.salesOrderId),\n\t\t\t\tcontract_reference: normalizeText(ubl.contractReference),\n\t\t\t\tproject_reference: normalizeText(ubl.projectReference),\n\t\t\t\tbilling_reference: ubl.billingReference\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tinvoice_id: normalizeText(ubl.billingReference.invoiceId),\n\t\t\t\t\t\t\tinvoice_issue_date: parseDate(\n\t\t\t\t\t\t\t\tubl.billingReference.invoiceIssueDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\ttax_point_date: parseDate(ubl.taxPointDate),\n\t\t\t\tinvoice_period: ubl.invoicePeriod ?? null,\n\t\t\t\tnote: normalizeText(ubl.note),\n\t\t\t\tpayment_means: ubl.paymentMeans\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcode: normalizeText(ubl.paymentMeans.code),\n\t\t\t\t\t\t\tcode_name: normalizeText(ubl.paymentMeans.codeName),\n\t\t\t\t\t\t\tpayment_id: normalizeText(ubl.paymentMeans.paymentId),\n\t\t\t\t\t\t\tiban: normalizeText(ubl.paymentMeans.iban),\n\t\t\t\t\t\t\tbic: normalizeText(ubl.paymentMeans.bic),\n\t\t\t\t\t\t\taccount_name: normalizeText(ubl.paymentMeans.accountName),\n\t\t\t\t\t\t\tmandate_id: normalizeText(ubl.paymentMeans.mandateId),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tpayment_means_list: paymentMeansList.map((item) => ({\n\t\t\t\t\tcode: normalizeText(item.code),\n\t\t\t\t\tcode_name: normalizeText(item.codeName),\n\t\t\t\t\tpayment_id: normalizeText(item.paymentId),\n\t\t\t\t\tiban: normalizeText(item.iban),\n\t\t\t\t\tbic: normalizeText(item.bic),\n\t\t\t\t\taccount_name: normalizeText(item.accountName),\n\t\t\t\t\tmandate_id: normalizeText(item.mandateId),\n\t\t\t\t})),\n\t\t\t\tdelivery: ubl.delivery\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tactual_delivery_date: parseDate(\n\t\t\t\t\t\t\t\tubl.delivery.actualDeliveryDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\taddress: addressToStructured(ubl.delivery.address),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tsupplier: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.seller.endpointId),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),\n\t\t\t\t\tregistration_name: normalizeText(ubl.seller.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.seller.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.seller.companyIdSchemeId),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.seller.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.seller.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.seller.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.seller.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.seller.contact?.email),\n\t\t\t\t},\n\t\t\t\treceiver: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.buyer.endpointId),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),\n\t\t\t\t\tregistration_name: normalizeText(ubl.buyer.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.buyer.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.buyer.companyIdSchemeId),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.buyer.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.buyer.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.buyer.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.buyer.contact?.email),\n\t\t\t\t},\n\t\t\t\tsupplier_address_structured: supplierAddressStructured,\n\t\t\t\treceiver_address_structured: receiverAddressStructured,\n\t\t\t\ttax_subtotals: ubl.taxSubtotals,\n\t\t\t\tallowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),\n\t\t\t\tattachments: attachmentMetadata,\n\t\t\t\tdocument_references: ubl.documentReferences ?? [],\n\t\t\t},\n\t\t},\n\t\tline_items: lineItems,\n\t\tconfidence: {\n\t\t\toverall: 1,\n\t\t\tfields: {\n\t\t\t\tinvoice_id: 1,\n\t\t\t\tinvoice_date: 1,\n\t\t\t\tdue_date: 1,\n\t\t\t\ttotal_amount: 1,\n\t\t\t\tsupplier_name: 1,\n\t\t\t},\n\t\t},\n\t};\n\n\treturn {\n\t\textracted,\n\t\trawPayload: {\n\t\t\tformat: \"ubl_xml\",\n\t\t\tinvoice: sanitizeRawUbl(ubl),\n\t\t},\n\t};\n};\n\n/**\n * Parse a UBL invoice from raw bytes and normalize it into a DTO.\n */\nexport const parseUblInvoiceDocument = (params: {\n\tbytes: Uint8Array;\n\tdocumentId: string;\n\tmimeType: string;\n}) => {\n\tconst xml = decodeXmlBytes(params.bytes);\n\tconst { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);\n\treturn {\n\t\trawPayload: {\n\t\t\t...rawPayload,\n\t\t\tmime_type: params.mimeType,\n\t\t},\n\t\textracted,\n\t\tproviderJobId: null as string | null,\n\t};\n};\n"],"mappings":";;AAmBA,MAAMA,WAAS;AACf,MAAMC,WACL;AAID,SAASC,UAAQ,QAAiB,KAAq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S,eAAe,GAAG;EAC5B;CACD;AACD;;;;AAKA,MAAa,2BAA2B,WAIlC;CACL,MAAM,MAAM,eAAe,OAAO,KAAK;CACvC,MAAM,EAAE,WAAW,eAAe,qBAAqB,KAAK,OAAO,UAAU;CAC7E,OAAO;EACN,YAAY;GACX,GAAG;GACH,WAAW,OAAO;EACnB;EACA;EACA,eAAe;CAChB;AACD"}
1
+ {"version":3,"file":"index.js","names":["CBC_NS","CAC_NS","cbcText","cacElement","cbcDirectText","stripDoctype","XmlDomParser","XmlDomParser"],"sources":["../src/parser.ts","../src/attachments.ts","../src/mlr.ts","../src/normalize.ts"],"sourcesContent":["import { DOMParser as XmlDomParser, type Element } from \"@xmldom/xmldom\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\n\tUblDelivery,\n\tUblDocumentReference,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblItemProperty,\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblParty,\n\tUblPartyIdentification,\n\tUblPaymentMeans,\n\tUblTaxSubtotal,\n} from \"./types.js\";\n\nconst CBC_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nconst CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n// --- DOM helpers ---\n\nfunction cbcText(parent: Element, tag: string): string {\n\tconst el = parent.getElementsByTagNameNS(CBC_NS, tag)[0];\n\treturn el?.textContent?.trim() ?? \"\";\n}\n\nfunction cacElement(parent: Element, tag: string): Element | null {\n\treturn parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacElements(parent: Element, tag: string): Element[] {\n\treturn Array.from(parent.getElementsByTagNameNS(CAC_NS, tag));\n}\n\nfunction cbcNumber(parent: Element, tag: string): number {\n\tconst n = Number.parseFloat(cbcText(parent, tag));\n\treturn Number.isNaN(n) ? 0 : n;\n}\n\nfunction childElementsByTagNs(\n\tparent: Element,\n\tnamespace: string,\n\ttag: string,\n): Element[] {\n\tconst elements: Element[] = [];\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst element = node as Element;\n\t\tif (element.namespaceURI === namespace && element.localName === tag) {\n\t\t\telements.push(element);\n\t\t}\n\t}\n\treturn elements;\n}\n\nfunction cbcDirectText(parent: Element, tag: string): string {\n\tconst el = childElementsByTagNs(parent, CBC_NS, tag)[0];\n\treturn el?.textContent?.trim() ?? \"\";\n}\n\nfunction cbcDirectNumber(parent: Element, tag: string): number | null {\n\tconst value = cbcDirectText(parent, tag);\n\tif (!value) return null;\n\tconst parsed = Number.parseFloat(value);\n\treturn Number.isNaN(parsed) ? null : parsed;\n}\n\nfunction cacDirectElement(parent: Element, tag: string): Element | null {\n\treturn childElementsByTagNs(parent, CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacDirectElements(parent: Element, tag: string): Element[] {\n\treturn childElementsByTagNs(parent, CAC_NS, tag);\n}\n\n// --- Section parsers ---\n\nfunction parseAddressFromElement(address: Element | null): UblAddress | undefined {\n\tif (!address) return undefined;\n\tconst country = cacElement(address, \"Country\");\n\treturn {\n\t\tstreet: cbcText(address, \"StreetName\"),\n\t\tadditionalStreet: cbcText(address, \"AdditionalStreetName\") || undefined,\n\t\tcity: cbcText(address, \"CityName\"),\n\t\tpostalZone: cbcText(address, \"PostalZone\"),\n\t\tcountrySubentity: cbcText(address, \"CountrySubentity\") || undefined,\n\t\tcountryCode: country ? cbcText(country, \"IdentificationCode\") : \"\",\n\t};\n}\n\nfunction parseAddress(party: Element): UblAddress | undefined {\n\tconst postal = cacElement(party, \"PostalAddress\");\n\treturn parseAddressFromElement(postal);\n}\n\nfunction parseTaxSchemeId(parent: Element | null): string | undefined {\n\tif (!parent) return undefined;\n\tconst taxScheme = cacElement(parent, \"TaxScheme\");\n\tif (!taxScheme) return undefined;\n\treturn cbcText(taxScheme, \"ID\") || undefined;\n}\n\nfunction parseContact(party: Element): import(\"./types.js\").UblContact | undefined {\n\tconst contact = cacElement(party, \"Contact\");\n\tif (!contact) return undefined;\n\tconst name = cbcText(contact, \"Name\");\n\tconst phone = cbcText(contact, \"Telephone\");\n\tconst email = cbcText(contact, \"ElectronicMail\");\n\tif (!name && !phone && !email) return undefined;\n\treturn {\n\t\tname: name || undefined,\n\t\tphone: phone || undefined,\n\t\temail: email || undefined,\n\t};\n}\n\nfunction parsePartyIdentifications(party: Element): UblPartyIdentification[] {\n\tconst ids = cacElements(party, \"PartyIdentification\");\n\tconst result: UblPartyIdentification[] = [];\n\tfor (const idEl of ids) {\n\t\tconst idValue = cbcText(idEl, \"ID\");\n\t\tif (!idValue) continue;\n\t\tconst schemeIdAttr = idEl\n\t\t\t.getElementsByTagNameNS(CBC_NS, \"ID\")[0]\n\t\t\t?.getAttribute(\"schemeID\");\n\t\tresult.push({\n\t\t\tid: idValue,\n\t\t\tschemeId: schemeIdAttr || undefined,\n\t\t});\n\t}\n\treturn result;\n}\n\nfunction parseParty(root: Element, role: string): UblParty {\n\tconst wrapper = cacElement(root, role);\n\tconst party = wrapper ? cacElement(wrapper, \"Party\") : null;\n\tif (!party) return { name: \"Unknown\" };\n\n\tconst partyName = cacElement(party, \"PartyName\");\n\tconst legalEntity = cacElement(party, \"PartyLegalEntity\");\n\tconst taxScheme = cacElement(party, \"PartyTaxScheme\");\n\tconst partyId = cacElement(party, \"PartyIdentification\");\n\tconst endpointEl = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tconst partyIdentifications = parsePartyIdentifications(party);\n\tconst companyIdEl = legalEntity\n\t\t? legalEntity.getElementsByTagNameNS(CBC_NS, \"CompanyID\")[0]\n\t\t: null;\n\n\treturn {\n\t\tname: partyName ? cbcText(partyName, \"Name\") : \"\",\n\t\tregistrationName: legalEntity\n\t\t\t? cbcText(legalEntity, \"RegistrationName\") || undefined\n\t\t\t: undefined,\n\t\tcompanyLegalForm: legalEntity\n\t\t\t? cbcText(legalEntity, \"CompanyLegalForm\") || undefined\n\t\t\t: undefined,\n\t\tvatId: taxScheme ? cbcText(taxScheme, \"CompanyID\") || undefined : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxScheme),\n\t\tcompanyId: companyIdEl\n\t\t\t? companyIdEl.textContent?.trim() || undefined\n\t\t\t: partyId\n\t\t\t\t? cbcText(partyId, \"ID\") || undefined\n\t\t\t\t: undefined,\n\t\tcompanyIdSchemeId: companyIdEl?.getAttribute(\"schemeID\") || undefined,\n\t\tendpointId: endpointEl?.textContent?.trim() || undefined,\n\t\tendpointSchemeId: endpointEl?.getAttribute(\"schemeID\") || undefined,\n\t\tpartyIdentifications:\n\t\t\tpartyIdentifications.length > 0 ? partyIdentifications : undefined,\n\t\taddress: parseAddress(party),\n\t\tcontact: parseContact(party),\n\t};\n}\n\nfunction parseTaxSubtotal(sub: Element): UblTaxSubtotal {\n\tconst cat = cacElement(sub, \"TaxCategory\");\n\treturn {\n\t\ttaxableAmount: cbcNumber(sub, \"TaxableAmount\"),\n\t\ttaxAmount: cbcNumber(sub, \"TaxAmount\"),\n\t\ttaxPercent: (cat ? cbcNumber(cat, \"Percent\") : 0) || cbcNumber(sub, \"Percent\"),\n\t\ttaxCategoryId: cat ? cbcText(cat, \"ID\") || undefined : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(cat),\n\t\ttaxExemptionReason: cat\n\t\t\t? cbcText(cat, \"TaxExemptionReason\") || undefined\n\t\t\t: undefined,\n\t};\n}\n\nfunction parseTaxSubtotalsFromTaxTotal(taxTotal: Element): UblTaxSubtotal[] {\n\treturn cacDirectElements(taxTotal, \"TaxSubtotal\").map(parseTaxSubtotal);\n}\n\nfunction parseTaxSubtotals(root: Element): UblTaxSubtotal[] {\n\tconst taxTotals = cacDirectElements(root, \"TaxTotal\");\n\tif (taxTotals.length === 0) return [];\n\treturn taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal);\n}\n\nfunction parseAllowanceCharge(charge: Element): UblAllowanceCharge {\n\tconst taxCategory = cacElement(charge, \"TaxCategory\");\n\tconst indicatorRaw = cbcDirectText(charge, \"ChargeIndicator\").toLowerCase();\n\tconst chargeIndicator = indicatorRaw === \"true\" || indicatorRaw === \"1\";\n\treturn {\n\t\tchargeIndicator,\n\t\tamount: cbcNumber(charge, \"Amount\"),\n\t\tbaseAmount: cbcDirectNumber(charge, \"BaseAmount\") ?? undefined,\n\t\tmultiplierFactorNumeric:\n\t\t\tcbcDirectNumber(charge, \"MultiplierFactorNumeric\") ?? undefined,\n\t\treason: cbcText(charge, \"AllowanceChargeReason\") || undefined,\n\t\treasonCode: cbcText(charge, \"AllowanceChargeReasonCode\") || undefined,\n\t\ttaxPercent: taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined,\n\t\ttaxCategoryId: taxCategory\n\t\t\t? cbcText(taxCategory, \"ID\") || undefined\n\t\t\t: undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxCategory),\n\t};\n}\n\nfunction parseAllowanceCharges(parent: Element): UblAllowanceCharge[] {\n\treturn cacDirectElements(parent, \"AllowanceCharge\").map(parseAllowanceCharge);\n}\n\nfunction parseLines(root: Element, isCreditNote: boolean): UblLine[] {\n\tconst qtyTag = isCreditNote ? \"CreditedQuantity\" : \"InvoicedQuantity\";\n\tconst lineTag = isCreditNote ? \"CreditNoteLine\" : \"InvoiceLine\";\n\n\treturn cacElements(root, lineTag).map((line) => {\n\t\tconst item = cacElement(line, \"Item\");\n\t\tconst price = cacElement(line, \"Price\");\n\t\tconst taxCategory = item ? cacElement(item, \"ClassifiedTaxCategory\") : null;\n\t\tconst sellersId = item ? cacElement(item, \"SellersItemIdentification\") : null;\n\t\tconst buyersId = item ? cacElement(item, \"BuyersItemIdentification\") : null;\n\t\tconst qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];\n\t\tconst lineExtensionAmount = cbcNumber(line, \"LineExtensionAmount\");\n\t\tconst lineTaxTotal = cacDirectElement(line, \"TaxTotal\");\n\t\tconst lineTaxSubtotals = lineTaxTotal\n\t\t\t? parseTaxSubtotalsFromTaxTotal(lineTaxTotal)\n\t\t\t: [];\n\t\tconst taxAmountFromSubtotals = lineTaxSubtotals.reduce(\n\t\t\t(sum, subtotal) => sum + subtotal.taxAmount,\n\t\t\t0,\n\t\t);\n\t\tconst taxAmountFromLineTotal = lineTaxTotal\n\t\t\t? cbcDirectNumber(lineTaxTotal, \"TaxAmount\")\n\t\t\t: null;\n\t\tconst taxPercent =\n\t\t\tlineTaxSubtotals[0]?.taxPercent ??\n\t\t\t(taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined);\n\t\tconst computedTaxAmount =\n\t\t\ttaxPercent !== undefined\n\t\t\t\t? Number(((lineExtensionAmount * taxPercent) / 100).toFixed(2))\n\t\t\t\t: undefined;\n\t\tconst lineAllowanceCharges = parseAllowanceCharges(line);\n\t\tconst priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];\n\t\tconst allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];\n\t\tconst discountAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum : sum + Math.abs(charge.amount),\n\t\t\t0,\n\t\t);\n\t\tconst chargeAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum + Math.abs(charge.amount) : sum,\n\t\t\t0,\n\t\t);\n\n\t\tconst additionalItemProperties: UblItemProperty[] = [];\n\t\tif (item) {\n\t\t\tfor (const prop of cacElements(item, \"AdditionalItemProperty\")) {\n\t\t\t\tconst propName = cbcText(prop, \"Name\");\n\t\t\t\tconst propValue = cbcText(prop, \"Value\");\n\t\t\t\tif (propName) {\n\t\t\t\t\tadditionalItemProperties.push({\n\t\t\t\t\t\tname: propName,\n\t\t\t\t\t\tvalue: propValue,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// EN16931 BT-146 (PriceAmount) is the price for BT-149 (BaseQuantity) units\n\t\t// of the item, not necessarily for one unit. Effective unit price is\n\t\t// PriceAmount / BaseQuantity, with BaseQuantity defaulting to 1 when absent.\n\t\tconst priceAmount = price ? cbcNumber(price, \"PriceAmount\") : 0;\n\t\tconst priceBaseQuantity = price ? cbcDirectNumber(price, \"BaseQuantity\") : null;\n\t\tconst unitPrice =\n\t\t\tpriceBaseQuantity && priceBaseQuantity > 0\n\t\t\t\t? priceAmount / priceBaseQuantity\n\t\t\t\t: priceAmount;\n\n\t\treturn {\n\t\t\tid: cbcText(line, \"ID\"),\n\t\t\tdescription: item ? cbcText(item, \"Description\") : \"\",\n\t\t\tquantity: cbcNumber(line, qtyTag),\n\t\t\tunitCode: qtyEl?.getAttribute(\"unitCode\") ?? \"\",\n\t\t\tunitPrice,\n\t\t\tlineExtensionAmount,\n\t\t\ttaxPercent,\n\t\t\ttaxAmount:\n\t\t\t\ttaxAmountFromLineTotal ??\n\t\t\t\t(lineTaxSubtotals.length > 0\n\t\t\t\t\t? taxAmountFromSubtotals\n\t\t\t\t\t: computedTaxAmount),\n\t\t\ttaxCategoryId:\n\t\t\t\tlineTaxSubtotals[0]?.taxCategoryId ??\n\t\t\t\t(taxCategory ? cbcText(taxCategory, \"ID\") || undefined : undefined),\n\t\t\ttaxSchemeId:\n\t\t\t\tlineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),\n\t\t\ttaxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : undefined,\n\t\t\tallowanceCharges:\n\t\t\t\tallowanceCharges.length > 0 ? allowanceCharges : undefined,\n\t\t\tdiscountAmount: discountAmount > 0 ? discountAmount : undefined,\n\t\t\tchargeAmount: chargeAmount > 0 ? chargeAmount : undefined,\n\t\t\titemName: item ? cbcText(item, \"Name\") || undefined : undefined,\n\t\t\tsellersItemId: sellersId\n\t\t\t\t? cbcText(sellersId, \"ID\") || undefined\n\t\t\t\t: undefined,\n\t\t\tbuyersItemId: buyersId ? cbcText(buyersId, \"ID\") || undefined : undefined,\n\t\t\tadditionalItemProperties:\n\t\t\t\tadditionalItemProperties.length > 0\n\t\t\t\t\t? additionalItemProperties\n\t\t\t\t\t: undefined,\n\t\t};\n\t});\n}\n\nfunction parseMonetaryTotal(root: Element): UblMonetaryTotal {\n\tconst total = cacDirectElement(root, \"LegalMonetaryTotal\");\n\tif (!total) {\n\t\treturn {\n\t\t\tlineExtensionAmount: 0,\n\t\t\ttaxExclusiveAmount: 0,\n\t\t\ttaxInclusiveAmount: 0,\n\t\t\tpayableAmount: 0,\n\t\t};\n\t}\n\treturn {\n\t\tlineExtensionAmount: cbcNumber(total, \"LineExtensionAmount\"),\n\t\ttaxExclusiveAmount: cbcNumber(total, \"TaxExclusiveAmount\"),\n\t\ttaxInclusiveAmount: cbcNumber(total, \"TaxInclusiveAmount\"),\n\t\tallowanceTotalAmount: cbcNumber(total, \"AllowanceTotalAmount\") || undefined,\n\t\tchargeTotalAmount: cbcNumber(total, \"ChargeTotalAmount\") || undefined,\n\t\tprepaidAmount: cbcNumber(total, \"PrepaidAmount\") || undefined,\n\t\tpayableRoundingAmount: cbcNumber(total, \"PayableRoundingAmount\") || undefined,\n\t\tpayableAmount: cbcNumber(total, \"PayableAmount\"),\n\t};\n}\n\nfunction parsePaymentMeansElement(pm: Element): UblPaymentMeans {\n\tconst account = cacElement(pm, \"PayeeFinancialAccount\");\n\tconst branch = account ? cacElement(account, \"FinancialInstitutionBranch\") : null;\n\tconst paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, \"PaymentMeansCode\")[0];\n\tconst mandate = cacElement(pm, \"PaymentMandate\");\n\n\treturn {\n\t\tcode: cbcText(pm, \"PaymentMeansCode\"),\n\t\tcodeName: paymentMeansCodeEl?.getAttribute(\"name\") || undefined,\n\t\tpaymentId: cbcText(pm, \"PaymentID\") || undefined,\n\t\tiban: account ? cbcText(account, \"ID\") || undefined : undefined,\n\t\tbic: branch ? cbcText(branch, \"ID\") || undefined : undefined,\n\t\taccountName: (account && cbcText(account, \"Name\")) || undefined,\n\t\tmandateId: mandate ? cbcText(mandate, \"ID\") || undefined : undefined,\n\t};\n}\n\nfunction parsePaymentMeansList(root: Element): UblPaymentMeans[] | undefined {\n\tconst list = cacElements(root, \"PaymentMeans\").map(parsePaymentMeansElement);\n\treturn list.length > 0 ? list : undefined;\n}\n\nfunction parseInvoicePeriod(root: Element): UblInvoicePeriod | undefined {\n\tconst period = cacElement(root, \"InvoicePeriod\");\n\tif (!period) return undefined;\n\n\tconst start = cbcText(period, \"StartDate\");\n\tconst end = cbcText(period, \"EndDate\");\n\tif (!start && !end) return undefined;\n\n\treturn {\n\t\tstartDate: start || undefined,\n\t\tendDate: end || undefined,\n\t\tdescriptionCode: cbcText(period, \"DescriptionCode\") || undefined,\n\t};\n}\n\nfunction parseDelivery(root: Element): UblDelivery | undefined {\n\tconst delivery = cacElement(root, \"Delivery\");\n\tif (!delivery) return undefined;\n\tconst actualDeliveryDate = cbcText(delivery, \"ActualDeliveryDate\") || undefined;\n\tconst deliveryLocation = cacElement(delivery, \"DeliveryLocation\");\n\tconst address = parseAddressFromElement(\n\t\tdeliveryLocation ? cacElement(deliveryLocation, \"Address\") : null,\n\t);\n\tif (!actualDeliveryDate && !address) return undefined;\n\treturn {\n\t\tactualDeliveryDate,\n\t\taddress,\n\t};\n}\n\nfunction parsePaymentTermsNote(root: Element): string | undefined {\n\tconst paymentTerms = cacElement(root, \"PaymentTerms\");\n\tif (!paymentTerms) return undefined;\n\tconst note = cbcText(paymentTerms, \"Note\");\n\treturn note || undefined;\n}\n\nfunction parseNotes(root: Element): string | undefined {\n\tconst noteEls = root.getElementsByTagNameNS(CBC_NS, \"Note\");\n\tconst notes: string[] = [];\n\tfor (let i = 0; i < noteEls.length; i++) {\n\t\tconst el = noteEls[i];\n\t\tif (!el) continue;\n\t\tif (el.parentElement === root || el.parentNode === root) {\n\t\t\tconst text = el.textContent?.trim();\n\t\t\tif (text) notes.push(text);\n\t\t}\n\t}\n\treturn notes.length > 0 ? notes.join(\"\\n\") : undefined;\n}\n\nfunction parseAttachments(root: Element): {\n\tattachments: UblAttachment[] | undefined;\n\tdocumentReferences: UblDocumentReference[] | undefined;\n} {\n\tconst refs = cacElements(root, \"AdditionalDocumentReference\");\n\tconst attachments: UblAttachment[] = [];\n\tconst documentReferences: UblDocumentReference[] = [];\n\n\tfor (const ref of refs) {\n\t\tconst attachment = cacElement(ref, \"Attachment\");\n\t\tconst refId = cbcText(ref, \"ID\");\n\t\tconst description = cbcText(ref, \"DocumentDescription\") || undefined;\n\n\t\tif (!attachment) {\n\t\t\t// Text-only document reference (e.g. terms & conditions, notices)\n\t\t\tif (refId || description) {\n\t\t\t\tdocumentReferences.push({ id: refId, description });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst binaryEl = attachment.getElementsByTagNameNS(\n\t\t\tCBC_NS,\n\t\t\t\"EmbeddedDocumentBinaryObject\",\n\t\t)[0];\n\t\tconst externalRef = cacElement(attachment, \"ExternalReference\");\n\n\t\tif (binaryEl) {\n\t\t\tconst content = binaryEl.textContent?.trim();\n\t\t\tif (content) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tfilename: binaryEl.getAttribute(\"filename\") || undefined,\n\t\t\t\t\tmimeCode: binaryEl.getAttribute(\"mimeCode\") || undefined,\n\t\t\t\t\tdescription,\n\t\t\t\t\tbase64Content: content,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (externalRef) {\n\t\t\tconst uri = cbcText(externalRef, \"URI\");\n\t\t\tif (uri) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tdescription,\n\t\t\t\t\texternalUri: uri,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tattachments: attachments.length > 0 ? attachments : undefined,\n\t\tdocumentReferences:\n\t\t\tdocumentReferences.length > 0 ? documentReferences : undefined,\n\t};\n}\n\nfunction parseBillingReference(root: Element): UblBillingReference | undefined {\n\tconst billingRef = cacElement(root, \"BillingReference\");\n\tif (!billingRef) return undefined;\n\tconst invoiceRef = cacElement(billingRef, \"InvoiceDocumentReference\");\n\tif (!invoiceRef) return undefined;\n\tconst invoiceId = cbcText(invoiceRef, \"ID\") || undefined;\n\tconst invoiceIssueDate = cbcText(invoiceRef, \"IssueDate\") || undefined;\n\tif (!invoiceId && !invoiceIssueDate) return undefined;\n\treturn { invoiceId, invoiceIssueDate };\n}\n\n// --- Main parser ---\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove\n * DOCTYPE blocks (including inline DTD subsets) before parsing.\n */\nconst stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\nexport function parseUblInvoice(xml: string): UblInvoice | null {\n\ttry {\n\t\tconst safeXml = stripDoctype(xml);\n\t\tconst BrowserDomParser = (globalThis as { DOMParser?: typeof XmlDomParser })\n\t\t\t.DOMParser;\n\t\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\t\tconst doc = parser.parseFromString(safeXml, \"text/xml\");\n\t\tif (doc.getElementsByTagName(\"parsererror\").length > 0) return null;\n\n\t\tconst root = doc.documentElement;\n\t\tif (!root) return null;\n\t\tconst localName = root.localName;\n\n\t\tlet documentType: \"Invoice\" | \"CreditNote\";\n\t\tif (localName === \"Invoice\") {\n\t\t\tdocumentType = \"Invoice\";\n\t\t} else if (localName === \"CreditNote\") {\n\t\t\tdocumentType = \"CreditNote\";\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst isCreditNote = documentType === \"CreditNote\";\n\t\tconst id = cbcText(root, \"ID\");\n\t\tif (!id) return null;\n\t\tconst paymentMeansList = parsePaymentMeansList(root);\n\t\tconst orderReference = cacElement(root, \"OrderReference\");\n\t\tconst contractReference = cacElement(root, \"ContractDocumentReference\");\n\t\tconst projectReference = cacElement(root, \"ProjectReference\");\n\t\tconst { attachments, documentReferences } = parseAttachments(root);\n\n\t\treturn {\n\t\t\tdocumentType,\n\t\t\tcustomizationId: cbcText(root, \"CustomizationID\") || undefined,\n\t\t\tprofileId: cbcText(root, \"ProfileID\") || undefined,\n\t\t\tid,\n\t\t\tinvoiceTypeCode:\n\t\t\t\tcbcText(root, \"InvoiceTypeCode\") ||\n\t\t\t\tcbcText(root, \"CreditNoteTypeCode\") ||\n\t\t\t\tundefined,\n\t\t\tissueDate: cbcText(root, \"IssueDate\"),\n\t\t\tdueDate: cbcText(root, \"DueDate\") || undefined,\n\t\t\ttaxPointDate: cbcText(root, \"TaxPointDate\") || undefined,\n\t\t\tcurrency: cbcText(root, \"DocumentCurrencyCode\"),\n\t\t\tbuyerReference: cbcText(root, \"BuyerReference\") || undefined,\n\t\t\torderReference: orderReference ? cbcText(orderReference, \"ID\") : undefined,\n\t\t\tsalesOrderId: orderReference\n\t\t\t\t? cbcText(orderReference, \"SalesOrderID\") || undefined\n\t\t\t\t: undefined,\n\t\t\tcontractReference: contractReference\n\t\t\t\t? cbcText(contractReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tprojectReference: projectReference\n\t\t\t\t? cbcText(projectReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tbillingReference: parseBillingReference(root),\n\t\t\tseller: parseParty(root, \"AccountingSupplierParty\"),\n\t\t\tbuyer: parseParty(root, \"AccountingCustomerParty\"),\n\t\t\tdelivery: parseDelivery(root),\n\t\t\tlines: parseLines(root, isCreditNote),\n\t\t\ttaxSubtotals: parseTaxSubtotals(root),\n\t\t\tmonetaryTotal: parseMonetaryTotal(root),\n\t\t\tpaymentMeansList,\n\t\t\tpaymentMeans: paymentMeansList?.[0],\n\t\t\tinvoicePeriod: parseInvoicePeriod(root),\n\t\t\tnote: parseNotes(root),\n\t\t\tpaymentTermsNote: parsePaymentTermsNote(root),\n\t\t\tattachments,\n\t\t\tdocumentReferences,\n\t\t\tallowanceCharges: parseAllowanceCharges(root),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import { parseUblInvoice } from \"./parser.js\";\nimport type { UblAttachment } from \"./types.js\";\n\n/**\n * An embedded attachment extracted from a UBL document's\n * `AdditionalDocumentReference` entries, with its binary content still\n * base64-encoded. `sizeBytes` is the approximate decoded size.\n */\nexport interface UblEmbeddedAttachment {\n\tid: string | null;\n\tfilename: string;\n\tmimeCode: string;\n\tsizeBytes: number;\n\t/** Zero-based position among the document's embedded attachments. */\n\tlineOrder: number;\n\tbase64Content: string;\n}\n\n/** Approximate decoded byte length of a base64 string. */\nconst base64DecodedSize = (base64: string) => Math.round((base64.length * 3) / 4);\n\n/**\n * Extract the embedded attachments (typically the human-readable PDF) from a\n * UBL invoice or credit note XML. Attachments referenced only by external URI\n * (no `EmbeddedDocumentBinaryObject`) are skipped; use {@link parseUblInvoice}\n * directly when those matter.\n */\nexport const extractUblEmbeddedAttachments = (xml: string): UblEmbeddedAttachment[] => {\n\tconst parsed = parseUblInvoice(xml);\n\tif (!parsed?.attachments || parsed.attachments.length === 0) return [];\n\n\treturn parsed.attachments\n\t\t.map((attachment, index): UblEmbeddedAttachment | null => {\n\t\t\tconst base64Content = attachment.base64Content?.trim();\n\t\t\tif (!base64Content) return null;\n\t\t\treturn {\n\t\t\t\tid: attachment.id || null,\n\t\t\t\tfilename: attachment.filename || `attachment-${index + 1}`,\n\t\t\t\tmimeCode: attachment.mimeCode || \"application/octet-stream\",\n\t\t\t\tsizeBytes: base64DecodedSize(base64Content),\n\t\t\t\tlineOrder: index,\n\t\t\t\tbase64Content,\n\t\t\t};\n\t\t})\n\t\t.filter((entry): entry is UblEmbeddedAttachment => entry !== null);\n};\n\n/**\n * Whether an attachment looks like a PDF, by MIME type first and filename\n * extension as a fallback.\n */\nexport const isPdfLikeAttachment = (\n\tattachment: Pick<UblAttachment, \"filename\" | \"mimeCode\">,\n): boolean => {\n\tconst mimeCode = attachment.mimeCode?.toLowerCase() ?? \"\";\n\tif (mimeCode === \"application/pdf\" || mimeCode.endsWith(\"/pdf\")) return true;\n\treturn attachment.filename?.toLowerCase().endsWith(\".pdf\") ?? false;\n};\n","import { type Document, DOMParser as XmlDomParser, type Element } from \"@xmldom/xmldom\";\n\nconst CBC_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nconst CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n/**\n * Peppol BIS MLR (Message Level Response) document-type identifier value\n * (Peppol `busdox-docid-qns` scheme).\n */\nexport const PEPPOL_MLR_DOCUMENT_TYPE_VALUE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1\";\n\n/** Peppol BIS MLR process identifier value. */\nexport const PEPPOL_MLR_PROCESS_VALUE = \"urn:fdc:peppol.eu:poacc:bis:mlr:3\";\n\n/**\n * A parsed Peppol Message Level Response (a UBL `ApplicationResponse`). Every\n * field is nullable: a given MLR may omit any of them.\n */\nexport interface PeppolMessageLevelResponse {\n\tcustomizationId: string | null;\n\tprofileId: string | null;\n\tresponseId: string | null;\n\tissueDate: string | null;\n\tissueTime: string | null;\n\treferencedDocumentId: string | null;\n\tresponseCode: string | null;\n\tdescription: string | null;\n\t/** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */\n\tsenderIdentifier: string | null;\n\t/** Receiver participant id as `schemeID:value`. */\n\treceiverIdentifier: string | null;\n}\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove DOCTYPE\n * blocks (including inline DTD subsets) before parsing.\n */\nconst stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\nconst parseXmlDocument = (xml: string): Document | null => {\n\tconst safeXml = stripDoctype(xml);\n\tconst BrowserDomParser = (globalThis as { DOMParser?: typeof XmlDomParser })\n\t\t.DOMParser;\n\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\tconst doc = parser.parseFromString(safeXml, \"text/xml\");\n\tif (doc.getElementsByTagName(\"parsererror\").length > 0) return null;\n\treturn doc;\n};\n\nconst trimmed = (value: string | null | undefined): string | null => {\n\tconst text = value?.trim();\n\treturn text ? text : null;\n};\n\n/** First descendant CBC element's trimmed text, or null. */\nconst cbcText = (parent: Element, tag: string): string | null =>\n\ttrimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);\n\n/**\n * First direct-child CBC element's trimmed text, or null. Used for the\n * top-level scalars so a nested `cbc:ID` (e.g. inside DocumentReference) cannot\n * shadow the ApplicationResponse's own id.\n */\nconst cbcDirectText = (parent: Element, tag: string): string | null => {\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst el = node as Element;\n\t\tif (el.namespaceURI === CBC_NS && el.localName === tag) {\n\t\t\treturn trimmed(el.textContent);\n\t\t}\n\t}\n\treturn null;\n};\n\n/** First descendant CAC element, or null. */\nconst cacElement = (parent: Element, tag: string): Element | null =>\n\tparent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n\n/**\n * The Peppol participant identifier of a SenderParty / ReceiverParty, rendered\n * as `schemeID:value` when the EndpointID carries a scheme and the value does\n * not already include one, otherwise the raw value.\n */\nconst endpointIdentifier = (party: Element | null): string | null => {\n\tif (!party) return null;\n\tconst endpoint = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tif (!endpoint) return null;\n\tconst id = trimmed(endpoint.textContent);\n\tconst scheme = endpoint.getAttribute(\"schemeID\");\n\tif (scheme && id && !id.includes(\":\")) return `${scheme}:${id}`;\n\treturn id;\n};\n\n/**\n * Locate the `ApplicationResponse` element, unwrapping a Standard Business\n * Document (SBDH) envelope when present. Returns null when the XML is not\n * parseable or contains no ApplicationResponse.\n */\nconst findApplicationResponse = (xml: string): Element | null => {\n\tlet doc: Document | null;\n\ttry {\n\t\tdoc = parseXmlDocument(xml);\n\t} catch {\n\t\treturn null;\n\t}\n\tconst root = doc?.documentElement;\n\tif (!root) return null;\n\tif (root.localName === \"ApplicationResponse\") return root;\n\tconst candidates = root.getElementsByTagName(\"*\");\n\tfor (let i = 0; i < candidates.length; i++) {\n\t\tconst el = candidates[i];\n\t\tif (el?.localName === \"ApplicationResponse\") return el;\n\t}\n\treturn null;\n};\n\n/**\n * Whether an inbound document is a Peppol Message Level Response, identified by\n * its document-type value, its process value, or by parsing the XML and finding\n * an `ApplicationResponse` root (SBDH-wrapped or not).\n */\nexport const isPeppolMessageLevelResponse = (params: {\n\tdocumentTypeValue?: string | null;\n\tprocessValue?: string | null;\n\txml?: string | null;\n}): boolean => {\n\tif (trimmed(params.documentTypeValue) === PEPPOL_MLR_DOCUMENT_TYPE_VALUE) {\n\t\treturn true;\n\t}\n\tif (trimmed(params.processValue) === PEPPOL_MLR_PROCESS_VALUE) return true;\n\tconst xml = trimmed(params.xml);\n\tif (!xml) return false;\n\treturn findApplicationResponse(xml) !== null;\n};\n\n/**\n * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping\n * an SBDH envelope when present. Throws when the XML is not an\n * ApplicationResponse.\n */\nexport const parsePeppolMessageLevelResponse = (\n\txml: string,\n): PeppolMessageLevelResponse => {\n\tconst root = findApplicationResponse(xml);\n\tif (!root) {\n\t\tthrow new Error(\"Document is not a Peppol Message Level Response\");\n\t}\n\n\tconst documentResponse = cacElement(root, \"DocumentResponse\");\n\tconst response = documentResponse ? cacElement(documentResponse, \"Response\") : null;\n\tconst documentReference = documentResponse\n\t\t? cacElement(documentResponse, \"DocumentReference\")\n\t\t: null;\n\n\treturn {\n\t\tcustomizationId: cbcDirectText(root, \"CustomizationID\"),\n\t\tprofileId: cbcDirectText(root, \"ProfileID\"),\n\t\tresponseId: cbcDirectText(root, \"ID\"),\n\t\tissueDate: cbcDirectText(root, \"IssueDate\"),\n\t\tissueTime: cbcDirectText(root, \"IssueTime\"),\n\t\treferencedDocumentId: documentReference\n\t\t\t? cbcText(documentReference, \"ID\")\n\t\t\t: null,\n\t\tresponseCode: response ? cbcText(response, \"ResponseCode\") : null,\n\t\tdescription: response ? cbcText(response, \"Description\") : null,\n\t\tsenderIdentifier: endpointIdentifier(cacElement(root, \"SenderParty\")),\n\t\treceiverIdentifier: endpointIdentifier(cacElement(root, \"ReceiverParty\")),\n\t};\n};\n","import { parseUblInvoice } from \"./parser.js\";\nimport type {\n\tInvoiceExtractionDTO,\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblInvoice,\n} from \"./types.js\";\n\n// --- Utility helpers ---\n\nconst UTF8_BOM = 0xfeff;\n\nconst normalizeText = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst upper = trimmed.toUpperCase();\n\tif (upper === \"NA\" || upper === \"N/A\") return null;\n\treturn trimmed;\n};\n\nconst toNumberOrNull = (value: number | null | undefined): number | null =>\n\tNumber.isFinite(value ?? Number.NaN) ? (value as number) : null;\n\nexport const normalizeCurrency = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\treturn trimmed.toUpperCase();\n};\n\nexport const parseDate = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst timestamp = Date.parse(trimmed);\n\tif (Number.isNaN(timestamp)) return null;\n\tconst iso = new Date(timestamp).toISOString();\n\treturn iso.slice(0, 10);\n};\n\n// --- Address helpers ---\n\nconst addressToString = (address?: UblAddress): string | null => {\n\tif (!address) return null;\n\tconst street = [address.street, address.additionalStreet]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst cityLine = [address.postalZone, address.city]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst countryLine = [address.countrySubentity, address.countryCode]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst lines = [street, cityLine, countryLine].filter((line) => line.length > 0);\n\treturn lines.length > 0 ? lines.join(\"\\n\") : null;\n};\n\nconst addressToStructured = (address?: UblAddress) => {\n\tif (!address) return null;\n\tconst line1 = [address.street, address.additionalStreet]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst result = {\n\t\tline1: normalizeText(line1),\n\t\tline2: null as string | null,\n\t\tcity: normalizeText(address.city),\n\t\tstate: normalizeText(address.countrySubentity),\n\t\tpostal_code: normalizeText(address.postalZone),\n\t\tcountry: normalizeText(address.countryCode),\n\t};\n\tconst hasValue = Object.values(result).some((value) => value);\n\treturn hasValue ? result : null;\n};\n\n// --- Attachment & charge sanitizers ---\n\nconst base64ByteLength = (content: string) => {\n\tconst sanitized = content.replace(/\\s+/g, \"\");\n\tif (!sanitized) return 0;\n\tconst paddingLength = sanitized.endsWith(\"==\")\n\t\t? 2\n\t\t: sanitized.endsWith(\"=\")\n\t\t\t? 1\n\t\t\t: 0;\n\treturn Math.floor((sanitized.length * 3) / 4) - paddingLength;\n};\n\nconst sanitizeAttachments = (attachments?: UblAttachment[]) =>\n\t(attachments ?? []).map((attachment) => ({\n\t\tid: normalizeText(attachment.id),\n\t\tfilename: normalizeText(attachment.filename),\n\t\tmime_code: normalizeText(attachment.mimeCode),\n\t\tdescription: normalizeText(attachment.description),\n\t\tsize_bytes: attachment.base64Content\n\t\t\t? base64ByteLength(attachment.base64Content)\n\t\t\t: null,\n\t\texternal_uri: normalizeText(attachment.externalUri),\n\t}));\n\nconst sanitizeAllowanceCharges = (charges?: UblAllowanceCharge[]) =>\n\t(charges ?? []).map((charge) => ({\n\t\tcharge_indicator: charge.chargeIndicator,\n\t\tamount: toNumberOrNull(charge.amount),\n\t\tbase_amount: toNumberOrNull(charge.baseAmount),\n\t\tmultiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),\n\t\treason: normalizeText(charge.reason),\n\t\treason_code: normalizeText(charge.reasonCode),\n\t\ttax_percent: toNumberOrNull(charge.taxPercent),\n\t\ttax_category_id: normalizeText(charge.taxCategoryId),\n\t\ttax_scheme_id: normalizeText(charge.taxSchemeId),\n\t}));\n\nconst sanitizeRawUbl = (ubl: UblInvoice) => ({\n\t...ubl,\n\tattachments: sanitizeAttachments(ubl.attachments),\n\tdocumentReferences: ubl.documentReferences ?? [],\n});\n\n// --- Summation helpers ---\n\nconst sumTaxTotal = (ubl: UblInvoice) => {\n\tconst subtotalSum = ubl.taxSubtotals.reduce(\n\t\t(sum, subtotal) => sum + subtotal.taxAmount,\n\t\t0,\n\t);\n\tif (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) {\n\t\treturn subtotalSum;\n\t}\n\treturn ubl.monetaryTotal.taxInclusiveAmount - ubl.monetaryTotal.taxExclusiveAmount;\n};\n\nconst sumAllowanceChargesByType = (\n\tcharges: UblAllowanceCharge[] | undefined,\n\tchargeIndicator: boolean,\n) =>\n\t(charges ?? []).reduce((sum, charge) => {\n\t\tif (charge.chargeIndicator !== chargeIndicator) return sum;\n\t\treturn sum + Math.abs(charge.amount);\n\t}, 0);\n\n// --- Public API ---\n\n/**\n * Decode raw XML bytes, stripping an optional UTF-8 BOM.\n */\nexport const decodeXmlBytes = (bytes: Uint8Array): string => {\n\tconst text = new TextDecoder(\"utf-8\").decode(bytes);\n\treturn text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;\n};\n\n/**\n * Parse a UBL XML string and normalize it into a flat DTO suitable for\n * database storage or API responses.\n */\nexport const normalizeUblResponse = (\n\txml: string,\n\tdocumentId: string,\n): {\n\textracted: InvoiceExtractionDTO;\n\trawPayload: Record<string, unknown>;\n} => {\n\tconst ubl = parseUblInvoice(xml);\n\tif (!ubl) {\n\t\tthrow new Error(\"Failed to parse UBL invoice XML\");\n\t}\n\n\tconst subtotal =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);\n\tconst total =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst prepaidAmount = toNumberOrNull(ubl.monetaryTotal.prepaidAmount);\n\tconst amountPaid =\n\t\tprepaidAmount ??\n\t\t(total !== null && amountDue !== null && total > amountDue\n\t\t\t? toNumberOrNull(total - amountDue)\n\t\t\t: null);\n\tconst taxTotal = toNumberOrNull(sumTaxTotal(ubl));\n\tconst hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;\n\tconst headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);\n\tconst headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);\n\tconst currency = normalizeCurrency(ubl.currency);\n\tconst paymentTerms = normalizeText(ubl.paymentTermsNote);\n\tconst poNumber =\n\t\tnormalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);\n\n\tconst lineItems = ubl.lines.map((line) => ({\n\t\tdescription:\n\t\t\tnormalizeText(line.description) ??\n\t\t\tnormalizeText(line.itemName) ??\n\t\t\t\"Line item\",\n\t\tquantity: toNumberOrNull(line.quantity),\n\t\tunit: normalizeText(line.unitCode),\n\t\tunit_price: toNumberOrNull(line.unitPrice),\n\t\tamount: toNumberOrNull(line.lineExtensionAmount),\n\t\ttax_amount: toNumberOrNull(line.taxAmount),\n\t\ttax_rate: toNumberOrNull(line.taxPercent),\n\t\tproduct_code:\n\t\t\tnormalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),\n\t\tdiscount_amount: toNumberOrNull(line.discountAmount),\n\t\textra: {\n\t\t\tubl_line_id: normalizeText(line.id),\n\t\t\titem_name: normalizeText(line.itemName),\n\t\t\tsellers_item_id: normalizeText(line.sellersItemId),\n\t\t\tbuyers_item_id: normalizeText(line.buyersItemId),\n\t\t\ttax_category_id: normalizeText(line.taxCategoryId),\n\t\t\ttax_scheme_id: normalizeText(line.taxSchemeId),\n\t\t\ttax_subtotals: line.taxSubtotals ?? [],\n\t\t\tallowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),\n\t\t\tcharge_amount: toNumberOrNull(line.chargeAmount),\n\t\t\tmetadata: line.additionalItemProperties\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tline.additionalItemProperties.map((p) => [p.name, p.value]),\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t},\n\t}));\n\n\tconst supplierAddress = addressToString(ubl.seller.address);\n\tconst receiverAddress = addressToString(ubl.buyer.address);\n\tconst supplierAddressStructured = addressToStructured(ubl.seller.address);\n\tconst receiverAddressStructured = addressToStructured(ubl.buyer.address);\n\tconst attachmentMetadata = sanitizeAttachments(ubl.attachments);\n\tconst paymentMeansList =\n\t\tubl.paymentMeansList && ubl.paymentMeansList.length > 0\n\t\t\t? ubl.paymentMeansList\n\t\t\t: ubl.paymentMeans\n\t\t\t\t? [ubl.paymentMeans]\n\t\t\t\t: [];\n\n\tconst extracted: InvoiceExtractionDTO = {\n\t\tprovider: \"ubl_xml\",\n\t\tdocument_id: documentId,\n\t\tinvoice: {\n\t\t\tinvoice_number: normalizeText(ubl.id),\n\t\t\tinvoice_date: parseDate(ubl.issueDate),\n\t\t\tdue_date: parseDate(ubl.dueDate),\n\t\t\tcurrency,\n\t\t\tsubtotal,\n\t\t\ttax_total: taxTotal,\n\t\t\ttotal,\n\t\t\tamount_due: amountDue,\n\t\t\tamount_paid: amountPaid,\n\t\t\tdiscount_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges\n\t\t\t\t\t? toNumberOrNull(headerDiscountTotal)\n\t\t\t\t\t: null),\n\t\t\tshipping_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),\n\t\t\tpayment_terms: paymentTerms,\n\t\t\tpo_number: poNumber,\n\t\t\tsupplier: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.seller.name) ??\n\t\t\t\t\tnormalizeText(ubl.seller.registrationName),\n\t\t\t\taddress: supplierAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.seller.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.seller.companyId),\n\t\t\t\tiban: normalizeText(ubl.paymentMeans?.iban),\n\t\t\t\tbic: normalizeText(ubl.paymentMeans?.bic),\n\t\t\t},\n\t\t\treceiver: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.buyer.name) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.registrationName),\n\t\t\t\taddress: receiverAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.buyer.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.companyId),\n\t\t\t},\n\t\t\textra: {\n\t\t\t\tdocument_type: ubl.documentType,\n\t\t\t\tcustomization_id: normalizeText(ubl.customizationId),\n\t\t\t\tprofile_id: normalizeText(ubl.profileId),\n\t\t\t\tinvoice_type_code: normalizeText(ubl.invoiceTypeCode),\n\t\t\t\tbuyer_reference: normalizeText(ubl.buyerReference),\n\t\t\t\torder_reference_id: normalizeText(ubl.orderReference),\n\t\t\t\tsales_order_id: normalizeText(ubl.salesOrderId),\n\t\t\t\tcontract_reference: normalizeText(ubl.contractReference),\n\t\t\t\tproject_reference: normalizeText(ubl.projectReference),\n\t\t\t\tbilling_reference: ubl.billingReference\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tinvoice_id: normalizeText(ubl.billingReference.invoiceId),\n\t\t\t\t\t\t\tinvoice_issue_date: parseDate(\n\t\t\t\t\t\t\t\tubl.billingReference.invoiceIssueDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\ttax_point_date: parseDate(ubl.taxPointDate),\n\t\t\t\tinvoice_period: ubl.invoicePeriod ?? null,\n\t\t\t\tnote: normalizeText(ubl.note),\n\t\t\t\tpayment_means: ubl.paymentMeans\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcode: normalizeText(ubl.paymentMeans.code),\n\t\t\t\t\t\t\tcode_name: normalizeText(ubl.paymentMeans.codeName),\n\t\t\t\t\t\t\tpayment_id: normalizeText(ubl.paymentMeans.paymentId),\n\t\t\t\t\t\t\tiban: normalizeText(ubl.paymentMeans.iban),\n\t\t\t\t\t\t\tbic: normalizeText(ubl.paymentMeans.bic),\n\t\t\t\t\t\t\taccount_name: normalizeText(ubl.paymentMeans.accountName),\n\t\t\t\t\t\t\tmandate_id: normalizeText(ubl.paymentMeans.mandateId),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tpayment_means_list: paymentMeansList.map((item) => ({\n\t\t\t\t\tcode: normalizeText(item.code),\n\t\t\t\t\tcode_name: normalizeText(item.codeName),\n\t\t\t\t\tpayment_id: normalizeText(item.paymentId),\n\t\t\t\t\tiban: normalizeText(item.iban),\n\t\t\t\t\tbic: normalizeText(item.bic),\n\t\t\t\t\taccount_name: normalizeText(item.accountName),\n\t\t\t\t\tmandate_id: normalizeText(item.mandateId),\n\t\t\t\t})),\n\t\t\t\tdelivery: ubl.delivery\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tactual_delivery_date: parseDate(\n\t\t\t\t\t\t\t\tubl.delivery.actualDeliveryDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\taddress: addressToStructured(ubl.delivery.address),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tsupplier: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.seller.endpointId),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),\n\t\t\t\t\tregistration_name: normalizeText(ubl.seller.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.seller.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.seller.companyIdSchemeId),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.seller.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.seller.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.seller.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.seller.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.seller.contact?.email),\n\t\t\t\t},\n\t\t\t\treceiver: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.buyer.endpointId),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),\n\t\t\t\t\tregistration_name: normalizeText(ubl.buyer.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.buyer.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.buyer.companyIdSchemeId),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.buyer.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.buyer.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.buyer.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.buyer.contact?.email),\n\t\t\t\t},\n\t\t\t\tsupplier_address_structured: supplierAddressStructured,\n\t\t\t\treceiver_address_structured: receiverAddressStructured,\n\t\t\t\ttax_subtotals: ubl.taxSubtotals,\n\t\t\t\tallowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),\n\t\t\t\tattachments: attachmentMetadata,\n\t\t\t\tdocument_references: ubl.documentReferences ?? [],\n\t\t\t},\n\t\t},\n\t\tline_items: lineItems,\n\t\tconfidence: {\n\t\t\toverall: 1,\n\t\t\tfields: {\n\t\t\t\tinvoice_id: 1,\n\t\t\t\tinvoice_date: 1,\n\t\t\t\tdue_date: 1,\n\t\t\t\ttotal_amount: 1,\n\t\t\t\tsupplier_name: 1,\n\t\t\t},\n\t\t},\n\t};\n\n\treturn {\n\t\textracted,\n\t\trawPayload: {\n\t\t\tformat: \"ubl_xml\",\n\t\t\tinvoice: sanitizeRawUbl(ubl),\n\t\t},\n\t};\n};\n\n/**\n * Parse a UBL invoice from raw bytes and normalize it into a DTO.\n */\nexport const parseUblInvoiceDocument = (params: {\n\tbytes: Uint8Array;\n\tdocumentId: string;\n\tmimeType: string;\n}) => {\n\tconst xml = decodeXmlBytes(params.bytes);\n\tconst { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);\n\treturn {\n\t\trawPayload: {\n\t\t\t...rawPayload,\n\t\t\tmime_type: params.mimeType,\n\t\t},\n\t\textracted,\n\t\tproviderJobId: null as string | null,\n\t};\n};\n"],"mappings":";;AAmBA,MAAMA,WAAS;AACf,MAAMC,WACL;AAID,SAASC,UAAQ,QAAiB,KAAqB;CAEtD,OADW,OAAO,uBAAuBF,UAAQ,GAAG,CAAC,CAAC,EAC7C,EAAE,aAAa,KAAK,KAAK;AACnC;AAEA,SAASG,aAAW,QAAiB,KAA6B;CACjE,OAAO,OAAO,uBAAuBF,UAAQ,GAAG,CAAC,CAAC,MAAM;AACzD;AAEA,SAAS,YAAY,QAAiB,KAAwB;CAC7D,OAAO,MAAM,KAAK,OAAO,uBAAuBA,UAAQ,GAAG,CAAC;AAC7D;AAEA,SAAS,UAAU,QAAiB,KAAqB;CACxD,MAAM,IAAI,OAAO,WAAWC,UAAQ,QAAQ,GAAG,CAAC;CAChD,OAAO,OAAO,MAAM,CAAC,IAAI,IAAI;AAC9B;AAEA,SAAS,qBACR,QACA,WACA,KACY;CACZ,MAAM,WAAsB,CAAC;CAC7B,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,WAAW,QAAQ,KAAK;EAClD,MAAM,OAAO,OAAO,WAA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c,IAAI,MAAM,gBAAgB;MAC5D,mBAAmB,cAAc,IAAI,MAAM,gBAAgB;MAC3D,oBAAoB,cAAc,IAAI,MAAM,gBAAgB;MAC5D,sBAAsB,cAAc,IAAI,MAAM,iBAAiB;MAC/D,eAAe,cAAc,IAAI,MAAM,WAAW;MAClD,uBAAuB,IAAI,MAAM,wBAAwB,CAAC;MAC1D,cAAc,cAAc,IAAI,MAAM,SAAS,IAAI;MACnD,eAAe,cAAc,IAAI,MAAM,SAAS,KAAK;MACrD,eAAe,cAAc,IAAI,MAAM,SAAS,KAAK;KACtD;KACA,6BAA6B;KAC7B,6BAA6B;KAC7B,eAAe,IAAI;KACnB,mBAAmB,yBAAyB,IAAI,gBAAgB;KAChE,aAAa;KACb,qBAAqB,IAAI,sBAAsB,CAAC;IACjD;GACD;GACA,YAAY;GACZ,YAAY;IACX,SAAS;IACT,QAAQ;KACP,YAAY;KACZ,cAAc;KACd,UAAU;KACV,cAAc;KACd,eAAe;IAChB;GACD;EAIQ;EACR,YAAY;GACX,QAAQ;GACR,SAAS,eAAe,GAAG;EAC5B;CACD;AACD;;;;AAKA,MAAa,2BAA2B,WAIlC;CACL,MAAM,MAAM,eAAe,OAAO,KAAK;CACvC,MAAM,EAAE,WAAW,eAAe,qBAAqB,KAAK,OAAO,UAAU;CAC7E,OAAO;EACN,YAAY;GACX,GAAG;GACH,WAAW,OAAO;EACnB;EACA;EACA,eAAe;CAChB;AACD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@financica/ubl",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "UBL (Universal Business Language) invoice toolkit for TypeScript: parse, build, and serialize Peppol BIS Billing 3.0 documents.",
5
5
  "homepage": "https://github.com/financica/ubl-ts#readme",
6
6
  "bugs": {