@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.
- package/dist/build/index.d.ts +183 -169
- package/dist/build/index.d.ts.map +1 -0
- package/dist/build/index.js +660 -595
- package/dist/build/index.js.map +1 -1
- package/dist/index.d.ts +224 -191
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +754 -732
- package/dist/index.js.map +1 -1
- package/package.json +26 -40
package/dist/build/index.js
CHANGED
|
@@ -1,630 +1,695 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
42
|
+
const escapeText = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
43
|
+
const escapeAttr = (value) => escapeText(value).replace(/"/g, """);
|
|
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
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
|
|
47
|
-
${serializeElement(root, 0)}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
)
|
|
158
|
-
]),
|
|
159
|
-
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
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
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
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
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
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
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
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
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
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
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
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
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
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
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
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
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
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
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
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
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
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
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
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
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
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
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
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
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
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
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
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
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
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
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
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
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
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
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
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
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
|