@financica/ubl 0.5.0 → 0.6.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.
@@ -253,6 +253,20 @@ declare const buildCompanyId: (params: {
253
253
  countryCode: string | null;
254
254
  companyNumber: string | null;
255
255
  }) => UblCompanyId | null;
256
+ /**
257
+ * Resolve the Peppol participant identifier for a VAT number, deriving the EAS
258
+ * scheme from the number's own country prefix (falling back to `countryCode`).
259
+ *
260
+ * `BE0206582284` → `{ scheme: "9925", value: "BE0206582284" }`
261
+ *
262
+ * The value keeps its country prefix, matching how participants register (the
263
+ * Peppol directory lists this party as `9925:be0206582284`). Returns `null`
264
+ * when the country has no VAT EAS scheme or the input is empty.
265
+ */
266
+ declare const resolveVatEndpoint: (params: {
267
+ vatNumber: string | null | undefined;
268
+ countryCode?: string | null;
269
+ }) => UblEndpoint | null;
256
270
  /**
257
271
  * Parse a Peppol participant identifier into a {@link UblEndpoint}.
258
272
  *
@@ -276,15 +290,30 @@ interface CustomerTaxIdentifiers {
276
290
  */
277
291
  declare const extractCustomerTaxIdentifiers: (taxIds: unknown) => CustomerTaxIdentifiers;
278
292
  /**
279
- * Return the candidate identifiers a Peppol receiver lookup will accept,
280
- * in priority order, with duplicates and nulls removed.
293
+ * Build the fully-qualified Peppol participant identifiers (`scheme:value`) a
294
+ * receiver lookup will accept, in priority order, de-duplicated.
295
+ *
296
+ * Stripe stores a customer's VAT number without a Peppol scheme (e.g.
297
+ * `BE0206582284`), but a participant lookup needs the qualified identifier
298
+ * (`9925:BE0206582284`). This attaches the right scheme:
299
+ *
300
+ * 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;
301
+ * 2. a GLN under EAS `0088`;
302
+ * 3. the VAT number under its country's VAT EAS scheme (see
303
+ * {@link resolveVatEndpoint});
304
+ * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)
305
+ * under EAS `0208` — many Belgian entities register only under that;
306
+ * 5. a generic tax/registration number under its country's company-ID scheme.
307
+ *
308
+ * `countryCode` (the customer's country, when known) disambiguates schemes for
309
+ * identifiers that don't carry a country prefix (GLN, plain tax numbers).
281
310
  */
282
311
  declare const listPeppolReceiverIdentifierCandidates: (customer: {
283
312
  peppolID?: string | null;
284
313
  glnNumber?: string | null;
285
314
  taxNumber?: string | null;
286
315
  vatNumber?: string | null;
287
- }) => string[];
316
+ }, countryCode?: string | null) => string[];
288
317
 
289
318
  /** Round a number to 2 decimal places (cents). */
290
319
  declare const roundCurrency: (value: number) => number;
