@financica/ubl 0.3.2 → 0.5.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.
@@ -0,0 +1,510 @@
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 };
24
+ };
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("");
30
+ };
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}>`;
45
+ };
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);
55
+ };
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()
63
+ ]);
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
77
+ ]);
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
+ ])
98
+ ]);
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)
103
+ ]);
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
+ ]);
117
+ };
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);
189
+ };
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;
197
+ };
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;
204
+ };
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
+ };
216
+ };
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/, "");
223
+ };
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();
229
+ };
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;
244
+ };
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
+ };
257
+ };
258
+ var parsePeppolEndpoint = (peppolId) => {
259
+ const normalized = normalizeString(peppolId);
260
+ if (!normalized) return null;
261
+ const separatorIndex = normalized.indexOf(":");
262
+ if (separatorIndex <= 0) return null;
263
+ const scheme = normalized.slice(0, separatorIndex).trim();
264
+ const value = normalized.slice(separatorIndex + 1).trim();
265
+ if (!scheme || !value) return null;
266
+ return { scheme, value };
267
+ };
268
+ var normalizeIdentifierType = (value) => value?.toLowerCase().replace(/[^a-z0-9]+/g, "_") ?? null;
269
+ var extractCustomerTaxIdentifiers = (taxIds) => {
270
+ let peppolID = null;
271
+ let glnNumber = null;
272
+ let taxNumber = null;
273
+ let vatNumber = null;
274
+ if (!Array.isArray(taxIds)) {
275
+ return { peppolID, glnNumber, taxNumber, vatNumber };
276
+ }
277
+ for (const entry of taxIds) {
278
+ if (!isRecord(entry)) continue;
279
+ const type = normalizeIdentifierType(normalizeString(entry.type));
280
+ const value = normalizeString(entry.value);
281
+ if (!type || !value) continue;
282
+ if (!peppolID && type.includes("peppol")) {
283
+ peppolID = value;
284
+ continue;
285
+ }
286
+ if (!glnNumber && type.includes("gln")) {
287
+ glnNumber = value;
288
+ continue;
289
+ }
290
+ if (!vatNumber && type.includes("vat")) {
291
+ vatNumber = value;
292
+ continue;
293
+ }
294
+ if (!taxNumber && type.includes("tax")) {
295
+ taxNumber = value;
296
+ }
297
+ }
298
+ return { peppolID, glnNumber, taxNumber, vatNumber };
299
+ };
300
+ var listPeppolReceiverIdentifierCandidates = (customer) => Array.from(
301
+ new Set(
302
+ [
303
+ normalizeString(customer.peppolID),
304
+ normalizeString(customer.glnNumber),
305
+ normalizeString(customer.taxNumber),
306
+ normalizeString(customer.vatNumber)
307
+ ].filter((value) => !!value)
308
+ )
309
+ );
310
+
311
+ // src/build/party.ts
312
+ var buildSupplierParty = (supplier) => {
313
+ const address = normalizeAddress(supplier.address, supplier.countryCode);
314
+ return {
315
+ endpoint: parsePeppolEndpoint(supplier.peppolID),
316
+ name: supplier.name,
317
+ address,
318
+ vatNumber: normalizeString(supplier.vatNumber),
319
+ legalName: supplier.name,
320
+ companyId: buildCompanyId({
321
+ countryCode: supplier.countryCode,
322
+ companyNumber: supplier.companyNumber ?? null
323
+ })
324
+ };
325
+ };
326
+
327
+ // src/build/attachment.ts
328
+ var buildPdfAttachment = (params) => ({
329
+ id: params.id ?? params.filename,
330
+ filename: params.filename,
331
+ mimeCode: "application/pdf",
332
+ base64: Buffer.from(params.bytes).toString("base64")
333
+ });
334
+ var sanitizeUblDocumentForAudit = (doc) => {
335
+ if (doc.attachments.length === 0) return doc;
336
+ return {
337
+ ...doc,
338
+ attachments: doc.attachments.map((attachment) => ({
339
+ ...attachment,
340
+ base64: `[omitted ${attachment.base64.length} chars]`
341
+ }))
342
+ };
343
+ };
344
+
345
+ // src/build/numeric.ts
346
+ var roundCurrency = (value) => Math.round((value + Number.EPSILON) * 100) / 100;
347
+ var centsToDecimal = (cents) => roundCurrency(cents / 100);
348
+
349
+ // src/build/tax-category.ts
350
+ var EXEMPT_TAXABILITY_REASONS = /* @__PURE__ */ new Set([
351
+ "customer_exempt",
352
+ "product_exempt",
353
+ "not_subject_to_tax",
354
+ "not_collecting",
355
+ "not_supported",
356
+ "portion_product_exempt"
357
+ ]);
358
+ var EXEMPTION_REASON_TEXT = {
359
+ reverse_charge: "Reverse charge",
360
+ customer_exempt: "Exempt based on customer status",
361
+ product_exempt: "Exempt based on the supplied goods or services",
362
+ portion_product_exempt: "Exempt based on the supplied goods or services",
363
+ not_subject_to_tax: "Not subject to VAT",
364
+ not_collecting: "VAT not collected",
365
+ not_supported: "VAT not applicable"
366
+ };
367
+ var normalizeTaxCategoryId = (value) => {
368
+ if (typeof value !== "string") return null;
369
+ const normalized = value.trim().toUpperCase();
370
+ return normalized.length > 0 ? normalized : null;
371
+ };
372
+ var taxCategoryFromReasonOrRate = (params) => {
373
+ const categoryHint = normalizeTaxCategoryId(params.taxCategoryId);
374
+ const reason = params.taxabilityReason;
375
+ if (categoryHint === "AE" || reason === "reverse_charge") {
376
+ return {
377
+ id: "AE",
378
+ percent: 0,
379
+ exemptionReason: EXEMPTION_REASON_TEXT.reverse_charge
380
+ };
381
+ }
382
+ if (categoryHint === "E" || reason && EXEMPT_TAXABILITY_REASONS.has(reason)) {
383
+ return {
384
+ id: "E",
385
+ percent: 0,
386
+ exemptionReason: (reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? "Exempt from VAT"
387
+ };
388
+ }
389
+ if (categoryHint === "Z" || reason === "zero_rated" || params.rate <= 0) {
390
+ return { id: "Z", percent: 0 };
391
+ }
392
+ return { id: "S", percent: params.rate };
393
+ };
394
+ var resolveTaxCategoryFromTaxAmounts = (taxAmounts, rate) => {
395
+ for (const ta of taxAmounts) {
396
+ if (!ta.taxability_reason) continue;
397
+ if (ta.taxability_reason === "reverse_charge") {
398
+ return taxCategoryFromReasonOrRate({
399
+ taxabilityReason: "reverse_charge",
400
+ rate
401
+ });
402
+ }
403
+ if (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) {
404
+ return taxCategoryFromReasonOrRate({
405
+ taxabilityReason: ta.taxability_reason,
406
+ rate
407
+ });
408
+ }
409
+ if (ta.taxability_reason === "zero_rated") {
410
+ return taxCategoryFromReasonOrRate({
411
+ taxabilityReason: "zero_rated",
412
+ rate
413
+ });
414
+ }
415
+ }
416
+ return taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });
417
+ };
418
+
419
+ // src/build/tax-totals.ts
420
+ var reconcileLinesToExclTotal = (lines, authoritativeTotalExclVat) => {
421
+ if (lines.length === 0) return lines;
422
+ const computed = roundCurrency(
423
+ lines.reduce((sum, line2) => sum + line2.lineExtensionAmount, 0)
424
+ );
425
+ const diff = roundCurrency(authoritativeTotalExclVat - computed);
426
+ if (diff === 0) return lines;
427
+ const largestIdx = lines.reduce(
428
+ (maxIdx, line2, idx, arr) => line2.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0) ? idx : maxIdx,
429
+ 0
430
+ );
431
+ return lines.map((line2, idx) => {
432
+ if (idx !== largestIdx) return line2;
433
+ const adjusted = roundCurrency(line2.lineExtensionAmount + diff);
434
+ return {
435
+ ...line2,
436
+ lineExtensionAmount: adjusted,
437
+ priceAmount: roundCurrency(adjusted / Math.max(line2.quantity, 1))
438
+ };
439
+ });
440
+ };
441
+ var categoryKey = (category) => `${category.id}:${category.percent}`;
442
+ var buildTaxTotals = (lines) => {
443
+ const groups = /* @__PURE__ */ new Map();
444
+ for (const line2 of lines) {
445
+ const key = categoryKey(line2.taxCategory);
446
+ const current = groups.get(key) ?? {
447
+ category: line2.taxCategory,
448
+ taxableAmount: 0
449
+ };
450
+ current.taxableAmount = roundCurrency(
451
+ current.taxableAmount + line2.lineExtensionAmount
452
+ );
453
+ groups.set(key, current);
454
+ }
455
+ const subtotals = Array.from(groups.values()).map((group) => ({
456
+ taxableAmount: group.taxableAmount,
457
+ taxAmount: roundCurrency(group.taxableAmount * group.category.percent / 100),
458
+ category: group.category
459
+ }));
460
+ const lineExtensionAmount = roundCurrency(
461
+ lines.reduce((sum, line2) => sum + line2.lineExtensionAmount, 0)
462
+ );
463
+ const taxAmount = roundCurrency(
464
+ subtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0)
465
+ );
466
+ const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
467
+ return {
468
+ taxTotal: { taxAmount, subtotals },
469
+ monetaryTotal: {
470
+ lineExtensionAmount,
471
+ taxExclusiveAmount: lineExtensionAmount,
472
+ taxInclusiveAmount,
473
+ payableAmount: taxInclusiveAmount
474
+ }
475
+ };
476
+ };
477
+ export {
478
+ COUNTRY_CODE_LIST_ID,
479
+ CREDIT_NOTE_TYPE_CODE,
480
+ DEFAULT_UNIT_CODE,
481
+ EXEMPT_TAXABILITY_REASONS,
482
+ INVOICE_TYPE_CODE,
483
+ NS_CAC,
484
+ NS_CBC,
485
+ NS_CREDIT_NOTE,
486
+ NS_INVOICE,
487
+ UBL_CUSTOMIZATION_ID,
488
+ UBL_PROFILE_ID,
489
+ VAT_TAX_SCHEME_ID,
490
+ buildCompanyId,
491
+ buildPdfAttachment,
492
+ buildSupplierParty,
493
+ buildTaxTotals,
494
+ centsToDecimal,
495
+ el,
496
+ extractCustomerTaxIdentifiers,
497
+ listPeppolReceiverIdentifierCandidates,
498
+ normalizeAddress,
499
+ normalizeCompanyNumberForCountry,
500
+ parsePeppolEndpoint,
501
+ reconcileLinesToExclTotal,
502
+ resolveCompanyIdScheme,
503
+ resolveTaxCategoryFromTaxAmounts,
504
+ roundCurrency,
505
+ sanitizeUblDocumentForAudit,
506
+ serializeDocument,
507
+ serializeUblDocument,
508
+ taxCategoryFromReasonOrRate
509
+ };
510
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/build/ubl/constants.ts","../../src/build/xml.ts","../../src/build/ubl/serialize.ts","../../src/build/utils.ts","../../src/build/address.ts","../../src/build/identifiers.ts","../../src/build/party.ts","../../src/build/attachment.ts","../../src/build/numeric.ts","../../src/build/tax-category.ts","../../src/build/tax-totals.ts"],"sourcesContent":["/** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */\n\n/** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */\nexport const UBL_CUSTOMIZATION_ID =\n\t\"urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0\";\n\n/** Peppol BIS Billing 3.0 process (BT-23). */\nexport const UBL_PROFILE_ID = \"urn:fdc:peppol.eu:2017:poacc:billing:01:1.0\";\n\n/** UNTDID 1001 — commercial invoice. */\nexport const INVOICE_TYPE_CODE = \"380\";\n/** UNTDID 1001 — credit note. */\nexport const CREDIT_NOTE_TYPE_CODE = \"381\";\n\n/** UN/ECE Recommendation 20 — \"one / piece\" (the default line unit). */\nexport const DEFAULT_UNIT_CODE = \"C62\";\n\n/** UNCL5153 — the VAT tax scheme identifier. */\nexport const VAT_TAX_SCHEME_ID = \"VAT\";\n\n/** ISO 3166-1 alpha-2 list identifier for `cbc:IdentificationCode`. */\nexport const COUNTRY_CODE_LIST_ID = \"ISO3166-1:Alpha2\";\n\nexport const NS_INVOICE = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nexport const NS_CREDIT_NOTE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\nexport const NS_CAC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\nexport const NS_CBC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\n","/**\n * Minimal, dependency-free XML builder + serializer.\n *\n * UBL is order-sensitive (every element sequence is fixed by the schema), so\n * children are always explicit, ordered arrays. There is no attribute or text\n * coercion magic beyond escaping — the UBL layer is responsible for emitting\n * elements in the right order.\n */\n\nexport type XmlAttrs = Record<string, string | number | null | undefined>;\n\nexport interface XmlElement {\n\tname: string;\n\tattrs?: XmlAttrs;\n\t/** Leaf text content. Mutually exclusive with `children`. */\n\ttext?: string | number | null;\n\t/** Child elements. Mutually exclusive with `text`. */\n\tchildren?: XmlElement[];\n}\n\n/** Falsy children are dropped, so callers can write `cond && el(...)`. */\ntype ChildSpec = XmlElement | null | undefined | false;\n\n/**\n * Build an XML element.\n *\n * el(\"cbc:ID\", null, \"INV-1\") → <cbc:ID>INV-1</cbc:ID>\n * el(\"cbc:Amount\", { currencyID: \"EUR\" }, \"10.00\") → <cbc:Amount currencyID=\"EUR\">10.00</cbc:Amount>\n * el(\"cac:Party\", null, [child, cond && child2]) → nested element\n */\nexport const el = (\n\tname: string,\n\tattrs?: XmlAttrs | null,\n\tcontent?: string | number | null | ChildSpec[],\n): XmlElement => {\n\tif (Array.isArray(content)) {\n\t\treturn {\n\t\t\tname,\n\t\t\tattrs: attrs ?? undefined,\n\t\t\tchildren: content.filter((c): c is XmlElement => Boolean(c)),\n\t\t};\n\t}\n\treturn { name, attrs: attrs ?? undefined, text: content ?? undefined };\n};\n\nconst escapeText = (value: string): string =>\n\tvalue.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\nconst escapeAttr = (value: string): string => escapeText(value).replace(/\"/g, \"&quot;\");\n\nconst serializeAttrs = (attrs: XmlAttrs | undefined): string => {\n\tif (!attrs) return \"\";\n\treturn Object.entries(attrs)\n\t\t.filter(([, value]) => value !== null && value !== undefined)\n\t\t.map(([key, value]) => ` ${key}=\"${escapeAttr(String(value))}\"`)\n\t\t.join(\"\");\n};\n\nconst serializeElement = (node: XmlElement, indentLevel: number): string => {\n\tconst pad = \" \".repeat(indentLevel);\n\tconst attrs = serializeAttrs(node.attrs);\n\n\tif (node.text !== undefined && node.text !== null) {\n\t\treturn `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;\n\t}\n\n\tconst children = node.children ?? [];\n\tif (children.length === 0) {\n\t\treturn `${pad}<${node.name}${attrs}/>`;\n\t}\n\n\tconst inner = children\n\t\t.map((child) => serializeElement(child, indentLevel + 1))\n\t\t.join(\"\\n\");\n\treturn `${pad}<${node.name}${attrs}>\\n${inner}\\n${pad}</${node.name}>`;\n};\n\n/** Serialize a root element into a UTF-8 XML document string. */\nexport const serializeDocument = (root: XmlElement): string =>\n\t`<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${serializeElement(root, 0)}\\n`;\n","import { el, serializeDocument, type XmlElement } from \"../xml\";\nimport {\n\tCOUNTRY_CODE_LIST_ID,\n\tCREDIT_NOTE_TYPE_CODE,\n\tINVOICE_TYPE_CODE,\n\tNS_CAC,\n\tNS_CBC,\n\tNS_CREDIT_NOTE,\n\tNS_INVOICE,\n\tUBL_CUSTOMIZATION_ID,\n\tUBL_PROFILE_ID,\n\tVAT_TAX_SCHEME_ID,\n} from \"./constants\";\nimport type {\n\tUblAddress,\n\tUblAttachment,\n\tUblDocument,\n\tUblLine,\n\tUblParty,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n} from \"./types\";\n\n/** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */\nconst amount = (value: number): string => value.toFixed(2);\n\n/** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */\nconst percent = (value: number): string => {\n\tconst rounded = Math.round(value * 100) / 100;\n\treturn Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);\n};\n\nconst money = (name: string, value: number, currency: string): XmlElement =>\n\tel(name, { currencyID: currency }, amount(value));\n\nconst vatTaxScheme = (): XmlElement =>\n\tel(\"cac:TaxScheme\", null, [el(\"cbc:ID\", null, VAT_TAX_SCHEME_ID)]);\n\n/**\n * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)\n * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption\n * reason for the non-charging categories (E/AE/O/K/G).\n */\nconst taxCategory = (name: string, category: UblTaxCategory): XmlElement =>\n\tel(name, null, [\n\t\tel(\"cbc:ID\", null, category.id),\n\t\tel(\"cbc:Percent\", null, percent(category.percent)),\n\t\tcategory.exemptionReason\n\t\t\t? el(\"cbc:TaxExemptionReason\", null, category.exemptionReason)\n\t\t\t: null,\n\t\tvatTaxScheme(),\n\t]);\n\nconst postalAddress = (address: UblAddress): XmlElement =>\n\tel(\"cac:PostalAddress\", null, [\n\t\taddress.street ? el(\"cbc:StreetName\", null, address.street) : null,\n\t\taddress.additionalStreet\n\t\t\t? el(\"cbc:AdditionalStreetName\", null, address.additionalStreet)\n\t\t\t: null,\n\t\taddress.city ? el(\"cbc:CityName\", null, address.city) : null,\n\t\taddress.postalZone ? el(\"cbc:PostalZone\", null, address.postalZone) : null,\n\t\taddress.countrySubentity\n\t\t\t? el(\"cbc:CountrySubentity\", null, address.countrySubentity)\n\t\t\t: null,\n\t\taddress.countryCode\n\t\t\t? el(\"cac:Country\", null, [\n\t\t\t\t\tel(\n\t\t\t\t\t\t\"cbc:IdentificationCode\",\n\t\t\t\t\t\t{ listID: COUNTRY_CODE_LIST_ID },\n\t\t\t\t\t\taddress.countryCode,\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t: null,\n\t]);\n\nconst party = (source: UblParty): XmlElement =>\n\tel(\"cac:Party\", null, [\n\t\tsource.endpoint\n\t\t\t? el(\n\t\t\t\t\t\"cbc:EndpointID\",\n\t\t\t\t\t{ schemeID: source.endpoint.scheme },\n\t\t\t\t\tsource.endpoint.value,\n\t\t\t\t)\n\t\t\t: null,\n\t\tel(\"cac:PartyName\", null, [el(\"cbc:Name\", null, source.name)]),\n\t\tpostalAddress(source.address),\n\t\tsource.vatNumber\n\t\t\t? el(\"cac:PartyTaxScheme\", null, [\n\t\t\t\t\tel(\"cbc:CompanyID\", null, source.vatNumber),\n\t\t\t\t\tvatTaxScheme(),\n\t\t\t\t])\n\t\t\t: null,\n\t\tel(\"cac:PartyLegalEntity\", null, [\n\t\t\tel(\"cbc:RegistrationName\", null, source.legalName ?? source.name),\n\t\t\tsource.companyId\n\t\t\t\t? el(\n\t\t\t\t\t\t\"cbc:CompanyID\",\n\t\t\t\t\t\tsource.companyId.scheme\n\t\t\t\t\t\t\t? { schemeID: source.companyId.scheme }\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\tsource.companyId.value,\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t]),\n\t]);\n\nconst taxSubtotal = (subtotal: UblTaxSubtotal, currency: string): XmlElement =>\n\tel(\"cac:TaxSubtotal\", null, [\n\t\tmoney(\"cbc:TaxableAmount\", subtotal.taxableAmount, currency),\n\t\tmoney(\"cbc:TaxAmount\", subtotal.taxAmount, currency),\n\t\ttaxCategory(\"cac:TaxCategory\", subtotal.category),\n\t]);\n\nconst line = (\n\tsource: UblLine,\n\tcurrency: string,\n\tdocumentType: UblDocument[\"documentType\"],\n): XmlElement => {\n\tconst lineElementName =\n\t\tdocumentType === \"creditNote\" ? \"cac:CreditNoteLine\" : \"cac:InvoiceLine\";\n\tconst quantityElementName =\n\t\tdocumentType === \"creditNote\" ? \"cbc:CreditedQuantity\" : \"cbc:InvoicedQuantity\";\n\n\treturn el(lineElementName, null, [\n\t\tel(\"cbc:ID\", null, source.id),\n\t\tel(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),\n\t\tmoney(\"cbc:LineExtensionAmount\", source.lineExtensionAmount, currency),\n\t\tel(\"cac:Item\", null, [\n\t\t\tel(\"cbc:Name\", null, source.name),\n\t\t\ttaxCategory(\"cac:ClassifiedTaxCategory\", source.taxCategory),\n\t\t]),\n\t\tel(\"cac:Price\", null, [money(\"cbc:PriceAmount\", source.priceAmount, currency)]),\n\t]);\n};\n\nconst attachmentReference = (attachment: UblAttachment): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tel(\"cbc:ID\", null, attachment.id),\n\t\tel(\"cac:Attachment\", null, [\n\t\t\tel(\n\t\t\t\t\"cbc:EmbeddedDocumentBinaryObject\",\n\t\t\t\t{ mimeCode: attachment.mimeCode, filename: attachment.filename },\n\t\t\t\tattachment.base64,\n\t\t\t),\n\t\t]),\n\t]);\n\nconst billingReference = (precedingInvoiceId: string): XmlElement =>\n\tel(\"cac:BillingReference\", null, [\n\t\tel(\"cac:InvoiceDocumentReference\", null, [\n\t\t\tel(\"cbc:ID\", null, precedingInvoiceId),\n\t\t]),\n\t]);\n\n/** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */\nexport const serializeUblDocument = (doc: UblDocument): string => {\n\tconst isCreditNote = doc.documentType === \"creditNote\";\n\tconst rootName = isCreditNote ? \"CreditNote\" : \"Invoice\";\n\tconst rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;\n\tconst typeCodeElement = isCreditNote\n\t\t? el(\"cbc:CreditNoteTypeCode\", null, CREDIT_NOTE_TYPE_CODE)\n\t\t: el(\"cbc:InvoiceTypeCode\", null, INVOICE_TYPE_CODE);\n\n\tconst children: (XmlElement | null | false)[] = [\n\t\tel(\"cbc:CustomizationID\", null, UBL_CUSTOMIZATION_ID),\n\t\tel(\"cbc:ProfileID\", null, UBL_PROFILE_ID),\n\t\tel(\"cbc:ID\", null, doc.id),\n\t\tel(\"cbc:IssueDate\", null, doc.issueDate),\n\t\t// CreditNote has no DueDate element in the UBL sequence.\n\t\t!isCreditNote && doc.dueDate ? el(\"cbc:DueDate\", null, doc.dueDate) : null,\n\t\ttypeCodeElement,\n\t\tdoc.note ? el(\"cbc:Note\", null, doc.note) : null,\n\t\tel(\"cbc:DocumentCurrencyCode\", null, doc.currency),\n\t\tdoc.buyerReference ? el(\"cbc:BuyerReference\", null, doc.buyerReference) : null,\n\t\tdoc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,\n\t\t...doc.attachments.map(attachmentReference),\n\t\tel(\"cac:AccountingSupplierParty\", null, [party(doc.supplier)]),\n\t\tel(\"cac:AccountingCustomerParty\", null, [party(doc.customer)]),\n\t\tel(\"cac:TaxTotal\", null, [\n\t\t\tmoney(\"cbc:TaxAmount\", doc.taxTotal.taxAmount, doc.currency),\n\t\t\t...doc.taxTotal.subtotals.map((subtotal) =>\n\t\t\t\ttaxSubtotal(subtotal, doc.currency),\n\t\t\t),\n\t\t]),\n\t\tel(\"cac:LegalMonetaryTotal\", null, [\n\t\t\tmoney(\n\t\t\t\t\"cbc:LineExtensionAmount\",\n\t\t\t\tdoc.monetaryTotal.lineExtensionAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\n\t\t\t\t\"cbc:TaxExclusiveAmount\",\n\t\t\t\tdoc.monetaryTotal.taxExclusiveAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\n\t\t\t\t\"cbc:TaxInclusiveAmount\",\n\t\t\t\tdoc.monetaryTotal.taxInclusiveAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\"cbc:PayableAmount\", doc.monetaryTotal.payableAmount, doc.currency),\n\t\t]),\n\t\t...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),\n\t];\n\n\tconst root = el(\n\t\trootName,\n\t\t{\n\t\t\txmlns: rootNamespace,\n\t\t\t\"xmlns:cac\": NS_CAC,\n\t\t\t\"xmlns:cbc\": NS_CBC,\n\t\t},\n\t\tchildren.filter((child): child is XmlElement => Boolean(child)),\n\t);\n\n\treturn serializeDocument(root);\n};\n","export const isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const normalizeString = (value: unknown): string | null => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\nexport const toNumber = (value: unknown): number => {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\tif (typeof value === \"string\") {\n\t\tconst parsed = Number(value);\n\t\tif (Number.isFinite(parsed)) return parsed;\n\t}\n\treturn 0;\n};\n","import type { UblAddress } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst normalizeCountryCode = (value: string | null | undefined): string | null => {\n\tconst trimmed = normalizeString(value);\n\tif (!trimmed) return null;\n\treturn trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;\n};\n\n/**\n * Normalize a free-form address (Stripe shape, custom shape, or an internal\n * shape) into a {@link UblAddress}.\n *\n * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`\n * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address\n * has no country, but never silently substitutes a caller's country — pass\n * `null` when \"no country\" is the right answer.\n */\nexport const normalizeAddress = (\n\taddress: unknown,\n\tfallbackCountryCode: string | null,\n\tfallbackLine?: string | null,\n): UblAddress => {\n\tconst record = isRecord(address) ? address : {};\n\tconst countryCode =\n\t\tnormalizeCountryCode(normalizeString(record.country)) ??\n\t\tnormalizeCountryCode(normalizeString(record.country_code)) ??\n\t\tnormalizeCountryCode(fallbackCountryCode);\n\treturn {\n\t\tstreet:\n\t\t\tnormalizeString(record.line1) ??\n\t\t\tnormalizeString(record.street) ??\n\t\t\tfallbackLine ??\n\t\t\tnull,\n\t\tadditionalStreet: normalizeString(record.line2),\n\t\tcity: normalizeString(record.city),\n\t\tpostalZone:\n\t\t\tnormalizeString(record.postal_code) ?? normalizeString(record.zip_code),\n\t\tcountrySubentity:\n\t\t\tnormalizeString(record.state) ?? normalizeString(record.country_subentity),\n\t\tcountryCode,\n\t};\n};\n","import type { UblCompanyId, UblEndpoint } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst cleanIdentifierValue = (value: string) =>\n\tvalue\n\t\t.trim()\n\t\t.replace(/\\s+/g, \"\")\n\t\t.replace(/[^A-Za-z0-9]/g, \"\");\n\nconst normalizeBelgianCompanyNumber = (value: string | null | undefined) => {\n\tif (!value) return \"\";\n\treturn cleanIdentifierValue(value).toUpperCase().replace(/^BE/, \"\");\n};\n\n/**\n * Strip whitespace/punctuation from a country-specific company number.\n * For Belgium, also strips an optional `BE` prefix.\n */\nexport const normalizeCompanyNumberForCountry = (\n\tcountryCode: string | null | undefined,\n\tcompanyNumber: string | null | undefined,\n) => {\n\tif (!companyNumber) return \"\";\n\tconst upper = countryCode?.trim().toUpperCase() ?? \"\";\n\tif (upper === \"BE\") return normalizeBelgianCompanyNumber(companyNumber);\n\treturn companyNumber.trim();\n};\n\n/**\n * Country code → Peppol/ISO 6523 ICD scheme for a legal registration number\n * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`).\n *\n * BE → 0208 (Belgian enterprise number, CBE/KBO/BCE)\n * NL → 0106 (Netherlands KvK)\n * FR → 0002 (France SIRENE)\n *\n * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).\n * Returns `null` when the scheme can't be determined, in which case the\n * CompanyID is emitted without a `schemeID` attribute.\n */\nexport const resolveCompanyIdScheme = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): string | null => {\n\tconst companyNumber = normalizeString(params.companyNumber);\n\tif (!companyNumber) return null;\n\n\tconst TABLE: Record<string, string> = {\n\t\tBE: \"0208\",\n\t\tNL: \"0106\",\n\t\tFR: \"0002\",\n\t};\n\n\tconst normalizedCountry =\n\t\tnormalizeString(params.countryCode)?.toUpperCase() ?? null;\n\tif (normalizedCountry && normalizedCountry in TABLE) {\n\t\treturn TABLE[normalizedCountry] ?? null;\n\t}\n\n\tconst countryPrefix = cleanIdentifierValue(companyNumber).toUpperCase().slice(0, 2);\n\treturn countryPrefix in TABLE ? (TABLE[countryPrefix] ?? null) : null;\n};\n\n/**\n * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the\n * country-appropriate ICD scheme when known. Returns `null` when there is no\n * company number.\n */\nexport const buildCompanyId = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): UblCompanyId | null => {\n\tconst normalized = normalizeString(\n\t\tnormalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),\n\t);\n\tif (!normalized) return null;\n\treturn {\n\t\tvalue: normalized,\n\t\tscheme: resolveCompanyIdScheme({\n\t\t\tcountryCode: params.countryCode,\n\t\t\tcompanyNumber: normalized,\n\t\t}),\n\t};\n};\n\n/**\n * Parse a Peppol participant identifier into a {@link UblEndpoint}.\n *\n * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns\n * `null` for values without an explicit scheme, since `cbc:EndpointID` requires\n * a `schemeID` and guessing one would mis-route the document.\n */\nexport const parsePeppolEndpoint = (\n\tpeppolId: string | null | undefined,\n): UblEndpoint | null => {\n\tconst normalized = normalizeString(peppolId);\n\tif (!normalized) return null;\n\tconst separatorIndex = normalized.indexOf(\":\");\n\tif (separatorIndex <= 0) return null;\n\tconst scheme = normalized.slice(0, separatorIndex).trim();\n\tconst value = normalized.slice(separatorIndex + 1).trim();\n\tif (!scheme || !value) return null;\n\treturn { scheme, value };\n};\n\nexport interface CustomerTaxIdentifiers {\n\tpeppolID: string | null;\n\tglnNumber: string | null;\n\ttaxNumber: string | null;\n\tvatNumber: string | null;\n}\n\nconst normalizeIdentifierType = (value: string | null) =>\n\tvalue?.toLowerCase().replace(/[^a-z0-9]+/g, \"_\") ?? null;\n\n/**\n * Pick the first usable Peppol identifier, GLN, VAT number, and tax number\n * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).\n *\n * Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.\n * Peppol IDs are typically stored as a custom `peppol_id` type.\n */\nexport const extractCustomerTaxIdentifiers = (\n\ttaxIds: unknown,\n): CustomerTaxIdentifiers => {\n\tlet peppolID: string | null = null;\n\tlet glnNumber: string | null = null;\n\tlet taxNumber: string | null = null;\n\tlet vatNumber: string | null = null;\n\n\tif (!Array.isArray(taxIds)) {\n\t\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n\t}\n\n\tfor (const entry of taxIds) {\n\t\tif (!isRecord(entry)) continue;\n\n\t\tconst type = normalizeIdentifierType(normalizeString(entry.type));\n\t\tconst value = normalizeString(entry.value);\n\t\tif (!type || !value) continue;\n\n\t\tif (!peppolID && type.includes(\"peppol\")) {\n\t\t\tpeppolID = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!glnNumber && type.includes(\"gln\")) {\n\t\t\tglnNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!vatNumber && type.includes(\"vat\")) {\n\t\t\tvatNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!taxNumber && type.includes(\"tax\")) {\n\t\t\ttaxNumber = value;\n\t\t}\n\t}\n\n\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n};\n\n/**\n * Return the candidate identifiers a Peppol receiver lookup will accept,\n * in priority order, with duplicates and nulls removed.\n */\nexport const listPeppolReceiverIdentifierCandidates = (customer: {\n\tpeppolID?: string | null;\n\tglnNumber?: string | null;\n\ttaxNumber?: string | null;\n\tvatNumber?: string | null;\n}) =>\n\tArray.from(\n\t\tnew Set(\n\t\t\t[\n\t\t\t\tnormalizeString(customer.peppolID),\n\t\t\t\tnormalizeString(customer.glnNumber),\n\t\t\t\tnormalizeString(customer.taxNumber),\n\t\t\t\tnormalizeString(customer.vatNumber),\n\t\t\t].filter((value): value is string => !!value),\n\t\t),\n\t);\n","import { normalizeAddress } from \"./address\";\nimport { buildCompanyId, parsePeppolEndpoint } from \"./identifiers\";\nimport type { UblParty } from \"./ubl/types\";\nimport { normalizeString } from \"./utils\";\n\n/**\n * Supplier (seller) VAT status. Drives how zero-VAT lines are reported when the\n * seller does not charge VAT:\n *\n * 1 — Subject to VAT (the normal case): line categories come from the data.\n * 2 — Not subject to VAT.\n * 3 — Small business / franchise exemption (e.g. Belgian Article 56bis).\n *\n * For statuses 2 and 3, {@link ../build.ts} coerces all line categories to a\n * non-charging exempt category so no VAT is reported.\n */\nexport type SupplierVatStatus = 1 | 2 | 3;\n\n/**\n * Caller-provided supplier data, normalized into a stable shape.\n *\n * Each consumer builds this from its own data store. Once a `UblSupplier`\n * exists, the party builder no longer needs to know where it came from.\n */\nexport interface UblSupplier {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** ISO 3166-1 alpha-2 country code (e.g. `\"BE\"`). */\n\tcountryCode: string;\n\t/**\n\t * Free-form address. Stripe-style fields (`line1`, `postal_code`, `country`)\n\t * and legacy/internal fields (`street`, `zip_code`) are both accepted.\n\t */\n\taddress: unknown;\n\t/** Country-specific company/registration number (e.g. BE enterprise number). */\n\tcompanyNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n\t/** Whether the supplier charges VAT. See {@link SupplierVatStatus}. */\n\tvatStatus: SupplierVatStatus;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n}\n\n/** Convert a {@link UblSupplier} into the supplier (seller) party. */\nexport const buildSupplierParty = (supplier: UblSupplier): UblParty => {\n\tconst address = normalizeAddress(supplier.address, supplier.countryCode);\n\treturn {\n\t\tendpoint: parsePeppolEndpoint(supplier.peppolID),\n\t\tname: supplier.name,\n\t\taddress,\n\t\tvatNumber: normalizeString(supplier.vatNumber),\n\t\tlegalName: supplier.name,\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode: supplier.countryCode,\n\t\t\tcompanyNumber: supplier.companyNumber ?? null,\n\t\t}),\n\t};\n};\n\n// buildCustomerPartyFromStripeInvoice lives in @financica/stripe-ubl (it is\n// Stripe-specific); this module is the generic UBL build core.\n","import type { UblAttachment, UblDocument } from \"./ubl/types\";\n\n/**\n * Build a UBL embedded-document attachment (BG-24) from raw bytes — e.g. the\n * rendered PDF of the invoice. Emitted as a `cac:AdditionalDocumentReference`\n * with an inline base64 `cbc:EmbeddedDocumentBinaryObject`.\n */\nexport const buildPdfAttachment = (params: {\n\tfilename: string;\n\tbytes: Uint8Array;\n\t/** Document reference ID (BT-122). Defaults to the filename. */\n\tid?: string;\n}): UblAttachment => ({\n\tid: params.id ?? params.filename,\n\tfilename: params.filename,\n\tmimeCode: \"application/pdf\",\n\tbase64: Buffer.from(params.bytes).toString(\"base64\"),\n});\n\n/**\n * Replace each attachment's base64 payload with `[omitted]` plus a length, so a\n * {@link UblDocument} is safe to log or persist for audit.\n */\nexport const sanitizeUblDocumentForAudit = (doc: UblDocument): UblDocument => {\n\tif (doc.attachments.length === 0) return doc;\n\treturn {\n\t\t...doc,\n\t\tattachments: doc.attachments.map((attachment) => ({\n\t\t\t...attachment,\n\t\t\tbase64: `[omitted ${attachment.base64.length} chars]`,\n\t\t})),\n\t};\n};\n","/** Round a number to 2 decimal places (cents). */\nexport const roundCurrency = (value: number) =>\n\tMath.round((value + Number.EPSILON) * 100) / 100;\n\n/** Convert an integer cent amount into a 2-decimal currency value. */\nexport const centsToDecimal = (cents: number) => roundCurrency(cents / 100);\n","import type { UblTaxCategory } from \"./ubl/types\";\n\n/**\n * Stripe Tax `taxability_reason` values that map to a VAT-exempt UBL category\n * (`E`). Reverse charge is handled separately (category `AE`).\n */\nexport const EXEMPT_TAXABILITY_REASONS = new Set([\n\t\"customer_exempt\",\n\t\"product_exempt\",\n\t\"not_subject_to_tax\",\n\t\"not_collecting\",\n\t\"not_supported\",\n\t\"portion_product_exempt\",\n]);\n\n/** Human-readable EN 16931 exemption reasons (BR-E-10 / BR-AE-10 / …). */\nconst EXEMPTION_REASON_TEXT: Record<string, string> = {\n\treverse_charge: \"Reverse charge\",\n\tcustomer_exempt: \"Exempt based on customer status\",\n\tproduct_exempt: \"Exempt based on the supplied goods or services\",\n\tportion_product_exempt: \"Exempt based on the supplied goods or services\",\n\tnot_subject_to_tax: \"Not subject to VAT\",\n\tnot_collecting: \"VAT not collected\",\n\tnot_supported: \"VAT not applicable\",\n};\n\nexport interface TaxAmountInfo {\n\tamount: number;\n\ttaxability_reason?: string | null;\n\ttax_rate_percentage?: number | null;\n}\n\nconst normalizeTaxCategoryId = (value: unknown) => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim().toUpperCase();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\n/**\n * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a\n * numeric rate into a {@link UblTaxCategory}.\n *\n * - Reverse charge → `AE` (0%, with exemption reason)\n * - Any other exempt reason → `E` (0%, with exemption reason)\n * - Category `Z` / rate ≤ 0 → `Z` (zero-rated, 0%)\n * - Otherwise → `S` (standard, the line's rate)\n */\nexport const taxCategoryFromReasonOrRate = (params: {\n\ttaxCategoryId?: string | null;\n\ttaxabilityReason: string | null;\n\trate: number;\n}): UblTaxCategory => {\n\tconst categoryHint = normalizeTaxCategoryId(params.taxCategoryId);\n\tconst reason = params.taxabilityReason;\n\n\tif (categoryHint === \"AE\" || reason === \"reverse_charge\") {\n\t\treturn {\n\t\t\tid: \"AE\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.reverse_charge,\n\t\t};\n\t}\n\tif (categoryHint === \"E\" || (reason && EXEMPT_TAXABILITY_REASONS.has(reason))) {\n\t\treturn {\n\t\t\tid: \"E\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason:\n\t\t\t\t(reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? \"Exempt from VAT\",\n\t\t};\n\t}\n\tif (categoryHint === \"Z\" || reason === \"zero_rated\" || params.rate <= 0) {\n\t\treturn { id: \"Z\", percent: 0 };\n\t}\n\treturn { id: \"S\", percent: params.rate };\n};\n\n/**\n * Resolve a {@link UblTaxCategory} from a line's Stripe tax info.\n *\n * Exempt / reverse-charge / zero-rated reasons take precedence over the rate;\n * otherwise the rate decides standard (`S`) vs zero-rated (`Z`).\n */\nexport const resolveTaxCategoryFromTaxAmounts = (\n\ttaxAmounts: TaxAmountInfo[],\n\trate: number,\n): UblTaxCategory => {\n\tfor (const ta of taxAmounts) {\n\t\tif (!ta.taxability_reason) continue;\n\t\tif (ta.taxability_reason === \"reverse_charge\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"reverse_charge\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: ta.taxability_reason,\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (ta.taxability_reason === \"zero_rated\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"zero_rated\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t}\n\treturn taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });\n};\n","import { roundCurrency } from \"./numeric\";\nimport type {\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"./ubl/types\";\n\n/**\n * Adjust the largest line's net amount so the line nets sum to the\n * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).\n *\n * Reconciling at the *line* level — rather than directly on the VAT breakdown —\n * keeps the document consistent bottom-up: the VAT category taxable amounts\n * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the\n * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level\n * coupon; larger ones indicate a real upstream data problem.\n */\nexport const reconcileLinesToExclTotal = (\n\tlines: UblLine[],\n\tauthoritativeTotalExclVat: number,\n): UblLine[] => {\n\tif (lines.length === 0) return lines;\n\tconst computed = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst diff = roundCurrency(authoritativeTotalExclVat - computed);\n\tif (diff === 0) return lines;\n\n\tconst largestIdx = lines.reduce(\n\t\t(maxIdx, line, idx, arr) =>\n\t\t\tline.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0)\n\t\t\t\t? idx\n\t\t\t\t: maxIdx,\n\t\t0,\n\t);\n\n\treturn lines.map((line, idx) => {\n\t\tif (idx !== largestIdx) return line;\n\t\tconst adjusted = roundCurrency(line.lineExtensionAmount + diff);\n\t\treturn {\n\t\t\t...line,\n\t\t\tlineExtensionAmount: adjusted,\n\t\t\tpriceAmount: roundCurrency(adjusted / Math.max(line.quantity, 1)),\n\t\t};\n\t});\n};\n\nconst categoryKey = (category: UblTaxCategory): string =>\n\t`${category.id}:${category.percent}`;\n\nexport interface BuildTaxTotalsResult {\n\ttaxTotal: UblTaxTotal;\n\tmonetaryTotal: UblMonetaryTotal;\n}\n\n/**\n * Group lines by `(category, percent)` into a VAT breakdown and compute the\n * document monetary totals.\n *\n * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,\n * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the\n * upstream per-line tax cents. This guarantees the breakdown is internally\n * consistent and passes validation; it can differ by a cent from the figure a\n * payment processor reported, which is an unavoidable artifact of representing\n * a cents-rounded system as a rate-based VAT breakdown.\n */\nexport const buildTaxTotals = (lines: UblLine[]): BuildTaxTotalsResult => {\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ category: UblTaxCategory; taxableAmount: number }\n\t>();\n\n\tfor (const line of lines) {\n\t\tconst key = categoryKey(line.taxCategory);\n\t\tconst current = groups.get(key) ?? {\n\t\t\tcategory: line.taxCategory,\n\t\t\ttaxableAmount: 0,\n\t\t};\n\t\tcurrent.taxableAmount = roundCurrency(\n\t\t\tcurrent.taxableAmount + line.lineExtensionAmount,\n\t\t);\n\t\tgroups.set(key, current);\n\t}\n\n\tconst subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({\n\t\ttaxableAmount: group.taxableAmount,\n\t\ttaxAmount: roundCurrency((group.taxableAmount * group.category.percent) / 100),\n\t\tcategory: group.category,\n\t}));\n\n\tconst lineExtensionAmount = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst taxAmount = roundCurrency(\n\t\tsubtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0),\n\t);\n\tconst taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);\n\n\treturn {\n\t\ttaxTotal: { taxAmount, subtotals },\n\t\tmonetaryTotal: {\n\t\t\tlineExtensionAmount,\n\t\t\ttaxExclusiveAmount: lineExtensionAmount,\n\t\t\ttaxInclusiveAmount,\n\t\t\tpayableAmount: taxInclusiveAmount,\n\t\t},\n\t};\n};\n"],"mappings":";AAGO,IAAM,uBACZ;AAGM,IAAM,iBAAiB;AAGvB,IAAM,oBAAoB;AAE1B,IAAM,wBAAwB;AAG9B,IAAM,oBAAoB;AAG1B,IAAM,oBAAoB;AAG1B,IAAM,uBAAuB;AAE7B,IAAM,aAAa;AACnB,IAAM,iBACZ;AACM,IAAM,SACZ;AACM,IAAM,SACZ;;;ACCM,IAAM,KAAK,CACjB,MACA,OACA,YACgB;AAChB,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC3B,WAAO;AAAA,MACN;AAAA,MACA,OAAO,SAAS;AAAA,MAChB,UAAU,QAAQ,OAAO,CAAC,MAAuB,QAAQ,CAAC,CAAC;AAAA,IAC5D;AAAA,EACD;AACA,SAAO,EAAE,MAAM,OAAO,SAAS,QAAW,MAAM,WAAW,OAAU;AACtE;AAEA,IAAM,aAAa,CAAC,UACnB,MAAM,QAAQ,MAAM,OAAO,EAAE,QAAQ,MAAM,MAAM,EAAE,QAAQ,MAAM,MAAM;AAExE,IAAM,aAAa,CAAC,UAA0B,WAAW,KAAK,EAAE,QAAQ,MAAM,QAAQ;AAEtF,IAAM,iBAAiB,CAAC,UAAwC;AAC/D,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,OAAO,QAAQ,KAAK,EACzB,OAAO,CAAC,CAAC,EAAE,KAAK,MAAM,UAAU,QAAQ,UAAU,MAAS,EAC3D,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,IAAI,GAAG,KAAK,W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AEA,IAAM,cAAc,CAAC,aACpB,GAAG,SAAS,EAAE,IAAI,SAAS,OAAO;AAkB5B,IAAM,iBAAiB,CAAC,UAA2C;AACzE,QAAM,SAAS,oBAAI,IAGjB;AAEF,aAAWA,SAAQ,OAAO;AACzB,UAAM,MAAM,YAAYA,MAAK,WAAW;AACxC,UAAM,UAAU,OAAO,IAAI,GAAG,KAAK;AAAA,MAClC,UAAUA,MAAK;AAAA,MACf,eAAe;AAAA,IAChB;AACA,YAAQ,gBAAgB;AAAA,MACvB,QAAQ,gBAAgBA,MAAK;AAAA,IAC9B;AACA,WAAO,IAAI,KAAK,OAAO;AAAA,EACxB;AAEA,QAAM,YAA8B,MAAM,KAAK,OAAO,OAAO,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,IAC/E,eAAe,MAAM;AAAA,IACrB,WAAW,cAAe,MAAM,gBAAgB,MAAM,SAAS,UAAW,GAAG;AAAA,IAC7E,UAAU,MAAM;AAAA,EACjB,EAAE;AAEF,QAAM,sBAAsB;AAAA,IAC3B,MAAM,OAAO,CAAC,KAAKA,UAAS,MAAMA,MAAK,qBAAqB,CAAC;AAAA,EAC9D;AACA,QAAM,YAAY;AAAA,IACjB,UAAU,OAAO,CAAC,KAAK,aAAa,MAAM,SAAS,WAAW,CAAC;AAAA,EAChE;AACA,QAAM,qBAAqB,cAAc,sBAAsB,SAAS;AAExE,SAAO;AAAA,IACN,UAAU,EAAE,WAAW,UAAU;AAAA,IACjC,eAAe;AAAA,MACd;AAAA,MACA,oBAAoB;AAAA,MACpB;AAAA,MACA,eAAe;AAAA,IAChB;AAAA,EACD;AACD;","names":["line"]}
package/dist/index.d.ts CHANGED
@@ -198,6 +198,48 @@ interface InvoiceExtractionDTO {
198
198
 
199
199
  declare function parseUblInvoice(xml: string): UblInvoice | null;
200
200
 
201
+ /**
202
+ * Peppol BIS MLR (Message Level Response) document-type identifier value
203
+ * (Peppol `busdox-docid-qns` scheme).
204
+ */
205
+ declare const PEPPOL_MLR_DOCUMENT_TYPE_VALUE = "urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1";
206
+ /** Peppol BIS MLR process identifier value. */
207
+ declare const PEPPOL_MLR_PROCESS_VALUE = "urn:fdc:peppol.eu:poacc:bis:mlr:3";
208
+ /**
209
+ * A parsed Peppol Message Level Response (a UBL `ApplicationResponse`). Every
210
+ * field is nullable: a given MLR may omit any of them.
211
+ */
212
+ interface PeppolMessageLevelResponse {
213
+ customizationId: string | null;
214
+ profileId: string | null;
215
+ responseId: string | null;
216
+ issueDate: string | null;
217
+ issueTime: string | null;
218
+ referencedDocumentId: string | null;
219
+ responseCode: string | null;
220
+ description: string | null;
221
+ /** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */
222
+ senderIdentifier: string | null;
223
+ /** Receiver participant id as `schemeID:value`. */
224
+ receiverIdentifier: string | null;
225
+ }
226
+ /**
227
+ * Whether an inbound document is a Peppol Message Level Response, identified by
228
+ * its document-type value, its process value, or by parsing the XML and finding
229
+ * an `ApplicationResponse` root (SBDH-wrapped or not).
230
+ */
231
+ declare const isPeppolMessageLevelResponse: (params: {
232
+ documentTypeValue?: string | null;
233
+ processValue?: string | null;
234
+ xml?: string | null;
235
+ }) => boolean;
236
+ /**
237
+ * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping
238
+ * an SBDH envelope when present. Throws when the XML is not an
239
+ * ApplicationResponse.
240
+ */
241
+ declare const parsePeppolMessageLevelResponse: (xml: string) => PeppolMessageLevelResponse;
242
+
201
243
  declare const normalizeCurrency: (value?: string | null) => string | null;
202
244
  declare const parseDate: (value?: string | null) => string | null;
203
245
  /**
@@ -227,4 +269,4 @@ declare const parseUblInvoiceDocument: (params: {
227
269
  providerJobId: string | null;
228
270
  };
229
271
 
230
- export { type InvoiceExtractionDTO, type UblAddress, type UblAllowanceCharge, type UblAttachment, type UblBillingReference, type UblContact, type UblDelivery, type UblDocumentReference, type UblInvoice, type UblInvoicePeriod, type UblItemProperty, type UblLine, type UblMonetaryTotal, type UblParty, type UblPartyIdentification, type UblPaymentMeans, type UblTaxSubtotal, decodeXmlBytes, normalizeCurrency, normalizeUblResponse, parseDate, parseUblInvoice, parseUblInvoiceDocument };
272
+ export { type InvoiceExtractionDTO, PEPPOL_MLR_DOCUMENT_TYPE_VALUE, PEPPOL_MLR_PROCESS_VALUE, type PeppolMessageLevelResponse, type UblAddress, type UblAllowanceCharge, type UblAttachment, type UblBillingReference, type UblContact, type UblDelivery, type UblDocumentReference, type UblInvoice, type UblInvoicePeriod, type UblItemProperty, type UblLine, type UblMonetaryTotal, type UblParty, type UblPartyIdentification, type UblPaymentMeans, type UblTaxSubtotal, decodeXmlBytes, isPeppolMessageLevelResponse, normalizeCurrency, normalizeUblResponse, parseDate, parsePeppolMessageLevelResponse, parseUblInvoice, parseUblInvoiceDocument };