@financica/ubl 0.19.2 → 0.19.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/build/index.d.ts +7 -6
- package/dist/build/index.d.ts.map +1 -1
- package/dist/build/index.js +8 -7
- package/dist/build/index.js.map +1 -1
- package/package.json +1 -1
- package/src/build/identifiers.ts +15 -11
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.19.3
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- **`listPeppolReceiverIdentifierCandidates` puts a Belgian party's `0208` ahead of its `9925`.** Belgium mandates registration under the enterprise number (`0208`); the VAT scheme (`9925`) is voluntary. With `9925` first, a party that moved access point but left a `9925` registration behind at the old one had its documents delivered there. `9925` stays in the list as the fallback for parties registered only under it.
|
|
8
|
+
|
|
3
9
|
## 0.19.2
|
|
4
10
|
|
|
5
11
|
### Fixed
|
package/dist/build/index.d.ts
CHANGED
|
@@ -266,12 +266,13 @@ declare const extractCustomerTaxIdentifiers: (taxIds: readonly CustomerTaxIdInpu
|
|
|
266
266
|
*
|
|
267
267
|
* 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;
|
|
268
268
|
* 2. a GLN under EAS `0088`;
|
|
269
|
-
* 3. the
|
|
270
|
-
*
|
|
271
|
-
*
|
|
272
|
-
*
|
|
273
|
-
* for Sweden, Norway and Denmark, whose VAT
|
|
274
|
-
* company number inside the VAT number
|
|
269
|
+
* 3. for Belgium, the enterprise number (VAT digits without the `BE` prefix)
|
|
270
|
+
* under EAS `0208`, ahead of the VAT scheme: Belgium mandates `0208`, and
|
|
271
|
+
* a stale `9925` left at a previous access point must not win the lookup;
|
|
272
|
+
* 4. the VAT number under its country's VAT EAS scheme (see
|
|
273
|
+
* {@link resolveVatEndpoint}); for Sweden, Norway and Denmark, whose VAT
|
|
274
|
+
* schemes were withdrawn, the company number inside the VAT number
|
|
275
|
+
* (`0007`, `0192`, `0184`);
|
|
275
276
|
* 5. a generic tax/registration number under its country's company-ID scheme.
|
|
276
277
|
*
|
|
277
278
|
* `countryCode` (the customer's country, when known) disambiguates schemes for
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/build/ubl/constants.ts","../../src/build/ubl/serialize.ts","../../src/build/address.ts","../../src/build/party.ts","../../src/build/attachment.ts","../../src/build/identifiers.ts","../../src/build/numeric.ts","../../src/build/tax-category.ts","../../src/build/tax-totals.ts","../../src/build/xml.ts","../../src/build/index.ts"],"mappings":";;;;cAGa;;cAIA;;cAGA;;cAEA;;cAGA;;cAGA;;cAGA;cAEA;cACA;cAEA;cAEA;;;;;;;;;;;;;;;;;;;;;;cC42BA,sBAAmB,KAAS;;cAuH5B,6BAAoB;;;;;;;;;;;UC9+BhB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;cAYY,mBAAgB,SACnB,iCAA+B,oCACN,iCAEhC;;;;;;;;;;;;;;;;;KCxBS;;;;;;;UAQK;;EAEhB;;EAEA;;;;;EAKA,SAAS;;EAET;;EAEA;;EAEA,WAAW;;EAEX;;;cAsBY,qBAAkB,UAAc,gBAAc;;;;;;;;UAsB1C;;EAEhB;;EAEA,SAAS;;;;;;;EAOT;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;cAcY,qBAAkB,UACpB,aAAW,mBACF,uBACjB;;;;;;;;cCrHU,qBAAkB;EAC9B;EACA,OAAO;;EAEP;MACG;;;;;cAWS,8BAA2B,KAAS,eAAa;;;;;;;cCLjD,mCAAgC,wCACN;;;;;;;;;;;cAmB1B,yBAAsB;EAClC;EACA;;;;;;;cAuBY,iBAAc;EAC1B;EACA;MACG;;;;;;;;;;;;;;;cA4BS,qBAAkB;EAC9B;EACA;MACG;;;;;;;;cAyBS,sBAAmB,wCAE7B;UAWc;EAChB;EACA;EACA;EACA;;;;;;;UAQgB;EAChB;EACA;;;;;;;;;cAaY,gCAA6B,iBACxB,4CACf
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/build/ubl/constants.ts","../../src/build/ubl/serialize.ts","../../src/build/address.ts","../../src/build/party.ts","../../src/build/attachment.ts","../../src/build/identifiers.ts","../../src/build/numeric.ts","../../src/build/tax-category.ts","../../src/build/tax-totals.ts","../../src/build/xml.ts","../../src/build/index.ts"],"mappings":";;;;cAGa;;cAIA;;cAGA;;cAEA;;cAGA;;cAGA;;cAGA;cAEA;cACA;cAEA;cAEA;;;;;;;;;;;;;;;;;;;;;;cC42BA,sBAAmB,KAAS;;cAuH5B,6BAAoB;;;;;;;;;;;UC9+BhB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;cAYY,mBAAgB,SACnB,iCAA+B,oCACN,iCAEhC;;;;;;;;;;;;;;;;;KCxBS;;;;;;;UAQK;;EAEhB;;EAEA;;;;;EAKA,SAAS;;EAET;;EAEA;;EAEA,WAAW;;EAEX;;;cAsBY,qBAAkB,UAAc,gBAAc;;;;;;;;UAsB1C;;EAEhB;;EAEA,SAAS;;;;;;;EAOT;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;cAcY,qBAAkB,UACpB,aAAW,mBACF,uBACjB;;;;;;;;cCrHU,qBAAkB;EAC9B;EACA,OAAO;;EAEP;MACG;;;;;cAWS,8BAA2B,KAAS,eAAa;;;;;;;cCLjD,mCAAgC,wCACN;;;;;;;;;;;cAmB1B,yBAAsB;EAClC;EACA;;;;;;;cAuBY,iBAAc;EAC1B;EACA;MACG;;;;;;;;;;;;;;;cA4BS,qBAAkB;EAC9B;EACA;MACG;;;;;;;;cAyBS,sBAAmB,wCAE7B;UAWc;EAChB;EACA;EACA;EACA;;;;;;;UAQgB;EAChB;EACA;;;;;;;;;cAaY,gCAA6B,iBACxB,4CACf;;;;;;;;;;;;;;;;;;;;;;;cAqDU,yCAAsC,UACxC,QAAQ,yBAAuB;;;;cCzN7B,gBAAa;;cAIb,iBAAc;;UAGV;;EAEhB;;;;;;EAMA;;;;;;;;;;;;;;;;;;;;cAqBY,kBAAe,kBAAoB,qBAAqB;;;;;;;cC7BxD,2BAAyB;UAsBrB;EAChB;EACA;EACA;;;;;;;;;;;;;cAiBY,8BAA2B;EACvC;EACA;EACA;MACG;;;;;;;cA8CS,mCAAgC,YAChC,iBAAe,iBAEzB;;;;;;;cAiCU,kCAA+B,OACpC,WAAS,WACL,mBAAiB,wCAE1B;;;;;;;;;;;;;cCpHU,4BAAyB,OAC9B,WAAS,sCAEd;UAqCc;EAChB,UAAU;EACV,eAAe;;UAGC;;;;;;EAMhB;;EAEA;;;;;;;EAOA,mBAAmB;;;;;;;;;;;;;;;;;;;;;cAsBP,iBAAc,OACnB,WAAS,UACN,0BACR;;;;;;;;;;;;cAkGU,8BAA2B,gBACzB,OACP,WAAS,UACN,KAAK,qEACb;;;;;;;;;;;KC1MS,WAAW;UAEN;EAChB;EACA,QAAQ;;EAER;;EAEA,WAAW;;;KAIP,YAAY;;;;;;;;cASJ,KAAE,cACF,QACJ,iBAAe,mCACY,gBACjC;;cAgDU,oBAAiB,MAAU;;;;KC1C5B,cAAc;;KAEd,YAAY"}
|
package/dist/build/index.js
CHANGED
|
@@ -670,12 +670,13 @@ const extractCustomerTaxIdentifiers = (taxIds) => {
|
|
|
670
670
|
*
|
|
671
671
|
* 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;
|
|
672
672
|
* 2. a GLN under EAS `0088`;
|
|
673
|
-
* 3. the
|
|
674
|
-
*
|
|
675
|
-
*
|
|
676
|
-
*
|
|
677
|
-
* for Sweden, Norway and Denmark, whose VAT
|
|
678
|
-
* company number inside the VAT number
|
|
673
|
+
* 3. for Belgium, the enterprise number (VAT digits without the `BE` prefix)
|
|
674
|
+
* under EAS `0208`, ahead of the VAT scheme: Belgium mandates `0208`, and
|
|
675
|
+
* a stale `9925` left at a previous access point must not win the lookup;
|
|
676
|
+
* 4. the VAT number under its country's VAT EAS scheme (see
|
|
677
|
+
* {@link resolveVatEndpoint}); for Sweden, Norway and Denmark, whose VAT
|
|
678
|
+
* schemes were withdrawn, the company number inside the VAT number
|
|
679
|
+
* (`0007`, `0192`, `0184`);
|
|
679
680
|
* 5. a generic tax/registration number under its country's company-ID scheme.
|
|
680
681
|
*
|
|
681
682
|
* `countryCode` (the customer's country, when known) disambiguates schemes for
|
|
@@ -697,11 +698,11 @@ const listPeppolReceiverIdentifierCandidates = (customer, countryCode) => {
|
|
|
697
698
|
vatNumber: customer.vatNumber,
|
|
698
699
|
countryCode
|
|
699
700
|
});
|
|
700
|
-
add(vat);
|
|
701
701
|
if (vat?.scheme === "9925") add(buildCompanyId({
|
|
702
702
|
countryCode: "BE",
|
|
703
703
|
companyNumber: customer.vatNumber ?? null
|
|
704
704
|
}));
|
|
705
|
+
add(vat);
|
|
705
706
|
const compactVat = (customer.vatNumber ?? "").replace(/[^A-Za-z0-9]/g, "").toUpperCase();
|
|
706
707
|
const swedishOrgNumber = /^SE(\d{10})01$/.exec(compactVat)?.[1];
|
|
707
708
|
if (swedishOrgNumber) add({
|
package/dist/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["categoryKey"],"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\t...(attrs ? { attrs } : {}),\n\t\t\tchildren: content.filter((c): c is XmlElement => Boolean(c)),\n\t\t};\n\t}\n\treturn {\n\t\tname,\n\t\t...(attrs ? { attrs } : {}),\n\t\t...(content !== undefined ? { text: content } : {}),\n\t};\n};\n\nconst escapeText = (value: string): string =>\n\tvalue.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n\nconst escapeAttr = (value: string): string => escapeText(value).replace(/\"/g, \""\");\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 { UblBuildError } from \"../../errors\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\n\tUblDelivery,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblLine,\n\tUblParty,\n\tUblPaymentMeans,\n\tUblSchemedId,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n} from \"../../types\";\nimport { 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\";\n\n// ── Validation ─────────────────────────────────────────────────────────\n//\n// The model is permissive (the parser reads whatever a document states); the\n// serializer is where EN 16931 / Peppol BIS Billing 3.0 mandatory fields and\n// the arithmetic business rules are enforced. Each check names the BT or the\n// rule and the model path in its message.\n\nconst missing = (what: string, path: string): UblBuildError =>\n\tnew UblBuildError(`Missing ${what} (${path})`);\n\nfunction required<T>(value: T | undefined, what: string, path: string): NonNullable<T> {\n\tif (value === undefined || value === null || value === \"\") {\n\t\tthrow missing(what, path);\n\t}\n\treturn value as NonNullable<T>;\n}\n\nconst round2 = (value: number): number => Math.round(value * 100) / 100;\n\n/** Sums of cent-rounded amounts must agree to the cent; R120 allows a cent either way. */\nconst assertEqual = (\n\trule: string,\n\tactual: number,\n\texpected: number,\n\tpath: string,\n\ttolerance = 0.005,\n): void => {\n\tif (Math.abs(actual - expected) > tolerance) {\n\t\tthrow new UblBuildError(\n\t\t\t`${rule}: ${path} is ${actual.toFixed(2)}, expected ${expected.toFixed(2)}`,\n\t\t);\n\t}\n};\n\n/** Category `O` (outside scope) is the one category BR-O-05 forbids a percent on. */\nconst requiresPercent = (categoryId: string): boolean => categoryId !== \"O\";\n\nconst validateTaxCategory = (\n\tcategory: UblTaxCategory | undefined,\n\tpath: string,\n): UblTaxCategory & { id: string } => {\n\tconst present = required(category, \"VAT category (BT-151/BT-118)\", path);\n\tconst id = required(present.id, \"VAT category code (BT-151/BT-118)\", `${path}.id`);\n\tif (requiresPercent(id) && present.percent === undefined) {\n\t\tthrow missing(`VAT rate (BT-152/BT-119) for category ${id}`, `${path}.percent`);\n\t}\n\treturn { ...present, id };\n};\n\nconst validateAllowanceCharge = (\n\titem: UblAllowanceCharge,\n\tpath: string,\n\tlevel: \"document\" | \"line\",\n): void => {\n\tconst kind = item.chargeIndicator ? \"charge\" : \"allowance\";\n\trequired(item.amount, `${kind} amount (BT-92/BT-99)`, `${path}.amount`);\n\tif (item.reason === undefined && item.reasonCode === undefined) {\n\t\tthrow missing(`${kind} reason or reason code (BT-97/BT-98)`, `${path}.reason`);\n\t}\n\tif (item.baseAmount !== undefined && item.multiplierFactorNumeric !== undefined) {\n\t\tassertEqual(\n\t\t\t\"PEPPOL-EN16931-R040\",\n\t\t\titem.amount ?? 0,\n\t\t\tround2((item.baseAmount * item.multiplierFactorNumeric) / 100),\n\t\t\t`${path}.amount`,\n\t\t\t0.01,\n\t\t);\n\t}\n\tif (level === \"document\") {\n\t\tvalidateTaxCategory(item.taxCategory, `${path}.taxCategory`);\n\t}\n};\n\nconst lineAllowanceTotal = (line: UblLine, charges: boolean): number =>\n\t(line.allowanceCharges ?? [])\n\t\t.filter((item) => item.chargeIndicator === charges)\n\t\t.reduce((sum, item) => sum + (item.amount ?? 0), 0);\n\nconst validateLine = (line: UblLine, index: number): void => {\n\tconst path = `lines[${index}]`;\n\trequired(line.id, \"line identifier (BT-126)\", `${path}.id`);\n\tconst quantity = required(\n\t\tline.quantity,\n\t\t\"invoiced quantity (BT-129)\",\n\t\t`${path}.quantity`,\n\t);\n\trequired(line.unitCode, \"unit code (BT-130)\", `${path}.unitCode`);\n\tconst unitPrice = required(\n\t\tline.unitPrice,\n\t\t\"net unit price (BT-146)\",\n\t\t`${path}.unitPrice`,\n\t);\n\tconst net = required(\n\t\tline.lineExtensionAmount,\n\t\t\"line net amount (BT-131)\",\n\t\t`${path}.lineExtensionAmount`,\n\t);\n\t// A negative line carries its sign on the quantity, never on the price.\n\tif (unitPrice < 0) {\n\t\tthrow new UblBuildError(\n\t\t\t`BR-27: ${path}.unitPrice is ${unitPrice}, the item net price shall not be negative`,\n\t\t);\n\t}\n\tvalidateTaxCategory(line.taxCategory, `${path}.taxCategory`);\n\t(line.allowanceCharges ?? []).forEach((item, itemIndex) =>\n\t\tvalidateAllowanceCharge(item, `${path}.allowanceCharges[${itemIndex}]`, \"line\"),\n\t);\n\t// BT-131 = BT-129 × BT-146 + line charges − line allowances. `unitPrice` is\n\t// the per-unit figure, so BT-149 is already accounted for.\n\tassertEqual(\n\t\t\"PEPPOL-EN16931-R120\",\n\t\tnet,\n\t\tround2(\n\t\t\tquantity * unitPrice +\n\t\t\t\tlineAllowanceTotal(line, true) -\n\t\t\t\tlineAllowanceTotal(line, false),\n\t\t),\n\t\t`${path}.lineExtensionAmount`,\n\t\t0.02,\n\t);\n};\n\nconst isExternalOnly = (attachment: UblAttachment): boolean =>\n\tattachment.externalUri !== undefined && attachment.base64Content === undefined;\n\nconst validateAttachment = (attachment: UblAttachment, index: number): void => {\n\tif (isExternalOnly(attachment)) return;\n\tconst path = `attachments[${index}]`;\n\trequired(attachment.filename, \"attachment filename (BT-125-2)\", `${path}.filename`);\n\trequired(\n\t\tattachment.mimeCode,\n\t\t\"attachment MIME code (BT-125-1)\",\n\t\t`${path}.mimeCode`,\n\t);\n\trequired(\n\t\tattachment.base64Content,\n\t\t\"attachment content (BT-125)\",\n\t\t`${path}.base64Content`,\n\t);\n};\n\n/** UNCL4461 codes whose payment means need a mandate (direct debit) or an account (credit transfer). */\nconst DIRECT_DEBIT_CODES = new Set([\"49\", \"59\"]);\nconst CREDIT_TRANSFER_CODES = new Set([\"30\", \"58\"]);\n\nconst validatePaymentMeans = (means: UblPaymentMeans, index: number): void => {\n\tconst path = `paymentMeansList[${index}]`;\n\tconst code = required(means.code, \"payment means code (BT-81)\", `${path}.code`);\n\tif (CREDIT_TRANSFER_CODES.has(code)) {\n\t\trequired(\n\t\t\tmeans.iban,\n\t\t\t`payment account (BT-84) for code ${code}`,\n\t\t\t`${path}.iban`,\n\t\t);\n\t}\n\tif (DIRECT_DEBIT_CODES.has(code)) {\n\t\trequired(\n\t\t\tmeans.mandateId,\n\t\t\t`mandate reference (BT-89) for code ${code}`,\n\t\t\t`${path}.mandateId`,\n\t\t);\n\t}\n};\n\nconst validateParty = (party: UblParty, role: string, nameBt: string): void => {\n\trequired(party.name, `${role} name (${nameBt})`, `${role}.name`);\n\tif (party.endpoint && party.endpoint.scheme === undefined) {\n\t\tthrow missing(`${role} endpoint scheme`, `${role}.endpoint.scheme`);\n\t}\n};\n\nconst paymentMeansList = (doc: UblInvoice): UblPaymentMeans[] =>\n\tdoc.paymentMeansList ?? (doc.paymentMeans ? [doc.paymentMeans] : []);\n\nconst sumBy = <T>(items: T[], pick: (item: T) => number): number =>\n\tround2(items.reduce((sum, item) => sum + pick(item), 0));\n\nconst categoryKey = (category: UblTaxCategory | undefined): string =>\n\t`${category?.id ?? \"\"}:${category?.percent ?? \"\"}`;\n\n/**\n * The document arithmetic EN 16931 fixes: BR-CO-10 (line sum), BR-CO-11/12\n * (allowance and charge sums), BR-CO-13 (total without VAT), BR-CO-15 (total\n * with VAT), BR-CO-16 (amount due) and the BR-S-08 family (each VAT category's\n * taxable amount is its line nets minus its allowances plus its charges).\n */\nconst validateArithmetic = (doc: UblInvoice): void => {\n\tconst total = doc.monetaryTotal;\n\tconst docItems = doc.allowanceCharges ?? [];\n\tconst allowances = docItems.filter((item) => !item.chargeIndicator);\n\tconst charges = docItems.filter((item) => item.chargeIndicator);\n\tconst lineSum = sumBy(doc.lines, (line) => line.lineExtensionAmount ?? 0);\n\tconst allowanceSum = sumBy(allowances, (item) => item.amount ?? 0);\n\tconst chargeSum = sumBy(charges, (item) => item.amount ?? 0);\n\n\tassertEqual(\n\t\t\"BR-CO-10\",\n\t\ttotal.lineExtensionAmount ?? 0,\n\t\tlineSum,\n\t\t\"monetaryTotal.lineExtensionAmount\",\n\t);\n\tif (allowances.length > 0 || total.allowanceTotalAmount !== undefined) {\n\t\tassertEqual(\n\t\t\t\"BR-CO-11\",\n\t\t\ttotal.allowanceTotalAmount ?? 0,\n\t\t\tallowanceSum,\n\t\t\t\"monetaryTotal.allowanceTotalAmount\",\n\t\t);\n\t}\n\tif (charges.length > 0 || total.chargeTotalAmount !== undefined) {\n\t\tassertEqual(\n\t\t\t\"BR-CO-12\",\n\t\t\ttotal.chargeTotalAmount ?? 0,\n\t\t\tchargeSum,\n\t\t\t\"monetaryTotal.chargeTotalAmount\",\n\t\t);\n\t}\n\tassertEqual(\n\t\t\"BR-CO-13\",\n\t\ttotal.taxExclusiveAmount ?? 0,\n\t\tround2(lineSum - allowanceSum + chargeSum),\n\t\t\"monetaryTotal.taxExclusiveAmount\",\n\t);\n\tassertEqual(\n\t\t\"BR-CO-15\",\n\t\ttotal.taxInclusiveAmount ?? 0,\n\t\tround2((total.taxExclusiveAmount ?? 0) + (doc.taxTotal.taxAmount ?? 0)),\n\t\t\"monetaryTotal.taxInclusiveAmount\",\n\t);\n\tassertEqual(\n\t\t\"BR-CO-16\",\n\t\ttotal.payableAmount ?? 0,\n\t\tround2(\n\t\t\t(total.taxInclusiveAmount ?? 0) -\n\t\t\t\t(total.prepaidAmount ?? 0) +\n\t\t\t\t(total.payableRoundingAmount ?? 0),\n\t\t),\n\t\t\"monetaryTotal.payableAmount\",\n\t);\n\n\tconst taxableByCategory = new Map<string, number>();\n\tconst add = (category: UblTaxCategory | undefined, amount: number): void => {\n\t\tconst key = categoryKey(category);\n\t\ttaxableByCategory.set(key, round2((taxableByCategory.get(key) ?? 0) + amount));\n\t};\n\tfor (const line of doc.lines) add(line.taxCategory, line.lineExtensionAmount ?? 0);\n\tfor (const item of docItems) {\n\t\tadd(\n\t\t\titem.taxCategory,\n\t\t\titem.chargeIndicator ? (item.amount ?? 0) : -(item.amount ?? 0),\n\t\t);\n\t}\n\tdoc.taxTotal.subtotals.forEach((subtotal, index) => {\n\t\tconst key = categoryKey(subtotal.category);\n\t\tconst expected = taxableByCategory.get(key);\n\t\tif (expected === undefined) {\n\t\t\tthrow new UblBuildError(\n\t\t\t\t`BR-S-08: taxTotal.subtotals[${index}] (${key}) has no line, allowance or charge in that category`,\n\t\t\t);\n\t\t}\n\t\tassertEqual(\n\t\t\t\"BR-S-08\",\n\t\t\tsubtotal.taxableAmount ?? 0,\n\t\t\texpected,\n\t\t\t`taxTotal.subtotals[${index}].taxableAmount`,\n\t\t);\n\t});\n};\n\nconst validateInvoice = (doc: UblInvoice): void => {\n\trequired(doc.id, \"document identifier (BT-1)\", \"id\");\n\trequired(doc.issueDate, \"issue date (BT-2)\", \"issueDate\");\n\trequired(doc.currency, \"document currency (BT-5)\", \"currency\");\n\tif (\n\t\tdoc.taxPointDate !== undefined &&\n\t\tdoc.invoicePeriod?.descriptionCode !== undefined\n\t) {\n\t\tthrow new UblBuildError(\n\t\t\t\"BR-CO-3: a tax point date (BT-7, taxPointDate) and a tax point date code (BT-8, invoicePeriod.descriptionCode) are mutually exclusive\",\n\t\t);\n\t}\n\tif (doc.taxCurrency !== undefined) {\n\t\trequired(\n\t\t\tdoc.taxTotal.taxAmountInTaxCurrency,\n\t\t\t\"VAT total in the accounting currency (BT-111, BR-53)\",\n\t\t\t\"taxTotal.taxAmountInTaxCurrency\",\n\t\t);\n\t}\n\tvalidateParty(doc.seller, \"seller\", \"BT-27\");\n\tvalidateParty(doc.buyer, \"buyer\", \"BT-44\");\n\tif (doc.payee) required(doc.payee.name, \"payee name (BT-59)\", \"payee.name\");\n\tif (doc.taxRepresentative) {\n\t\trequired(\n\t\t\tdoc.taxRepresentative.name,\n\t\t\t\"tax representative name (BT-62)\",\n\t\t\t\"taxRepresentative.name\",\n\t\t);\n\t\trequired(\n\t\t\tdoc.taxRepresentative.vatId,\n\t\t\t\"tax representative VAT identifier (BT-63)\",\n\t\t\t\"taxRepresentative.vatId\",\n\t\t);\n\t\trequired(\n\t\t\tdoc.taxRepresentative.address?.countryCode,\n\t\t\t\"tax representative country (BT-69)\",\n\t\t\t\"taxRepresentative.address.countryCode\",\n\t\t);\n\t}\n\tif (doc.lines.length === 0) {\n\t\tthrow new UblBuildError(\"A document needs at least one line (BG-25, lines)\");\n\t}\n\tdoc.lines.forEach(validateLine);\n\t(doc.allowanceCharges ?? []).forEach((item, index) =>\n\t\tvalidateAllowanceCharge(item, `allowanceCharges[${index}]`, \"document\"),\n\t);\n\tpaymentMeansList(doc).forEach(validatePaymentMeans);\n\trequired(doc.taxTotal.taxAmount, \"total VAT amount (BT-110)\", \"taxTotal.taxAmount\");\n\tconst total = doc.monetaryTotal;\n\trequired(\n\t\ttotal.lineExtensionAmount,\n\t\t\"sum of line net amounts (BT-106)\",\n\t\t\"monetaryTotal.lineExtensionAmount\",\n\t);\n\trequired(\n\t\ttotal.taxExclusiveAmount,\n\t\t\"total without VAT (BT-109)\",\n\t\t\"monetaryTotal.taxExclusiveAmount\",\n\t);\n\trequired(\n\t\ttotal.taxInclusiveAmount,\n\t\t\"total with VAT (BT-112)\",\n\t\t\"monetaryTotal.taxInclusiveAmount\",\n\t);\n\trequired(total.payableAmount, \"amount due (BT-115)\", \"monetaryTotal.payableAmount\");\n\t(doc.attachments ?? []).forEach(validateAttachment);\n\tvalidateArithmetic(doc);\n};\n\n// ── Formatting ─────────────────────────────────────────────────────────\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 optionalMoney = (\n\tname: string,\n\tvalue: number | undefined,\n\tcurrency: string,\n): XmlElement | null => (value !== undefined ? money(name, value, currency) : null);\n\nconst text = (name: string, value: string | undefined): XmlElement | null =>\n\tvalue !== undefined ? el(name, null, value) : null;\n\nconst schemedId = (name: string, id: UblSchemedId | undefined): XmlElement | null =>\n\tid !== undefined\n\t\t? el(name, id.scheme !== undefined ? { schemeID: id.scheme } : null, id.value)\n\t\t: null;\n\nconst taxScheme = (schemeId: string | undefined): XmlElement =>\n\tel(\"cac:TaxScheme\", null, [el(\"cbc:ID\", null, schemeId ?? 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 and on document allowances and\n * charges). EN 16931 requires an exemption reason for the non-charging\n * categories (E/AE/O/K/G); the code precedes the text in the sequence.\n */\nconst taxCategory = (\n\tname: string,\n\tcategory: UblTaxCategory,\n\tpath: string,\n): XmlElement => {\n\tconst valid = validateTaxCategory(category, path);\n\treturn el(name, null, [\n\t\tel(\"cbc:ID\", null, valid.id),\n\t\tvalid.percent !== undefined\n\t\t\t? el(\"cbc:Percent\", null, percent(valid.percent))\n\t\t\t: null,\n\t\ttext(\"cbc:TaxExemptionReasonCode\", valid.exemptionReasonCode),\n\t\ttext(\"cbc:TaxExemptionReason\", valid.exemptionReason),\n\t\ttaxScheme(valid.schemeId),\n\t]);\n};\n\nconst addressChildren = (address: UblAddress): (XmlElement | null)[] => [\n\ttext(\"cbc:StreetName\", address.street),\n\ttext(\"cbc:AdditionalStreetName\", address.additionalStreet),\n\ttext(\"cbc:CityName\", address.city),\n\ttext(\"cbc:PostalZone\", address.postalZone),\n\ttext(\"cbc:CountrySubentity\", address.countrySubentity),\n\taddress.countryCode !== undefined\n\t\t? el(\"cac:Country\", null, [\n\t\t\t\tel(\n\t\t\t\t\t\"cbc:IdentificationCode\",\n\t\t\t\t\t{ listID: COUNTRY_CODE_LIST_ID },\n\t\t\t\t\taddress.countryCode,\n\t\t\t\t),\n\t\t\t])\n\t\t: null,\n];\n\nconst postalAddress = (address: UblAddress): XmlElement =>\n\tel(\"cac:PostalAddress\", null, addressChildren(address));\n\nconst partyIdentifications = (source: UblParty): XmlElement[] =>\n\t(source.partyIdentifications ?? []).map((identification) =>\n\t\tel(\"cac:PartyIdentification\", null, [\n\t\t\tel(\n\t\t\t\t\"cbc:ID\",\n\t\t\t\tidentification.schemeId !== undefined\n\t\t\t\t\t? { schemeID: identification.schemeId }\n\t\t\t\t\t: null,\n\t\t\t\tidentification.id,\n\t\t\t),\n\t\t]),\n\t);\n\nconst partyName = (name: string): XmlElement =>\n\tel(\"cac:PartyName\", null, [el(\"cbc:Name\", null, name)]);\n\nconst partyTaxScheme = (source: UblParty): XmlElement | null =>\n\tsource.vatId !== undefined\n\t\t? el(\"cac:PartyTaxScheme\", null, [\n\t\t\t\tel(\"cbc:CompanyID\", null, source.vatId),\n\t\t\t\ttaxScheme(source.taxSchemeId),\n\t\t\t])\n\t\t: null;\n\nconst companyId = (source: UblParty): XmlElement | null =>\n\tsource.companyId\n\t\t? el(\n\t\t\t\t\"cbc:CompanyID\",\n\t\t\t\tsource.companyId.scheme !== undefined\n\t\t\t\t\t? { schemeID: source.companyId.scheme }\n\t\t\t\t\t: null,\n\t\t\t\tsource.companyId.value,\n\t\t\t)\n\t\t: null;\n\nconst contact = (source: UblParty): XmlElement | null =>\n\tsource.contact\n\t\t? el(\"cac:Contact\", null, [\n\t\t\t\ttext(\"cbc:Name\", source.contact.name),\n\t\t\t\ttext(\"cbc:Telephone\", source.contact.phone),\n\t\t\t\ttext(\"cbc:ElectronicMail\", source.contact.email),\n\t\t\t])\n\t\t: null;\n\n/** `cac:Party` for the seller and buyer (BG-4, BG-7). */\nconst party = (source: UblParty, name: string): 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\t...partyIdentifications(source),\n\t\tpartyName(name),\n\t\tsource.address ? postalAddress(source.address) : null,\n\t\tpartyTaxScheme(source),\n\t\tel(\"cac:PartyLegalEntity\", null, [\n\t\t\tel(\"cbc:RegistrationName\", null, source.registrationName ?? name),\n\t\t\tcompanyId(source),\n\t\t\ttext(\"cbc:CompanyLegalForm\", source.companyLegalForm),\n\t\t]),\n\t\tcontact(source),\n\t]);\n\n/** `cac:PayeeParty` (BG-10): identification, name and legal entity id, unwrapped. */\nconst payeeParty = (source: UblParty): XmlElement =>\n\tel(\"cac:PayeeParty\", null, [\n\t\t...partyIdentifications(source),\n\t\tpartyName(source.name ?? \"\"),\n\t\tsource.companyId ? el(\"cac:PartyLegalEntity\", null, [companyId(source)]) : null,\n\t]);\n\n/** `cac:TaxRepresentativeParty` (BG-11): name, address and VAT id, unwrapped. */\nconst taxRepresentativeParty = (source: UblParty): XmlElement =>\n\tel(\"cac:TaxRepresentativeParty\", null, [\n\t\tpartyName(source.name ?? \"\"),\n\t\tsource.address ? postalAddress(source.address) : null,\n\t\tpartyTaxScheme(source),\n\t]);\n\n/** `cac:Delivery` (BG-13). */\nconst delivery = (source: UblDelivery): XmlElement | null => {\n\tconst location =\n\t\tsource.locationId !== undefined || source.address !== undefined\n\t\t\t? el(\"cac:DeliveryLocation\", null, [\n\t\t\t\t\tschemedId(\"cbc:ID\", source.locationId),\n\t\t\t\t\tsource.address\n\t\t\t\t\t\t? el(\"cac:Address\", null, addressChildren(source.address))\n\t\t\t\t\t\t: null,\n\t\t\t\t])\n\t\t\t: null;\n\tconst deliveryParty =\n\t\tsource.partyName !== undefined\n\t\t\t? el(\"cac:DeliveryParty\", null, [partyName(source.partyName)])\n\t\t\t: null;\n\tif (source.actualDeliveryDate === undefined && !location && !deliveryParty)\n\t\treturn null;\n\treturn el(\"cac:Delivery\", null, [\n\t\ttext(\"cbc:ActualDeliveryDate\", source.actualDeliveryDate),\n\t\tlocation,\n\t\tdeliveryParty,\n\t]);\n};\n\n/**\n * `cac:PaymentMeans` (BG-16). On a credit note BT-9 has no root element and\n * rides in the first payment means as `cbc:PaymentDueDate`. `cbc:NetworkID`\n * is schema-mandatory inside `cac:CardAccount` and carries no business term;\n * the BIS example value is `NA`.\n */\nconst paymentMeans = (\n\tsource: UblPaymentMeans,\n\tdueDate: string | undefined,\n): XmlElement =>\n\tel(\"cac:PaymentMeans\", null, [\n\t\tel(\n\t\t\t\"cbc:PaymentMeansCode\",\n\t\t\tsource.codeName !== undefined ? { name: source.codeName } : null,\n\t\t\tsource.code ?? \"\",\n\t\t),\n\t\ttext(\"cbc:PaymentDueDate\", dueDate),\n\t\ttext(\"cbc:PaymentID\", source.paymentId),\n\t\tsource.cardNumber !== undefined\n\t\t\t? el(\"cac:CardAccount\", null, [\n\t\t\t\t\tel(\"cbc:PrimaryAccountNumberID\", null, source.cardNumber),\n\t\t\t\t\tel(\"cbc:NetworkID\", null, \"NA\"),\n\t\t\t\t\ttext(\"cbc:HolderName\", source.cardHolder),\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.iban !== undefined\n\t\t\t? el(\"cac:PayeeFinancialAccount\", null, [\n\t\t\t\t\tel(\"cbc:ID\", null, source.iban),\n\t\t\t\t\ttext(\"cbc:Name\", source.accountName),\n\t\t\t\t\tsource.bic !== undefined\n\t\t\t\t\t\t? el(\"cac:FinancialInstitutionBranch\", null, [\n\t\t\t\t\t\t\t\tel(\"cbc:ID\", null, source.bic),\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t: null,\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.mandateId !== undefined\n\t\t\t? el(\"cac:PaymentMandate\", null, [\n\t\t\t\t\tel(\"cbc:ID\", null, source.mandateId),\n\t\t\t\t\tsource.debitedAccount !== undefined\n\t\t\t\t\t\t? el(\"cac:PayerFinancialAccount\", null, [\n\t\t\t\t\t\t\t\tel(\"cbc:ID\", null, source.debitedAccount),\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t: null,\n\t\t\t\t])\n\t\t\t: null,\n\t]);\n\n/**\n * `cac:AllowanceCharge` at document level (BG-20/BG-21, with its VAT\n * category) and line level (BG-27/BG-28, without: the line's category\n * applies).\n */\nconst allowanceCharge = (\n\titem: UblAllowanceCharge,\n\tcurrency: string,\n\tpath: string,\n\tlevel: \"document\" | \"line\",\n): XmlElement =>\n\tel(\"cac:AllowanceCharge\", null, [\n\t\tel(\"cbc:ChargeIndicator\", null, item.chargeIndicator ? \"true\" : \"false\"),\n\t\ttext(\"cbc:AllowanceChargeReasonCode\", item.reasonCode),\n\t\ttext(\"cbc:AllowanceChargeReason\", item.reason),\n\t\titem.multiplierFactorNumeric !== undefined\n\t\t\t? el(\n\t\t\t\t\t\"cbc:MultiplierFactorNumeric\",\n\t\t\t\t\tnull,\n\t\t\t\t\tpercent(item.multiplierFactorNumeric),\n\t\t\t\t)\n\t\t\t: null,\n\t\tmoney(\"cbc:Amount\", item.amount ?? 0, currency),\n\t\toptionalMoney(\"cbc:BaseAmount\", item.baseAmount, currency),\n\t\tlevel === \"document\"\n\t\t\t? taxCategory(\n\t\t\t\t\t\"cac:TaxCategory\",\n\t\t\t\t\titem.taxCategory ?? {},\n\t\t\t\t\t`${path}.taxCategory`,\n\t\t\t\t)\n\t\t\t: null,\n\t]);\n\nconst taxSubtotal = (\n\tsubtotal: UblTaxSubtotal,\n\tcurrency: string,\n\tindex: number,\n): XmlElement => {\n\tconst path = `taxTotal.subtotals[${index}]`;\n\treturn el(\"cac:TaxSubtotal\", null, [\n\t\tmoney(\n\t\t\t\"cbc:TaxableAmount\",\n\t\t\trequired(\n\t\t\t\tsubtotal.taxableAmount,\n\t\t\t\t\"taxable amount (BT-116)\",\n\t\t\t\t`${path}.taxableAmount`,\n\t\t\t),\n\t\t\tcurrency,\n\t\t),\n\t\tmoney(\n\t\t\t\"cbc:TaxAmount\",\n\t\t\trequired(subtotal.taxAmount, \"VAT amount (BT-117)\", `${path}.taxAmount`),\n\t\t\tcurrency,\n\t\t),\n\t\ttaxCategory(\n\t\t\t\"cac:TaxCategory\",\n\t\t\trequired(subtotal.category, \"VAT category (BT-118)\", `${path}.category`),\n\t\t\t`${path}.category`,\n\t\t),\n\t]);\n};\n\n/**\n * `cac:LegalMonetaryTotal` children, in UBL sequence order. BT-107/BT-108 are\n * written when the document carries allowances or charges; BT-113 and BT-114\n * are omitted when absent or zero.\n */\nconst legalMonetaryTotalChildren = (doc: UblInvoice): XmlElement[] => {\n\tconst { currency, monetaryTotal: total } = doc;\n\tconst hasAllowances = (doc.allowanceCharges ?? []).some(\n\t\t(item) => !item.chargeIndicator,\n\t);\n\tconst hasCharges = (doc.allowanceCharges ?? []).some(\n\t\t(item) => item.chargeIndicator,\n\t);\n\tconst children: (XmlElement | null)[] = [\n\t\tmoney(\"cbc:LineExtensionAmount\", total.lineExtensionAmount ?? 0, currency),\n\t\tmoney(\"cbc:TaxExclusiveAmount\", total.taxExclusiveAmount ?? 0, currency),\n\t\tmoney(\"cbc:TaxInclusiveAmount\", total.taxInclusiveAmount ?? 0, currency),\n\t\thasAllowances || total.allowanceTotalAmount\n\t\t\t? money(\n\t\t\t\t\t\"cbc:AllowanceTotalAmount\",\n\t\t\t\t\ttotal.allowanceTotalAmount ?? 0,\n\t\t\t\t\tcurrency,\n\t\t\t\t)\n\t\t\t: null,\n\t\thasCharges || total.chargeTotalAmount\n\t\t\t? money(\"cbc:ChargeTotalAmount\", total.chargeTotalAmount ?? 0, currency)\n\t\t\t: null,\n\t\ttotal.prepaidAmount\n\t\t\t? money(\"cbc:PrepaidAmount\", total.prepaidAmount, currency)\n\t\t\t: null,\n\t\ttotal.payableRoundingAmount\n\t\t\t? money(\"cbc:PayableRoundingAmount\", total.payableRoundingAmount, currency)\n\t\t\t: null,\n\t\tmoney(\"cbc:PayableAmount\", total.payableAmount ?? 0, currency),\n\t];\n\treturn children.filter((child): child is XmlElement => Boolean(child));\n};\n\n/**\n * `cac:InvoicePeriod`. Null when neither bound is set — an empty period element\n * fails BR-CO-19, which requires at least one of the two dates. BT-8 (the tax\n * point date code) is only meaningful on the document period.\n */\nconst invoicePeriod = (period: UblInvoicePeriod | undefined): XmlElement | null => {\n\tif (!period || (period.startDate === undefined && period.endDate === undefined)) {\n\t\treturn null;\n\t}\n\treturn el(\"cac:InvoicePeriod\", null, [\n\t\ttext(\"cbc:StartDate\", period.startDate),\n\t\ttext(\"cbc:EndDate\", period.endDate),\n\t\ttext(\"cbc:DescriptionCode\", period.descriptionCode),\n\t]);\n};\n\nconst item = (source: UblLine): XmlElement =>\n\tel(\"cac:Item\", null, [\n\t\ttext(\"cbc:Description\", source.description),\n\t\t// BT-153 is mandatory; BT-154 stands in when the line has no name.\n\t\tel(\"cbc:Name\", null, source.itemName ?? source.description ?? source.id),\n\t\tsource.buyersItemId !== undefined\n\t\t\t? el(\"cac:BuyersItemIdentification\", null, [\n\t\t\t\t\tel(\"cbc:ID\", null, source.buyersItemId),\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.sellersItemId !== undefined\n\t\t\t? el(\"cac:SellersItemIdentification\", null, [\n\t\t\t\t\tel(\"cbc:ID\", null, source.sellersItemId),\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.standardItemId !== undefined\n\t\t\t? el(\"cac:StandardItemIdentification\", null, [\n\t\t\t\t\tschemedId(\"cbc:ID\", source.standardItemId),\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.originCountryCode !== undefined\n\t\t\t? el(\"cac:OriginCountry\", null, [\n\t\t\t\t\tel(\"cbc:IdentificationCode\", null, source.originCountryCode),\n\t\t\t\t])\n\t\t\t: null,\n\t\t...(source.commodityClassifications ?? []).map((classification) =>\n\t\t\tel(\"cac:CommodityClassification\", null, [\n\t\t\t\tel(\n\t\t\t\t\t\"cbc:ItemClassificationCode\",\n\t\t\t\t\t{\n\t\t\t\t\t\tlistID: classification.listId,\n\t\t\t\t\t\tlistVersionID: classification.listVersionId,\n\t\t\t\t\t},\n\t\t\t\t\tclassification.value,\n\t\t\t\t),\n\t\t\t]),\n\t\t),\n\t\ttaxCategory(\n\t\t\t\"cac:ClassifiedTaxCategory\",\n\t\t\tsource.taxCategory ?? {},\n\t\t\t`lines[${source.id}].taxCategory`,\n\t\t),\n\t\t...(source.additionalItemProperties ?? []).map((property) =>\n\t\t\tel(\"cac:AdditionalItemProperty\", null, [\n\t\t\t\tel(\"cbc:Name\", null, property.name),\n\t\t\t\tel(\"cbc:Value\", null, property.value ?? \"\"),\n\t\t\t]),\n\t\t),\n\t]);\n\nconst line = (\n\tsource: UblLine,\n\tcurrency: string,\n\tdocumentType: UblInvoice[\"documentType\"],\n): XmlElement => {\n\tconst isCreditNote = documentType === \"CreditNote\";\n\tconst lineElementName = isCreditNote ? \"cac:CreditNoteLine\" : \"cac:InvoiceLine\";\n\tconst quantityElementName = isCreditNote\n\t\t? \"cbc:CreditedQuantity\"\n\t\t: \"cbc:InvoicedQuantity\";\n\tconst unitCode = source.unitCode ?? \"\";\n\t// BT-146 covers BT-149 units; the model holds the per-unit price.\n\tconst priceAmount = (source.unitPrice ?? 0) * (source.baseQuantity ?? 1);\n\n\treturn el(lineElementName, null, [\n\t\tel(\"cbc:ID\", null, source.id),\n\t\ttext(\"cbc:Note\", source.note),\n\t\tel(quantityElementName, { unitCode }, String(source.quantity ?? 0)),\n\t\tmoney(\"cbc:LineExtensionAmount\", source.lineExtensionAmount ?? 0, currency),\n\t\ttext(\"cbc:AccountingCost\", source.accountingCost),\n\t\tinvoicePeriod(source.invoicePeriod),\n\t\tsource.orderLineReference !== undefined\n\t\t\t? el(\"cac:OrderLineReference\", null, [\n\t\t\t\t\tel(\"cbc:LineID\", null, source.orderLineReference),\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.objectIdentifier !== undefined\n\t\t\t? el(\"cac:DocumentReference\", null, [\n\t\t\t\t\tschemedId(\"cbc:ID\", source.objectIdentifier),\n\t\t\t\t\tel(\"cbc:DocumentTypeCode\", null, \"130\"),\n\t\t\t\t])\n\t\t\t: null,\n\t\t...(source.allowanceCharges ?? []).map((entry, index) =>\n\t\t\tallowanceCharge(\n\t\t\t\tentry,\n\t\t\t\tcurrency,\n\t\t\t\t`lines[${source.id}].allowanceCharges[${index}]`,\n\t\t\t\t\"line\",\n\t\t\t),\n\t\t),\n\t\titem(source),\n\t\t// BT-149's unit code must match the invoiced/credited quantity's\n\t\t// (PEPPOL-EN16931-R130).\n\t\tel(\"cac:Price\", null, [\n\t\t\tmoney(\"cbc:PriceAmount\", priceAmount, currency),\n\t\t\tsource.baseQuantity !== undefined\n\t\t\t\t? el(\"cbc:BaseQuantity\", { unitCode }, String(source.baseQuantity))\n\t\t\t\t: null,\n\t\t\tsource.priceAllowance !== undefined\n\t\t\t\t? el(\"cac:AllowanceCharge\", null, [\n\t\t\t\t\t\tel(\"cbc:ChargeIndicator\", null, \"false\"),\n\t\t\t\t\t\tmoney(\n\t\t\t\t\t\t\t\"cbc:Amount\",\n\t\t\t\t\t\t\tsource.priceAllowance.amount ?? 0,\n\t\t\t\t\t\t\tcurrency,\n\t\t\t\t\t\t),\n\t\t\t\t\t\toptionalMoney(\n\t\t\t\t\t\t\t\"cbc:BaseAmount\",\n\t\t\t\t\t\t\tsource.priceAllowance.baseAmount,\n\t\t\t\t\t\t\tcurrency,\n\t\t\t\t\t\t),\n\t\t\t\t\t])\n\t\t\t\t: null,\n\t\t]),\n\t]);\n};\n\nconst attachmentReference = (attachment: UblAttachment): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tel(\n\t\t\t\"cbc:ID\",\n\t\t\tnull,\n\t\t\tattachment.id ?? attachment.filename ?? attachment.externalUri ?? \"\",\n\t\t),\n\t\ttext(\"cbc:DocumentDescription\", attachment.description),\n\t\tel(\"cac:Attachment\", null, [\n\t\t\tisExternalOnly(attachment)\n\t\t\t\t? el(\"cac:ExternalReference\", null, [\n\t\t\t\t\t\tel(\"cbc:URI\", null, attachment.externalUri ?? \"\"),\n\t\t\t\t\t])\n\t\t\t\t: el(\n\t\t\t\t\t\t\"cbc:EmbeddedDocumentBinaryObject\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmimeCode: attachment.mimeCode ?? \"\",\n\t\t\t\t\t\t\tfilename: attachment.filename ?? \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tattachment.base64Content ?? \"\",\n\t\t\t\t\t),\n\t\t]),\n\t]);\n\n/** A typed `cac:AdditionalDocumentReference` without attachment (BT-17, BT-18, BT-11 on a credit note). */\nconst typedDocumentReference = (id: UblSchemedId, typeCode: string): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tschemedId(\"cbc:ID\", id),\n\t\tel(\"cbc:DocumentTypeCode\", null, typeCode),\n\t]);\n\nconst documentReference = (name: string, id: string | undefined): XmlElement | null =>\n\tid !== undefined ? el(name, null, [el(\"cbc:ID\", null, id)]) : null;\n\n/**\n * `cac:OrderReference`. BT-13 (the buyer's order number) is the element's\n * mandatory child, so a sales order id (BT-14) alone is not emitted.\n */\nconst orderReference = (doc: UblInvoice): XmlElement | null => {\n\tif (doc.orderReference === undefined) return null;\n\treturn el(\"cac:OrderReference\", null, [\n\t\tel(\"cbc:ID\", null, doc.orderReference),\n\t\ttext(\"cbc:SalesOrderID\", doc.salesOrderId),\n\t]);\n};\n\nconst billingReference = (reference: UblBillingReference): XmlElement | null => {\n\tif (reference.invoiceId === undefined) return null;\n\treturn el(\"cac:BillingReference\", null, [\n\t\tel(\"cac:InvoiceDocumentReference\", null, [\n\t\t\tel(\"cbc:ID\", null, reference.invoiceId),\n\t\t\ttext(\"cbc:IssueDate\", reference.invoiceIssueDate),\n\t\t]),\n\t]);\n};\n\n/**\n * Serialize a {@link UblInvoice} into a Peppol BIS Billing 3.0 XML string.\n *\n * Writes every EN 16931 business term the model holds, at its position in the\n * UBL 2.1 sequence: the header terms (`customizationId`, `profileId` and\n * `invoiceTypeCode` default to the BIS values), the references (BT-10 to\n * BT-19), the parties with identifications, legal form and contacts, the\n * payee and tax representative, delivery, payment means, payment terms,\n * document and line allowances and charges, the VAT breakdown (plus BT-111 in\n * the accounting currency), the monetary totals, attachments and document\n * references, and lines with their item identifiers, classifications,\n * properties, price discount and classified VAT category. Line-level tax\n * totals are not emitted: BIS Billing 3.0 forbids them.\n *\n * @throws {UblBuildError} when a field EN 16931 / Peppol BIS makes mandatory\n * is missing (naming the BT and the model path), or when the document's\n * arithmetic breaks a business rule: BR-CO-3, BR-CO-10 to BR-CO-13, BR-CO-15,\n * BR-CO-16, BR-53, the BR-S-08 family, PEPPOL-EN16931-R040 and R120.\n */\nexport const serializeUblInvoice = (doc: UblInvoice): string => {\n\tvalidateInvoice(doc);\n\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(\n\t\t\t\t\"cbc:CreditNoteTypeCode\",\n\t\t\t\tnull,\n\t\t\t\tdoc.invoiceTypeCode ?? CREDIT_NOTE_TYPE_CODE,\n\t\t\t)\n\t\t: el(\"cbc:InvoiceTypeCode\", null, doc.invoiceTypeCode ?? INVOICE_TYPE_CODE);\n\tconst taxPointDate = text(\"cbc:TaxPointDate\", doc.taxPointDate);\n\tconst means = paymentMeansList(doc);\n\t// A credit note has no cbc:DueDate: BT-9 goes in the first PaymentMeans.\n\tconst creditNoteDueDate =\n\t\tisCreditNote && means.length > 0 ? doc.dueDate : undefined;\n\n\tconst children: (XmlElement | null | false)[] = [\n\t\tel(\"cbc:CustomizationID\", null, doc.customizationId ?? UBL_CUSTOMIZATION_ID),\n\t\tel(\"cbc:ProfileID\", null, doc.profileId ?? UBL_PROFILE_ID),\n\t\tel(\"cbc:ID\", null, doc.id),\n\t\tel(\"cbc:IssueDate\", null, doc.issueDate),\n\t\t!isCreditNote ? text(\"cbc:DueDate\", doc.dueDate) : null,\n\t\t// The CreditNote sequence puts BT-7 before the type code, Invoice after the note.\n\t\tisCreditNote ? taxPointDate : null,\n\t\ttypeCodeElement,\n\t\ttext(\"cbc:Note\", doc.note),\n\t\t!isCreditNote ? taxPointDate : null,\n\t\tel(\"cbc:DocumentCurrencyCode\", null, doc.currency),\n\t\ttext(\"cbc:TaxCurrencyCode\", doc.taxCurrency),\n\t\ttext(\"cbc:AccountingCost\", doc.accountingCost),\n\t\ttext(\"cbc:BuyerReference\", doc.buyerReference),\n\t\tinvoicePeriod(doc.invoicePeriod),\n\t\torderReference(doc),\n\t\tdoc.billingReference ? billingReference(doc.billingReference) : null,\n\t\tdocumentReference(\"cac:DespatchDocumentReference\", doc.despatchReference),\n\t\tdocumentReference(\"cac:ReceiptDocumentReference\", doc.receivingAdviceReference),\n\t\tdocumentReference(\"cac:ContractDocumentReference\", doc.contractReference),\n\t\t...(doc.attachments ?? []).map(attachmentReference),\n\t\t...(doc.documentReferences ?? []).map((reference) =>\n\t\t\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\t\t\tel(\"cbc:ID\", null, reference.id ?? \"\"),\n\t\t\t\ttext(\"cbc:DocumentDescription\", reference.description),\n\t\t\t]),\n\t\t),\n\t\tdoc.invoicedObjectId !== undefined\n\t\t\t? typedDocumentReference(doc.invoicedObjectId, \"130\")\n\t\t\t: null,\n\t\t!isCreditNote && doc.tenderReference !== undefined\n\t\t\t? typedDocumentReference({ value: doc.tenderReference }, \"50\")\n\t\t\t: null,\n\t\t// UBL's CreditNote has no cac:ProjectReference; BIS uses type code 50.\n\t\tisCreditNote && doc.projectReference !== undefined\n\t\t\t? typedDocumentReference({ value: doc.projectReference }, \"50\")\n\t\t\t: null,\n\t\t!isCreditNote\n\t\t\t? documentReference(\"cac:ProjectReference\", doc.projectReference)\n\t\t\t: null,\n\t\tel(\"cac:AccountingSupplierParty\", null, [\n\t\t\tparty(doc.seller, doc.seller.name ?? \"\"),\n\t\t]),\n\t\tel(\"cac:AccountingCustomerParty\", null, [\n\t\t\tparty(doc.buyer, doc.buyer.name ?? \"\"),\n\t\t]),\n\t\tdoc.payee ? payeeParty(doc.payee) : null,\n\t\tdoc.taxRepresentative ? taxRepresentativeParty(doc.taxRepresentative) : null,\n\t\tdoc.delivery ? delivery(doc.delivery) : null,\n\t\t...means.map((entry, index) =>\n\t\t\tpaymentMeans(entry, index === 0 ? creditNoteDueDate : undefined),\n\t\t),\n\t\t// BT-20. In both sequences PaymentTerms sits after PaymentMeans and\n\t\t// before AllowanceCharge and TaxTotal.\n\t\tdoc.paymentTermsNote !== undefined\n\t\t\t? el(\"cac:PaymentTerms\", null, [el(\"cbc:Note\", null, doc.paymentTermsNote)])\n\t\t\t: null,\n\t\t...(doc.allowanceCharges ?? []).map((entry, index) =>\n\t\t\tallowanceCharge(\n\t\t\t\tentry,\n\t\t\t\tdoc.currency,\n\t\t\t\t`allowanceCharges[${index}]`,\n\t\t\t\t\"document\",\n\t\t\t),\n\t\t),\n\t\tel(\"cac:TaxTotal\", null, [\n\t\t\tmoney(\"cbc:TaxAmount\", doc.taxTotal.taxAmount ?? 0, doc.currency),\n\t\t\t...doc.taxTotal.subtotals.map((subtotal, index) =>\n\t\t\t\ttaxSubtotal(subtotal, doc.currency, index),\n\t\t\t),\n\t\t]),\n\t\t// BT-111: a second TaxTotal carrying only the VAT total in BT-6.\n\t\tdoc.taxCurrency !== undefined\n\t\t\t? el(\"cac:TaxTotal\", null, [\n\t\t\t\t\tmoney(\n\t\t\t\t\t\t\"cbc:TaxAmount\",\n\t\t\t\t\t\tdoc.taxTotal.taxAmountInTaxCurrency ?? 0,\n\t\t\t\t\t\tdoc.taxCurrency,\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t: null,\n\t\tel(\"cac:LegalMonetaryTotal\", null, legalMonetaryTotalChildren(doc)),\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\n/** Alias of {@link serializeUblInvoice}, kept under the historical name. */\nexport const serializeUblDocument = serializeUblInvoice;\n","/** Trim a string; `undefined` when missing or blank. */\nexport const normalizeString = (\n\tvalue: string | null | undefined,\n): string | undefined => {\n\tif (typeof value !== \"string\") return undefined;\n\tconst normalized = value.trim();\n\treturn normalized.length > 0 ? normalized : undefined;\n};\n\n/** Drop `undefined`-valued keys so an absent field is an absent key. */\nexport const compact = <T extends object>(value: T): T =>\n\tObject.fromEntries(\n\t\tObject.entries(value).filter(([, entry]) => entry !== undefined),\n\t) as T;\n","import type { UblAddress } from \"../types\";\nimport { compact, normalizeString } from \"./utils\";\n\nconst normalizeCountryCode = (value: string | null | undefined): string | undefined => {\n\tconst trimmed = normalizeString(value);\n\tif (!trimmed) return undefined;\n\treturn trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : undefined;\n};\n\n/**\n * A free-form postal address as accepted by {@link normalizeAddress}.\n *\n * Both the Stripe shape (`line1`, `postal_code`, `country`, `state`) and the\n * legacy/internal shape (`street`, `zip_code`, `country_code`,\n * `country_subentity`) are accepted; when both keys are present the Stripe\n * one wins.\n */\nexport interface AddressInput {\n\tline1?: string | null;\n\tline2?: string | null;\n\tstreet?: string | null;\n\tcity?: string | null;\n\tpostal_code?: string | null;\n\tzip_code?: string | null;\n\tstate?: string | null;\n\tcountry_subentity?: string | null;\n\tcountry?: string | null;\n\tcountry_code?: string | null;\n}\n\n/**\n * Normalize a free-form address (Stripe shape, custom shape, or an internal\n * shape) into a {@link UblAddress}. An absent part is an absent key.\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: AddressInput | null | undefined,\n\tfallbackCountryCode: string | null,\n\tfallbackLine?: string | null,\n): UblAddress => {\n\tconst record: AddressInput = address ?? {};\n\tconst countryCode =\n\t\tnormalizeCountryCode(normalizeString(record.country)) ??\n\t\tnormalizeCountryCode(normalizeString(record.country_code)) ??\n\t\tnormalizeCountryCode(fallbackCountryCode);\n\treturn compact({\n\t\tstreet:\n\t\t\tnormalizeString(record.line1) ??\n\t\t\tnormalizeString(record.street) ??\n\t\t\tnormalizeString(fallbackLine),\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 { getPeppolIdentifierSchemes } from \"@financica/peppol/countries\";\nimport {\n\tcountryFromVatNumber,\n\tnormalizeParticipantValue,\n} from \"@financica/peppol/identifiers\";\nimport type { UblCompanyId, UblEndpoint } from \"../types\";\nimport { compact, normalizeString } from \"./utils\";\n\nconst normalizeBelgianCompanyNumber = (value: string | null | undefined) => {\n\tif (!value) return \"\";\n\t// EAS 0208 (BE:EN) is 10 bare digits, so the printed dots are decoration.\n\treturn normalizeParticipantValue(\"0208\", 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 * Peppol/ISO 6523 ICD scheme for a legal registration number\n * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`), e.g. BE → `0208`\n * (enterprise number), NL → `0106` (KvK), FR → `0002` (SIRENE). The table is\n * `@financica/peppol`'s country profiles.\n *\n * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).\n * Returns `undefined` 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 | undefined => {\n\tconst companyNumber = normalizeString(params.companyNumber);\n\tif (!companyNumber) return undefined;\n\n\tconst fromCountry =\n\t\tgetPeppolIdentifierSchemes(params.countryCode)?.companyIdentifierScheme ??\n\t\tundefined;\n\tif (fromCountry) return fromCountry;\n\n\t// Only sniffing the country prefix, e.g. `BE0793904121` → `BE`.\n\tconst prefix = companyNumber\n\t\t.replace(/[^A-Za-z]/g, \"\")\n\t\t.toUpperCase()\n\t\t.slice(0, 2);\n\treturn getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? undefined;\n};\n\n/**\n * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the\n * country-appropriate ICD scheme when known. Returns `undefined` when there is no\n * company number.\n */\nexport const buildCompanyId = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): UblCompanyId | undefined => {\n\tconst normalized = normalizeString(\n\t\tnormalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),\n\t);\n\tif (!normalized) return undefined;\n\treturn compact({\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 * 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 scheme comes from `@financica/peppol`'s country resolution, so countries\n * that route on their registry number alone (Norway, Denmark) yield `undefined`\n * here — their VAT number is not a Peppol participant identifier.\n *\n * The value keeps its country prefix, matching how participants register (the\n * Peppol directory lists this party as `9925:be0206582284`). Returns `undefined`\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 | undefined;\n}): UblEndpoint | undefined => {\n\tconst value = normalizeString(params.vatNumber);\n\tif (!value) return undefined;\n\n\tconst fromPrefix = countryFromVatNumber(value);\n\tconst scheme =\n\t\tgetPeppolIdentifierSchemes(fromPrefix)?.vatIdentifierScheme ??\n\t\tgetPeppolIdentifierSchemes(params.countryCode)?.vatIdentifierScheme;\n\tif (!scheme) return undefined;\n\n\t// Every scheme in the table is a VAT scheme, whose value carries no\n\t// separator, so the printed dots/spaces are dropped.\n\tconst cleaned = normalizeParticipantValue(scheme, value).toUpperCase();\n\tif (!cleaned) return undefined;\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 * `undefined` 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 | undefined => {\n\tconst normalized = normalizeString(peppolId);\n\tif (!normalized) return undefined;\n\tconst separatorIndex = normalized.indexOf(\":\");\n\tif (separatorIndex <= 0) return undefined;\n\tconst scheme = normalized.slice(0, separatorIndex).trim();\n\tconst value = normalized.slice(separatorIndex + 1).trim();\n\tif (!scheme || !value) return undefined;\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\n/**\n * One customer tax identifier as stored by Stripe (`customer_tax_ids[]`) or an\n * equivalent `{type, value}` pair. `type` is a Stripe tax-ID type such as\n * `eu_vat`, or a custom type such as `peppol_id`; blank entries are skipped.\n */\nexport interface CustomerTaxIdInput {\n\ttype: string | null | undefined;\n\tvalue: string | null | undefined;\n}\n\nconst normalizeIdentifierType = (value: string | undefined) =>\n\tvalue?.toLowerCase().replace(/[^a-z0-9]+/g, \"_\");\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: readonly CustomerTaxIdInput[] | null | undefined,\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\tfor (const entry of taxIds ?? []) {\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\t// Any other typed id (ca_gst_hst, au_abn, us_ein, ...) is a registration\n\t\t// number: it goes to BT-30, not BT-31.\n\t\tif (!taxNumber) taxNumber = value;\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 * for Sweden, Norway and Denmark, whose VAT schemes were withdrawn, the\n * company number inside the VAT number (`0007`, `0192`, `0184`);\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: Partial<CustomerTaxIdentifiers>,\n\tcountryCode?: string | null,\n): string[] => {\n\tconst candidates: string[] = [];\n\tconst add = (id: { scheme?: string | undefined; value: string } | undefined) => {\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: normalizeParticipantValue(\"0088\", 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(\n\t\t\tbuildCompanyId({\n\t\t\t\tcountryCode: \"BE\",\n\t\t\t\tcompanyNumber: customer.vatNumber ?? null,\n\t\t\t}),\n\t\t);\n\t}\n\n\t// 4b. Sweden has no VAT scheme left (SE:VAT 9955 is withdrawn); a Swedish VAT\n\t// number is the organisationsnummer + `01`, registered under EAS 0007.\n\tconst compactVat = (customer.vatNumber ?? \"\")\n\t\t.replace(/[^A-Za-z0-9]/g, \"\")\n\t\t.toUpperCase();\n\tconst swedishOrgNumber = /^SE(\\d{10})01$/.exec(compactVat)?.[1];\n\tif (swedishOrgNumber) add({ scheme: \"0007\", value: swedishOrgNumber });\n\n\t// 4c. Norway likewise (NO:VAT 9909 is withdrawn): a Norwegian VAT number is\n\t// the organisasjonsnummer + `MVA`, registered under EAS 0192. Stripe's\n\t// `no_vat` type stores it without the `NO` prefix (`123456789MVA`), so the\n\t// prefix is optional, and a bare `…MVA` counts only for a Norwegian customer.\n\tconst norwegianOrgNumber = /^(NO)?(\\d{9})MVA$/.exec(compactVat);\n\tif (\n\t\tnorwegianOrgNumber?.[2] &&\n\t\t(norwegianOrgNumber[1] || countryCode?.toUpperCase() === \"NO\")\n\t) {\n\t\tadd({ scheme: \"0192\", value: norwegianOrgNumber[2] });\n\t}\n\n\t// 4d. Denmark (DK:VAT 9902 is withdrawn): the VAT number is `DK` + the CVR\n\t// number, registered under EAS 0184.\n\tconst danishCvr = /^DK(\\d{8})$/.exec(compactVat)?.[1];\n\tif (danishCvr) add({ scheme: \"0184\", value: danishCvr });\n\n\t// 5. A generic tax/registration number → its country's company-ID scheme.\n\tconst tax = normalizeString(customer.taxNumber);\n\tif (tax)\n\t\tadd(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));\n\n\treturn Array.from(new Set(candidates));\n};\n","import { type AddressInput, normalizeAddress } from \"./address\";\nimport { buildCompanyId, parsePeppolEndpoint, resolveVatEndpoint } from \"./identifiers\";\nimport type { UblAddress, UblEndpoint, UblParty } from \"../types\";\nimport { compact, 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 * - `subject` — subject to VAT (the normal case): line categories come from\n * the data.\n * - `not_subject` — not subject to VAT.\n * - `small_business` — small business / franchise exemption (e.g. Belgian\n * Article 56bis).\n *\n * For the last two, `coerceLinesForSupplierVatStatus` (tax-category.ts) turns\n * every line into a non-charging exempt category so no VAT is reported.\n * Providers that encode this numerically (Scrada: 1/2/3) map at their boundary.\n */\nexport type SupplierVatStatus = \"subject\" | \"not_subject\" | \"small_business\";\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: AddressInput | null;\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/**\n * A VAT identifier (BT-31 / BT-48) with its country prefix, which BR-CO-09\n * requires. Some stores keep it without one: Stripe's `no_vat` is\n * `123456789MVA`, so a Norwegian buyer's VAT number failed validation on\n * every invoice. A value that starts with a digit gets the party's own\n * country (Greece writes `EL`); a value that already has letters in front is\n * left as it is.\n */\nconst prefixedVatId = (\n\tvatNumber: string | null | undefined,\n\tcountryCode: string | null | undefined,\n): string | undefined => {\n\tconst vat = normalizeString(vatNumber);\n\tconst country = normalizeString(countryCode)?.toUpperCase();\n\tif (!vat || !country || !/^\\d/.test(vat)) return vat;\n\treturn `${country === \"GR\" ? \"EL\" : country}${vat}`;\n};\n\n/** Convert a {@link UblSupplier} into the seller party (`cac:AccountingSupplierParty`). */\nexport const buildSupplierParty = (supplier: UblSupplier): UblParty => {\n\tconst address = normalizeAddress(supplier.address, supplier.countryCode);\n\treturn compact({\n\t\tendpoint: parsePeppolEndpoint(supplier.peppolID),\n\t\tname: supplier.name,\n\t\tregistrationName: supplier.name,\n\t\taddress,\n\t\tvatId: prefixedVatId(supplier.vatNumber, supplier.countryCode),\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/**\n * Caller-provided customer (buyer) data, normalized into a stable shape.\n *\n * Each consumer (the Stripe adapter, app-specific row builders) resolves its\n * own identifiers and address, then hands this generic shape to\n * {@link buildCustomerParty}, so the Peppol routing logic lives in one place.\n */\nexport interface UblCustomer {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** Customer address, already normalized by the caller. */\n\taddress: UblAddress;\n\t/**\n\t * The customer's ISO 3166-1 alpha-2 country, used to resolve VAT/registration\n\t * schemes for identifiers that don't carry a country prefix. Pass the\n\t * customer's *own* country (never the supplier's) so the document is not\n\t * mis-routed; falls back to the address country when omitted.\n\t */\n\tcountryCode?: string | null;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n\t/** Global Location Number (resolved under EAS `0088`). */\n\tglnNumber?: string | null;\n\t/** Generic tax/registration number (no VAT prefix). */\n\ttaxNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n}\n\n/**\n * Convert a {@link UblCustomer} into the buyer party (`cac:AccountingCustomerParty`).\n *\n * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in\n * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered\n * identifier), then an explicit Peppol ID, then a GLN (scheme `0088`), then the\n * VAT number mapped to its country's VAT EAS scheme (e.g. BE → `9925`). That\n * last step matters because most data stores hold a customer's VAT without a\n * scheme, so without it a VAT-only customer would have no endpoint and the\n * document would be unroutable.\n */\nexport const buildCustomerParty = (\n\tcustomer: UblCustomer,\n\tendpointOverride?: UblEndpoint | null,\n): UblParty => {\n\tconst countryCode =\n\t\tnormalizeString(customer.countryCode) ?? customer.address.countryCode ?? null;\n\tconst endpoint =\n\t\tendpointOverride ??\n\t\tparsePeppolEndpoint(customer.peppolID) ??\n\t\t(customer.glnNumber\n\t\t\t? { scheme: \"0088\", value: customer.glnNumber }\n\t\t\t: undefined) ??\n\t\tresolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\n\treturn compact({\n\t\tendpoint,\n\t\tname: customer.name,\n\t\tregistrationName: customer.name,\n\t\taddress: customer.address,\n\t\tvatId: prefixedVatId(customer.vatNumber, countryCode),\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode,\n\t\t\tcompanyNumber: customer.taxNumber ?? null,\n\t\t}),\n\t});\n};\n","import type { UblAttachment, UblInvoice } from \"../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\tbase64Content: 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 UblInvoice} is safe to log or persist for audit.\n */\nexport const sanitizeUblDocumentForAudit = (doc: UblInvoice): UblInvoice => {\n\tif (!doc.attachments?.length) return doc;\n\treturn {\n\t\t...doc,\n\t\tattachments: doc.attachments.map((attachment) =>\n\t\t\tattachment.base64Content === undefined\n\t\t\t\t? attachment\n\t\t\t\t: {\n\t\t\t\t\t\t...attachment,\n\t\t\t\t\t\tbase64Content: `[omitted ${attachment.base64Content.length} chars]`,\n\t\t\t\t\t},\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\n/** The `cac:Price` pair for a line: the per-unit price and the optional BT-149. */\nexport interface UnitPrice {\n\t/** Net price of one unit (`UblLine.unitPrice`). */\n\tunitPrice: number;\n\t/**\n\t * `cbc:BaseQuantity` (BT-149) — set when the per-unit price is not exact in\n\t * cents; the serializer then emits `PriceAmount = unitPrice × baseQuantity`\n\t * (the line net). Omitted = 1.\n\t */\n\tbaseQuantity?: number | undefined;\n}\n\n/**\n * Derive the `cac:Price` for a line whose net total is authoritative.\n *\n * Peppol rule PEPPOL-EN16931-R120 checks\n * `quantity × (PriceAmount ÷ BaseQuantity)` against the line net amount within\n * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that\n * whenever the division doesn't land on a cent: 940.00 over 14 units gives\n * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and\n * rejected as a fatal validation error.\n *\n * So the cent-rounded unit price is only used when it reproduces the net\n * exactly. Otherwise the line is priced as a whole via BT-149: `unitPrice` is\n * the exact (unrounded) `net ÷ quantity` and `baseQuantity` = the quantity, so\n * the serializer writes `PriceAmount` = the net and `BaseQuantity` = the\n * quantity, which is exact at any magnitude instead of merely within tolerance\n * — the residual of a rounded unit price grows with quantity and would\n * eventually breach 0.02 at any fixed precision.\n */\nexport const deriveUnitPrice = (netTotal: number, quantity: number): UnitPrice => {\n\t// A zero or fractional-to-zero quantity still has to price something; BT-149\n\t// must be a positive number (PEPPOL-EN16931-R121), so floor the divisor at 1.\n\tconst units = quantity > 0 ? quantity : 1;\n\tconst perUnit = roundCurrency(netTotal / units);\n\tif (roundCurrency(perUnit * units) === roundCurrency(netTotal)) {\n\t\treturn { unitPrice: perUnit };\n\t}\n\treturn { unitPrice: roundCurrency(netTotal) / units, baseQuantity: units };\n};\n","import type { SupplierVatStatus } from \"./party\";\nimport type { UblLine, UblTaxCategory } from \"../types\";\nimport { normalizeString } from \"./utils\";\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\tintra_community: \"Intra-community supply\",\n\texport: \"Export outside the EU\",\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: string | null | undefined): string | undefined =>\n\tnormalizeString(value)?.toUpperCase();\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 * - Intra-community supply → `K` (0%, with exemption reason)\n * - Export outside the EU → `G` (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 === \"K\" || reason === \"intra_community\") {\n\t\treturn {\n\t\t\tid: \"K\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT[\"intra_community\"],\n\t\t};\n\t}\n\tif (categoryHint === \"G\" || reason === \"export\") {\n\t\treturn {\n\t\t\tid: \"G\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT[\"export\"],\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] : undefined) ??\n\t\t\t\t\"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 (\n\t\t\tta.taxability_reason === \"reverse_charge\" ||\n\t\t\tta.taxability_reason === \"zero_rated\" ||\n\t\t\tEXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)\n\t\t) {\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}\n\treturn taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });\n};\n\n/**\n * BT-120 text for a small-business/franchise exemption, by supplier country.\n * Countries without a specific legal reference fall back to the generic text.\n */\nconst SMALL_BUSINESS_EXEMPTION_REASON_BY_COUNTRY: Record<string, string> = {\n\tBE: \"Exempt — small business scheme (Article 56bis)\",\n};\nconst SMALL_BUSINESS_EXEMPTION_REASON = \"Exempt — small business scheme\";\nconst NOT_SUBJECT_EXEMPTION_REASON = \"Seller not subject to VAT\";\n\n/**\n * When the supplier does not charge VAT, coerce every line to a non-charging\n * exempt category (`E`, 0%) with the appropriate BT-120 reason, so the document\n * reports no VAT regardless of what the upstream line tax data implied. Lines\n * are returned untouched for a `subject` supplier.\n */\nexport const coerceLinesForSupplierVatStatus = (\n\tlines: UblLine[],\n\tvatStatus: SupplierVatStatus,\n\tsupplierCountryCode?: string | null,\n): UblLine[] => {\n\tif (vatStatus === \"subject\") return lines;\n\tconst country = normalizeString(supplierCountryCode)?.toUpperCase();\n\tconst exemptionReason =\n\t\tvatStatus === \"small_business\"\n\t\t\t? ((country && SMALL_BUSINESS_EXEMPTION_REASON_BY_COUNTRY[country]) ??\n\t\t\t\tSMALL_BUSINESS_EXEMPTION_REASON)\n\t\t\t: NOT_SUBJECT_EXEMPTION_REASON;\n\treturn lines.map((line) => ({\n\t\t...line,\n\t\ttaxCategory: { id: \"E\", percent: 0, exemptionReason },\n\t}));\n};\n","import { UblBuildError } from \"../errors\";\nimport type {\n\tUblAllowanceCharge,\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"../types\";\nimport { deriveUnitPrice, roundCurrency } from \"./numeric\";\nimport { compact } from \"./utils\";\n\nconst lineNet = (line: UblLine): number => line.lineExtensionAmount ?? 0;\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(lines.reduce((sum, line) => sum + lineNet(line), 0));\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\tlineNet(line) > lineNet(arr[maxIdx] ?? line) ? idx : 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(lineNet(line) + diff);\n\t\t// Re-derive the price from the adjusted net through the shared helper —\n\t\t// nudging the net without re-deriving BT-146/BT-149 to match is exactly\n\t\t// what PEPPOL-EN16931-R120 rejects. Assign `baseQuantity` unconditionally\n\t\t// so a line that no longer needs one doesn't keep a stale value.\n\t\t// The price may never be negative (BR-27): a net that ends up below zero\n\t\t// carries its sign on the quantity instead.\n\t\tconst units = Math.abs(line.quantity ?? 0);\n\t\tconst { unitPrice, baseQuantity } = deriveUnitPrice(Math.abs(adjusted), units);\n\t\treturn compact({\n\t\t\t...line,\n\t\t\tquantity:\n\t\t\t\tline.quantity === undefined ? undefined : adjusted < 0 ? -units : units,\n\t\t\tlineExtensionAmount: adjusted,\n\t\t\tunitPrice,\n\t\t\tbaseQuantity,\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\nexport interface BuildTaxTotalsOptions {\n\t/**\n\t * BT-113 — amount already paid, **gross (VAT-inclusive)**. Subtracted from\n\t * BT-112 to derive the outstanding `payableAmount` (BR-CO-16). Pass the full\n\t * gross total for a settled document so it reports a payable amount of 0.\n\t */\n\tprepaidAmount?: number;\n\t/** BT-114 — rounding applied to the payable amount. */\n\tpayableRoundingAmount?: number;\n\t/**\n\t * Document-level allowances and charges (BG-20/BG-21). Each one joins the\n\t * VAT breakdown of its own category (BR-S-08: taxable = line nets −\n\t * allowances + charges) and feeds BT-107/BT-108, so BT-109 is\n\t * BT-106 − BT-107 + BT-108 (BR-CO-13). Put the same array on the document.\n\t */\n\tallowanceCharges?: UblAllowanceCharge[];\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 *\n * `payableAmount` is derived per BR-CO-16 (`BT-112 − BT-113 + BT-114`) so the\n * invariant holds by construction. The result is *not* clamped: a prepayment\n * exceeding the total yields a negative payable amount, surfacing the upstream\n * overpayment rather than hiding it.\n *\n * @throws {UblBuildError} for a line, allowance or charge without a\n * `taxCategory` — there is no VAT breakdown to put it in.\n */\nexport const buildTaxTotals = (\n\tlines: UblLine[],\n\toptions?: BuildTaxTotalsOptions,\n): 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\tif (!line.taxCategory) {\n\t\t\tthrow new UblBuildError(\n\t\t\t\t`Line ${line.id} has no taxCategory (BT-151); cannot build the VAT breakdown`,\n\t\t\t);\n\t\t}\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(current.taxableAmount + lineNet(line));\n\t\tgroups.set(key, current);\n\t}\n\tconst allowanceCharges = options?.allowanceCharges ?? [];\n\tfor (const [index, item] of allowanceCharges.entries()) {\n\t\tif (!item.taxCategory) {\n\t\t\tthrow new UblBuildError(\n\t\t\t\t`allowanceCharges[${index}] has no taxCategory (BT-95/BT-102); cannot build the VAT breakdown`,\n\t\t\t);\n\t\t}\n\t\tconst key = categoryKey(item.taxCategory);\n\t\tconst current = groups.get(key) ?? {\n\t\t\tcategory: item.taxCategory,\n\t\t\ttaxableAmount: 0,\n\t\t};\n\t\tconst signed = item.chargeIndicator ? (item.amount ?? 0) : -(item.amount ?? 0);\n\t\tcurrent.taxableAmount = roundCurrency(current.taxableAmount + signed);\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(\n\t\t\t(group.taxableAmount * (group.category.percent ?? 0)) / 100,\n\t\t),\n\t\tcategory: group.category,\n\t}));\n\n\tconst lineExtensionAmount = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + lineNet(line), 0),\n\t);\n\tconst taxAmount = roundCurrency(\n\t\tsubtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0),\n\t);\n\tconst allowanceTotalAmount = roundCurrency(\n\t\tallowanceCharges\n\t\t\t.filter((item) => !item.chargeIndicator)\n\t\t\t.reduce((sum, item) => sum + (item.amount ?? 0), 0),\n\t);\n\tconst chargeTotalAmount = roundCurrency(\n\t\tallowanceCharges\n\t\t\t.filter((item) => item.chargeIndicator)\n\t\t\t.reduce((sum, item) => sum + (item.amount ?? 0), 0),\n\t);\n\tconst taxExclusiveAmount = roundCurrency(\n\t\tlineExtensionAmount - allowanceTotalAmount + chargeTotalAmount,\n\t);\n\tconst taxInclusiveAmount = roundCurrency(taxExclusiveAmount + taxAmount);\n\n\tconst prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);\n\tconst payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);\n\tconst payableAmount = roundCurrency(\n\t\ttaxInclusiveAmount - prepaidAmount + payableRoundingAmount,\n\t);\n\n\treturn {\n\t\ttaxTotal: { taxAmount, subtotals },\n\t\tmonetaryTotal: {\n\t\t\tlineExtensionAmount,\n\t\t\ttaxExclusiveAmount,\n\t\t\ttaxInclusiveAmount,\n\t\t\t...(allowanceTotalAmount ? { allowanceTotalAmount } : {}),\n\t\t\t...(chargeTotalAmount ? { chargeTotalAmount } : {}),\n\t\t\t...(prepaidAmount ? { prepaidAmount } : {}),\n\t\t\t...(payableRoundingAmount ? { payableRoundingAmount } : {}),\n\t\t\tpayableAmount,\n\t\t},\n\t};\n};\n\n/**\n * Split one document-level amount into an allowance or charge per VAT\n * category the lines use, pro rata by each category's line nets, so a\n * shipping charge or an invoice-wide discount on a mixed-rate invoice lands in\n * the right VAT subtotals (an ancillary cost follows the supply it belongs to).\n * Cent remainders go to the largest shares so the parts sum to `amount`\n * exactly; categories that receive nothing are omitted. With no positive\n * line net at all the whole amount goes to the first line's category.\n *\n * @throws {UblBuildError} for a line without a `taxCategory`.\n */\nexport const allocateAcrossTaxCategories = (\n\tamount: number,\n\tlines: UblLine[],\n\ttemplate: Pick<UblAllowanceCharge, \"chargeIndicator\" | \"reason\" | \"reasonCode\">,\n): UblAllowanceCharge[] => {\n\tconst groups = new Map<string, { category: UblTaxCategory; net: number }>();\n\tfor (const line of lines) {\n\t\tif (!line.taxCategory) {\n\t\t\tthrow new UblBuildError(\n\t\t\t\t`Line ${line.id} has no taxCategory (BT-151); cannot allocate across categories`,\n\t\t\t);\n\t\t}\n\t\tconst key = categoryKey(line.taxCategory);\n\t\tconst current = groups.get(key) ?? { category: line.taxCategory, net: 0 };\n\t\tcurrent.net = roundCurrency(current.net + Math.max(0, lineNet(line)));\n\t\tgroups.set(key, current);\n\t}\n\tconst entries = Array.from(groups.values());\n\tconst total = roundCurrency(amount);\n\tif (entries.length === 0 || total === 0) return [];\n\tconst netSum = entries.reduce((sum, entry) => sum + entry.net, 0);\n\tconst shares =\n\t\tnetSum > 0\n\t\t\t? entries.map((entry) => (total * entry.net) / netSum)\n\t\t\t: entries.map((_entry, index) => (index === 0 ? total : 0));\n\tconst cents = shares.map((share) => Math.floor(share * 100 + 1e-9));\n\tlet remainder =\n\t\tMath.round(total * 100) - cents.reduce((sum, value) => sum + value, 0);\n\tconst order = shares\n\t\t.map((share, index) => ({\n\t\t\tindex,\n\t\t\tfraction: share * 100 - Math.floor(share * 100 + 1e-9),\n\t\t}))\n\t\t.sort((a, b) => b.fraction - a.fraction);\n\tfor (const { index } of order) {\n\t\tif (remainder <= 0) break;\n\t\tcents[index] = (cents[index] ?? 0) + 1;\n\t\tremainder -= 1;\n\t}\n\treturn entries.flatMap((entry, index) => {\n\t\tconst value = (cents[index] ?? 0) / 100;\n\t\tif (value === 0) return [];\n\t\treturn [compact({ ...template, amount: value, taxCategory: entry.category })];\n\t});\n};\n"],"mappings":";;;;;;AAGA,MAAa,uBACZ;;AAGD,MAAa,iBAAiB;;AAG9B,MAAa,oBAAoB;;AAEjC,MAAa,wBAAwB;;AAGrC,MAAa,oBAAoB;;AAGjC,MAAa,oBAAoB;;AAGjC,MAAa,uBAAuB;AAEpC,MAAa,aAAa;AAC1B,MAAa,iBACZ;AACD,MAAa,SACZ;AACD,MAAa,SACZ;;;;;;;;;;ACCD,MAAa,MACZ,MACA,OACA,YACgB;CAChB,IAAI,MAAM,QAAQ,OAAO,GACxB,OAAO;EACN;EACA,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EACzB,UAAU,QAAQ,QAAQ,MAAuB,QAAQ,CAAC,CAAC;CAC5D;CAED,OAAO;EACN;EACA,GAAI,QAAQ,EAAE,MAAM,IAAI,CAA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MAAM,UAAU,MAAM,KAAK,OAAO,OAAO,CAAC;CAC1C,MAAM,QAAQ,cAAc,MAAM;CAClC,IAAI,QAAQ,WAAW,KAAK,UAAU,GAAG,OAAO,CAAC;CACjD,MAAM,SAAS,QAAQ,QAAQ,KAAK,UAAU,MAAM,MAAM,KAAK,CAAC;CAChE,MAAM,SACL,SAAS,IACN,QAAQ,KAAK,UAAW,QAAQ,MAAM,MAAO,MAAM,IACnD,QAAQ,KAAK,QAAQ,UAAW,UAAU,IAAI,QAAQ,CAAE;CAC5D,MAAM,QAAQ,OAAO,KAAK,UAAU,KAAK,MAAM,QAAQ,MAAM,IAAI,CAAC;CAClE,IAAI,YACH,KAAK,MAAM,QAAQ,GAAG,IAAI,MAAM,QAAQ,KAAK,UAAU,MAAM,OAAO,CAAC;CACtE,MAAM,QAAQ,OACZ,KAAK,OAAO,WAAW;EACvB;EACA,UAAU,QAAQ,MAAM,KAAK,MAAM,QAAQ,MAAM,IAAI;CACtD,EAAE,CAAC,CACF,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;CACxC,KAAK,MAAM,EAAE,WAAW,OAAO;EAC9B,IAAI,aAAa,GAAG;EACpB,MAAM,UAAU,MAAM,UAAU,KAAK;EACrC,aAAa;CACd;CACA,OAAO,QAAQ,SAAS,OAAO,UAAU;EACxC,MAAM,SAAS,MAAM,UAAU,KAAK;EACpC,IAAI,UAAU,GAAG,OAAO,CAAC;EACzB,OAAO,CAAC,QAAQ;GAAE,GAAG;GAAU,QAAQ;GAAO,aAAa,MAAM;EAAS,CAAC,CAAC;CAC7E,CAAC;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["categoryKey"],"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\t...(attrs ? { attrs } : {}),\n\t\t\tchildren: content.filter((c): c is XmlElement => Boolean(c)),\n\t\t};\n\t}\n\treturn {\n\t\tname,\n\t\t...(attrs ? { attrs } : {}),\n\t\t...(content !== undefined ? { text: content } : {}),\n\t};\n};\n\nconst escapeText = (value: string): string =>\n\tvalue.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n\nconst escapeAttr = (value: string): string => escapeText(value).replace(/\"/g, \""\");\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 { UblBuildError } from \"../../errors\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\n\tUblDelivery,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblLine,\n\tUblParty,\n\tUblPaymentMeans,\n\tUblSchemedId,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n} from \"../../types\";\nimport { 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\";\n\n// ── Validation ─────────────────────────────────────────────────────────\n//\n// The model is permissive (the parser reads whatever a document states); the\n// serializer is where EN 16931 / Peppol BIS Billing 3.0 mandatory fields and\n// the arithmetic business rules are enforced. Each check names the BT or the\n// rule and the model path in its message.\n\nconst missing = (what: string, path: string): UblBuildError =>\n\tnew UblBuildError(`Missing ${what} (${path})`);\n\nfunction required<T>(value: T | undefined, what: string, path: string): NonNullable<T> {\n\tif (value === undefined || value === null || value === \"\") {\n\t\tthrow missing(what, path);\n\t}\n\treturn value as NonNullable<T>;\n}\n\nconst round2 = (value: number): number => Math.round(value * 100) / 100;\n\n/** Sums of cent-rounded amounts must agree to the cent; R120 allows a cent either way. */\nconst assertEqual = (\n\trule: string,\n\tactual: number,\n\texpected: number,\n\tpath: string,\n\ttolerance = 0.005,\n): void => {\n\tif (Math.abs(actual - expected) > tolerance) {\n\t\tthrow new UblBuildError(\n\t\t\t`${rule}: ${path} is ${actual.toFixed(2)}, expected ${expected.toFixed(2)}`,\n\t\t);\n\t}\n};\n\n/** Category `O` (outside scope) is the one category BR-O-05 forbids a percent on. */\nconst requiresPercent = (categoryId: string): boolean => categoryId !== \"O\";\n\nconst validateTaxCategory = (\n\tcategory: UblTaxCategory | undefined,\n\tpath: string,\n): UblTaxCategory & { id: string } => {\n\tconst present = required(category, \"VAT category (BT-151/BT-118)\", path);\n\tconst id = required(present.id, \"VAT category code (BT-151/BT-118)\", `${path}.id`);\n\tif (requiresPercent(id) && present.percent === undefined) {\n\t\tthrow missing(`VAT rate (BT-152/BT-119) for category ${id}`, `${path}.percent`);\n\t}\n\treturn { ...present, id };\n};\n\nconst validateAllowanceCharge = (\n\titem: UblAllowanceCharge,\n\tpath: string,\n\tlevel: \"document\" | \"line\",\n): void => {\n\tconst kind = item.chargeIndicator ? \"charge\" : \"allowance\";\n\trequired(item.amount, `${kind} amount (BT-92/BT-99)`, `${path}.amount`);\n\tif (item.reason === undefined && item.reasonCode === undefined) {\n\t\tthrow missing(`${kind} reason or reason code (BT-97/BT-98)`, `${path}.reason`);\n\t}\n\tif (item.baseAmount !== undefined && item.multiplierFactorNumeric !== undefined) {\n\t\tassertEqual(\n\t\t\t\"PEPPOL-EN16931-R040\",\n\t\t\titem.amount ?? 0,\n\t\t\tround2((item.baseAmount * item.multiplierFactorNumeric) / 100),\n\t\t\t`${path}.amount`,\n\t\t\t0.01,\n\t\t);\n\t}\n\tif (level === \"document\") {\n\t\tvalidateTaxCategory(item.taxCategory, `${path}.taxCategory`);\n\t}\n};\n\nconst lineAllowanceTotal = (line: UblLine, charges: boolean): number =>\n\t(line.allowanceCharges ?? [])\n\t\t.filter((item) => item.chargeIndicator === charges)\n\t\t.reduce((sum, item) => sum + (item.amount ?? 0), 0);\n\nconst validateLine = (line: UblLine, index: number): void => {\n\tconst path = `lines[${index}]`;\n\trequired(line.id, \"line identifier (BT-126)\", `${path}.id`);\n\tconst quantity = required(\n\t\tline.quantity,\n\t\t\"invoiced quantity (BT-129)\",\n\t\t`${path}.quantity`,\n\t);\n\trequired(line.unitCode, \"unit code (BT-130)\", `${path}.unitCode`);\n\tconst unitPrice = required(\n\t\tline.unitPrice,\n\t\t\"net unit price (BT-146)\",\n\t\t`${path}.unitPrice`,\n\t);\n\tconst net = required(\n\t\tline.lineExtensionAmount,\n\t\t\"line net amount (BT-131)\",\n\t\t`${path}.lineExtensionAmount`,\n\t);\n\t// A negative line carries its sign on the quantity, never on the price.\n\tif (unitPrice < 0) {\n\t\tthrow new UblBuildError(\n\t\t\t`BR-27: ${path}.unitPrice is ${unitPrice}, the item net price shall not be negative`,\n\t\t);\n\t}\n\tvalidateTaxCategory(line.taxCategory, `${path}.taxCategory`);\n\t(line.allowanceCharges ?? []).forEach((item, itemIndex) =>\n\t\tvalidateAllowanceCharge(item, `${path}.allowanceCharges[${itemIndex}]`, \"line\"),\n\t);\n\t// BT-131 = BT-129 × BT-146 + line charges − line allowances. `unitPrice` is\n\t// the per-unit figure, so BT-149 is already accounted for.\n\tassertEqual(\n\t\t\"PEPPOL-EN16931-R120\",\n\t\tnet,\n\t\tround2(\n\t\t\tquantity * unitPrice +\n\t\t\t\tlineAllowanceTotal(line, true) -\n\t\t\t\tlineAllowanceTotal(line, false),\n\t\t),\n\t\t`${path}.lineExtensionAmount`,\n\t\t0.02,\n\t);\n};\n\nconst isExternalOnly = (attachment: UblAttachment): boolean =>\n\tattachment.externalUri !== undefined && attachment.base64Content === undefined;\n\nconst validateAttachment = (attachment: UblAttachment, index: number): void => {\n\tif (isExternalOnly(attachment)) return;\n\tconst path = `attachments[${index}]`;\n\trequired(attachment.filename, \"attachment filename (BT-125-2)\", `${path}.filename`);\n\trequired(\n\t\tattachment.mimeCode,\n\t\t\"attachment MIME code (BT-125-1)\",\n\t\t`${path}.mimeCode`,\n\t);\n\trequired(\n\t\tattachment.base64Content,\n\t\t\"attachment content (BT-125)\",\n\t\t`${path}.base64Content`,\n\t);\n};\n\n/** UNCL4461 codes whose payment means need a mandate (direct debit) or an account (credit transfer). */\nconst DIRECT_DEBIT_CODES = new Set([\"49\", \"59\"]);\nconst CREDIT_TRANSFER_CODES = new Set([\"30\", \"58\"]);\n\nconst validatePaymentMeans = (means: UblPaymentMeans, index: number): void => {\n\tconst path = `paymentMeansList[${index}]`;\n\tconst code = required(means.code, \"payment means code (BT-81)\", `${path}.code`);\n\tif (CREDIT_TRANSFER_CODES.has(code)) {\n\t\trequired(\n\t\t\tmeans.iban,\n\t\t\t`payment account (BT-84) for code ${code}`,\n\t\t\t`${path}.iban`,\n\t\t);\n\t}\n\tif (DIRECT_DEBIT_CODES.has(code)) {\n\t\trequired(\n\t\t\tmeans.mandateId,\n\t\t\t`mandate reference (BT-89) for code ${code}`,\n\t\t\t`${path}.mandateId`,\n\t\t);\n\t}\n};\n\nconst validateParty = (party: UblParty, role: string, nameBt: string): void => {\n\trequired(party.name, `${role} name (${nameBt})`, `${role}.name`);\n\tif (party.endpoint && party.endpoint.scheme === undefined) {\n\t\tthrow missing(`${role} endpoint scheme`, `${role}.endpoint.scheme`);\n\t}\n};\n\nconst paymentMeansList = (doc: UblInvoice): UblPaymentMeans[] =>\n\tdoc.paymentMeansList ?? (doc.paymentMeans ? [doc.paymentMeans] : []);\n\nconst sumBy = <T>(items: T[], pick: (item: T) => number): number =>\n\tround2(items.reduce((sum, item) => sum + pick(item), 0));\n\nconst categoryKey = (category: UblTaxCategory | undefined): string =>\n\t`${category?.id ?? \"\"}:${category?.percent ?? \"\"}`;\n\n/**\n * The document arithmetic EN 16931 fixes: BR-CO-10 (line sum), BR-CO-11/12\n * (allowance and charge sums), BR-CO-13 (total without VAT), BR-CO-15 (total\n * with VAT), BR-CO-16 (amount due) and the BR-S-08 family (each VAT category's\n * taxable amount is its line nets minus its allowances plus its charges).\n */\nconst validateArithmetic = (doc: UblInvoice): void => {\n\tconst total = doc.monetaryTotal;\n\tconst docItems = doc.allowanceCharges ?? [];\n\tconst allowances = docItems.filter((item) => !item.chargeIndicator);\n\tconst charges = docItems.filter((item) => item.chargeIndicator);\n\tconst lineSum = sumBy(doc.lines, (line) => line.lineExtensionAmount ?? 0);\n\tconst allowanceSum = sumBy(allowances, (item) => item.amount ?? 0);\n\tconst chargeSum = sumBy(charges, (item) => item.amount ?? 0);\n\n\tassertEqual(\n\t\t\"BR-CO-10\",\n\t\ttotal.lineExtensionAmount ?? 0,\n\t\tlineSum,\n\t\t\"monetaryTotal.lineExtensionAmount\",\n\t);\n\tif (allowances.length > 0 || total.allowanceTotalAmount !== undefined) {\n\t\tassertEqual(\n\t\t\t\"BR-CO-11\",\n\t\t\ttotal.allowanceTotalAmount ?? 0,\n\t\t\tallowanceSum,\n\t\t\t\"monetaryTotal.allowanceTotalAmount\",\n\t\t);\n\t}\n\tif (charges.length > 0 || total.chargeTotalAmount !== undefined) {\n\t\tassertEqual(\n\t\t\t\"BR-CO-12\",\n\t\t\ttotal.chargeTotalAmount ?? 0,\n\t\t\tchargeSum,\n\t\t\t\"monetaryTotal.chargeTotalAmount\",\n\t\t);\n\t}\n\tassertEqual(\n\t\t\"BR-CO-13\",\n\t\ttotal.taxExclusiveAmount ?? 0,\n\t\tround2(lineSum - allowanceSum + chargeSum),\n\t\t\"monetaryTotal.taxExclusiveAmount\",\n\t);\n\tassertEqual(\n\t\t\"BR-CO-15\",\n\t\ttotal.taxInclusiveAmount ?? 0,\n\t\tround2((total.taxExclusiveAmount ?? 0) + (doc.taxTotal.taxAmount ?? 0)),\n\t\t\"monetaryTotal.taxInclusiveAmount\",\n\t);\n\tassertEqual(\n\t\t\"BR-CO-16\",\n\t\ttotal.payableAmount ?? 0,\n\t\tround2(\n\t\t\t(total.taxInclusiveAmount ?? 0) -\n\t\t\t\t(total.prepaidAmount ?? 0) +\n\t\t\t\t(total.payableRoundingAmount ?? 0),\n\t\t),\n\t\t\"monetaryTotal.payableAmount\",\n\t);\n\n\tconst taxableByCategory = new Map<string, number>();\n\tconst add = (category: UblTaxCategory | undefined, amount: number): void => {\n\t\tconst key = categoryKey(category);\n\t\ttaxableByCategory.set(key, round2((taxableByCategory.get(key) ?? 0) + amount));\n\t};\n\tfor (const line of doc.lines) add(line.taxCategory, line.lineExtensionAmount ?? 0);\n\tfor (const item of docItems) {\n\t\tadd(\n\t\t\titem.taxCategory,\n\t\t\titem.chargeIndicator ? (item.amount ?? 0) : -(item.amount ?? 0),\n\t\t);\n\t}\n\tdoc.taxTotal.subtotals.forEach((subtotal, index) => {\n\t\tconst key = categoryKey(subtotal.category);\n\t\tconst expected = taxableByCategory.get(key);\n\t\tif (expected === undefined) {\n\t\t\tthrow new UblBuildError(\n\t\t\t\t`BR-S-08: taxTotal.subtotals[${index}] (${key}) has no line, allowance or charge in that category`,\n\t\t\t);\n\t\t}\n\t\tassertEqual(\n\t\t\t\"BR-S-08\",\n\t\t\tsubtotal.taxableAmount ?? 0,\n\t\t\texpected,\n\t\t\t`taxTotal.subtotals[${index}].taxableAmount`,\n\t\t);\n\t});\n};\n\nconst validateInvoice = (doc: UblInvoice): void => {\n\trequired(doc.id, \"document identifier (BT-1)\", \"id\");\n\trequired(doc.issueDate, \"issue date (BT-2)\", \"issueDate\");\n\trequired(doc.currency, \"document currency (BT-5)\", \"currency\");\n\tif (\n\t\tdoc.taxPointDate !== undefined &&\n\t\tdoc.invoicePeriod?.descriptionCode !== undefined\n\t) {\n\t\tthrow new UblBuildError(\n\t\t\t\"BR-CO-3: a tax point date (BT-7, taxPointDate) and a tax point date code (BT-8, invoicePeriod.descriptionCode) are mutually exclusive\",\n\t\t);\n\t}\n\tif (doc.taxCurrency !== undefined) {\n\t\trequired(\n\t\t\tdoc.taxTotal.taxAmountInTaxCurrency,\n\t\t\t\"VAT total in the accounting currency (BT-111, BR-53)\",\n\t\t\t\"taxTotal.taxAmountInTaxCurrency\",\n\t\t);\n\t}\n\tvalidateParty(doc.seller, \"seller\", \"BT-27\");\n\tvalidateParty(doc.buyer, \"buyer\", \"BT-44\");\n\tif (doc.payee) required(doc.payee.name, \"payee name (BT-59)\", \"payee.name\");\n\tif (doc.taxRepresentative) {\n\t\trequired(\n\t\t\tdoc.taxRepresentative.name,\n\t\t\t\"tax representative name (BT-62)\",\n\t\t\t\"taxRepresentative.name\",\n\t\t);\n\t\trequired(\n\t\t\tdoc.taxRepresentative.vatId,\n\t\t\t\"tax representative VAT identifier (BT-63)\",\n\t\t\t\"taxRepresentative.vatId\",\n\t\t);\n\t\trequired(\n\t\t\tdoc.taxRepresentative.address?.countryCode,\n\t\t\t\"tax representative country (BT-69)\",\n\t\t\t\"taxRepresentative.address.countryCode\",\n\t\t);\n\t}\n\tif (doc.lines.length === 0) {\n\t\tthrow new UblBuildError(\"A document needs at least one line (BG-25, lines)\");\n\t}\n\tdoc.lines.forEach(validateLine);\n\t(doc.allowanceCharges ?? []).forEach((item, index) =>\n\t\tvalidateAllowanceCharge(item, `allowanceCharges[${index}]`, \"document\"),\n\t);\n\tpaymentMeansList(doc).forEach(validatePaymentMeans);\n\trequired(doc.taxTotal.taxAmount, \"total VAT amount (BT-110)\", \"taxTotal.taxAmount\");\n\tconst total = doc.monetaryTotal;\n\trequired(\n\t\ttotal.lineExtensionAmount,\n\t\t\"sum of line net amounts (BT-106)\",\n\t\t\"monetaryTotal.lineExtensionAmount\",\n\t);\n\trequired(\n\t\ttotal.taxExclusiveAmount,\n\t\t\"total without VAT (BT-109)\",\n\t\t\"monetaryTotal.taxExclusiveAmount\",\n\t);\n\trequired(\n\t\ttotal.taxInclusiveAmount,\n\t\t\"total with VAT (BT-112)\",\n\t\t\"monetaryTotal.taxInclusiveAmount\",\n\t);\n\trequired(total.payableAmount, \"amount due (BT-115)\", \"monetaryTotal.payableAmount\");\n\t(doc.attachments ?? []).forEach(validateAttachment);\n\tvalidateArithmetic(doc);\n};\n\n// ── Formatting ─────────────────────────────────────────────────────────\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 optionalMoney = (\n\tname: string,\n\tvalue: number | undefined,\n\tcurrency: string,\n): XmlElement | null => (value !== undefined ? money(name, value, currency) : null);\n\nconst text = (name: string, value: string | undefined): XmlElement | null =>\n\tvalue !== undefined ? el(name, null, value) : null;\n\nconst schemedId = (name: string, id: UblSchemedId | undefined): XmlElement | null =>\n\tid !== undefined\n\t\t? el(name, id.scheme !== undefined ? { schemeID: id.scheme } : null, id.value)\n\t\t: null;\n\nconst taxScheme = (schemeId: string | undefined): XmlElement =>\n\tel(\"cac:TaxScheme\", null, [el(\"cbc:ID\", null, schemeId ?? 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 and on document allowances and\n * charges). EN 16931 requires an exemption reason for the non-charging\n * categories (E/AE/O/K/G); the code precedes the text in the sequence.\n */\nconst taxCategory = (\n\tname: string,\n\tcategory: UblTaxCategory,\n\tpath: string,\n): XmlElement => {\n\tconst valid = validateTaxCategory(category, path);\n\treturn el(name, null, [\n\t\tel(\"cbc:ID\", null, valid.id),\n\t\tvalid.percent !== undefined\n\t\t\t? el(\"cbc:Percent\", null, percent(valid.percent))\n\t\t\t: null,\n\t\ttext(\"cbc:TaxExemptionReasonCode\", valid.exemptionReasonCode),\n\t\ttext(\"cbc:TaxExemptionReason\", valid.exemptionReason),\n\t\ttaxScheme(valid.schemeId),\n\t]);\n};\n\nconst addressChildren = (address: UblAddress): (XmlElement | null)[] => [\n\ttext(\"cbc:StreetName\", address.street),\n\ttext(\"cbc:AdditionalStreetName\", address.additionalStreet),\n\ttext(\"cbc:CityName\", address.city),\n\ttext(\"cbc:PostalZone\", address.postalZone),\n\ttext(\"cbc:CountrySubentity\", address.countrySubentity),\n\taddress.countryCode !== undefined\n\t\t? el(\"cac:Country\", null, [\n\t\t\t\tel(\n\t\t\t\t\t\"cbc:IdentificationCode\",\n\t\t\t\t\t{ listID: COUNTRY_CODE_LIST_ID },\n\t\t\t\t\taddress.countryCode,\n\t\t\t\t),\n\t\t\t])\n\t\t: null,\n];\n\nconst postalAddress = (address: UblAddress): XmlElement =>\n\tel(\"cac:PostalAddress\", null, addressChildren(address));\n\nconst partyIdentifications = (source: UblParty): XmlElement[] =>\n\t(source.partyIdentifications ?? []).map((identification) =>\n\t\tel(\"cac:PartyIdentification\", null, [\n\t\t\tel(\n\t\t\t\t\"cbc:ID\",\n\t\t\t\tidentification.schemeId !== undefined\n\t\t\t\t\t? { schemeID: identification.schemeId }\n\t\t\t\t\t: null,\n\t\t\t\tidentification.id,\n\t\t\t),\n\t\t]),\n\t);\n\nconst partyName = (name: string): XmlElement =>\n\tel(\"cac:PartyName\", null, [el(\"cbc:Name\", null, name)]);\n\nconst partyTaxScheme = (source: UblParty): XmlElement | null =>\n\tsource.vatId !== undefined\n\t\t? el(\"cac:PartyTaxScheme\", null, [\n\t\t\t\tel(\"cbc:CompanyID\", null, source.vatId),\n\t\t\t\ttaxScheme(source.taxSchemeId),\n\t\t\t])\n\t\t: null;\n\nconst companyId = (source: UblParty): XmlElement | null =>\n\tsource.companyId\n\t\t? el(\n\t\t\t\t\"cbc:CompanyID\",\n\t\t\t\tsource.companyId.scheme !== undefined\n\t\t\t\t\t? { schemeID: source.companyId.scheme }\n\t\t\t\t\t: null,\n\t\t\t\tsource.companyId.value,\n\t\t\t)\n\t\t: null;\n\nconst contact = (source: UblParty): XmlElement | null =>\n\tsource.contact\n\t\t? el(\"cac:Contact\", null, [\n\t\t\t\ttext(\"cbc:Name\", source.contact.name),\n\t\t\t\ttext(\"cbc:Telephone\", source.contact.phone),\n\t\t\t\ttext(\"cbc:ElectronicMail\", source.contact.email),\n\t\t\t])\n\t\t: null;\n\n/** `cac:Party` for the seller and buyer (BG-4, BG-7). */\nconst party = (source: UblParty, name: string): 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\t...partyIdentifications(source),\n\t\tpartyName(name),\n\t\tsource.address ? postalAddress(source.address) : null,\n\t\tpartyTaxScheme(source),\n\t\tel(\"cac:PartyLegalEntity\", null, [\n\t\t\tel(\"cbc:RegistrationName\", null, source.registrationName ?? name),\n\t\t\tcompanyId(source),\n\t\t\ttext(\"cbc:CompanyLegalForm\", source.companyLegalForm),\n\t\t]),\n\t\tcontact(source),\n\t]);\n\n/** `cac:PayeeParty` (BG-10): identification, name and legal entity id, unwrapped. */\nconst payeeParty = (source: UblParty): XmlElement =>\n\tel(\"cac:PayeeParty\", null, [\n\t\t...partyIdentifications(source),\n\t\tpartyName(source.name ?? \"\"),\n\t\tsource.companyId ? el(\"cac:PartyLegalEntity\", null, [companyId(source)]) : null,\n\t]);\n\n/** `cac:TaxRepresentativeParty` (BG-11): name, address and VAT id, unwrapped. */\nconst taxRepresentativeParty = (source: UblParty): XmlElement =>\n\tel(\"cac:TaxRepresentativeParty\", null, [\n\t\tpartyName(source.name ?? \"\"),\n\t\tsource.address ? postalAddress(source.address) : null,\n\t\tpartyTaxScheme(source),\n\t]);\n\n/** `cac:Delivery` (BG-13). */\nconst delivery = (source: UblDelivery): XmlElement | null => {\n\tconst location =\n\t\tsource.locationId !== undefined || source.address !== undefined\n\t\t\t? el(\"cac:DeliveryLocation\", null, [\n\t\t\t\t\tschemedId(\"cbc:ID\", source.locationId),\n\t\t\t\t\tsource.address\n\t\t\t\t\t\t? el(\"cac:Address\", null, addressChildren(source.address))\n\t\t\t\t\t\t: null,\n\t\t\t\t])\n\t\t\t: null;\n\tconst deliveryParty =\n\t\tsource.partyName !== undefined\n\t\t\t? el(\"cac:DeliveryParty\", null, [partyName(source.partyName)])\n\t\t\t: null;\n\tif (source.actualDeliveryDate === undefined && !location && !deliveryParty)\n\t\treturn null;\n\treturn el(\"cac:Delivery\", null, [\n\t\ttext(\"cbc:ActualDeliveryDate\", source.actualDeliveryDate),\n\t\tlocation,\n\t\tdeliveryParty,\n\t]);\n};\n\n/**\n * `cac:PaymentMeans` (BG-16). On a credit note BT-9 has no root element and\n * rides in the first payment means as `cbc:PaymentDueDate`. `cbc:NetworkID`\n * is schema-mandatory inside `cac:CardAccount` and carries no business term;\n * the BIS example value is `NA`.\n */\nconst paymentMeans = (\n\tsource: UblPaymentMeans,\n\tdueDate: string | undefined,\n): XmlElement =>\n\tel(\"cac:PaymentMeans\", null, [\n\t\tel(\n\t\t\t\"cbc:PaymentMeansCode\",\n\t\t\tsource.codeName !== undefined ? { name: source.codeName } : null,\n\t\t\tsource.code ?? \"\",\n\t\t),\n\t\ttext(\"cbc:PaymentDueDate\", dueDate),\n\t\ttext(\"cbc:PaymentID\", source.paymentId),\n\t\tsource.cardNumber !== undefined\n\t\t\t? el(\"cac:CardAccount\", null, [\n\t\t\t\t\tel(\"cbc:PrimaryAccountNumberID\", null, source.cardNumber),\n\t\t\t\t\tel(\"cbc:NetworkID\", null, \"NA\"),\n\t\t\t\t\ttext(\"cbc:HolderName\", source.cardHolder),\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.iban !== undefined\n\t\t\t? el(\"cac:PayeeFinancialAccount\", null, [\n\t\t\t\t\tel(\"cbc:ID\", null, source.iban),\n\t\t\t\t\ttext(\"cbc:Name\", source.accountName),\n\t\t\t\t\tsource.bic !== undefined\n\t\t\t\t\t\t? el(\"cac:FinancialInstitutionBranch\", null, [\n\t\t\t\t\t\t\t\tel(\"cbc:ID\", null, source.bic),\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t: null,\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.mandateId !== undefined\n\t\t\t? el(\"cac:PaymentMandate\", null, [\n\t\t\t\t\tel(\"cbc:ID\", null, source.mandateId),\n\t\t\t\t\tsource.debitedAccount !== undefined\n\t\t\t\t\t\t? el(\"cac:PayerFinancialAccount\", null, [\n\t\t\t\t\t\t\t\tel(\"cbc:ID\", null, source.debitedAccount),\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t: null,\n\t\t\t\t])\n\t\t\t: null,\n\t]);\n\n/**\n * `cac:AllowanceCharge` at document level (BG-20/BG-21, with its VAT\n * category) and line level (BG-27/BG-28, without: the line's category\n * applies).\n */\nconst allowanceCharge = (\n\titem: UblAllowanceCharge,\n\tcurrency: string,\n\tpath: string,\n\tlevel: \"document\" | \"line\",\n): XmlElement =>\n\tel(\"cac:AllowanceCharge\", null, [\n\t\tel(\"cbc:ChargeIndicator\", null, item.chargeIndicator ? \"true\" : \"false\"),\n\t\ttext(\"cbc:AllowanceChargeReasonCode\", item.reasonCode),\n\t\ttext(\"cbc:AllowanceChargeReason\", item.reason),\n\t\titem.multiplierFactorNumeric !== undefined\n\t\t\t? el(\n\t\t\t\t\t\"cbc:MultiplierFactorNumeric\",\n\t\t\t\t\tnull,\n\t\t\t\t\tpercent(item.multiplierFactorNumeric),\n\t\t\t\t)\n\t\t\t: null,\n\t\tmoney(\"cbc:Amount\", item.amount ?? 0, currency),\n\t\toptionalMoney(\"cbc:BaseAmount\", item.baseAmount, currency),\n\t\tlevel === \"document\"\n\t\t\t? taxCategory(\n\t\t\t\t\t\"cac:TaxCategory\",\n\t\t\t\t\titem.taxCategory ?? {},\n\t\t\t\t\t`${path}.taxCategory`,\n\t\t\t\t)\n\t\t\t: null,\n\t]);\n\nconst taxSubtotal = (\n\tsubtotal: UblTaxSubtotal,\n\tcurrency: string,\n\tindex: number,\n): XmlElement => {\n\tconst path = `taxTotal.subtotals[${index}]`;\n\treturn el(\"cac:TaxSubtotal\", null, [\n\t\tmoney(\n\t\t\t\"cbc:TaxableAmount\",\n\t\t\trequired(\n\t\t\t\tsubtotal.taxableAmount,\n\t\t\t\t\"taxable amount (BT-116)\",\n\t\t\t\t`${path}.taxableAmount`,\n\t\t\t),\n\t\t\tcurrency,\n\t\t),\n\t\tmoney(\n\t\t\t\"cbc:TaxAmount\",\n\t\t\trequired(subtotal.taxAmount, \"VAT amount (BT-117)\", `${path}.taxAmount`),\n\t\t\tcurrency,\n\t\t),\n\t\ttaxCategory(\n\t\t\t\"cac:TaxCategory\",\n\t\t\trequired(subtotal.category, \"VAT category (BT-118)\", `${path}.category`),\n\t\t\t`${path}.category`,\n\t\t),\n\t]);\n};\n\n/**\n * `cac:LegalMonetaryTotal` children, in UBL sequence order. BT-107/BT-108 are\n * written when the document carries allowances or charges; BT-113 and BT-114\n * are omitted when absent or zero.\n */\nconst legalMonetaryTotalChildren = (doc: UblInvoice): XmlElement[] => {\n\tconst { currency, monetaryTotal: total } = doc;\n\tconst hasAllowances = (doc.allowanceCharges ?? []).some(\n\t\t(item) => !item.chargeIndicator,\n\t);\n\tconst hasCharges = (doc.allowanceCharges ?? []).some(\n\t\t(item) => item.chargeIndicator,\n\t);\n\tconst children: (XmlElement | null)[] = [\n\t\tmoney(\"cbc:LineExtensionAmount\", total.lineExtensionAmount ?? 0, currency),\n\t\tmoney(\"cbc:TaxExclusiveAmount\", total.taxExclusiveAmount ?? 0, currency),\n\t\tmoney(\"cbc:TaxInclusiveAmount\", total.taxInclusiveAmount ?? 0, currency),\n\t\thasAllowances || total.allowanceTotalAmount\n\t\t\t? money(\n\t\t\t\t\t\"cbc:AllowanceTotalAmount\",\n\t\t\t\t\ttotal.allowanceTotalAmount ?? 0,\n\t\t\t\t\tcurrency,\n\t\t\t\t)\n\t\t\t: null,\n\t\thasCharges || total.chargeTotalAmount\n\t\t\t? money(\"cbc:ChargeTotalAmount\", total.chargeTotalAmount ?? 0, currency)\n\t\t\t: null,\n\t\ttotal.prepaidAmount\n\t\t\t? money(\"cbc:PrepaidAmount\", total.prepaidAmount, currency)\n\t\t\t: null,\n\t\ttotal.payableRoundingAmount\n\t\t\t? money(\"cbc:PayableRoundingAmount\", total.payableRoundingAmount, currency)\n\t\t\t: null,\n\t\tmoney(\"cbc:PayableAmount\", total.payableAmount ?? 0, currency),\n\t];\n\treturn children.filter((child): child is XmlElement => Boolean(child));\n};\n\n/**\n * `cac:InvoicePeriod`. Null when neither bound is set — an empty period element\n * fails BR-CO-19, which requires at least one of the two dates. BT-8 (the tax\n * point date code) is only meaningful on the document period.\n */\nconst invoicePeriod = (period: UblInvoicePeriod | undefined): XmlElement | null => {\n\tif (!period || (period.startDate === undefined && period.endDate === undefined)) {\n\t\treturn null;\n\t}\n\treturn el(\"cac:InvoicePeriod\", null, [\n\t\ttext(\"cbc:StartDate\", period.startDate),\n\t\ttext(\"cbc:EndDate\", period.endDate),\n\t\ttext(\"cbc:DescriptionCode\", period.descriptionCode),\n\t]);\n};\n\nconst item = (source: UblLine): XmlElement =>\n\tel(\"cac:Item\", null, [\n\t\ttext(\"cbc:Description\", source.description),\n\t\t// BT-153 is mandatory; BT-154 stands in when the line has no name.\n\t\tel(\"cbc:Name\", null, source.itemName ?? source.description ?? source.id),\n\t\tsource.buyersItemId !== undefined\n\t\t\t? el(\"cac:BuyersItemIdentification\", null, [\n\t\t\t\t\tel(\"cbc:ID\", null, source.buyersItemId),\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.sellersItemId !== undefined\n\t\t\t? el(\"cac:SellersItemIdentification\", null, [\n\t\t\t\t\tel(\"cbc:ID\", null, source.sellersItemId),\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.standardItemId !== undefined\n\t\t\t? el(\"cac:StandardItemIdentification\", null, [\n\t\t\t\t\tschemedId(\"cbc:ID\", source.standardItemId),\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.originCountryCode !== undefined\n\t\t\t? el(\"cac:OriginCountry\", null, [\n\t\t\t\t\tel(\"cbc:IdentificationCode\", null, source.originCountryCode),\n\t\t\t\t])\n\t\t\t: null,\n\t\t...(source.commodityClassifications ?? []).map((classification) =>\n\t\t\tel(\"cac:CommodityClassification\", null, [\n\t\t\t\tel(\n\t\t\t\t\t\"cbc:ItemClassificationCode\",\n\t\t\t\t\t{\n\t\t\t\t\t\tlistID: classification.listId,\n\t\t\t\t\t\tlistVersionID: classification.listVersionId,\n\t\t\t\t\t},\n\t\t\t\t\tclassification.value,\n\t\t\t\t),\n\t\t\t]),\n\t\t),\n\t\ttaxCategory(\n\t\t\t\"cac:ClassifiedTaxCategory\",\n\t\t\tsource.taxCategory ?? {},\n\t\t\t`lines[${source.id}].taxCategory`,\n\t\t),\n\t\t...(source.additionalItemProperties ?? []).map((property) =>\n\t\t\tel(\"cac:AdditionalItemProperty\", null, [\n\t\t\t\tel(\"cbc:Name\", null, property.name),\n\t\t\t\tel(\"cbc:Value\", null, property.value ?? \"\"),\n\t\t\t]),\n\t\t),\n\t]);\n\nconst line = (\n\tsource: UblLine,\n\tcurrency: string,\n\tdocumentType: UblInvoice[\"documentType\"],\n): XmlElement => {\n\tconst isCreditNote = documentType === \"CreditNote\";\n\tconst lineElementName = isCreditNote ? \"cac:CreditNoteLine\" : \"cac:InvoiceLine\";\n\tconst quantityElementName = isCreditNote\n\t\t? \"cbc:CreditedQuantity\"\n\t\t: \"cbc:InvoicedQuantity\";\n\tconst unitCode = source.unitCode ?? \"\";\n\t// BT-146 covers BT-149 units; the model holds the per-unit price.\n\tconst priceAmount = (source.unitPrice ?? 0) * (source.baseQuantity ?? 1);\n\n\treturn el(lineElementName, null, [\n\t\tel(\"cbc:ID\", null, source.id),\n\t\ttext(\"cbc:Note\", source.note),\n\t\tel(quantityElementName, { unitCode }, String(source.quantity ?? 0)),\n\t\tmoney(\"cbc:LineExtensionAmount\", source.lineExtensionAmount ?? 0, currency),\n\t\ttext(\"cbc:AccountingCost\", source.accountingCost),\n\t\tinvoicePeriod(source.invoicePeriod),\n\t\tsource.orderLineReference !== undefined\n\t\t\t? el(\"cac:OrderLineReference\", null, [\n\t\t\t\t\tel(\"cbc:LineID\", null, source.orderLineReference),\n\t\t\t\t])\n\t\t\t: null,\n\t\tsource.objectIdentifier !== undefined\n\t\t\t? el(\"cac:DocumentReference\", null, [\n\t\t\t\t\tschemedId(\"cbc:ID\", source.objectIdentifier),\n\t\t\t\t\tel(\"cbc:DocumentTypeCode\", null, \"130\"),\n\t\t\t\t])\n\t\t\t: null,\n\t\t...(source.allowanceCharges ?? []).map((entry, index) =>\n\t\t\tallowanceCharge(\n\t\t\t\tentry,\n\t\t\t\tcurrency,\n\t\t\t\t`lines[${source.id}].allowanceCharges[${index}]`,\n\t\t\t\t\"line\",\n\t\t\t),\n\t\t),\n\t\titem(source),\n\t\t// BT-149's unit code must match the invoiced/credited quantity's\n\t\t// (PEPPOL-EN16931-R130).\n\t\tel(\"cac:Price\", null, [\n\t\t\tmoney(\"cbc:PriceAmount\", priceAmount, currency),\n\t\t\tsource.baseQuantity !== undefined\n\t\t\t\t? el(\"cbc:BaseQuantity\", { unitCode }, String(source.baseQuantity))\n\t\t\t\t: null,\n\t\t\tsource.priceAllowance !== undefined\n\t\t\t\t? el(\"cac:AllowanceCharge\", null, [\n\t\t\t\t\t\tel(\"cbc:ChargeIndicator\", null, \"false\"),\n\t\t\t\t\t\tmoney(\n\t\t\t\t\t\t\t\"cbc:Amount\",\n\t\t\t\t\t\t\tsource.priceAllowance.amount ?? 0,\n\t\t\t\t\t\t\tcurrency,\n\t\t\t\t\t\t),\n\t\t\t\t\t\toptionalMoney(\n\t\t\t\t\t\t\t\"cbc:BaseAmount\",\n\t\t\t\t\t\t\tsource.priceAllowance.baseAmount,\n\t\t\t\t\t\t\tcurrency,\n\t\t\t\t\t\t),\n\t\t\t\t\t])\n\t\t\t\t: null,\n\t\t]),\n\t]);\n};\n\nconst attachmentReference = (attachment: UblAttachment): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tel(\n\t\t\t\"cbc:ID\",\n\t\t\tnull,\n\t\t\tattachment.id ?? attachment.filename ?? attachment.externalUri ?? \"\",\n\t\t),\n\t\ttext(\"cbc:DocumentDescription\", attachment.description),\n\t\tel(\"cac:Attachment\", null, [\n\t\t\tisExternalOnly(attachment)\n\t\t\t\t? el(\"cac:ExternalReference\", null, [\n\t\t\t\t\t\tel(\"cbc:URI\", null, attachment.externalUri ?? \"\"),\n\t\t\t\t\t])\n\t\t\t\t: el(\n\t\t\t\t\t\t\"cbc:EmbeddedDocumentBinaryObject\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmimeCode: attachment.mimeCode ?? \"\",\n\t\t\t\t\t\t\tfilename: attachment.filename ?? \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tattachment.base64Content ?? \"\",\n\t\t\t\t\t),\n\t\t]),\n\t]);\n\n/** A typed `cac:AdditionalDocumentReference` without attachment (BT-17, BT-18, BT-11 on a credit note). */\nconst typedDocumentReference = (id: UblSchemedId, typeCode: string): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tschemedId(\"cbc:ID\", id),\n\t\tel(\"cbc:DocumentTypeCode\", null, typeCode),\n\t]);\n\nconst documentReference = (name: string, id: string | undefined): XmlElement | null =>\n\tid !== undefined ? el(name, null, [el(\"cbc:ID\", null, id)]) : null;\n\n/**\n * `cac:OrderReference`. BT-13 (the buyer's order number) is the element's\n * mandatory child, so a sales order id (BT-14) alone is not emitted.\n */\nconst orderReference = (doc: UblInvoice): XmlElement | null => {\n\tif (doc.orderReference === undefined) return null;\n\treturn el(\"cac:OrderReference\", null, [\n\t\tel(\"cbc:ID\", null, doc.orderReference),\n\t\ttext(\"cbc:SalesOrderID\", doc.salesOrderId),\n\t]);\n};\n\nconst billingReference = (reference: UblBillingReference): XmlElement | null => {\n\tif (reference.invoiceId === undefined) return null;\n\treturn el(\"cac:BillingReference\", null, [\n\t\tel(\"cac:InvoiceDocumentReference\", null, [\n\t\t\tel(\"cbc:ID\", null, reference.invoiceId),\n\t\t\ttext(\"cbc:IssueDate\", reference.invoiceIssueDate),\n\t\t]),\n\t]);\n};\n\n/**\n * Serialize a {@link UblInvoice} into a Peppol BIS Billing 3.0 XML string.\n *\n * Writes every EN 16931 business term the model holds, at its position in the\n * UBL 2.1 sequence: the header terms (`customizationId`, `profileId` and\n * `invoiceTypeCode` default to the BIS values), the references (BT-10 to\n * BT-19), the parties with identifications, legal form and contacts, the\n * payee and tax representative, delivery, payment means, payment terms,\n * document and line allowances and charges, the VAT breakdown (plus BT-111 in\n * the accounting currency), the monetary totals, attachments and document\n * references, and lines with their item identifiers, classifications,\n * properties, price discount and classified VAT category. Line-level tax\n * totals are not emitted: BIS Billing 3.0 forbids them.\n *\n * @throws {UblBuildError} when a field EN 16931 / Peppol BIS makes mandatory\n * is missing (naming the BT and the model path), or when the document's\n * arithmetic breaks a business rule: BR-CO-3, BR-CO-10 to BR-CO-13, BR-CO-15,\n * BR-CO-16, BR-53, the BR-S-08 family, PEPPOL-EN16931-R040 and R120.\n */\nexport const serializeUblInvoice = (doc: UblInvoice): string => {\n\tvalidateInvoice(doc);\n\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(\n\t\t\t\t\"cbc:CreditNoteTypeCode\",\n\t\t\t\tnull,\n\t\t\t\tdoc.invoiceTypeCode ?? CREDIT_NOTE_TYPE_CODE,\n\t\t\t)\n\t\t: el(\"cbc:InvoiceTypeCode\", null, doc.invoiceTypeCode ?? INVOICE_TYPE_CODE);\n\tconst taxPointDate = text(\"cbc:TaxPointDate\", doc.taxPointDate);\n\tconst means = paymentMeansList(doc);\n\t// A credit note has no cbc:DueDate: BT-9 goes in the first PaymentMeans.\n\tconst creditNoteDueDate =\n\t\tisCreditNote && means.length > 0 ? doc.dueDate : undefined;\n\n\tconst children: (XmlElement | null | false)[] = [\n\t\tel(\"cbc:CustomizationID\", null, doc.customizationId ?? UBL_CUSTOMIZATION_ID),\n\t\tel(\"cbc:ProfileID\", null, doc.profileId ?? UBL_PROFILE_ID),\n\t\tel(\"cbc:ID\", null, doc.id),\n\t\tel(\"cbc:IssueDate\", null, doc.issueDate),\n\t\t!isCreditNote ? text(\"cbc:DueDate\", doc.dueDate) : null,\n\t\t// The CreditNote sequence puts BT-7 before the type code, Invoice after the note.\n\t\tisCreditNote ? taxPointDate : null,\n\t\ttypeCodeElement,\n\t\ttext(\"cbc:Note\", doc.note),\n\t\t!isCreditNote ? taxPointDate : null,\n\t\tel(\"cbc:DocumentCurrencyCode\", null, doc.currency),\n\t\ttext(\"cbc:TaxCurrencyCode\", doc.taxCurrency),\n\t\ttext(\"cbc:AccountingCost\", doc.accountingCost),\n\t\ttext(\"cbc:BuyerReference\", doc.buyerReference),\n\t\tinvoicePeriod(doc.invoicePeriod),\n\t\torderReference(doc),\n\t\tdoc.billingReference ? billingReference(doc.billingReference) : null,\n\t\tdocumentReference(\"cac:DespatchDocumentReference\", doc.despatchReference),\n\t\tdocumentReference(\"cac:ReceiptDocumentReference\", doc.receivingAdviceReference),\n\t\tdocumentReference(\"cac:ContractDocumentReference\", doc.contractReference),\n\t\t...(doc.attachments ?? []).map(attachmentReference),\n\t\t...(doc.documentReferences ?? []).map((reference) =>\n\t\t\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\t\t\tel(\"cbc:ID\", null, reference.id ?? \"\"),\n\t\t\t\ttext(\"cbc:DocumentDescription\", reference.description),\n\t\t\t]),\n\t\t),\n\t\tdoc.invoicedObjectId !== undefined\n\t\t\t? typedDocumentReference(doc.invoicedObjectId, \"130\")\n\t\t\t: null,\n\t\t!isCreditNote && doc.tenderReference !== undefined\n\t\t\t? typedDocumentReference({ value: doc.tenderReference }, \"50\")\n\t\t\t: null,\n\t\t// UBL's CreditNote has no cac:ProjectReference; BIS uses type code 50.\n\t\tisCreditNote && doc.projectReference !== undefined\n\t\t\t? typedDocumentReference({ value: doc.projectReference }, \"50\")\n\t\t\t: null,\n\t\t!isCreditNote\n\t\t\t? documentReference(\"cac:ProjectReference\", doc.projectReference)\n\t\t\t: null,\n\t\tel(\"cac:AccountingSupplierParty\", null, [\n\t\t\tparty(doc.seller, doc.seller.name ?? \"\"),\n\t\t]),\n\t\tel(\"cac:AccountingCustomerParty\", null, [\n\t\t\tparty(doc.buyer, doc.buyer.name ?? \"\"),\n\t\t]),\n\t\tdoc.payee ? payeeParty(doc.payee) : null,\n\t\tdoc.taxRepresentative ? taxRepresentativeParty(doc.taxRepresentative) : null,\n\t\tdoc.delivery ? delivery(doc.delivery) : null,\n\t\t...means.map((entry, index) =>\n\t\t\tpaymentMeans(entry, index === 0 ? creditNoteDueDate : undefined),\n\t\t),\n\t\t// BT-20. In both sequences PaymentTerms sits after PaymentMeans and\n\t\t// before AllowanceCharge and TaxTotal.\n\t\tdoc.paymentTermsNote !== undefined\n\t\t\t? el(\"cac:PaymentTerms\", null, [el(\"cbc:Note\", null, doc.paymentTermsNote)])\n\t\t\t: null,\n\t\t...(doc.allowanceCharges ?? []).map((entry, index) =>\n\t\t\tallowanceCharge(\n\t\t\t\tentry,\n\t\t\t\tdoc.currency,\n\t\t\t\t`allowanceCharges[${index}]`,\n\t\t\t\t\"document\",\n\t\t\t),\n\t\t),\n\t\tel(\"cac:TaxTotal\", null, [\n\t\t\tmoney(\"cbc:TaxAmount\", doc.taxTotal.taxAmount ?? 0, doc.currency),\n\t\t\t...doc.taxTotal.subtotals.map((subtotal, index) =>\n\t\t\t\ttaxSubtotal(subtotal, doc.currency, index),\n\t\t\t),\n\t\t]),\n\t\t// BT-111: a second TaxTotal carrying only the VAT total in BT-6.\n\t\tdoc.taxCurrency !== undefined\n\t\t\t? el(\"cac:TaxTotal\", null, [\n\t\t\t\t\tmoney(\n\t\t\t\t\t\t\"cbc:TaxAmount\",\n\t\t\t\t\t\tdoc.taxTotal.taxAmountInTaxCurrency ?? 0,\n\t\t\t\t\t\tdoc.taxCurrency,\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t: null,\n\t\tel(\"cac:LegalMonetaryTotal\", null, legalMonetaryTotalChildren(doc)),\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\n/** Alias of {@link serializeUblInvoice}, kept under the historical name. */\nexport const serializeUblDocument = serializeUblInvoice;\n","/** Trim a string; `undefined` when missing or blank. */\nexport const normalizeString = (\n\tvalue: string | null | undefined,\n): string | undefined => {\n\tif (typeof value !== \"string\") return undefined;\n\tconst normalized = value.trim();\n\treturn normalized.length > 0 ? normalized : undefined;\n};\n\n/** Drop `undefined`-valued keys so an absent field is an absent key. */\nexport const compact = <T extends object>(value: T): T =>\n\tObject.fromEntries(\n\t\tObject.entries(value).filter(([, entry]) => entry !== undefined),\n\t) as T;\n","import type { UblAddress } from \"../types\";\nimport { compact, normalizeString } from \"./utils\";\n\nconst normalizeCountryCode = (value: string | null | undefined): string | undefined => {\n\tconst trimmed = normalizeString(value);\n\tif (!trimmed) return undefined;\n\treturn trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : undefined;\n};\n\n/**\n * A free-form postal address as accepted by {@link normalizeAddress}.\n *\n * Both the Stripe shape (`line1`, `postal_code`, `country`, `state`) and the\n * legacy/internal shape (`street`, `zip_code`, `country_code`,\n * `country_subentity`) are accepted; when both keys are present the Stripe\n * one wins.\n */\nexport interface AddressInput {\n\tline1?: string | null;\n\tline2?: string | null;\n\tstreet?: string | null;\n\tcity?: string | null;\n\tpostal_code?: string | null;\n\tzip_code?: string | null;\n\tstate?: string | null;\n\tcountry_subentity?: string | null;\n\tcountry?: string | null;\n\tcountry_code?: string | null;\n}\n\n/**\n * Normalize a free-form address (Stripe shape, custom shape, or an internal\n * shape) into a {@link UblAddress}. An absent part is an absent key.\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: AddressInput | null | undefined,\n\tfallbackCountryCode: string | null,\n\tfallbackLine?: string | null,\n): UblAddress => {\n\tconst record: AddressInput = address ?? {};\n\tconst countryCode =\n\t\tnormalizeCountryCode(normalizeString(record.country)) ??\n\t\tnormalizeCountryCode(normalizeString(record.country_code)) ??\n\t\tnormalizeCountryCode(fallbackCountryCode);\n\treturn compact({\n\t\tstreet:\n\t\t\tnormalizeString(record.line1) ??\n\t\t\tnormalizeString(record.street) ??\n\t\t\tnormalizeString(fallbackLine),\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 { getPeppolIdentifierSchemes } from \"@financica/peppol/countries\";\nimport {\n\tcountryFromVatNumber,\n\tnormalizeParticipantValue,\n} from \"@financica/peppol/identifiers\";\nimport type { UblCompanyId, UblEndpoint } from \"../types\";\nimport { compact, normalizeString } from \"./utils\";\n\nconst normalizeBelgianCompanyNumber = (value: string | null | undefined) => {\n\tif (!value) return \"\";\n\t// EAS 0208 (BE:EN) is 10 bare digits, so the printed dots are decoration.\n\treturn normalizeParticipantValue(\"0208\", 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 * Peppol/ISO 6523 ICD scheme for a legal registration number\n * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`), e.g. BE → `0208`\n * (enterprise number), NL → `0106` (KvK), FR → `0002` (SIRENE). The table is\n * `@financica/peppol`'s country profiles.\n *\n * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).\n * Returns `undefined` 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 | undefined => {\n\tconst companyNumber = normalizeString(params.companyNumber);\n\tif (!companyNumber) return undefined;\n\n\tconst fromCountry =\n\t\tgetPeppolIdentifierSchemes(params.countryCode)?.companyIdentifierScheme ??\n\t\tundefined;\n\tif (fromCountry) return fromCountry;\n\n\t// Only sniffing the country prefix, e.g. `BE0793904121` → `BE`.\n\tconst prefix = companyNumber\n\t\t.replace(/[^A-Za-z]/g, \"\")\n\t\t.toUpperCase()\n\t\t.slice(0, 2);\n\treturn getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? undefined;\n};\n\n/**\n * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the\n * country-appropriate ICD scheme when known. Returns `undefined` when there is no\n * company number.\n */\nexport const buildCompanyId = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): UblCompanyId | undefined => {\n\tconst normalized = normalizeString(\n\t\tnormalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),\n\t);\n\tif (!normalized) return undefined;\n\treturn compact({\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 * 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 scheme comes from `@financica/peppol`'s country resolution, so countries\n * that route on their registry number alone (Norway, Denmark) yield `undefined`\n * here — their VAT number is not a Peppol participant identifier.\n *\n * The value keeps its country prefix, matching how participants register (the\n * Peppol directory lists this party as `9925:be0206582284`). Returns `undefined`\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 | undefined;\n}): UblEndpoint | undefined => {\n\tconst value = normalizeString(params.vatNumber);\n\tif (!value) return undefined;\n\n\tconst fromPrefix = countryFromVatNumber(value);\n\tconst scheme =\n\t\tgetPeppolIdentifierSchemes(fromPrefix)?.vatIdentifierScheme ??\n\t\tgetPeppolIdentifierSchemes(params.countryCode)?.vatIdentifierScheme;\n\tif (!scheme) return undefined;\n\n\t// Every scheme in the table is a VAT scheme, whose value carries no\n\t// separator, so the printed dots/spaces are dropped.\n\tconst cleaned = normalizeParticipantValue(scheme, value).toUpperCase();\n\tif (!cleaned) return undefined;\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 * `undefined` 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 | undefined => {\n\tconst normalized = normalizeString(peppolId);\n\tif (!normalized) return undefined;\n\tconst separatorIndex = normalized.indexOf(\":\");\n\tif (separatorIndex <= 0) return undefined;\n\tconst scheme = normalized.slice(0, separatorIndex).trim();\n\tconst value = normalized.slice(separatorIndex + 1).trim();\n\tif (!scheme || !value) return undefined;\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\n/**\n * One customer tax identifier as stored by Stripe (`customer_tax_ids[]`) or an\n * equivalent `{type, value}` pair. `type` is a Stripe tax-ID type such as\n * `eu_vat`, or a custom type such as `peppol_id`; blank entries are skipped.\n */\nexport interface CustomerTaxIdInput {\n\ttype: string | null | undefined;\n\tvalue: string | null | undefined;\n}\n\nconst normalizeIdentifierType = (value: string | undefined) =>\n\tvalue?.toLowerCase().replace(/[^a-z0-9]+/g, \"_\");\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: readonly CustomerTaxIdInput[] | null | undefined,\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\tfor (const entry of taxIds ?? []) {\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\t// Any other typed id (ca_gst_hst, au_abn, us_ein, ...) is a registration\n\t\t// number: it goes to BT-30, not BT-31.\n\t\tif (!taxNumber) taxNumber = value;\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. for Belgium, the enterprise number (VAT digits without the `BE` prefix)\n * under EAS `0208`, ahead of the VAT scheme: Belgium mandates `0208`, and\n * a stale `9925` left at a previous access point must not win the lookup;\n * 4. the VAT number under its country's VAT EAS scheme (see\n * {@link resolveVatEndpoint}); for Sweden, Norway and Denmark, whose VAT\n * schemes were withdrawn, the company number inside the VAT number\n * (`0007`, `0192`, `0184`);\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: Partial<CustomerTaxIdentifiers>,\n\tcountryCode?: string | null,\n): string[] => {\n\tconst candidates: string[] = [];\n\tconst add = (id: { scheme?: string | undefined; value: string } | undefined) => {\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: normalizeParticipantValue(\"0088\", gln) });\n\n\t// 3. Belgium: the enterprise number under EAS 0208 (the VAT digits without\n\t// the `BE` prefix) comes first. It is the identifier Belgium mandates, so a\n\t// party registered under both is addressed where it is required to be, and\n\t// a 9925 left behind at a former access point cannot capture the document.\n\tconst vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\tif (vat?.scheme === \"9925\") {\n\t\tadd(\n\t\t\tbuildCompanyId({\n\t\t\t\tcountryCode: \"BE\",\n\t\t\t\tcompanyNumber: customer.vatNumber ?? null,\n\t\t\t}),\n\t\t);\n\t}\n\n\t// 4. VAT number → the country's VAT EAS scheme (e.g. BE → 9925), the\n\t// fallback for parties registered only under it.\n\tadd(vat);\n\n\t// 4b. Sweden has no VAT scheme left (SE:VAT 9955 is withdrawn); a Swedish VAT\n\t// number is the organisationsnummer + `01`, registered under EAS 0007.\n\tconst compactVat = (customer.vatNumber ?? \"\")\n\t\t.replace(/[^A-Za-z0-9]/g, \"\")\n\t\t.toUpperCase();\n\tconst swedishOrgNumber = /^SE(\\d{10})01$/.exec(compactVat)?.[1];\n\tif (swedishOrgNumber) add({ scheme: \"0007\", value: swedishOrgNumber });\n\n\t// 4c. Norway likewise (NO:VAT 9909 is withdrawn): a Norwegian VAT number is\n\t// the organisasjonsnummer + `MVA`, registered under EAS 0192. Stripe's\n\t// `no_vat` type stores it without the `NO` prefix (`123456789MVA`), so the\n\t// prefix is optional, and a bare `…MVA` counts only for a Norwegian customer.\n\tconst norwegianOrgNumber = /^(NO)?(\\d{9})MVA$/.exec(compactVat);\n\tif (\n\t\tnorwegianOrgNumber?.[2] &&\n\t\t(norwegianOrgNumber[1] || countryCode?.toUpperCase() === \"NO\")\n\t) {\n\t\tadd({ scheme: \"0192\", value: norwegianOrgNumber[2] });\n\t}\n\n\t// 4d. Denmark (DK:VAT 9902 is withdrawn): the VAT number is `DK` + the CVR\n\t// number, registered under EAS 0184.\n\tconst danishCvr = /^DK(\\d{8})$/.exec(compactVat)?.[1];\n\tif (danishCvr) add({ scheme: \"0184\", value: danishCvr });\n\n\t// 5. A generic tax/registration number → its country's company-ID scheme.\n\tconst tax = normalizeString(customer.taxNumber);\n\tif (tax)\n\t\tadd(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));\n\n\treturn Array.from(new Set(candidates));\n};\n","import { type AddressInput, normalizeAddress } from \"./address\";\nimport { buildCompanyId, parsePeppolEndpoint, resolveVatEndpoint } from \"./identifiers\";\nimport type { UblAddress, UblEndpoint, UblParty } from \"../types\";\nimport { compact, 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 * - `subject` — subject to VAT (the normal case): line categories come from\n * the data.\n * - `not_subject` — not subject to VAT.\n * - `small_business` — small business / franchise exemption (e.g. Belgian\n * Article 56bis).\n *\n * For the last two, `coerceLinesForSupplierVatStatus` (tax-category.ts) turns\n * every line into a non-charging exempt category so no VAT is reported.\n * Providers that encode this numerically (Scrada: 1/2/3) map at their boundary.\n */\nexport type SupplierVatStatus = \"subject\" | \"not_subject\" | \"small_business\";\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: AddressInput | null;\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/**\n * A VAT identifier (BT-31 / BT-48) with its country prefix, which BR-CO-09\n * requires. Some stores keep it without one: Stripe's `no_vat` is\n * `123456789MVA`, so a Norwegian buyer's VAT number failed validation on\n * every invoice. A value that starts with a digit gets the party's own\n * country (Greece writes `EL`); a value that already has letters in front is\n * left as it is.\n */\nconst prefixedVatId = (\n\tvatNumber: string | null | undefined,\n\tcountryCode: string | null | undefined,\n): string | undefined => {\n\tconst vat = normalizeString(vatNumber);\n\tconst country = normalizeString(countryCode)?.toUpperCase();\n\tif (!vat || !country || !/^\\d/.test(vat)) return vat;\n\treturn `${country === \"GR\" ? \"EL\" : country}${vat}`;\n};\n\n/** Convert a {@link UblSupplier} into the seller party (`cac:AccountingSupplierParty`). */\nexport const buildSupplierParty = (supplier: UblSupplier): UblParty => {\n\tconst address = normalizeAddress(supplier.address, supplier.countryCode);\n\treturn compact({\n\t\tendpoint: parsePeppolEndpoint(supplier.peppolID),\n\t\tname: supplier.name,\n\t\tregistrationName: supplier.name,\n\t\taddress,\n\t\tvatId: prefixedVatId(supplier.vatNumber, supplier.countryCode),\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/**\n * Caller-provided customer (buyer) data, normalized into a stable shape.\n *\n * Each consumer (the Stripe adapter, app-specific row builders) resolves its\n * own identifiers and address, then hands this generic shape to\n * {@link buildCustomerParty}, so the Peppol routing logic lives in one place.\n */\nexport interface UblCustomer {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** Customer address, already normalized by the caller. */\n\taddress: UblAddress;\n\t/**\n\t * The customer's ISO 3166-1 alpha-2 country, used to resolve VAT/registration\n\t * schemes for identifiers that don't carry a country prefix. Pass the\n\t * customer's *own* country (never the supplier's) so the document is not\n\t * mis-routed; falls back to the address country when omitted.\n\t */\n\tcountryCode?: string | null;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n\t/** Global Location Number (resolved under EAS `0088`). */\n\tglnNumber?: string | null;\n\t/** Generic tax/registration number (no VAT prefix). */\n\ttaxNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n}\n\n/**\n * Convert a {@link UblCustomer} into the buyer party (`cac:AccountingCustomerParty`).\n *\n * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in\n * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered\n * identifier), then an explicit Peppol ID, then a GLN (scheme `0088`), then the\n * VAT number mapped to its country's VAT EAS scheme (e.g. BE → `9925`). That\n * last step matters because most data stores hold a customer's VAT without a\n * scheme, so without it a VAT-only customer would have no endpoint and the\n * document would be unroutable.\n */\nexport const buildCustomerParty = (\n\tcustomer: UblCustomer,\n\tendpointOverride?: UblEndpoint | null,\n): UblParty => {\n\tconst countryCode =\n\t\tnormalizeString(customer.countryCode) ?? customer.address.countryCode ?? null;\n\tconst endpoint =\n\t\tendpointOverride ??\n\t\tparsePeppolEndpoint(customer.peppolID) ??\n\t\t(customer.glnNumber\n\t\t\t? { scheme: \"0088\", value: customer.glnNumber }\n\t\t\t: undefined) ??\n\t\tresolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\n\treturn compact({\n\t\tendpoint,\n\t\tname: customer.name,\n\t\tregistrationName: customer.name,\n\t\taddress: customer.address,\n\t\tvatId: prefixedVatId(customer.vatNumber, countryCode),\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode,\n\t\t\tcompanyNumber: customer.taxNumber ?? null,\n\t\t}),\n\t});\n};\n","import type { UblAttachment, UblInvoice } from \"../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\tbase64Content: 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 UblInvoice} is safe to log or persist for audit.\n */\nexport const sanitizeUblDocumentForAudit = (doc: UblInvoice): UblInvoice => {\n\tif (!doc.attachments?.length) return doc;\n\treturn {\n\t\t...doc,\n\t\tattachments: doc.attachments.map((attachment) =>\n\t\t\tattachment.base64Content === undefined\n\t\t\t\t? attachment\n\t\t\t\t: {\n\t\t\t\t\t\t...attachment,\n\t\t\t\t\t\tbase64Content: `[omitted ${attachment.base64Content.length} chars]`,\n\t\t\t\t\t},\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\n/** The `cac:Price` pair for a line: the per-unit price and the optional BT-149. */\nexport interface UnitPrice {\n\t/** Net price of one unit (`UblLine.unitPrice`). */\n\tunitPrice: number;\n\t/**\n\t * `cbc:BaseQuantity` (BT-149) — set when the per-unit price is not exact in\n\t * cents; the serializer then emits `PriceAmount = unitPrice × baseQuantity`\n\t * (the line net). Omitted = 1.\n\t */\n\tbaseQuantity?: number | undefined;\n}\n\n/**\n * Derive the `cac:Price` for a line whose net total is authoritative.\n *\n * Peppol rule PEPPOL-EN16931-R120 checks\n * `quantity × (PriceAmount ÷ BaseQuantity)` against the line net amount within\n * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that\n * whenever the division doesn't land on a cent: 940.00 over 14 units gives\n * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and\n * rejected as a fatal validation error.\n *\n * So the cent-rounded unit price is only used when it reproduces the net\n * exactly. Otherwise the line is priced as a whole via BT-149: `unitPrice` is\n * the exact (unrounded) `net ÷ quantity` and `baseQuantity` = the quantity, so\n * the serializer writes `PriceAmount` = the net and `BaseQuantity` = the\n * quantity, which is exact at any magnitude instead of merely within tolerance\n * — the residual of a rounded unit price grows with quantity and would\n * eventually breach 0.02 at any fixed precision.\n */\nexport const deriveUnitPrice = (netTotal: number, quantity: number): UnitPrice => {\n\t// A zero or fractional-to-zero quantity still has to price something; BT-149\n\t// must be a positive number (PEPPOL-EN16931-R121), so floor the divisor at 1.\n\tconst units = quantity > 0 ? quantity : 1;\n\tconst perUnit = roundCurrency(netTotal / units);\n\tif (roundCurrency(perUnit * units) === roundCurrency(netTotal)) {\n\t\treturn { unitPrice: perUnit };\n\t}\n\treturn { unitPrice: roundCurrency(netTotal) / units, baseQuantity: units };\n};\n","import type { SupplierVatStatus } from \"./party\";\nimport type { UblLine, UblTaxCategory } from \"../types\";\nimport { normalizeString } from \"./utils\";\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\tintra_community: \"Intra-community supply\",\n\texport: \"Export outside the EU\",\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: string | null | undefined): string | undefined =>\n\tnormalizeString(value)?.toUpperCase();\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 * - Intra-community supply → `K` (0%, with exemption reason)\n * - Export outside the EU → `G` (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 === \"K\" || reason === \"intra_community\") {\n\t\treturn {\n\t\t\tid: \"K\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT[\"intra_community\"],\n\t\t};\n\t}\n\tif (categoryHint === \"G\" || reason === \"export\") {\n\t\treturn {\n\t\t\tid: \"G\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT[\"export\"],\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] : undefined) ??\n\t\t\t\t\"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 (\n\t\t\tta.taxability_reason === \"reverse_charge\" ||\n\t\t\tta.taxability_reason === \"zero_rated\" ||\n\t\t\tEXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)\n\t\t) {\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}\n\treturn taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });\n};\n\n/**\n * BT-120 text for a small-business/franchise exemption, by supplier country.\n * Countries without a specific legal reference fall back to the generic text.\n */\nconst SMALL_BUSINESS_EXEMPTION_REASON_BY_COUNTRY: Record<string, string> = {\n\tBE: \"Exempt — small business scheme (Article 56bis)\",\n};\nconst SMALL_BUSINESS_EXEMPTION_REASON = \"Exempt — small business scheme\";\nconst NOT_SUBJECT_EXEMPTION_REASON = \"Seller not subject to VAT\";\n\n/**\n * When the supplier does not charge VAT, coerce every line to a non-charging\n * exempt category (`E`, 0%) with the appropriate BT-120 reason, so the document\n * reports no VAT regardless of what the upstream line tax data implied. Lines\n * are returned untouched for a `subject` supplier.\n */\nexport const coerceLinesForSupplierVatStatus = (\n\tlines: UblLine[],\n\tvatStatus: SupplierVatStatus,\n\tsupplierCountryCode?: string | null,\n): UblLine[] => {\n\tif (vatStatus === \"subject\") return lines;\n\tconst country = normalizeString(supplierCountryCode)?.toUpperCase();\n\tconst exemptionReason =\n\t\tvatStatus === \"small_business\"\n\t\t\t? ((country && SMALL_BUSINESS_EXEMPTION_REASON_BY_COUNTRY[country]) ??\n\t\t\t\tSMALL_BUSINESS_EXEMPTION_REASON)\n\t\t\t: NOT_SUBJECT_EXEMPTION_REASON;\n\treturn lines.map((line) => ({\n\t\t...line,\n\t\ttaxCategory: { id: \"E\", percent: 0, exemptionReason },\n\t}));\n};\n","import { UblBuildError } from \"../errors\";\nimport type {\n\tUblAllowanceCharge,\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"../types\";\nimport { deriveUnitPrice, roundCurrency } from \"./numeric\";\nimport { compact } from \"./utils\";\n\nconst lineNet = (line: UblLine): number => line.lineExtensionAmount ?? 0;\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(lines.reduce((sum, line) => sum + lineNet(line), 0));\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\tlineNet(line) > lineNet(arr[maxIdx] ?? line) ? idx : 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(lineNet(line) + diff);\n\t\t// Re-derive the price from the adjusted net through the shared helper —\n\t\t// nudging the net without re-deriving BT-146/BT-149 to match is exactly\n\t\t// what PEPPOL-EN16931-R120 rejects. Assign `baseQuantity` unconditionally\n\t\t// so a line that no longer needs one doesn't keep a stale value.\n\t\t// The price may never be negative (BR-27): a net that ends up below zero\n\t\t// carries its sign on the quantity instead.\n\t\tconst units = Math.abs(line.quantity ?? 0);\n\t\tconst { unitPrice, baseQuantity } = deriveUnitPrice(Math.abs(adjusted), units);\n\t\treturn compact({\n\t\t\t...line,\n\t\t\tquantity:\n\t\t\t\tline.quantity === undefined ? undefined : adjusted < 0 ? -units : units,\n\t\t\tlineExtensionAmount: adjusted,\n\t\t\tunitPrice,\n\t\t\tbaseQuantity,\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\nexport interface BuildTaxTotalsOptions {\n\t/**\n\t * BT-113 — amount already paid, **gross (VAT-inclusive)**. Subtracted from\n\t * BT-112 to derive the outstanding `payableAmount` (BR-CO-16). Pass the full\n\t * gross total for a settled document so it reports a payable amount of 0.\n\t */\n\tprepaidAmount?: number;\n\t/** BT-114 — rounding applied to the payable amount. */\n\tpayableRoundingAmount?: number;\n\t/**\n\t * Document-level allowances and charges (BG-20/BG-21). Each one joins the\n\t * VAT breakdown of its own category (BR-S-08: taxable = line nets −\n\t * allowances + charges) and feeds BT-107/BT-108, so BT-109 is\n\t * BT-106 − BT-107 + BT-108 (BR-CO-13). Put the same array on the document.\n\t */\n\tallowanceCharges?: UblAllowanceCharge[];\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 *\n * `payableAmount` is derived per BR-CO-16 (`BT-112 − BT-113 + BT-114`) so the\n * invariant holds by construction. The result is *not* clamped: a prepayment\n * exceeding the total yields a negative payable amount, surfacing the upstream\n * overpayment rather than hiding it.\n *\n * @throws {UblBuildError} for a line, allowance or charge without a\n * `taxCategory` — there is no VAT breakdown to put it in.\n */\nexport const buildTaxTotals = (\n\tlines: UblLine[],\n\toptions?: BuildTaxTotalsOptions,\n): 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\tif (!line.taxCategory) {\n\t\t\tthrow new UblBuildError(\n\t\t\t\t`Line ${line.id} has no taxCategory (BT-151); cannot build the VAT breakdown`,\n\t\t\t);\n\t\t}\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(current.taxableAmount + lineNet(line));\n\t\tgroups.set(key, current);\n\t}\n\tconst allowanceCharges = options?.allowanceCharges ?? [];\n\tfor (const [index, item] of allowanceCharges.entries()) {\n\t\tif (!item.taxCategory) {\n\t\t\tthrow new UblBuildError(\n\t\t\t\t`allowanceCharges[${index}] has no taxCategory (BT-95/BT-102); cannot build the VAT breakdown`,\n\t\t\t);\n\t\t}\n\t\tconst key = categoryKey(item.taxCategory);\n\t\tconst current = groups.get(key) ?? {\n\t\t\tcategory: item.taxCategory,\n\t\t\ttaxableAmount: 0,\n\t\t};\n\t\tconst signed = item.chargeIndicator ? (item.amount ?? 0) : -(item.amount ?? 0);\n\t\tcurrent.taxableAmount = roundCurrency(current.taxableAmount + signed);\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(\n\t\t\t(group.taxableAmount * (group.category.percent ?? 0)) / 100,\n\t\t),\n\t\tcategory: group.category,\n\t}));\n\n\tconst lineExtensionAmount = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + lineNet(line), 0),\n\t);\n\tconst taxAmount = roundCurrency(\n\t\tsubtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0),\n\t);\n\tconst allowanceTotalAmount = roundCurrency(\n\t\tallowanceCharges\n\t\t\t.filter((item) => !item.chargeIndicator)\n\t\t\t.reduce((sum, item) => sum + (item.amount ?? 0), 0),\n\t);\n\tconst chargeTotalAmount = roundCurrency(\n\t\tallowanceCharges\n\t\t\t.filter((item) => item.chargeIndicator)\n\t\t\t.reduce((sum, item) => sum + (item.amount ?? 0), 0),\n\t);\n\tconst taxExclusiveAmount = roundCurrency(\n\t\tlineExtensionAmount - allowanceTotalAmount + chargeTotalAmount,\n\t);\n\tconst taxInclusiveAmount = roundCurrency(taxExclusiveAmount + taxAmount);\n\n\tconst prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);\n\tconst payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);\n\tconst payableAmount = roundCurrency(\n\t\ttaxInclusiveAmount - prepaidAmount + payableRoundingAmount,\n\t);\n\n\treturn {\n\t\ttaxTotal: { taxAmount, subtotals },\n\t\tmonetaryTotal: {\n\t\t\tlineExtensionAmount,\n\t\t\ttaxExclusiveAmount,\n\t\t\ttaxInclusiveAmount,\n\t\t\t...(allowanceTotalAmount ? { allowanceTotalAmount } : {}),\n\t\t\t...(chargeTotalAmount ? { chargeTotalAmount } : {}),\n\t\t\t...(prepaidAmount ? { prepaidAmount } : {}),\n\t\t\t...(payableRoundingAmount ? { payableRoundingAmount } : {}),\n\t\t\tpayableAmount,\n\t\t},\n\t};\n};\n\n/**\n * Split one document-level amount into an allowance or charge per VAT\n * category the lines use, pro rata by each category's line nets, so a\n * shipping charge or an invoice-wide discount on a mixed-rate invoice lands in\n * the right VAT subtotals (an ancillary cost follows the supply it belongs to).\n * Cent remainders go to the largest shares so the parts sum to `amount`\n * exactly; categories that receive nothing are omitted. With no positive\n * line net at all the whole amount goes to the first line's category.\n *\n * @throws {UblBuildError} for a line without a `taxCategory`.\n */\nexport const allocateAcrossTaxCategories = (\n\tamount: number,\n\tlines: UblLine[],\n\ttemplate: Pick<UblAllowanceCharge, \"chargeIndicator\" | \"reason\" | \"reasonCode\">,\n): UblAllowanceCharge[] => {\n\tconst groups = new Map<string, { category: UblTaxCategory; net: number }>();\n\tfor (const line of lines) {\n\t\tif (!line.taxCategory) {\n\t\t\tthrow new UblBuildError(\n\t\t\t\t`Line ${line.id} has no taxCategory (BT-151); cannot allocate across categories`,\n\t\t\t);\n\t\t}\n\t\tconst key = categoryKey(line.taxCategory);\n\t\tconst current = groups.get(key) ?? { category: line.taxCategory, net: 0 };\n\t\tcurrent.net = roundCurrency(current.net + Math.max(0, lineNet(line)));\n\t\tgroups.set(key, current);\n\t}\n\tconst entries = Array.from(groups.values());\n\tconst total = roundCurrency(amount);\n\tif (entries.length === 0 || total === 0) return [];\n\tconst netSum = entries.reduce((sum, entry) => sum + entry.net, 0);\n\tconst shares =\n\t\tnetSum > 0\n\t\t\t? entries.map((entry) => (total * entry.net) / netSum)\n\t\t\t: entries.map((_entry, index) => (index === 0 ? total : 0));\n\tconst cents = shares.map((share) => Math.floor(share * 100 + 1e-9));\n\tlet remainder =\n\t\tMath.round(total * 100) - cents.reduce((sum, value) => sum + value, 0);\n\tconst order = shares\n\t\t.map((share, index) => ({\n\t\t\tindex,\n\t\t\tfraction: share * 100 - Math.floor(share * 100 + 1e-9),\n\t\t}))\n\t\t.sort((a, b) => b.fraction - a.fraction);\n\tfor (const { index } of order) {\n\t\tif (remainder <= 0) break;\n\t\tcents[index] = (cents[index] ?? 0) + 1;\n\t\tremainder -= 1;\n\t}\n\treturn entries.flatMap((entry, index) => {\n\t\tconst value = (cents[index] ?? 0) / 100;\n\t\tif (value === 0) return [];\n\t\treturn [compact({ ...template, amount: value, taxCategory: entry.category })];\n\t});\n};\n"],"mappings":";;;;;;AAGA,MAAa,uBACZ;;AAGD,MAAa,iBAAiB;;AAG9B,MAAa,oBAAoB;;AAEjC,MAAa,wBAAwB;;AAGrC,MAAa,oBAAoB;;AAGjC,MAAa,oBAAoB;;AAGjC,MAAa,uBAAu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AC,QAAQ;GAAE,GAAG;GAAU,QAAQ;GAAO,aAAa,MAAM;EAAS,CAAC,CAAC;CAC7E,CAAC;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@financica/ubl",
|
|
3
|
-
"version": "0.19.
|
|
3
|
+
"version": "0.19.3",
|
|
4
4
|
"description": "UBL (Universal Business Language) invoices in TypeScript: parse, build and serialize Peppol BIS Billing 3.0 documents.",
|
|
5
5
|
"homepage": "https://github.com/financica/ts-libs/tree/main/packages/ubl#readme",
|
|
6
6
|
"bugs": "https://github.com/financica/ts-libs/issues",
|
package/src/build/identifiers.ts
CHANGED
|
@@ -203,12 +203,13 @@ export const extractCustomerTaxIdentifiers = (
|
|
|
203
203
|
*
|
|
204
204
|
* 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;
|
|
205
205
|
* 2. a GLN under EAS `0088`;
|
|
206
|
-
* 3. the
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
210
|
-
* for Sweden, Norway and Denmark, whose VAT
|
|
211
|
-
* company number inside the VAT number
|
|
206
|
+
* 3. for Belgium, the enterprise number (VAT digits without the `BE` prefix)
|
|
207
|
+
* under EAS `0208`, ahead of the VAT scheme: Belgium mandates `0208`, and
|
|
208
|
+
* a stale `9925` left at a previous access point must not win the lookup;
|
|
209
|
+
* 4. the VAT number under its country's VAT EAS scheme (see
|
|
210
|
+
* {@link resolveVatEndpoint}); for Sweden, Norway and Denmark, whose VAT
|
|
211
|
+
* schemes were withdrawn, the company number inside the VAT number
|
|
212
|
+
* (`0007`, `0192`, `0184`);
|
|
212
213
|
* 5. a generic tax/registration number under its country's company-ID scheme.
|
|
213
214
|
*
|
|
214
215
|
* `countryCode` (the customer's country, when known) disambiguates schemes for
|
|
@@ -231,12 +232,11 @@ export const listPeppolReceiverIdentifierCandidates = (
|
|
|
231
232
|
const gln = normalizeString(customer.glnNumber);
|
|
232
233
|
if (gln) add({ scheme: "0088", value: normalizeParticipantValue("0088", gln) });
|
|
233
234
|
|
|
234
|
-
// 3.
|
|
235
|
+
// 3. Belgium: the enterprise number under EAS 0208 (the VAT digits without
|
|
236
|
+
// the `BE` prefix) comes first. It is the identifier Belgium mandates, so a
|
|
237
|
+
// party registered under both is addressed where it is required to be, and
|
|
238
|
+
// a 9925 left behind at a former access point cannot capture the document.
|
|
235
239
|
const vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });
|
|
236
|
-
add(vat);
|
|
237
|
-
|
|
238
|
-
// 4. Belgium also reaches parties by enterprise number under EAS 0208; it is
|
|
239
|
-
// the VAT digits without the `BE` prefix, and some entities register only so.
|
|
240
240
|
if (vat?.scheme === "9925") {
|
|
241
241
|
add(
|
|
242
242
|
buildCompanyId({
|
|
@@ -246,6 +246,10 @@ export const listPeppolReceiverIdentifierCandidates = (
|
|
|
246
246
|
);
|
|
247
247
|
}
|
|
248
248
|
|
|
249
|
+
// 4. VAT number → the country's VAT EAS scheme (e.g. BE → 9925), the
|
|
250
|
+
// fallback for parties registered only under it.
|
|
251
|
+
add(vat);
|
|
252
|
+
|
|
249
253
|
// 4b. Sweden has no VAT scheme left (SE:VAT 9955 is withdrawn); a Swedish VAT
|
|
250
254
|
// number is the organisationsnummer + `01`, registered under EAS 0007.
|
|
251
255
|
const compactVat = (customer.vatNumber ?? "")
|