@@ -381,4 +410,4 @@ declare const el: (name: string, attrs?: XmlAttrs | null, content?: string | num
381
410
  /** Serialize a root element into a UTF-8 XML document string. */
382
411
  declare const serializeDocument: (root: XmlElement) => string;
383
412
 
384
- export { type BuildTaxTotalsResult, COUNTRY_CODE_LIST_ID, CREDIT_NOTE_TYPE_CODE, type CustomerTaxIdentifiers, DEFAULT_UNIT_CODE, EXEMPT_TAXABILITY_REASONS, INVOICE_TYPE_CODE, NS_CAC, NS_CBC, NS_CREDIT_NOTE, NS_INVOICE, type SupplierVatStatus, type TaxAmountInfo, UBL_CUSTOMIZATION_ID, UBL_PROFILE_ID, type UblAddress, type UblAttachment, type UblCompanyId, type UblDocument, type UblEndpoint, type UblLine, type UblMonetaryTotal, type UblParty, type UblSupplier, type UblTaxCategory, type UblTaxSubtotal, type UblTaxTotal, VAT_TAX_SCHEME_ID, type XmlAttrs, type XmlElement, buildCompanyId, buildPdfAttachment, buildSupplierParty, buildTaxTotals, centsToDecimal, el, extractCustomerTaxIdentifiers, listPeppolReceiverIdentifierCandidates, normalizeAddress, normalizeCompanyNumberForCountry, parsePeppolEndpoint, reconcileLinesToExclTotal, resolveCompanyIdScheme, resolveTaxCategoryFromTaxAmounts, roundCurrency, sanitizeUblDocumentForAudit, serializeDocument, serializeUblDocument, taxCategoryFromReasonOrRate };
413
+ export { type BuildTaxTotalsResult, COUNTRY_CODE_LIST_ID, CREDIT_NOTE_TYPE_CODE, type CustomerTaxIdentifiers, DEFAULT_UNIT_CODE, EXEMPT_TAXABILITY_REASONS, INVOICE_TYPE_CODE, NS_CAC, NS_CBC, NS_CREDIT_NOTE, NS_INVOICE, type SupplierVatStatus, type TaxAmountInfo, UBL_CUSTOMIZATION_ID, UBL_PROFILE_ID, type UblAddress, type UblAttachment, type UblCompanyId, type UblDocument, type UblEndpoint, type UblLine, type UblMonetaryTotal, type UblParty, type UblSupplier, type UblTaxCategory, type UblTaxSubtotal, type UblTaxTotal, VAT_TAX_SCHEME_ID, type XmlAttrs, type XmlElement, buildCompanyId, buildPdfAttachment, buildSupplierParty, buildTaxTotals, centsToDecimal, el, extractCustomerTaxIdentifiers, listPeppolReceiverIdentifierCandidates, normalizeAddress, normalizeCompanyNumberForCountry, parsePeppolEndpoint, reconcileLinesToExclTotal, resolveCompanyIdScheme, resolveTaxCategoryFromTaxAmounts, resolveVatEndpoint, roundCurrency, sanitizeUblDocumentForAudit, serializeDocument, serializeUblDocument, taxCategoryFromReasonOrRate };
@@ -255,6 +255,101 @@ var buildCompanyId = (params) => {
255
255
  })
256
256
  };
257
257
  };
