@financica/ubl 0.7.0 → 0.9.0

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