@financica/ubl 0.8.0 → 0.10.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.
@@ -1,630 +1,716 @@
1
- // src/build/ubl/constants.ts
2
- var UBL_CUSTOMIZATION_ID = "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0";
3
- var UBL_PROFILE_ID = "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0";
4
- var INVOICE_TYPE_CODE = "380";
5
- var CREDIT_NOTE_TYPE_CODE = "381";
6
- var DEFAULT_UNIT_CODE = "C62";
7
- var VAT_TAX_SCHEME_ID = "VAT";
8
- var COUNTRY_CODE_LIST_ID = "ISO3166-1:Alpha2";
9
- var NS_INVOICE = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
10
- var NS_CREDIT_NOTE = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
11
- var NS_CAC = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
12
- var NS_CBC = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
13
-
14
- // src/build/xml.ts
15
- var el = (name, attrs, content) => {
16
- if (Array.isArray(content)) {
17
- return {
18
- name,
19
- attrs: attrs ?? void 0,
20
- children: content.filter((c) => Boolean(c))
21
- };
22
- }
23
- return { name, attrs: attrs ?? void 0, text: content ?? void 0 };
1
+ //#region src/build/ubl/constants.ts
2
+ /** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */
3
+ /** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */
4
+ const UBL_CUSTOMIZATION_ID = "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0";
5
+ /** Peppol BIS Billing 3.0 process (BT-23). */
6
+ const UBL_PROFILE_ID = "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0";
7
+ /** UNTDID 1001 — commercial invoice. */
8
+ const INVOICE_TYPE_CODE = "380";
9
+ /** UNTDID 1001 — credit note. */
10
+ const CREDIT_NOTE_TYPE_CODE = "381";
11
+ /** UN/ECE Recommendation 20 — "one / piece" (the default line unit). */
12
+ const DEFAULT_UNIT_CODE = "C62";
13
+ /** UNCL5153 — the VAT tax scheme identifier. */
14
+ const VAT_TAX_SCHEME_ID = "VAT";
15
+ /** ISO 3166-1 alpha-2 list identifier for `cbc:IdentificationCode`. */
16
+ const COUNTRY_CODE_LIST_ID = "ISO3166-1:Alpha2";
17
+ const NS_INVOICE = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
18
+ const NS_CREDIT_NOTE = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
19
+ const NS_CAC = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
20
+ const NS_CBC = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
21
+ //#endregion
22
+ //#region src/build/xml.ts
23
+ /**
24
+ * Build an XML element.
25
+ *
26
+ * el("cbc:ID", null, "INV-1") → <cbc:ID>INV-1</cbc:ID>
27
+ * el("cbc:Amount", { currencyID: "EUR" }, "10.00") → <cbc:Amount currencyID="EUR">10.00</cbc:Amount>
28
+ * el("cac:Party", null, [child, cond && child2]) → nested element
29
+ */
30
+ const el = (name, attrs, content) => {
31
+ if (Array.isArray(content)) return {
32
+ name,
33
+ attrs: attrs ?? void 0,
34
+ children: content.filter((c) => Boolean(c))
35
+ };
36
+ return {
37
+ name,
38
+ attrs: attrs ?? void 0,
39
+ text: content ?? void 0
40
+ };
24
41
  };
25
- var escapeText = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
26
- var escapeAttr = (value) => escapeText(value).replace(/"/g, "&quot;");
27
- var serializeAttrs = (attrs) => {
28
- if (!attrs) return "";
29
- return Object.entries(attrs).filter(([, value]) => value !== null && value !== void 0).map(([key, value]) => ` ${key}="${escapeAttr(String(value))}"`).join("");
42
+ const escapeText = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
43
+ const escapeAttr = (value) => escapeText(value).replace(/"/g, "&quot;");
44
+ const serializeAttrs = (attrs) => {
45
+ if (!attrs) return "";
46
+ return Object.entries(attrs).filter(([, value]) => value !== null && value !== void 0).map(([key, value]) => ` ${key}="${escapeAttr(String(value))}"`).join("");
30
47
  };
31
- var serializeElement = (node, indentLevel) => {
32
- const pad = " ".repeat(indentLevel);
33
- const attrs = serializeAttrs(node.attrs);
34
- if (node.text !== void 0 && node.text !== null) {
35
- return `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;
36
- }
37
- const children = node.children ?? [];
38
- if (children.length === 0) {
39
- return `${pad}<${node.name}${attrs}/>`;
40
- }
41
- const inner = children.map((child) => serializeElement(child, indentLevel + 1)).join("\n");
42
- return `${pad}<${node.name}${attrs}>
43
- ${inner}
44
- ${pad}</${node.name}>`;
48
+ const serializeElement = (node, indentLevel) => {
49
+ const pad = " ".repeat(indentLevel);
50
+ const attrs = serializeAttrs(node.attrs);
51
+ if (node.text !== void 0 && node.text !== null) return `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;
52
+ const children = node.children ?? [];
53
+ if (children.length === 0) return `${pad}<${node.name}${attrs}/>`;
54
+ const inner = children.map((child) => serializeElement(child, indentLevel + 1)).join("\n");
55
+ return `${pad}<${node.name}${attrs}>\n${inner}\n${pad}</${node.name}>`;
45
56
  };
46
- var serializeDocument = (root) => `<?xml version="1.0" encoding="UTF-8"?>
47
- ${serializeElement(root, 0)}
48
- `;
49
-
50
- // src/build/ubl/serialize.ts
51
- var amount = (value) => value.toFixed(2);
52
- var percent = (value) => {
53
- const rounded = Math.round(value * 100) / 100;
54
- return Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);
57
+ /** Serialize a root element into a UTF-8 XML document string. */
58
+ const serializeDocument = (root) => `<?xml version="1.0" encoding="UTF-8"?>\n${serializeElement(root, 0)}\n`;
59
+ //#endregion
60
+ //#region src/build/ubl/serialize.ts
61
+ /** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */
62
+ const amount = (value) => value.toFixed(2);
63
+ /** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */
64
+ const percent = (value) => {
65
+ const rounded = Math.round(value * 100) / 100;
66
+ return Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);
55
67
  };
56
- var money = (name, value, currency) => el(name, { currencyID: currency }, amount(value));
57
- var vatTaxScheme = () => el("cac:TaxScheme", null, [el("cbc:ID", null, VAT_TAX_SCHEME_ID)]);
58
- var taxCategory = (name, category) => el(name, null, [
59
- el("cbc:ID", null, category.id),
60
- el("cbc:Percent", null, percent(category.percent)),
61
- category.exemptionReason ? el("cbc:TaxExemptionReason", null, category.exemptionReason) : null,
62
- vatTaxScheme()
68
+ const money = (name, value, currency) => el(name, { currencyID: currency }, amount(value));
69
+ const vatTaxScheme = () => el("cac:TaxScheme", null, [el("cbc:ID", null, "VAT")]);
70
+ /**
71
+ * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)
72
+ * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption
73
+ * reason for the non-charging categories (E/AE/O/K/G).
74
+ */
75
+ const taxCategory = (name, category) => el(name, null, [
76
+ el("cbc:ID", null, category.id),
77
+ el("cbc:Percent", null, percent(category.percent)),
78
+ category.exemptionReason ? el("cbc:TaxExemptionReason", null, category.exemptionReason) : null,
79
+ vatTaxScheme()
63
80
  ]);
64
- var postalAddress = (address) => el("cac:PostalAddress", null, [
65
- address.street ? el("cbc:StreetName", null, address.street) : null,
66
- address.additionalStreet ? el("cbc:AdditionalStreetName", null, address.additionalStreet) : null,
67
- address.city ? el("cbc:CityName", null, address.city) : null,
68
- address.postalZone ? el("cbc:PostalZone", null, address.postalZone) : null,
69
- address.countrySubentity ? el("cbc:CountrySubentity", null, address.countrySubentity) : null,
70
- address.countryCode ? el("cac:Country", null, [
71
- el(
72
- "cbc:IdentificationCode",
73
- { listID: COUNTRY_CODE_LIST_ID },
74
- address.countryCode
75
- )
76
- ]) : null
81
+ const postalAddress = (address) => el("cac:PostalAddress", null, [
82
+ address.street ? el("cbc:StreetName", null, address.street) : null,
83
+ address.additionalStreet ? el("cbc:AdditionalStreetName", null, address.additionalStreet) : null,
84
+ address.city ? el("cbc:CityName", null, address.city) : null,
85
+ address.postalZone ? el("cbc:PostalZone", null, address.postalZone) : null,
86
+ address.countrySubentity ? el("cbc:CountrySubentity", null, address.countrySubentity) : null,
87
+ address.countryCode ? el("cac:Country", null, [el("cbc:IdentificationCode", { listID: COUNTRY_CODE_LIST_ID }, address.countryCode)]) : null
77
88
  ]);
78
- var party = (source) => el("cac:Party", null, [
79
- source.endpoint ? el(
80
- "cbc:EndpointID",
81
- { schemeID: source.endpoint.scheme },
82
- source.endpoint.value
83
- ) : null,
84
- el("cac:PartyName", null, [el("cbc:Name", null, source.name)]),
85
- postalAddress(source.address),
86
- source.vatNumber ? el("cac:PartyTaxScheme", null, [
87
- el("cbc:CompanyID", null, source.vatNumber),
88
- vatTaxScheme()
89
- ]) : null,
90
- el("cac:PartyLegalEntity", null, [
91
- el("cbc:RegistrationName", null, source.legalName ?? source.name),
92
- source.companyId ? el(
93
- "cbc:CompanyID",
94
- source.companyId.scheme ? { schemeID: source.companyId.scheme } : null,
95
- source.companyId.value
96
- ) : null
97
- ])
89
+ const party = (source) => el("cac:Party", null, [
90
+ source.endpoint ? el("cbc:EndpointID", { schemeID: source.endpoint.scheme }, source.endpoint.value) : null,
91
+ el("cac:PartyName", null, [el("cbc:Name", null, source.name)]),
92
+ postalAddress(source.address),
93
+ source.vatNumber ? el("cac:PartyTaxScheme", null, [el("cbc:CompanyID", null, source.vatNumber), vatTaxScheme()]) : null,
94
+ el("cac:PartyLegalEntity", null, [el("cbc:RegistrationName", null, source.legalName ?? source.name), source.companyId ? el("cbc:CompanyID", source.companyId.scheme ? { schemeID: source.companyId.scheme } : null, source.companyId.value) : null])
98
95
  ]);
99
- var taxSubtotal = (subtotal, currency) => el("cac:TaxSubtotal", null, [
100
- money("cbc:TaxableAmount", subtotal.taxableAmount, currency),
101
- money("cbc:TaxAmount", subtotal.taxAmount, currency),
102
- taxCategory("cac:TaxCategory", subtotal.category)
96
+ const taxSubtotal = (subtotal, currency) => el("cac:TaxSubtotal", null, [
97
+ money("cbc:TaxableAmount", subtotal.taxableAmount, currency),
98
+ money("cbc:TaxAmount", subtotal.taxAmount, currency),
99
+ taxCategory("cac:TaxCategory", subtotal.category)
103
100
  ]);
104
- var line = (source, currency, documentType) => {
105
- const lineElementName = documentType === "creditNote" ? "cac:CreditNoteLine" : "cac:InvoiceLine";
106
- const quantityElementName = documentType === "creditNote" ? "cbc:CreditedQuantity" : "cbc:InvoicedQuantity";
107
- return el(lineElementName, null, [
108
- el("cbc:ID", null, source.id),
109
- el(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),
110
- money("cbc:LineExtensionAmount", source.lineExtensionAmount, currency),
111
- el("cac:Item", null, [
112
- el("cbc:Name", null, source.name),
113
- taxCategory("cac:ClassifiedTaxCategory", source.taxCategory)
114
- ]),
115
- el("cac:Price", null, [money("cbc:PriceAmount", source.priceAmount, currency)])
116
- ]);
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));
117
116
  };
118
- var attachmentReference = (attachment) => el("cac:AdditionalDocumentReference", null, [
119
- el("cbc:ID", null, attachment.id),
120
- el("cac:Attachment", null, [
121
- el(
122
- "cbc:EmbeddedDocumentBinaryObject",
123
- { mimeCode: attachment.mimeCode, filename: attachment.filename },
124
- attachment.base64
125
- )
126
- ])
127
- ]);
128
- var billingReference = (precedingInvoiceId) => el("cac:BillingReference", null, [
129
- el("cac:InvoiceDocumentReference", null, [
130
- el("cbc:ID", null, precedingInvoiceId)
131
- ])
132
- ]);
133
- var serializeUblDocument = (doc) => {
134
- const isCreditNote = doc.documentType === "creditNote";
135
- const rootName = isCreditNote ? "CreditNote" : "Invoice";
136
- const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
137
- const typeCodeElement = isCreditNote ? el("cbc:CreditNoteTypeCode", null, CREDIT_NOTE_TYPE_CODE) : el("cbc:InvoiceTypeCode", null, INVOICE_TYPE_CODE);
138
- const children = [
139
- el("cbc:CustomizationID", null, UBL_CUSTOMIZATION_ID),
140
- el("cbc:ProfileID", null, UBL_PROFILE_ID),
141
- el("cbc:ID", null, doc.id),
142
- el("cbc:IssueDate", null, doc.issueDate),
143
- // CreditNote has no DueDate element in the UBL sequence.
144
- !isCreditNote && doc.dueDate ? el("cbc:DueDate", null, doc.dueDate) : null,
145
- typeCodeElement,
146
- doc.note ? el("cbc:Note", null, doc.note) : null,
147
- el("cbc:DocumentCurrencyCode", null, doc.currency),
148
- doc.buyerReference ? el("cbc:BuyerReference", null, doc.buyerReference) : null,
149
- doc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,
150
- ...doc.attachments.map(attachmentReference),
151
- el("cac:AccountingSupplierParty", null, [party(doc.supplier)]),
152
- el("cac:AccountingCustomerParty", null, [party(doc.customer)]),
153
- el("cac:TaxTotal", null, [
154
- money("cbc:TaxAmount", doc.taxTotal.taxAmount, doc.currency),
155
- ...doc.taxTotal.subtotals.map(
156
- (subtotal) => taxSubtotal(subtotal, doc.currency)
157
- )
158
- ]),
159
- el("cac:LegalMonetaryTotal", null, [
160
- money(
161
- "cbc:LineExtensionAmount",
162
- doc.monetaryTotal.lineExtensionAmount,
163
- doc.currency
164
- ),
165
- money(
166
- "cbc:TaxExclusiveAmount",
167
- doc.monetaryTotal.taxExclusiveAmount,
168
- doc.currency
169
- ),
170
- money(
171
- "cbc:TaxInclusiveAmount",
172
- doc.monetaryTotal.taxInclusiveAmount,
173
- doc.currency
174
- ),
175
- money("cbc:PayableAmount", doc.monetaryTotal.payableAmount, doc.currency)
176
- ]),
177
- ...doc.lines.map((source) => line(source, doc.currency, doc.documentType))
178
- ];
179
- const root = el(
180
- rootName,
181
- {
182
- xmlns: rootNamespace,
183
- "xmlns:cac": NS_CAC,
184
- "xmlns:cbc": NS_CBC
185
- },
186
- children.filter((child) => Boolean(child))
187
- );
188
- return serializeDocument(root);
117
+ const line = (source, currency, documentType) => {
118
+ const lineElementName = documentType === "creditNote" ? "cac:CreditNoteLine" : "cac:InvoiceLine";
119
+ const quantityElementName = documentType === "creditNote" ? "cbc:CreditedQuantity" : "cbc:InvoicedQuantity";
120
+ return el(lineElementName, null, [
121
+ el("cbc:ID", null, source.id),
122
+ el(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),
123
+ money("cbc:LineExtensionAmount", source.lineExtensionAmount, currency),
124
+ el("cac:Item", null, [el("cbc:Name", null, source.name), taxCategory("cac:ClassifiedTaxCategory", source.taxCategory)]),
125
+ el("cac:Price", null, [money("cbc:PriceAmount", source.priceAmount, currency)])
126
+ ]);
189
127
  };
190
-
191
- // src/build/utils.ts
192
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
193
- var normalizeString = (value) => {
194
- if (typeof value !== "string") return null;
195
- const normalized = value.trim();
196
- return normalized.length > 0 ? normalized : null;
128
+ const attachmentReference = (attachment) => el("cac:AdditionalDocumentReference", null, [el("cbc:ID", null, attachment.id), el("cac:Attachment", null, [el("cbc:EmbeddedDocumentBinaryObject", {
129
+ mimeCode: attachment.mimeCode,
130
+ filename: attachment.filename
131
+ }, attachment.base64)])]);
132
+ const billingReference = (precedingInvoiceId) => el("cac:BillingReference", null, [el("cac:InvoiceDocumentReference", null, [el("cbc:ID", null, precedingInvoiceId)])]);
133
+ /** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */
134
+ const serializeUblDocument = (doc) => {
135
+ const isCreditNote = doc.documentType === "creditNote";
136
+ const rootName = isCreditNote ? "CreditNote" : "Invoice";
137
+ const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
138
+ const typeCodeElement = isCreditNote ? el("cbc:CreditNoteTypeCode", null, "381") : el("cbc:InvoiceTypeCode", null, "380");
139
+ const children = [
140
+ el("cbc:CustomizationID", null, UBL_CUSTOMIZATION_ID),
141
+ el("cbc:ProfileID", null, UBL_PROFILE_ID),
142
+ el("cbc:ID", null, doc.id),
143
+ el("cbc:IssueDate", null, doc.issueDate),
144
+ !isCreditNote && doc.dueDate ? el("cbc:DueDate", null, doc.dueDate) : null,
145
+ typeCodeElement,
146
+ doc.note ? el("cbc:Note", null, doc.note) : null,
147
+ el("cbc:DocumentCurrencyCode", null, doc.currency),
148
+ doc.buyerReference ? el("cbc:BuyerReference", null, doc.buyerReference) : null,
149
+ doc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,
150
+ ...doc.attachments.map(attachmentReference),
151
+ el("cac:AccountingSupplierParty", null, [party(doc.supplier)]),
152
+ el("cac:AccountingCustomerParty", null, [party(doc.customer)]),
153
+ el("cac:TaxTotal", null, [money("cbc:TaxAmount", doc.taxTotal.taxAmount, doc.currency), ...doc.taxTotal.subtotals.map((subtotal) => taxSubtotal(subtotal, doc.currency))]),
154
+ el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
155
+ ...doc.lines.map((source) => line(source, doc.currency, doc.documentType))
156
+ ];
157
+ return serializeDocument(el(rootName, {
158
+ xmlns: rootNamespace,
159
+ "xmlns:cac": NS_CAC,
160
+ "xmlns:cbc": NS_CBC
161
+ }, children.filter((child) => Boolean(child))));
197
162
  };
198
-
199
- // src/build/address.ts
200
- var normalizeCountryCode = (value) => {
201
- const trimmed = normalizeString(value);
202
- if (!trimmed) return null;
203
- return trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;
163
+ //#endregion
164
+ //#region src/build/utils.ts
165
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
166
+ const normalizeString = (value) => {
167
+ if (typeof value !== "string") return null;
168
+ const normalized = value.trim();
169
+ return normalized.length > 0 ? normalized : null;
204
170
  };
205
- var normalizeAddress = (address, fallbackCountryCode, fallbackLine) => {
206
- const record = isRecord(address) ? address : {};
207
- const countryCode = normalizeCountryCode(normalizeString(record.country)) ?? normalizeCountryCode(normalizeString(record.country_code)) ?? normalizeCountryCode(fallbackCountryCode);
208
- return {
209
- street: normalizeString(record.line1) ?? normalizeString(record.street) ?? fallbackLine ?? null,
210
- additionalStreet: normalizeString(record.line2),
211
- city: normalizeString(record.city),
212
- postalZone: normalizeString(record.postal_code) ?? normalizeString(record.zip_code),
213
- countrySubentity: normalizeString(record.state) ?? normalizeString(record.country_subentity),
214
- countryCode
215
- };
171
+ //#endregion
172
+ //#region src/build/address.ts
173
+ const normalizeCountryCode = (value) => {
174
+ const trimmed = normalizeString(value);
175
+ if (!trimmed) return null;
176
+ return trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;
216
177
  };
217
-
218
- // src/build/identifiers.ts
219
- var cleanIdentifierValue = (value) => value.trim().replace(/\s+/g, "").replace(/[^A-Za-z0-9]/g, "");
220
- var normalizeBelgianCompanyNumber = (value) => {
221
- if (!value) return "";
222
- return cleanIdentifierValue(value).toUpperCase().replace(/^BE/, "");
178
+ /**
179
+ * Normalize a free-form address (Stripe shape, custom shape, or an internal
180
+ * shape) into a {@link UblAddress}.
181
+ *
182
+ * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`
183
+ * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address
184
+ * has no country, but never silently substitutes a caller's country — pass
185
+ * `null` when "no country" is the right answer.
186
+ */
187
+ const normalizeAddress = (address, fallbackCountryCode, fallbackLine) => {
188
+ const record = isRecord(address) ? address : {};
189
+ const countryCode = normalizeCountryCode(normalizeString(record.country)) ?? normalizeCountryCode(normalizeString(record.country_code)) ?? normalizeCountryCode(fallbackCountryCode);
190
+ return {
191
+ street: normalizeString(record.line1) ?? normalizeString(record.street) ?? fallbackLine ?? null,
192
+ additionalStreet: normalizeString(record.line2),
193
+ city: normalizeString(record.city),
194
+ postalZone: normalizeString(record.postal_code) ?? normalizeString(record.zip_code),
195
+ countrySubentity: normalizeString(record.state) ?? normalizeString(record.country_subentity),
196
+ countryCode
197
+ };
223
198
  };
224
- var normalizeCompanyNumberForCountry = (countryCode, companyNumber) => {
225
- if (!companyNumber) return "";
226
- const upper = countryCode?.trim().toUpperCase() ?? "";
227
- if (upper === "BE") return normalizeBelgianCompanyNumber(companyNumber);
228
- return companyNumber.trim();
199
+ //#endregion
200
+ //#region src/build/identifiers.ts
201
+ const cleanIdentifierValue = (value) => value.trim().replace(/\s+/g, "").replace(/[^A-Za-z0-9]/g, "");
202
+ const normalizeBelgianCompanyNumber = (value) => {
203
+ if (!value) return "";
204
+ return cleanIdentifierValue(value).toUpperCase().replace(/^BE/, "");
229
205
  };
230
- var resolveCompanyIdScheme = (params) => {
231
- const companyNumber = normalizeString(params.companyNumber);
232
- if (!companyNumber) return null;
233
- const TABLE = {
234
- BE: "0208",
235
- NL: "0106",
236
- FR: "0002"
237
- };
238
- const normalizedCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;
239
- if (normalizedCountry && normalizedCountry in TABLE) {
240
- return TABLE[normalizedCountry] ?? null;
241
- }
242
- const countryPrefix = cleanIdentifierValue(companyNumber).toUpperCase().slice(0, 2);
243
- return countryPrefix in TABLE ? TABLE[countryPrefix] ?? null : null;
206
+ /**
207
+ * Strip whitespace/punctuation from a country-specific company number.
208
+ * For Belgium, also strips an optional `BE` prefix.
209
+ */
210
+ const normalizeCompanyNumberForCountry = (countryCode, companyNumber) => {
211
+ if (!companyNumber) return "";
212
+ if ((countryCode?.trim().toUpperCase() ?? "") === "BE") return normalizeBelgianCompanyNumber(companyNumber);
213
+ return companyNumber.trim();
244
214
  };
245
- var buildCompanyId = (params) => {
246
- const normalized = normalizeString(
247
- normalizeCompanyNumberForCountry(params.countryCode, params.companyNumber)
248
- );
249
- if (!normalized) return null;
250
- return {
251
- value: normalized,
252
- scheme: resolveCompanyIdScheme({
253
- countryCode: params.countryCode,
254
- companyNumber: normalized
255
- })
256
- };
215
+ /**
216
+ * Country code → Peppol/ISO 6523 ICD scheme for a legal registration number
217
+ * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`).
218
+ *
219
+ * BE → 0208 (Belgian enterprise number, CBE/KBO/BCE)
220
+ * NL → 0106 (Netherlands KvK)
221
+ * FR → 0002 (France SIRENE)
222
+ *
223
+ * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).
224
+ * Returns `null` when the scheme can't be determined, in which case the
225
+ * CompanyID is emitted without a `schemeID` attribute.
226
+ */
227
+ const resolveCompanyIdScheme = (params) => {
228
+ const companyNumber = normalizeString(params.companyNumber);
229
+ if (!companyNumber) return null;
230
+ const TABLE = {
231
+ BE: "0208",
232
+ NL: "0106",
233
+ FR: "0002"
234
+ };
235
+ const normalizedCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;
236
+ if (normalizedCountry && normalizedCountry in TABLE) return TABLE[normalizedCountry] ?? null;
237
+ const countryPrefix = cleanIdentifierValue(companyNumber).toUpperCase().slice(0, 2);
238
+ return countryPrefix in TABLE ? TABLE[countryPrefix] ?? null : null;
257
239
  };
258
- var VAT_SCHEME_BY_COUNTRY = {
259
- AD: "9922",
260
- // Andorra
261
- AL: "9923",
262
- // Albania
263
- AT: "9914",
264
- // Austria
265
- BA: "9924",
266
- // Bosnia and Herzegovina
267
- BE: "9925",
268
- // Belgium
269
- BG: "9926",
270
- // Bulgaria
271
- CH: "9927",
272
- // Switzerland
273
- CY: "9928",
274
- // Cyprus
275
- CZ: "9929",
276
- // Czech Republic
277
- DE: "9930",
278
- // Germany
279
- EE: "9931",
280
- // Estonia
281
- ES: "9920",
282
- // Spain (Spanish Tax Administration)
283
- FI: "0213",
284
- // Finland (Finnish VAT Identifier)
285
- FR: "9957",
286
- // France
287
- GB: "9932",
288
- // United Kingdom
289
- GR: "9933",
290
- // Greece (VAT prefix "EL")
291
- HR: "9934",
292
- // Croatia
293
- HU: "9910",
294
- // Hungary
295
- IE: "9935",
296
- // Ireland
297
- LI: "9936",
298
- // Liechtenstein
299
- LT: "9937",
300
- // Lithuania
301
- LU: "9938",
302
- // Luxembourg
303
- LV: "9939",
304
- // Latvia
305
- MC: "9940",
306
- // Monaco
307
- ME: "9941",
308
- // Montenegro
309
- MK: "9942",
310
- // North Macedonia
311
- MT: "9943",
312
- // Malta
313
- NL: "9944",
314
- // Netherlands
315
- PL: "9945",
316
- // Poland
317
- PT: "9946",
318
- // Portugal
319
- RO: "9947",
320
- // Romania
321
- RS: "9948",
322
- // Serbia
323
- SI: "9949",
324
- // Slovenia
325
- SK: "9950",
326
- // Slovakia
327
- SM: "9951",
328
- // San Marino
329
- TR: "9952",
330
- // Turkey
331
- VA: "9953"
332
- // Holy See / Vatican City
240
+ /**
241
+ * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the
242
+ * country-appropriate ICD scheme when known. Returns `null` when there is no
243
+ * company number.
244
+ */
245
+ const buildCompanyId = (params) => {
246
+ const normalized = normalizeString(normalizeCompanyNumberForCountry(params.countryCode, params.companyNumber));
247
+ if (!normalized) return null;
248
+ return {
249
+ value: normalized,
250
+ scheme: resolveCompanyIdScheme({
251
+ countryCode: params.countryCode,
252
+ companyNumber: normalized
253
+ })
254
+ };
333
255
  };
334
- var VAT_PREFIX_TO_COUNTRY = {
335
- EL: "GR",
336
- // Greece issues VAT numbers with the "EL" prefix
337
- XI: "GB"
338
- // Northern Ireland VAT is issued under the UK scheme
256
+ /**
257
+ * Country code → Peppol EAS scheme for a *VAT* identifier, keyed by ISO 3166-1
258
+ * alpha-2. Source: Peppol Code Lists – Participant Identifier Schemes (EAS),
259
+ * Peppol BIS Billing 3.0 (November 2025 release).
260
+ *
261
+ * Only countries that publish a VAT-based EAS scheme appear here. Some (e.g.
262
+ * SE/DK/NO) address Peppol participants by organisation number rather than VAT
263
+ * and are intentionally absent — see {@link resolveCompanyIdScheme}.
264
+ */
265
+ const VAT_SCHEME_BY_COUNTRY = {
266
+ AD: "9922",
267
+ AL: "9923",
268
+ AT: "9914",
269
+ BA: "9924",
270
+ BE: "9925",
271
+ BG: "9926",
272
+ CH: "9927",
273
+ CY: "9928",
274
+ CZ: "9929",
275
+ DE: "9930",
276
+ EE: "9931",
277
+ ES: "9920",
278
+ FI: "0213",
279
+ FR: "9957",
280
+ GB: "9932",
281
+ GR: "9933",
282
+ HR: "9934",
283
+ HU: "9910",
284
+ IE: "9935",
285
+ LI: "9936",
286
+ LT: "9937",
287
+ LU: "9938",
288
+ LV: "9939",
289
+ MC: "9940",
290
+ ME: "9941",
291
+ MK: "9942",
292
+ MT: "9943",
293
+ NL: "9944",
294
+ PL: "9945",
295
+ PT: "9946",
296
+ RO: "9947",
297
+ RS: "9948",
298
+ SI: "9949",
299
+ SK: "9950",
300
+ SM: "9951",
301
+ TR: "9952",
302
+ VA: "9953"
339
303
  };
340
- var resolveVatEndpoint = (params) => {
341
- const value = normalizeString(params.vatNumber);
342
- if (!value) return null;
343
- const cleaned = cleanIdentifierValue(value).toUpperCase();
344
- if (!cleaned) return null;
345
- const prefix = cleaned.slice(0, 2);
346
- const fromPrefix = /^[A-Z]{2}$/.test(prefix) ? VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix : null;
347
- const fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;
348
- const country = fromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;
349
- const scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : void 0;
350
- if (!scheme) return null;
351
- return { scheme, value: cleaned };
304
+ /**
305
+ * VAT registration prefixes that differ from the ISO 3166-1 alpha-2 country
306
+ * code, so a VAT number's leading two letters still resolve to the right scheme.
307
+ */
308
+ const VAT_PREFIX_TO_COUNTRY = {
309
+ EL: "GR",
310
+ XI: "GB"
352
311
  };
353
- var parsePeppolEndpoint = (peppolId) => {
354
- const normalized = normalizeString(peppolId);
355
- if (!normalized) return null;
356
- const separatorIndex = normalized.indexOf(":");
357
- if (separatorIndex <= 0) return null;
358
- const scheme = normalized.slice(0, separatorIndex).trim();
359
- const value = normalized.slice(separatorIndex + 1).trim();
360
- if (!scheme || !value) return null;
361
- return { scheme, value };
312
+ /**
313
+ * Resolve the Peppol participant identifier for a VAT number, deriving the EAS
314
+ * scheme from the number's own country prefix (falling back to `countryCode`).
315
+ *
316
+ * `BE0206582284` → `{ scheme: "9925", value: "BE0206582284" }`
317
+ *
318
+ * The value keeps its country prefix, matching how participants register (the
319
+ * Peppol directory lists this party as `9925:be0206582284`). Returns `null`
320
+ * when the country has no VAT EAS scheme or the input is empty.
321
+ */
322
+ const resolveVatEndpoint = (params) => {
323
+ const value = normalizeString(params.vatNumber);
324
+ if (!value) return null;
325
+ const cleaned = cleanIdentifierValue(value).toUpperCase();
326
+ if (!cleaned) return null;
327
+ const prefix = cleaned.slice(0, 2);
328
+ const fromPrefix = /^[A-Z]{2}$/.test(prefix) ? VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix : null;
329
+ const fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;
330
+ const country = fromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;
331
+ const scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : void 0;
332
+ if (!scheme) return null;
333
+ return {
334
+ scheme,
335
+ value: cleaned
336
+ };
362
337
  };
363
- var normalizeIdentifierType = (value) => value?.toLowerCase().replace(/[^a-z0-9]+/g, "_") ?? null;
364
- var extractCustomerTaxIdentifiers = (taxIds) => {
365
- let peppolID = null;
366
- let glnNumber = null;
367
- let taxNumber = null;
368
- let vatNumber = null;
369
- if (!Array.isArray(taxIds)) {
370
- return { peppolID, glnNumber, taxNumber, vatNumber };
371
- }
372
- for (const entry of taxIds) {
373
- if (!isRecord(entry)) continue;
374
- const type = normalizeIdentifierType(normalizeString(entry.type));
375
- const value = normalizeString(entry.value);
376
- if (!type || !value) continue;
377
- if (!peppolID && type.includes("peppol")) {
378
- peppolID = value;
379
- continue;
380
- }
381
- if (!glnNumber && type.includes("gln")) {
382
- glnNumber = value;
383
- continue;
384
- }
385
- if (!vatNumber && type.includes("vat")) {
386
- vatNumber = value;
387
- continue;
388
- }
389
- if (!taxNumber && type.includes("tax")) {
390
- taxNumber = value;
391
- }
392
- }
393
- return { peppolID, glnNumber, taxNumber, vatNumber };
338
+ /**
339
+ * Parse a Peppol participant identifier into a {@link UblEndpoint}.
340
+ *
341
+ * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns
342
+ * `null` for values without an explicit scheme, since `cbc:EndpointID` requires
343
+ * a `schemeID` and guessing one would mis-route the document.
344
+ */
345
+ const parsePeppolEndpoint = (peppolId) => {
346
+ const normalized = normalizeString(peppolId);
347
+ if (!normalized) return null;
348
+ const separatorIndex = normalized.indexOf(":");
349
+ if (separatorIndex <= 0) return null;
350
+ const scheme = normalized.slice(0, separatorIndex).trim();
351
+ const value = normalized.slice(separatorIndex + 1).trim();
352
+ if (!scheme || !value) return null;
353
+ return {
354
+ scheme,
355
+ value
356
+ };
394
357
  };
395
- var listPeppolReceiverIdentifierCandidates = (customer, countryCode) => {
396
- const candidates = [];
397
- const add = (id) => {
398
- if (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);
399
- };
400
- const peppol = normalizeString(customer.peppolID);
401
- if (peppol) candidates.push(peppol);
402
- const gln = normalizeString(customer.glnNumber);
403
- if (gln) add({ scheme: "0088", value: cleanIdentifierValue(gln) });
404
- const vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });
405
- add(vat);
406
- if (vat?.scheme === "9925") {
407
- add(buildCompanyId({ countryCode: "BE", companyNumber: customer.vatNumber ?? null }));
408
- }
409
- const tax = normalizeString(customer.taxNumber);
410
- if (tax) add(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));
411
- return Array.from(new Set(candidates));
358
+ const normalizeIdentifierType = (value) => value?.toLowerCase().replace(/[^a-z0-9]+/g, "_") ?? null;
359
+ /**
360
+ * Pick the first usable Peppol identifier, GLN, VAT number, and tax number
361
+ * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).
362
+ *
363
+ * Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.
364
+ * Peppol IDs are typically stored as a custom `peppol_id` type.
365
+ */
366
+ const extractCustomerTaxIdentifiers = (taxIds) => {
367
+ let peppolID = null;
368
+ let glnNumber = null;
369
+ let taxNumber = null;
370
+ let vatNumber = null;
371
+ if (!Array.isArray(taxIds)) return {
372
+ peppolID,
373
+ glnNumber,
374
+ taxNumber,
375
+ vatNumber
376
+ };
377
+ for (const entry of taxIds) {
378
+ if (!isRecord(entry)) continue;
379
+ const type = normalizeIdentifierType(normalizeString(entry.type));
380
+ const value = normalizeString(entry.value);
381
+ if (!type || !value) continue;
382
+ if (!peppolID && type.includes("peppol")) {
383
+ peppolID = value;
384
+ continue;
385
+ }
386
+ if (!glnNumber && type.includes("gln")) {
387
+ glnNumber = value;
388
+ continue;
389
+ }
390
+ if (!vatNumber && type.includes("vat")) {
391
+ vatNumber = value;
392
+ continue;
393
+ }
394
+ if (!taxNumber && type.includes("tax")) taxNumber = value;
395
+ }
396
+ return {
397
+ peppolID,
398
+ glnNumber,
399
+ taxNumber,
400
+ vatNumber
401
+ };
412
402
  };
413
-
414
- // src/build/party.ts
415
- var buildSupplierParty = (supplier) => {
416
- const address = normalizeAddress(supplier.address, supplier.countryCode);
417
- return {
418
- endpoint: parsePeppolEndpoint(supplier.peppolID),
419
- name: supplier.name,
420
- address,
421
- vatNumber: normalizeString(supplier.vatNumber),
422
- legalName: supplier.name,
423
- companyId: buildCompanyId({
424
- countryCode: supplier.countryCode,
425
- companyNumber: supplier.companyNumber ?? null
426
- })
427
- };
403
+ /**
404
+ * Build the fully-qualified Peppol participant identifiers (`scheme:value`) a
405
+ * receiver lookup will accept, in priority order, de-duplicated.
406
+ *
407
+ * Stripe stores a customer's VAT number without a Peppol scheme (e.g.
408
+ * `BE0206582284`), but a participant lookup needs the qualified identifier
409
+ * (`9925:BE0206582284`). This attaches the right scheme:
410
+ *
411
+ * 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;
412
+ * 2. a GLN under EAS `0088`;
413
+ * 3. the VAT number under its country's VAT EAS scheme (see
414
+ * {@link resolveVatEndpoint});
415
+ * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)
416
+ * under EAS `0208` — many Belgian entities register only under that;
417
+ * 5. a generic tax/registration number under its country's company-ID scheme.
418
+ *
419
+ * `countryCode` (the customer's country, when known) disambiguates schemes for
420
+ * identifiers that don't carry a country prefix (GLN, plain tax numbers).
421
+ */
422
+ const listPeppolReceiverIdentifierCandidates = (customer, countryCode) => {
423
+ const candidates = [];
424
+ const add = (id) => {
425
+ if (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);
426
+ };
427
+ const peppol = normalizeString(customer.peppolID);
428
+ if (peppol) candidates.push(peppol);
429
+ const gln = normalizeString(customer.glnNumber);
430
+ if (gln) add({
431
+ scheme: "0088",
432
+ value: cleanIdentifierValue(gln)
433
+ });
434
+ const vat = resolveVatEndpoint({
435
+ vatNumber: customer.vatNumber,
436
+ countryCode
437
+ });
438
+ add(vat);
439
+ if (vat?.scheme === "9925") add(buildCompanyId({
440
+ countryCode: "BE",
441
+ companyNumber: customer.vatNumber ?? null
442
+ }));
443
+ const tax = normalizeString(customer.taxNumber);
444
+ if (tax) add(buildCompanyId({
445
+ countryCode: countryCode ?? null,
446
+ companyNumber: tax
447
+ }));
448
+ return Array.from(new Set(candidates));
428
449
  };
429
- var buildCustomerParty = (customer, endpointOverride) => {
430
- const countryCode = normalizeString(customer.countryCode) ?? customer.address.countryCode;
431
- const endpoint = endpointOverride ?? parsePeppolEndpoint(customer.peppolID) ?? (customer.glnNumber ? { scheme: "0088", value: customer.glnNumber } : null) ?? resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });
432
- return {
433
- endpoint,
434
- name: customer.name,
435
- address: customer.address,
436
- vatNumber: normalizeString(customer.vatNumber),
437
- legalName: customer.name,
438
- companyId: buildCompanyId({
439
- countryCode,
440
- companyNumber: customer.taxNumber ?? null
441
- })
442
- };
450
+ //#endregion
451
+ //#region src/build/party.ts
452
+ /** Convert a {@link UblSupplier} into the supplier (seller) party. */
453
+ const buildSupplierParty = (supplier) => {
454
+ const address = normalizeAddress(supplier.address, supplier.countryCode);
455
+ return {
456
+ endpoint: parsePeppolEndpoint(supplier.peppolID),
457
+ name: supplier.name,
458
+ address,
459
+ vatNumber: normalizeString(supplier.vatNumber),
460
+ legalName: supplier.name,
461
+ companyId: buildCompanyId({
462
+ countryCode: supplier.countryCode,
463
+ companyNumber: supplier.companyNumber ?? null
464
+ })
465
+ };
443
466
  };
444
-
445
- // src/build/attachment.ts
446
- var buildPdfAttachment = (params) => ({
447
- id: params.id ?? params.filename,
448
- filename: params.filename,
449
- mimeCode: "application/pdf",
450
- base64: Buffer.from(params.bytes).toString("base64")
467
+ /**
468
+ * Convert a {@link UblCustomer} into the customer (buyer) party.
469
+ *
470
+ * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in
471
+ * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered
472
+ * identifier), then an explicit Peppol ID, then a GLN (scheme `0088`), then the
473
+ * VAT number mapped to its country's VAT EAS scheme (e.g. BE → `9925`). That
474
+ * last step matters because most data stores hold a customer's VAT without a
475
+ * scheme, so without it a VAT-only customer would have no endpoint and the
476
+ * document would be unroutable.
477
+ */
478
+ const buildCustomerParty = (customer, endpointOverride) => {
479
+ const countryCode = normalizeString(customer.countryCode) ?? customer.address.countryCode;
480
+ return {
481
+ endpoint: endpointOverride ?? parsePeppolEndpoint(customer.peppolID) ?? (customer.glnNumber ? {
482
+ scheme: "0088",
483
+ value: customer.glnNumber
484
+ } : null) ?? resolveVatEndpoint({
485
+ vatNumber: customer.vatNumber,
486
+ countryCode
487
+ }),
488
+ name: customer.name,
489
+ address: customer.address,
490
+ vatNumber: normalizeString(customer.vatNumber),
491
+ legalName: customer.name,
492
+ companyId: buildCompanyId({
493
+ countryCode,
494
+ companyNumber: customer.taxNumber ?? null
495
+ })
496
+ };
497
+ };
498
+ //#endregion
499
+ //#region src/build/attachment.ts
500
+ /**
501
+ * Build a UBL embedded-document attachment (BG-24) from raw bytes — e.g. the
502
+ * rendered PDF of the invoice. Emitted as a `cac:AdditionalDocumentReference`
503
+ * with an inline base64 `cbc:EmbeddedDocumentBinaryObject`.
504
+ */
505
+ const buildPdfAttachment = (params) => ({
506
+ id: params.id ?? params.filename,
507
+ filename: params.filename,
508
+ mimeCode: "application/pdf",
509
+ base64: Buffer.from(params.bytes).toString("base64")
451
510
  });
452
- var sanitizeUblDocumentForAudit = (doc) => {
453
- if (doc.attachments.length === 0) return doc;
454
- return {
455
- ...doc,
456
- attachments: doc.attachments.map((attachment) => ({
457
- ...attachment,
458
- base64: `[omitted ${attachment.base64.length} chars]`
459
- }))
460
- };
511
+ /**
512
+ * Replace each attachment's base64 payload with `[omitted]` plus a length, so a
513
+ * {@link UblDocument} is safe to log or persist for audit.
514
+ */
515
+ const sanitizeUblDocumentForAudit = (doc) => {
516
+ if (doc.attachments.length === 0) return doc;
517
+ return {
518
+ ...doc,
519
+ attachments: doc.attachments.map((attachment) => ({
520
+ ...attachment,
521
+ base64: `[omitted ${attachment.base64.length} chars]`
522
+ }))
523
+ };
461
524
  };
462
-
463
- // src/build/numeric.ts
464
- var roundCurrency = (value) => Math.round((value + Number.EPSILON) * 100) / 100;
465
- var centsToDecimal = (cents) => roundCurrency(cents / 100);
466
-
467
- // src/build/tax-category.ts
468
- var EXEMPT_TAXABILITY_REASONS = /* @__PURE__ */ new Set([
469
- "customer_exempt",
470
- "product_exempt",
471
- "not_subject_to_tax",
472
- "not_collecting",
473
- "not_supported",
474
- "portion_product_exempt"
525
+ //#endregion
526
+ //#region src/build/numeric.ts
527
+ /** Round a number to 2 decimal places (cents). */
528
+ const roundCurrency = (value) => Math.round((value + Number.EPSILON) * 100) / 100;
529
+ /** Convert an integer cent amount into a 2-decimal currency value. */
530
+ const centsToDecimal = (cents) => roundCurrency(cents / 100);
531
+ //#endregion
532
+ //#region src/build/tax-category.ts
533
+ /**
534
+ * Stripe Tax `taxability_reason` values that map to a VAT-exempt UBL category
535
+ * (`E`). Reverse charge is handled separately (category `AE`).
536
+ */
537
+ const EXEMPT_TAXABILITY_REASONS = /* @__PURE__ */ new Set([
538
+ "customer_exempt",
539
+ "product_exempt",
540
+ "not_subject_to_tax",
541
+ "not_collecting",
542
+ "not_supported",
543
+ "portion_product_exempt"
475
544
  ]);
476
- var EXEMPTION_REASON_TEXT = {
477
- reverse_charge: "Reverse charge",
478
- customer_exempt: "Exempt based on customer status",
479
- product_exempt: "Exempt based on the supplied goods or services",
480
- portion_product_exempt: "Exempt based on the supplied goods or services",
481
- not_subject_to_tax: "Not subject to VAT",
482
- not_collecting: "VAT not collected",
483
- not_supported: "VAT not applicable"
545
+ /** Human-readable EN 16931 exemption reasons (BR-E-10 / BR-AE-10 / …). */
546
+ const EXEMPTION_REASON_TEXT = {
547
+ reverse_charge: "Reverse charge",
548
+ intra_community: "Intra-community supply",
549
+ export: "Export outside the EU",
550
+ customer_exempt: "Exempt based on customer status",
551
+ product_exempt: "Exempt based on the supplied goods or services",
552
+ portion_product_exempt: "Exempt based on the supplied goods or services",
553
+ not_subject_to_tax: "Not subject to VAT",
554
+ not_collecting: "VAT not collected",
555
+ not_supported: "VAT not applicable"
484
556
  };
485
- var normalizeTaxCategoryId = (value) => {
486
- if (typeof value !== "string") return null;
487
- const normalized = value.trim().toUpperCase();
488
- return normalized.length > 0 ? normalized : null;
557
+ const normalizeTaxCategoryId = (value) => {
558
+ if (typeof value !== "string") return null;
559
+ const normalized = value.trim().toUpperCase();
560
+ return normalized.length > 0 ? normalized : null;
489
561
  };
490
- var taxCategoryFromReasonOrRate = (params) => {
491
- const categoryHint = normalizeTaxCategoryId(params.taxCategoryId);
492
- const reason = params.taxabilityReason;
493
- if (categoryHint === "AE" || reason === "reverse_charge") {
494
- return {
495
- id: "AE",
496
- percent: 0,
497
- exemptionReason: EXEMPTION_REASON_TEXT.reverse_charge
498
- };
499
- }
500
- if (categoryHint === "E" || reason && EXEMPT_TAXABILITY_REASONS.has(reason)) {
501
- return {
502
- id: "E",
503
- percent: 0,
504
- exemptionReason: (reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? "Exempt from VAT"
505
- };
506
- }
507
- if (categoryHint === "Z" || reason === "zero_rated" || params.rate <= 0) {
508
- return { id: "Z", percent: 0 };
509
- }
510
- return { id: "S", percent: params.rate };
562
+ /**
563
+ * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a
564
+ * numeric rate into a {@link UblTaxCategory}.
565
+ *
566
+ * - Reverse charge → `AE` (0%, with exemption reason)
567
+ * - Intra-community supply → `K` (0%, with exemption reason)
568
+ * - Export outside the EU → `G` (0%, with exemption reason)
569
+ * - Any other exempt reason → `E` (0%, with exemption reason)
570
+ * - Category `Z` / rate ≤ 0 → `Z` (zero-rated, 0%)
571
+ * - Otherwise → `S` (standard, the line's rate)
572
+ */
573
+ const taxCategoryFromReasonOrRate = (params) => {
574
+ const categoryHint = normalizeTaxCategoryId(params.taxCategoryId);
575
+ const reason = params.taxabilityReason;
576
+ if (categoryHint === "AE" || reason === "reverse_charge") return {
577
+ id: "AE",
578
+ percent: 0,
579
+ exemptionReason: EXEMPTION_REASON_TEXT.reverse_charge
580
+ };
581
+ if (categoryHint === "K" || reason === "intra_community") return {
582
+ id: "K",
583
+ percent: 0,
584
+ exemptionReason: EXEMPTION_REASON_TEXT.intra_community
585
+ };
586
+ if (categoryHint === "G" || reason === "export") return {
587
+ id: "G",
588
+ percent: 0,
589
+ exemptionReason: EXEMPTION_REASON_TEXT.export
590
+ };
591
+ if (categoryHint === "E" || reason && EXEMPT_TAXABILITY_REASONS.has(reason)) return {
592
+ id: "E",
593
+ percent: 0,
594
+ exemptionReason: (reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? "Exempt from VAT"
595
+ };
596
+ if (categoryHint === "Z" || reason === "zero_rated" || params.rate <= 0) return {
597
+ id: "Z",
598
+ percent: 0
599
+ };
600
+ return {
601
+ id: "S",
602
+ percent: params.rate
603
+ };
511
604
  };
512
- var resolveTaxCategoryFromTaxAmounts = (taxAmounts, rate) => {
513
- for (const ta of taxAmounts) {
514
- if (!ta.taxability_reason) continue;
515
- if (ta.taxability_reason === "reverse_charge") {
516
- return taxCategoryFromReasonOrRate({
517
- taxabilityReason: "reverse_charge",
518
- rate
519
- });
520
- }
521
- if (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) {
522
- return taxCategoryFromReasonOrRate({
523
- taxabilityReason: ta.taxability_reason,
524
- rate
525
- });
526
- }
527
- if (ta.taxability_reason === "zero_rated") {
528
- return taxCategoryFromReasonOrRate({
529
- taxabilityReason: "zero_rated",
530
- rate
531
- });
532
- }
533
- }
534
- return taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });
605
+ /**
606
+ * Resolve a {@link UblTaxCategory} from a line's Stripe tax info.
607
+ *
608
+ * Exempt / reverse-charge / zero-rated reasons take precedence over the rate;
609
+ * otherwise the rate decides standard (`S`) vs zero-rated (`Z`).
610
+ */
611
+ const resolveTaxCategoryFromTaxAmounts = (taxAmounts, rate) => {
612
+ for (const ta of taxAmounts) {
613
+ if (!ta.taxability_reason) continue;
614
+ if (ta.taxability_reason === "reverse_charge") return taxCategoryFromReasonOrRate({
615
+ taxabilityReason: "reverse_charge",
616
+ rate
617
+ });
618
+ if (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) return taxCategoryFromReasonOrRate({
619
+ taxabilityReason: ta.taxability_reason,
620
+ rate
621
+ });
622
+ if (ta.taxability_reason === "zero_rated") return taxCategoryFromReasonOrRate({
623
+ taxabilityReason: "zero_rated",
624
+ rate
625
+ });
626
+ }
627
+ return taxCategoryFromReasonOrRate({
628
+ taxabilityReason: null,
629
+ rate
630
+ });
535
631
  };
536
-
537
- // src/build/tax-totals.ts
538
- var reconcileLinesToExclTotal = (lines, authoritativeTotalExclVat) => {
539
- if (lines.length === 0) return lines;
540
- const computed = roundCurrency(
541
- lines.reduce((sum, line2) => sum + line2.lineExtensionAmount, 0)
542
- );
543
- const diff = roundCurrency(authoritativeTotalExclVat - computed);
544
- if (diff === 0) return lines;
545
- const largestIdx = lines.reduce(
546
- (maxIdx, line2, idx, arr) => line2.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0) ? idx : maxIdx,
547
- 0
548
- );
549
- return lines.map((line2, idx) => {
550
- if (idx !== largestIdx) return line2;
551
- const adjusted = roundCurrency(line2.lineExtensionAmount + diff);
552
- return {
553
- ...line2,
554
- lineExtensionAmount: adjusted,
555
- priceAmount: roundCurrency(adjusted / Math.max(line2.quantity, 1))
556
- };
557
- });
558
- };
559
- var categoryKey = (category) => `${category.id}:${category.percent}`;
560
- var buildTaxTotals = (lines) => {
561
- const groups = /* @__PURE__ */ new Map();
562
- for (const line2 of lines) {
563
- const key = categoryKey(line2.taxCategory);
564
- const current = groups.get(key) ?? {
565
- category: line2.taxCategory,
566
- taxableAmount: 0
567
- };
568
- current.taxableAmount = roundCurrency(
569
- current.taxableAmount + line2.lineExtensionAmount
570
- );
571
- groups.set(key, current);
572
- }
573
- const subtotals = Array.from(groups.values()).map((group) => ({
574
- taxableAmount: group.taxableAmount,
575
- taxAmount: roundCurrency(group.taxableAmount * group.category.percent / 100),
576
- category: group.category
577
- }));
578
- const lineExtensionAmount = roundCurrency(
579
- lines.reduce((sum, line2) => sum + line2.lineExtensionAmount, 0)
580
- );
581
- const taxAmount = roundCurrency(
582
- subtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0)
583
- );
584
- const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
585
- return {
586
- taxTotal: { taxAmount, subtotals },
587
- monetaryTotal: {
588
- lineExtensionAmount,
589
- taxExclusiveAmount: lineExtensionAmount,
590
- taxInclusiveAmount,
591
- payableAmount: taxInclusiveAmount
592
- }
593
- };
632
+ //#endregion
633
+ //#region src/build/tax-totals.ts
634
+ /**
635
+ * Adjust the largest line's net amount so the line nets sum to the
636
+ * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).
637
+ *
638
+ * Reconciling at the *line* level — rather than directly on the VAT breakdown —
639
+ * keeps the document consistent bottom-up: the VAT category taxable amounts
640
+ * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the
641
+ * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level
642
+ * coupon; larger ones indicate a real upstream data problem.
643
+ */
644
+ const reconcileLinesToExclTotal = (lines, authoritativeTotalExclVat) => {
645
+ if (lines.length === 0) return lines;
646
+ const diff = roundCurrency(authoritativeTotalExclVat - roundCurrency(lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0)));
647
+ if (diff === 0) return lines;
648
+ const largestIdx = lines.reduce((maxIdx, line, idx, arr) => line.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0) ? idx : maxIdx, 0);
649
+ return lines.map((line, idx) => {
650
+ if (idx !== largestIdx) return line;
651
+ const adjusted = roundCurrency(line.lineExtensionAmount + diff);
652
+ return {
653
+ ...line,
654
+ lineExtensionAmount: adjusted,
655
+ priceAmount: roundCurrency(adjusted / Math.max(line.quantity, 1))
656
+ };
657
+ });
594
658
  };
595
- export {
596
- COUNTRY_CODE_LIST_ID,
597
- CREDIT_NOTE_TYPE_CODE,
598
- DEFAULT_UNIT_CODE,
599
- EXEMPT_TAXABILITY_REASONS,
600
- INVOICE_TYPE_CODE,
601
- NS_CAC,
602
- NS_CBC,
603
- NS_CREDIT_NOTE,
604
- NS_INVOICE,
605
- UBL_CUSTOMIZATION_ID,
606
- UBL_PROFILE_ID,
607
- VAT_TAX_SCHEME_ID,
608
- buildCompanyId,
609
- buildCustomerParty,
610
- buildPdfAttachment,
611
- buildSupplierParty,
612
- buildTaxTotals,
613
- centsToDecimal,
614
- el,
615
- extractCustomerTaxIdentifiers,
616
- listPeppolReceiverIdentifierCandidates,
617
- normalizeAddress,
618
- normalizeCompanyNumberForCountry,
619
- parsePeppolEndpoint,
620
- reconcileLinesToExclTotal,
621
- resolveCompanyIdScheme,
622
- resolveTaxCategoryFromTaxAmounts,
623
- resolveVatEndpoint,
624
- roundCurrency,
625
- sanitizeUblDocumentForAudit,
626
- serializeDocument,
627
- serializeUblDocument,
628
- taxCategoryFromReasonOrRate
659
+ const categoryKey = (category) => `${category.id}:${category.percent}`;
660
+ /**
661
+ * Group lines by `(category, percent)` into a VAT breakdown and compute the
662
+ * document monetary totals.
663
+ *
664
+ * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,
665
+ * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the
666
+ * upstream per-line tax cents. This guarantees the breakdown is internally
667
+ * consistent and passes validation; it can differ by a cent from the figure a
668
+ * payment processor reported, which is an unavoidable artifact of representing
669
+ * a cents-rounded system as a rate-based VAT breakdown.
670
+ *
671
+ * `payableAmount` is derived per BR-CO-16 (`BT-112 − BT-113 + BT-114`) so the
672
+ * invariant holds by construction. The result is *not* clamped: a prepayment
673
+ * exceeding the total yields a negative payable amount, surfacing the upstream
674
+ * overpayment rather than hiding it.
675
+ */
676
+ const buildTaxTotals = (lines, options) => {
677
+ const groups = /* @__PURE__ */ new Map();
678
+ for (const line of lines) {
679
+ const key = categoryKey(line.taxCategory);
680
+ const current = groups.get(key) ?? {
681
+ category: line.taxCategory,
682
+ taxableAmount: 0
683
+ };
684
+ current.taxableAmount = roundCurrency(current.taxableAmount + line.lineExtensionAmount);
685
+ groups.set(key, current);
686
+ }
687
+ const subtotals = Array.from(groups.values()).map((group) => ({
688
+ taxableAmount: group.taxableAmount,
689
+ taxAmount: roundCurrency(group.taxableAmount * group.category.percent / 100),
690
+ category: group.category
691
+ }));
692
+ const lineExtensionAmount = roundCurrency(lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0));
693
+ const taxAmount = roundCurrency(subtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0));
694
+ const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
695
+ const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
696
+ const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
697
+ const payableAmount = roundCurrency(taxInclusiveAmount - prepaidAmount + payableRoundingAmount);
698
+ return {
699
+ taxTotal: {
700
+ taxAmount,
701
+ subtotals
702
+ },
703
+ monetaryTotal: {
704
+ lineExtensionAmount,
705
+ taxExclusiveAmount: lineExtensionAmount,
706
+ taxInclusiveAmount,
707
+ ...prepaidAmount ? { prepaidAmount } : {},
708
+ ...payableRoundingAmount ? { payableRoundingAmount } : {},
709
+ payableAmount
710
+ }
711
+ };
629
712
  };
713
+ //#endregion
714
+ 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 };
715
+
630
716
  //# sourceMappingURL=index.js.map