258
+ var VAT_SCHEME_BY_COUNTRY = {
259
+ AD: "9922",
260
+ // Andorra
261
+ AL: "9923",
262
+ // Albania
263
+ AT: "9914",
264
+ // Austria
265
+ BA: "9924",
266
+ // Bosnia and Herzegovina
267
+ BE: "9925",
268
+ // Belgium
269
+ BG: "9926",
270
+ // Bulgaria
271
+ CH: "9927",
272
+ // Switzerland
273
+ CY: "9928",
274
+ // Cyprus
275
+ CZ: "9929",
276
+ // Czech Republic
277
+ DE: "9930",
278
+ // Germany
279
+ EE: "9931",
280
+ // Estonia
281
+ ES: "9920",
282
+ // Spain (Spanish Tax Administration)
283
+ FI: "0213",
284
+ // Finland (Finnish VAT Identifier)
285
+ FR: "9957",
286
+ // France
287
+ GB: "9932",
288
+ // United Kingdom
289
+ GR: "9933",
290
+ // Greece (VAT prefix "EL")
291
+ HR: "9934",
292
+ // Croatia
293
+ HU: "9910",
294
+ // Hungary
295
+ IE: "9935",
296
+ // Ireland
297
+ LI: "9936",
298
+ // Liechtenstein
299
+ LT: "9937",
300
+ // Lithuania
301
+ LU: "9938",
302
+ // Luxembourg
303
+ LV: "9939",
304
+ // Latvia
305
+ MC: "9940",
306
+ // Monaco
307
+ ME: "9941",
308
+ // Montenegro
309
+ MK: "9942",
310
+ // North Macedonia
311
+ MT: "9943",
312
+ // Malta
313
+ NL: "9944",
314
+ // Netherlands
315
+ PL: "9945",
316
+ // Poland
317
+ PT: "9946",
318
+ // Portugal
319
+ RO: "9947",
320
+ // Romania
321
+ RS: "9948",
322
+ // Serbia
323
+ SI: "9949",
324
+ // Slovenia
325
+ SK: "9950",
326
+ // Slovakia
327
+ SM: "9951",
328
+ // San Marino
329
+ TR: "9952",
330
+ // Turkey
331
+ VA: "9953"
332
+ // Holy See / Vatican City
333
+ };
334
+ var VAT_PREFIX_TO_COUNTRY = {
335
+ EL: "GR",
336
+ // Greece issues VAT numbers with the "EL" prefix
337
+ XI: "GB"
338
+ // Northern Ireland VAT is issued under the UK scheme
339
+ };
340
+ var resolveVatEndpoint = (params) => {
341
+ const value = normalizeString(params.vatNumber);
342
+ if (!value) return null;
343
+ const cleaned = cleanIdentifierValue(value).toUpperCase();
344
+ if (!cleaned) return null;
345
+ const prefix = cleaned.slice(0, 2);
346
+ const fromPrefix = /^[A-Z]{2}$/.test(prefix) ? VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix : null;
347
+ const fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;
348
+ const country = fromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;
349
+ const scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : void 0;
350
+ if (!scheme) return null;
351
+ return { scheme, value: cleaned };
352
+ };
258
353
  var parsePeppolEndpoint = (peppolId) => {
259
354
  const normalized = normalizeString(peppolId);
260
355
  if (!normalized) return null;
@@ -297,16 +392,24 @@ var extractCustomerTaxIdentifiers = (taxIds) => {
297
392
  }
298
393
  return { peppolID, glnNumber, taxNumber, vatNumber };
299
394
  };
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
- );
395
+ var listPeppolReceiverIdentifierCandidates = (customer, countryCode) => {
396
+ const candidates = [];
397
+ const add = (id) => {
398
+ if (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);
399
+ };
400
+ const peppol = normalizeString(customer.peppolID);
401
+ if (peppol) candidates.push(peppol);
402
+ const gln = normalizeString(customer.glnNumber);
403
+ if (gln) add({ scheme: "0088", value: cleanIdentifierValue(gln) });
404
+ const vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });
405
+ add(vat);
406
+ if (vat?.scheme === "9925") {
407
+ add(buildCompanyId({ countryCode: "BE", companyNumber: customer.vatNumber ?? null }));
408
+ }
409
+ const tax = normalizeString(customer.taxNumber);
410
+ if (tax) add(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));
411
+ return Array.from(new Set(candidates));
412
+ };
310
413
 
311
414
  // src/build/party.ts
312
415
  var buildSupplierParty = (supplier) => {
@@ -501,6 +604,7 @@ export {
501
604
  reconcileLinesToExclTotal,
502
605
  resolveCompanyIdScheme,
503
606
  resolveTaxCategoryFromTaxAmounts,
607
+ resolveVatEndpoint,
504
608
  roundCurrency,
505
609
  sanitizeUblDocumentForAudit,
506
610
  serializeDocument,
@@ -1 +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,IAA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9B;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"]}
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 * Country code → Peppol EAS scheme for a *VAT* identifier, keyed by ISO 3166-1\n * alpha-2. Source: Peppol Code Lists – Participant Identifier Schemes (EAS),\n * Peppol BIS Billing 3.0 (November 2025 release).\n *\n * Only countries that publish a VAT-based EAS scheme appear here. Some (e.g.\n * SE/DK/NO) address Peppol participants by organisation number rather than VAT\n * and are intentionally absent — see {@link resolveCompanyIdScheme}.\n */\nconst VAT_SCHEME_BY_COUNTRY: Record<string, string> = {\n\tAD: \"9922\", // Andorra\n\tAL: \"9923\", // Albania\n\tAT: \"9914\", // Austria\n\tBA: \"9924\", // Bosnia and Herzegovina\n\tBE: \"9925\", // Belgium\n\tBG: \"9926\", // Bulgaria\n\tCH: \"9927\", // Switzerland\n\tCY: \"9928\", // Cyprus\n\tCZ: \"9929\", // Czech Republic\n\tDE: \"9930\", // Germany\n\tEE: \"9931\", // Estonia\n\tES: \"9920\", // Spain (Spanish Tax Administration)\n\tFI: \"0213\", // Finland (Finnish VAT Identifier)\n\tFR: \"9957\", // France\n\tGB: \"9932\", // United Kingdom\n\tGR: \"9933\", // Greece (VAT prefix \"EL\")\n\tHR: \"9934\", // Croatia\n\tHU: \"9910\", // Hungary\n\tIE: \"9935\", // Ireland\n\tLI: \"9936\", // Liechtenstein\n\tLT: \"9937\", // Lithuania\n\tLU: \"9938\", // Luxembourg\n\tLV: \"9939\", // Latvia\n\tMC: \"9940\", // Monaco\n\tME: \"9941\", // Montenegro\n\tMK: \"9942\", // North Macedonia\n\tMT: \"9943\", // Malta\n\tNL: \"9944\", // Netherlands\n\tPL: \"9945\", // Poland\n\tPT: \"9946\", // Portugal\n\tRO: \"9947\", // Romania\n\tRS: \"9948\", // Serbia\n\tSI: \"9949\", // Slovenia\n\tSK: \"9950\", // Slovakia\n\tSM: \"9951\", // San Marino\n\tTR: \"9952\", // Turkey\n\tVA: \"9953\", // Holy See / Vatican City\n};\n\n/**\n * VAT registration prefixes that differ from the ISO 3166-1 alpha-2 country\n * code, so a VAT number's leading two letters still resolve to the right scheme.\n */\nconst VAT_PREFIX_TO_COUNTRY: Record<string, string> = {\n\tEL: \"GR\", // Greece issues VAT numbers with the \"EL\" prefix\n\tXI: \"GB\", // Northern Ireland VAT is issued under the UK scheme\n};\n\n/**\n * Resolve the Peppol participant identifier for a VAT number, deriving the EAS\n * scheme from the number's own country prefix (falling back to `countryCode`).\n *\n * `BE0206582284` → `{ scheme: \"9925\", value: \"BE0206582284\" }`\n *\n * The value keeps its country prefix, matching how participants register (the\n * Peppol directory lists this party as `9925:be0206582284`). Returns `null`\n * when the country has no VAT EAS scheme or the input is empty.\n */\nexport const resolveVatEndpoint = (params: {\n\tvatNumber: string | null | undefined;\n\tcountryCode?: string | null;\n}): UblEndpoint | null => {\n\tconst value = normalizeString(params.vatNumber);\n\tif (!value) return null;\n\tconst cleaned = cleanIdentifierValue(value).toUpperCase();\n\tif (!cleaned) return null;\n\n\tconst prefix = cleaned.slice(0, 2);\n\tconst fromPrefix = /^[A-Z]{2}$/.test(prefix)\n\t\t? (VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix)\n\t\t: null;\n\tconst fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;\n\n\tconst country =\n\t\tfromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;\n\tconst scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : undefined;\n\tif (!scheme) return null;\n\n\treturn { scheme, value: cleaned };\n};\n\n/**\n * Parse a Peppol participant identifier into a {@link UblEndpoint}.\n *\n * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns\n * `null` for values without an explicit scheme, since `cbc:EndpointID` requires\n * a `schemeID` and guessing one would mis-route the document.\n */\nexport const parsePeppolEndpoint = (\n\tpeppolId: string | null | undefined,\n): UblEndpoint | null => {\n\tconst normalized = normalizeString(peppolId);\n\tif (!normalized) return null;\n\tconst separatorIndex = normalized.indexOf(\":\");\n\tif (separatorIndex <= 0) return null;\n\tconst scheme = normalized.slice(0, separatorIndex).trim();\n\tconst value = normalized.slice(separatorIndex + 1).trim();\n\tif (!scheme || !value) return null;\n\treturn { scheme, value };\n};\n\nexport interface CustomerTaxIdentifiers {\n\tpeppolID: string | null;\n\tglnNumber: string | null;\n\ttaxNumber: string | null;\n\tvatNumber: string | null;\n}\n\nconst normalizeIdentifierType = (value: string | null) =>\n\tvalue?.toLowerCase().replace(/[^a-z0-9]+/g, \"_\") ?? null;\n\n/**\n * Pick the first usable Peppol identifier, GLN, VAT number, and tax number\n * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).\n *\n * Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.\n * Peppol IDs are typically stored as a custom `peppol_id` type.\n */\nexport const extractCustomerTaxIdentifiers = (\n\ttaxIds: unknown,\n): CustomerTaxIdentifiers => {\n\tlet peppolID: string | null = null;\n\tlet glnNumber: string | null = null;\n\tlet taxNumber: string | null = null;\n\tlet vatNumber: string | null = null;\n\n\tif (!Array.isArray(taxIds)) {\n\t\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n\t}\n\n\tfor (const entry of taxIds) {\n\t\tif (!isRecord(entry)) continue;\n\n\t\tconst type = normalizeIdentifierType(normalizeString(entry.type));\n\t\tconst value = normalizeString(entry.value);\n\t\tif (!type || !value) continue;\n\n\t\tif (!peppolID && type.includes(\"peppol\")) {\n\t\t\tpeppolID = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!glnNumber && type.includes(\"gln\")) {\n\t\t\tglnNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!vatNumber && type.includes(\"vat\")) {\n\t\t\tvatNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!taxNumber && type.includes(\"tax\")) {\n\t\t\ttaxNumber = value;\n\t\t}\n\t}\n\n\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n};\n\n/**\n * Build the fully-qualified Peppol participant identifiers (`scheme:value`) a\n * receiver lookup will accept, in priority order, de-duplicated.\n *\n * Stripe stores a customer's VAT number without a Peppol scheme (e.g.\n * `BE0206582284`), but a participant lookup needs the qualified identifier\n * (`9925:BE0206582284`). This attaches the right scheme:\n *\n * 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;\n * 2. a GLN under EAS `0088`;\n * 3. the VAT number under its country's VAT EAS scheme (see\n * {@link resolveVatEndpoint});\n * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)\n * under EAS `0208` — many Belgian entities register only under that;\n * 5. a generic tax/registration number under its country's company-ID scheme.\n *\n * `countryCode` (the customer's country, when known) disambiguates schemes for\n * identifiers that don't carry a country prefix (GLN, plain tax numbers).\n */\nexport const listPeppolReceiverIdentifierCandidates = (\n\tcustomer: {\n\t\tpeppolID?: string | null;\n\t\tglnNumber?: string | null;\n\t\ttaxNumber?: string | null;\n\t\tvatNumber?: string | null;\n\t},\n\tcountryCode?: string | null,\n): string[] => {\n\tconst candidates: string[] = [];\n\tconst add = (id: { scheme?: string | null; value: string } | null) => {\n\t\tif (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);\n\t};\n\n\t// 1. An explicit Peppol ID already carries its own scheme.\n\tconst peppol = normalizeString(customer.peppolID);\n\tif (peppol) candidates.push(peppol);\n\n\t// 2. GLN → EAS 0088 (Global Location Number).\n\tconst gln = normalizeString(customer.glnNumber);\n\tif (gln) add({ scheme: \"0088\", value: cleanIdentifierValue(gln) });\n\n\t// 3. VAT number → the country's VAT EAS scheme (e.g. BE → 9925).\n\tconst vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\tadd(vat);\n\n\t// 4. Belgium also reaches parties by enterprise number under EAS 0208; it is\n\t// the VAT digits without the `BE` prefix, and some entities register only so.\n\tif (vat?.scheme === \"9925\") {\n\t\tadd(buildCompanyId({ countryCode: \"BE\", companyNumber: customer.vatNumber ?? null }));\n\t}\n\n\t// 5. A generic tax/registration number → its country's company-ID scheme.\n\tconst tax = normalizeString(customer.taxNumber);\n\tif (tax) add(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));\n\n\treturn Array.from(new Set(candidates));\n};\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,WAAW,OAAO,KAAK,CAAC,CAAC,GAAG,EAC9D,KAAK,EAA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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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@financica/ubl",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "UBL (Universal Business Language) invoice toolkit for TypeScript: parse, build, and serialize Peppol BIS Billing 3.0 documents.",
5
5
  "license": "MIT",
6
6
  "type": "module",