@financica/ubl 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,143 @@
1
+ import { deriveUnitPrice, roundCurrency } from "./numeric";
2
+ import type {
3
+ UblLine,
4
+ UblMonetaryTotal,
5
+ UblTaxCategory,
6
+ UblTaxSubtotal,
7
+ UblTaxTotal,
8
+ } from "./ubl/types";
9
+
10
+ /**
11
+ * Adjust the largest line's net amount so the line nets sum to the
12
+ * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).
13
+ *
14
+ * Reconciling at the *line* level — rather than directly on the VAT breakdown —
15
+ * keeps the document consistent bottom-up: the VAT category taxable amounts
16
+ * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the
17
+ * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level
18
+ * coupon; larger ones indicate a real upstream data problem.
19
+ */
20
+ export const reconcileLinesToExclTotal = (
21
+ lines: UblLine[],
22
+ authoritativeTotalExclVat: number,
23
+ ): UblLine[] => {
24
+ if (lines.length === 0) return lines;
25
+ const computed = roundCurrency(
26
+ lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),
27
+ );
28
+ const diff = roundCurrency(authoritativeTotalExclVat - computed);
29
+ if (diff === 0) return lines;
30
+
31
+ const largestIdx = lines.reduce(
32
+ (maxIdx, line, idx, arr) =>
33
+ line.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0)
34
+ ? idx
35
+ : maxIdx,
36
+ 0,
37
+ );
38
+
39
+ return lines.map((line, idx) => {
40
+ if (idx !== largestIdx) return line;
41
+ const adjusted = roundCurrency(line.lineExtensionAmount + diff);
42
+ // Re-derive the price from the adjusted net through the shared helper —
43
+ // nudging the net without re-deriving BT-146/BT-149 to match is exactly
44
+ // what PEPPOL-EN16931-R120 rejects. Assign `baseQuantity` unconditionally
45
+ // so a line that no longer needs one doesn't keep a stale value.
46
+ const { priceAmount, baseQuantity } = deriveUnitPrice(adjusted, line.quantity);
47
+ return {
48
+ ...line,
49
+ lineExtensionAmount: adjusted,
50
+ priceAmount,
51
+ baseQuantity,
52
+ };
53
+ });
54
+ };
55
+
56
+ const categoryKey = (category: UblTaxCategory): string =>
57
+ `${category.id}:${category.percent}`;
58
+
59
+ export interface BuildTaxTotalsResult {
60
+ taxTotal: UblTaxTotal;
61
+ monetaryTotal: UblMonetaryTotal;
62
+ }
63
+
64
+ export interface BuildTaxTotalsOptions {
65
+ /**
66
+ * BT-113 — amount already paid, **gross (VAT-inclusive)**. Subtracted from
67
+ * BT-112 to derive the outstanding `payableAmount` (BR-CO-16). Pass the full
68
+ * gross total for a settled document so it reports a payable amount of 0.
69
+ */
70
+ prepaidAmount?: number;
71
+ /** BT-114 — rounding applied to the payable amount. */
72
+ payableRoundingAmount?: number;
73
+ }
74
+
75
+ /**
76
+ * Group lines by `(category, percent)` into a VAT breakdown and compute the
77
+ * document monetary totals.
78
+ *
79
+ * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,
80
+ * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the
81
+ * upstream per-line tax cents. This guarantees the breakdown is internally
82
+ * consistent and passes validation; it can differ by a cent from the figure a
83
+ * payment processor reported, which is an unavoidable artifact of representing
84
+ * a cents-rounded system as a rate-based VAT breakdown.
85
+ *
86
+ * `payableAmount` is derived per BR-CO-16 (`BT-112 − BT-113 + BT-114`) so the
87
+ * invariant holds by construction. The result is *not* clamped: a prepayment
88
+ * exceeding the total yields a negative payable amount, surfacing the upstream
89
+ * overpayment rather than hiding it.
90
+ */
91
+ export const buildTaxTotals = (
92
+ lines: UblLine[],
93
+ options?: BuildTaxTotalsOptions,
94
+ ): BuildTaxTotalsResult => {
95
+ const groups = new Map<
96
+ string,
97
+ { category: UblTaxCategory; taxableAmount: number }
98
+ >();
99
+
100
+ for (const line of lines) {
101
+ const key = categoryKey(line.taxCategory);
102
+ const current = groups.get(key) ?? {
103
+ category: line.taxCategory,
104
+ taxableAmount: 0,
105
+ };
106
+ current.taxableAmount = roundCurrency(
107
+ current.taxableAmount + line.lineExtensionAmount,
108
+ );
109
+ groups.set(key, current);
110
+ }
111
+
112
+ const subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({
113
+ taxableAmount: group.taxableAmount,
114
+ taxAmount: roundCurrency((group.taxableAmount * group.category.percent) / 100),
115
+ category: group.category,
116
+ }));
117
+
118
+ const lineExtensionAmount = roundCurrency(
119
+ lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),
120
+ );
121
+ const taxAmount = roundCurrency(
122
+ subtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0),
123
+ );
124
+ const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
125
+
126
+ const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
127
+ const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
128
+ const payableAmount = roundCurrency(
129
+ taxInclusiveAmount - prepaidAmount + payableRoundingAmount,
130
+ );
131
+
132
+ return {
133
+ taxTotal: { taxAmount, subtotals },
134
+ monetaryTotal: {
135
+ lineExtensionAmount,
136
+ taxExclusiveAmount: lineExtensionAmount,
137
+ taxInclusiveAmount,
138
+ ...(prepaidAmount ? { prepaidAmount } : {}),
139
+ ...(payableRoundingAmount ? { payableRoundingAmount } : {}),
140
+ payableAmount,
141
+ },
142
+ };
143
+ };
@@ -0,0 +1,30 @@
1
+ /** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */
2
+
3
+ /** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */
4
+ export const UBL_CUSTOMIZATION_ID =
5
+ "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0";
6
+
7
+ /** Peppol BIS Billing 3.0 process (BT-23). */
8
+ export const UBL_PROFILE_ID = "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0";
9
+
10
+ /** UNTDID 1001 — commercial invoice. */
11
+ export const INVOICE_TYPE_CODE = "380";
12
+ /** UNTDID 1001 — credit note. */
13
+ export const CREDIT_NOTE_TYPE_CODE = "381";
14
+
15
+ /** UN/ECE Recommendation 20 — "one / piece" (the default line unit). */
16
+ export const DEFAULT_UNIT_CODE = "C62";
17
+
18
+ /** UNCL5153 — the VAT tax scheme identifier. */
19
+ export const VAT_TAX_SCHEME_ID = "VAT";
20
+
21
+ /** ISO 3166-1 alpha-2 list identifier for `cbc:IdentificationCode`. */
22
+ export const COUNTRY_CODE_LIST_ID = "ISO3166-1:Alpha2";
23
+
24
+ export const NS_INVOICE = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
25
+ export const NS_CREDIT_NOTE =
26
+ "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
27
+ export const NS_CAC =
28
+ "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
29
+ export const NS_CBC =
30
+ "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
@@ -0,0 +1,258 @@
1
+ import { el, serializeDocument, type XmlElement } from "../xml";
2
+ import {
3
+ COUNTRY_CODE_LIST_ID,
4
+ CREDIT_NOTE_TYPE_CODE,
5
+ INVOICE_TYPE_CODE,
6
+ NS_CAC,
7
+ NS_CBC,
8
+ NS_CREDIT_NOTE,
9
+ NS_INVOICE,
10
+ UBL_CUSTOMIZATION_ID,
11
+ UBL_PROFILE_ID,
12
+ VAT_TAX_SCHEME_ID,
13
+ } from "./constants";
14
+ import type {
15
+ UblAddress,
16
+ UblAttachment,
17
+ UblDocument,
18
+ UblLine,
19
+ UblParty,
20
+ UblPeriod,
21
+ UblTaxCategory,
22
+ UblTaxSubtotal,
23
+ } from "./types";
24
+
25
+ /** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */
26
+ const amount = (value: number): string => value.toFixed(2);
27
+
28
+ /** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */
29
+ const percent = (value: number): string => {
30
+ const rounded = Math.round(value * 100) / 100;
31
+ return Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);
32
+ };
33
+
34
+ const money = (name: string, value: number, currency: string): XmlElement =>
35
+ el(name, { currencyID: currency }, amount(value));
36
+
37
+ const vatTaxScheme = (): XmlElement =>
38
+ el("cac:TaxScheme", null, [el("cbc:ID", null, VAT_TAX_SCHEME_ID)]);
39
+
40
+ /**
41
+ * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)
42
+ * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption
43
+ * reason for the non-charging categories (E/AE/O/K/G).
44
+ */
45
+ const taxCategory = (name: string, category: UblTaxCategory): XmlElement =>
46
+ el(name, null, [
47
+ el("cbc:ID", null, category.id),
48
+ el("cbc:Percent", null, percent(category.percent)),
49
+ category.exemptionReason
50
+ ? el("cbc:TaxExemptionReason", null, category.exemptionReason)
51
+ : null,
52
+ vatTaxScheme(),
53
+ ]);
54
+
55
+ const postalAddress = (address: UblAddress): XmlElement =>
56
+ el("cac:PostalAddress", null, [
57
+ address.street ? el("cbc:StreetName", null, address.street) : null,
58
+ address.additionalStreet
59
+ ? el("cbc:AdditionalStreetName", null, address.additionalStreet)
60
+ : null,
61
+ address.city ? el("cbc:CityName", null, address.city) : null,
62
+ address.postalZone ? el("cbc:PostalZone", null, address.postalZone) : null,
63
+ address.countrySubentity
64
+ ? el("cbc:CountrySubentity", null, address.countrySubentity)
65
+ : null,
66
+ address.countryCode
67
+ ? el("cac:Country", null, [
68
+ el(
69
+ "cbc:IdentificationCode",
70
+ { listID: COUNTRY_CODE_LIST_ID },
71
+ address.countryCode,
72
+ ),
73
+ ])
74
+ : null,
75
+ ]);
76
+
77
+ const party = (source: UblParty): XmlElement =>
78
+ el("cac:Party", null, [
79
+ source.endpoint
80
+ ? el(
81
+ "cbc:EndpointID",
82
+ { schemeID: source.endpoint.scheme },
83
+ source.endpoint.value,
84
+ )
85
+ : null,
86
+ el("cac:PartyName", null, [el("cbc:Name", null, source.name)]),
87
+ postalAddress(source.address),
88
+ source.vatNumber
89
+ ? el("cac:PartyTaxScheme", null, [
90
+ el("cbc:CompanyID", null, source.vatNumber),
91
+ vatTaxScheme(),
92
+ ])
93
+ : null,
94
+ el("cac:PartyLegalEntity", null, [
95
+ el("cbc:RegistrationName", null, source.legalName ?? source.name),
96
+ source.companyId
97
+ ? el(
98
+ "cbc:CompanyID",
99
+ source.companyId.scheme
100
+ ? { schemeID: source.companyId.scheme }
101
+ : null,
102
+ source.companyId.value,
103
+ )
104
+ : null,
105
+ ]),
106
+ ]);
107
+
108
+ const taxSubtotal = (subtotal: UblTaxSubtotal, currency: string): XmlElement =>
109
+ el("cac:TaxSubtotal", null, [
110
+ money("cbc:TaxableAmount", subtotal.taxableAmount, currency),
111
+ money("cbc:TaxAmount", subtotal.taxAmount, currency),
112
+ taxCategory("cac:TaxCategory", subtotal.category),
113
+ ]);
114
+
115
+ /**
116
+ * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`
117
+ * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`
118
+ * — emitting them after it produces schema-invalid XML.
119
+ */
120
+ const legalMonetaryTotalChildren = (doc: UblDocument): XmlElement[] => {
121
+ const { currency, monetaryTotal: total } = doc;
122
+ const children: (XmlElement | null)[] = [
123
+ money("cbc:LineExtensionAmount", total.lineExtensionAmount, currency),
124
+ money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount, currency),
125
+ money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount, currency),
126
+ total.prepaidAmount
127
+ ? money("cbc:PrepaidAmount", total.prepaidAmount, currency)
128
+ : null,
129
+ total.payableRoundingAmount
130
+ ? money("cbc:PayableRoundingAmount", total.payableRoundingAmount, currency)
131
+ : null,
132
+ money("cbc:PayableAmount", total.payableAmount, currency),
133
+ ];
134
+ return children.filter((child): child is XmlElement => Boolean(child));
135
+ };
136
+
137
+ /**
138
+ * `cac:InvoicePeriod`. Null when neither bound is set — an empty period element
139
+ * fails BR-CO-19, which requires at least one of the two dates.
140
+ */
141
+ const invoicePeriod = (period: UblPeriod | null | undefined): XmlElement | null => {
142
+ if (!period || (!period.startDate && !period.endDate)) return null;
143
+ return el(
144
+ "cac:InvoicePeriod",
145
+ null,
146
+ [
147
+ period.startDate ? el("cbc:StartDate", null, period.startDate) : null,
148
+ period.endDate ? el("cbc:EndDate", null, period.endDate) : null,
149
+ ].filter((child): child is XmlElement => Boolean(child)),
150
+ );
151
+ };
152
+
153
+ const line = (
154
+ source: UblLine,
155
+ currency: string,
156
+ documentType: UblDocument["documentType"],
157
+ ): XmlElement => {
158
+ const lineElementName =
159
+ documentType === "creditNote" ? "cac:CreditNoteLine" : "cac:InvoiceLine";
160
+ const quantityElementName =
161
+ documentType === "creditNote" ? "cbc:CreditedQuantity" : "cbc:InvoicedQuantity";
162
+
163
+ return el(lineElementName, null, [
164
+ el("cbc:ID", null, source.id),
165
+ el(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),
166
+ money("cbc:LineExtensionAmount", source.lineExtensionAmount, currency),
167
+ invoicePeriod(source.invoicePeriod),
168
+ el("cac:Item", null, [
169
+ el("cbc:Name", null, source.name),
170
+ taxCategory("cac:ClassifiedTaxCategory", source.taxCategory),
171
+ ]),
172
+ // BT-149's unit code must match the invoiced/credited quantity's
173
+ // (PEPPOL-EN16931-R130).
174
+ el("cac:Price", null, [
175
+ money("cbc:PriceAmount", source.priceAmount, currency),
176
+ source.baseQuantity != null
177
+ ? el(
178
+ "cbc:BaseQuantity",
179
+ { unitCode: source.unitCode },
180
+ String(source.baseQuantity),
181
+ )
182
+ : null,
183
+ ]),
184
+ ]);
185
+ };
186
+
187
+ const attachmentReference = (attachment: UblAttachment): XmlElement =>
188
+ el("cac:AdditionalDocumentReference", null, [
189
+ el("cbc:ID", null, attachment.id),
190
+ el("cac:Attachment", null, [
191
+ el(
192
+ "cbc:EmbeddedDocumentBinaryObject",
193
+ { mimeCode: attachment.mimeCode, filename: attachment.filename },
194
+ attachment.base64,
195
+ ),
196
+ ]),
197
+ ]);
198
+
199
+ const billingReference = (precedingInvoiceId: string): XmlElement =>
200
+ el("cac:BillingReference", null, [
201
+ el("cac:InvoiceDocumentReference", null, [
202
+ el("cbc:ID", null, precedingInvoiceId),
203
+ ]),
204
+ ]);
205
+
206
+ /** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */
207
+ export const serializeUblDocument = (doc: UblDocument): string => {
208
+ const isCreditNote = doc.documentType === "creditNote";
209
+ const rootName = isCreditNote ? "CreditNote" : "Invoice";
210
+ const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
211
+ const typeCodeElement = isCreditNote
212
+ ? el("cbc:CreditNoteTypeCode", null, CREDIT_NOTE_TYPE_CODE)
213
+ : el("cbc:InvoiceTypeCode", null, INVOICE_TYPE_CODE);
214
+
215
+ const children: (XmlElement | null | false)[] = [
216
+ el("cbc:CustomizationID", null, UBL_CUSTOMIZATION_ID),
217
+ el("cbc:ProfileID", null, UBL_PROFILE_ID),
218
+ el("cbc:ID", null, doc.id),
219
+ el("cbc:IssueDate", null, doc.issueDate),
220
+ // CreditNote has no DueDate element in the UBL sequence.
221
+ !isCreditNote && doc.dueDate ? el("cbc:DueDate", null, doc.dueDate) : null,
222
+ typeCodeElement,
223
+ doc.note ? el("cbc:Note", null, doc.note) : null,
224
+ el("cbc:DocumentCurrencyCode", null, doc.currency),
225
+ doc.buyerReference ? el("cbc:BuyerReference", null, doc.buyerReference) : null,
226
+ invoicePeriod(doc.invoicePeriod),
227
+ doc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,
228
+ ...doc.attachments.map(attachmentReference),
229
+ el("cac:AccountingSupplierParty", null, [party(doc.supplier)]),
230
+ el("cac:AccountingCustomerParty", null, [party(doc.customer)]),
231
+ // BT-20. In both the Invoice and CreditNote sequences PaymentTerms sits
232
+ // after the parties (and PaymentMeans, which we do not emit) and before
233
+ // TaxTotal.
234
+ doc.paymentTermsNote
235
+ ? el("cac:PaymentTerms", null, [el("cbc:Note", null, doc.paymentTermsNote)])
236
+ : null,
237
+ el("cac:TaxTotal", null, [
238
+ money("cbc:TaxAmount", doc.taxTotal.taxAmount, doc.currency),
239
+ ...doc.taxTotal.subtotals.map((subtotal) =>
240
+ taxSubtotal(subtotal, doc.currency),
241
+ ),
242
+ ]),
243
+ el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
244
+ ...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),
245
+ ];
246
+
247
+ const root = el(
248
+ rootName,
249
+ {
250
+ xmlns: rootNamespace,
251
+ "xmlns:cac": NS_CAC,
252
+ "xmlns:cbc": NS_CBC,
253
+ },
254
+ children.filter((child): child is XmlElement => Boolean(child)),
255
+ );
256
+
257
+ return serializeDocument(root);
258
+ };
@@ -0,0 +1,179 @@
1
+ /**
2
+ * A vendor-neutral model of a Peppol BIS Billing 3.0 document.
3
+ *
4
+ * This is the intermediate representation the builders in `../` (and, for
5
+ * Stripe data, `stripe-ubl`) produce; `./serialize.ts` turns it into UBL XML.
6
+ * It is deliberately a thin, construction-oriented mirror of the UBL fields we
7
+ * populate — not a full UBL object graph.
8
+ */
9
+
10
+ export interface UblAddress {
11
+ /** `cbc:StreetName` (BT-35). */
12
+ street: string | null;
13
+ /** `cbc:AdditionalStreetName` (BT-36). */
14
+ additionalStreet: string | null;
15
+ /** `cbc:CityName` (BT-37). */
16
+ city: string | null;
17
+ /** `cbc:PostalZone` (BT-38). */
18
+ postalZone: string | null;
19
+ /** `cbc:CountrySubentity` (BT-39). */
20
+ countrySubentity: string | null;
21
+ /** `cac:Country/cbc:IdentificationCode` (BT-40) — ISO 3166-1 alpha-2. */
22
+ countryCode: string | null;
23
+ }
24
+
25
+ /** Peppol participant identifier, e.g. scheme `0208`, value `0800279001`. */
26
+ export interface UblEndpoint {
27
+ scheme: string;
28
+ value: string;
29
+ }
30
+
31
+ /** Legal registration identifier, e.g. a Belgian enterprise number. */
32
+ export interface UblCompanyId {
33
+ value: string;
34
+ /** ICD scheme (e.g. `0208` for the Belgian CBE), when known. */
35
+ scheme?: string | null;
36
+ }
37
+
38
+ export interface UblParty {
39
+ /** `cbc:EndpointID` (BT-49/BT-34) — the Peppol routing identifier. */
40
+ endpoint: UblEndpoint | null;
41
+ /** `cac:PartyName/cbc:Name` (BT-27/BT-44). */
42
+ name: string;
43
+ address: UblAddress;
44
+ /** `cac:PartyTaxScheme/cbc:CompanyID` with `VAT` scheme (BT-31/BT-48). */
45
+ vatNumber: string | null;
46
+ /** `cac:PartyLegalEntity/cbc:RegistrationName` (BT-27/BT-44). Defaults to `name`. */
47
+ legalName: string | null;
48
+ /** `cac:PartyLegalEntity/cbc:CompanyID` (BT-30/BT-47). */
49
+ companyId: UblCompanyId | null;
50
+ }
51
+
52
+ /**
53
+ * VAT breakdown category. `id` is a UNCL5305 code:
54
+ * - `S` Standard rate
55
+ * - `Z` Zero-rated goods
56
+ * - `E` Exempt from VAT
57
+ * - `AE` VAT reverse charge
58
+ * - `O` Services outside scope of tax
59
+ * - `K` Intra-community supply
60
+ * - `G` Export outside the EU
61
+ */
62
+ export interface UblTaxCategory {
63
+ id: string;
64
+ percent: number;
65
+ /** Required by EN 16931 (BR-E-10/BR-AE-10/…) for non-`S`/`Z` categories. */
66
+ exemptionReason?: string | null | undefined;
67
+ }
68
+
69
+ export interface UblLine {
70
+ /** `cbc:ID` (BT-126) — line identifier. */
71
+ id: string;
72
+ /** `cac:Item/cbc:Name` (BT-153). */
73
+ name: string;
74
+ /** `cbc:InvoicedQuantity` / `cbc:CreditedQuantity` (BT-129). */
75
+ quantity: number;
76
+ /** UN/ECE Rec 20 unit code (BT-130). */
77
+ unitCode: string;
78
+ /** `cbc:LineExtensionAmount` (BT-131) — net of VAT, after line discounts. */
79
+ lineExtensionAmount: number;
80
+ /** `cac:Price/cbc:PriceAmount` (BT-146) — net unit price. */
81
+ priceAmount: number;
82
+ /**
83
+ * `cac:Price/cbc:BaseQuantity` (BT-149) — the number of units `priceAmount`
84
+ * covers. Omitted means 1. Set it when the net doesn't divide evenly into
85
+ * cents, so `quantity × (priceAmount ÷ baseQuantity)` reproduces the line
86
+ * net exactly (PEPPOL-EN16931-R120); see `deriveUnitPrice`.
87
+ */
88
+ baseQuantity?: number | undefined;
89
+ /** `cac:InvoicePeriod` (BT-134/BT-135) — the line's own service period. */
90
+ invoicePeriod?: UblPeriod | null;
91
+ taxCategory: UblTaxCategory;
92
+ }
93
+
94
+ export interface UblTaxSubtotal {
95
+ /** `cbc:TaxableAmount` (BT-116). */
96
+ taxableAmount: number;
97
+ /** `cbc:TaxAmount` (BT-117). */
98
+ taxAmount: number;
99
+ category: UblTaxCategory;
100
+ }
101
+
102
+ export interface UblTaxTotal {
103
+ /** `cbc:TaxAmount` (BT-110) — sum of subtotal tax amounts. */
104
+ taxAmount: number;
105
+ subtotals: UblTaxSubtotal[];
106
+ }
107
+
108
+ export interface UblMonetaryTotal {
109
+ /** BT-106 — sum of line net amounts. */
110
+ lineExtensionAmount: number;
111
+ /** BT-109 — total without VAT. */
112
+ taxExclusiveAmount: number;
113
+ /** BT-112 — total with VAT. */
114
+ taxInclusiveAmount: number;
115
+ /**
116
+ * BT-113 — sum of amounts paid in advance. **Gross (VAT-inclusive)**, since
117
+ * BR-CO-16 subtracts it directly from BT-112. Omitted when absent or zero.
118
+ */
119
+ prepaidAmount?: number;
120
+ /** BT-114 — rounding applied to the payable amount. Omitted when absent or zero. */
121
+ payableRoundingAmount?: number;
122
+ /**
123
+ * BT-115 — amount due for payment, i.e. the *outstanding* amount.
124
+ * BR-CO-16: `BT-115 = BT-112 − BT-113 + BT-114`.
125
+ */
126
+ payableAmount: number;
127
+ }
128
+
129
+ /** An embedded supporting document (BG-24), e.g. the rendered PDF. */
130
+ export interface UblAttachment {
131
+ /** `cac:AdditionalDocumentReference/cbc:ID` (BT-122). */
132
+ id: string;
133
+ /** `cbc:EmbeddedDocumentBinaryObject/@filename`. */
134
+ filename: string;
135
+ /** MIME type, e.g. `application/pdf`. */
136
+ mimeCode: string;
137
+ /** Base64-encoded document bytes. */
138
+ base64: string;
139
+ }
140
+
141
+ /**
142
+ * A service period: BT-73/BT-74 on the document, BT-134/BT-135 on a line.
143
+ * Either bound may stand alone — UBL allows a half-open period — but a period
144
+ * with neither is omitted entirely.
145
+ */
146
+ export interface UblPeriod {
147
+ /** `YYYY-MM-DD`. */
148
+ startDate: string | null;
149
+ /** `YYYY-MM-DD`, inclusive. */
150
+ endDate: string | null;
151
+ }
152
+
153
+ export interface UblDocument {
154
+ documentType: "invoice" | "creditNote";
155
+ /** Invoice / credit note number (BT-1). */
156
+ id: string;
157
+ /** Issue date (BT-2), `YYYY-MM-DD`. */
158
+ issueDate: string;
159
+ /** Payment due date (BT-9). Invoices only. */
160
+ dueDate: string | null;
161
+ /** Free-text note (BT-22). */
162
+ note: string | null;
163
+ /** Payment terms note (BT-20, `cac:PaymentTerms/cbc:Note`). */
164
+ paymentTermsNote?: string | null;
165
+ /** Document currency (BT-5). */
166
+ currency: string;
167
+ /** Buyer reference (BT-10). */
168
+ buyerReference: string | null;
169
+ /** Invoicing period (BT-73/BT-74). */
170
+ invoicePeriod?: UblPeriod | null;
171
+ /** For credit notes: the referenced original invoice number (BT-25). */
172
+ precedingInvoiceId: string | null;
173
+ supplier: UblParty;
174
+ customer: UblParty;
175
+ lines: UblLine[];
176
+ taxTotal: UblTaxTotal;
177
+ monetaryTotal: UblMonetaryTotal;
178
+ attachments: UblAttachment[];
179
+ }
@@ -0,0 +1,6 @@
1
+ /** Trim a string; `null` when missing or blank. */
2
+ export const normalizeString = (value: string | null | undefined): string | null => {
3
+ if (typeof value !== "string") return null;
4
+ const normalized = value.trim();
5
+ return normalized.length > 0 ? normalized : null;
6
+ };
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Minimal, dependency-free XML builder + serializer.
3
+ *
4
+ * UBL is order-sensitive (every element sequence is fixed by the schema), so
5
+ * children are always explicit, ordered arrays. There is no attribute or text
6
+ * coercion magic beyond escaping — the UBL layer is responsible for emitting
7
+ * elements in the right order.
8
+ */
9
+
10
+ export type XmlAttrs = Record<string, string | number | null | undefined>;
11
+
12
+ export interface XmlElement {
13
+ name: string;
14
+ attrs?: XmlAttrs;
15
+ /** Leaf text content. Mutually exclusive with `children`. */
16
+ text?: string | number | null;
17
+ /** Child elements. Mutually exclusive with `text`. */
18
+ children?: XmlElement[];
19
+ }
20
+
21
+ /** Falsy children are dropped, so callers can write `cond && el(...)`. */
22
+ type ChildSpec = XmlElement | null | undefined | false;
23
+
24
+ /**
25
+ * Build an XML element.
26
+ *
27
+ * el("cbc:ID", null, "INV-1") → <cbc:ID>INV-1</cbc:ID>
28
+ * el("cbc:Amount", { currencyID: "EUR" }, "10.00") → <cbc:Amount currencyID="EUR">10.00</cbc:Amount>
29
+ * el("cac:Party", null, [child, cond && child2]) → nested element
30
+ */
31
+ export const el = (
32
+ name: string,
33
+ attrs?: XmlAttrs | null,
34
+ content?: string | number | null | ChildSpec[],
35
+ ): XmlElement => {
36
+ if (Array.isArray(content)) {
37
+ return {
38
+ name,
39
+ ...(attrs ? { attrs } : {}),
40
+ children: content.filter((c): c is XmlElement => Boolean(c)),
41
+ };
42
+ }
43
+ return {
44
+ name,
45
+ ...(attrs ? { attrs } : {}),
46
+ ...(content !== undefined ? { text: content } : {}),
47
+ };
48
+ };
49
+
50
+ const escapeText = (value: string): string =>
51
+ value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
52
+
53
+ const escapeAttr = (value: string): string => escapeText(value).replace(/"/g, "&quot;");
54
+
55
+ const serializeAttrs = (attrs: XmlAttrs | undefined): string => {
56
+ if (!attrs) return "";
57
+ return Object.entries(attrs)
58
+ .filter(([, value]) => value !== null && value !== undefined)
59
+ .map(([key, value]) => ` ${key}="${escapeAttr(String(value))}"`)
60
+ .join("");
61
+ };
62
+
63
+ const serializeElement = (node: XmlElement, indentLevel: number): string => {
64
+ const pad = " ".repeat(indentLevel);
65
+ const attrs = serializeAttrs(node.attrs);
66
+
67
+ if (node.text !== undefined && node.text !== null) {
68
+ return `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;
69
+ }
70
+
71
+ const children = node.children ?? [];
72
+ if (children.length === 0) {
73
+ return `${pad}<${node.name}${attrs}/>`;
74
+ }
75
+
76
+ const inner = children
77
+ .map((child) => serializeElement(child, indentLevel + 1))
78
+ .join("\n");
79
+ return `${pad}<${node.name}${attrs}>\n${inner}\n${pad}</${node.name}>`;
80
+ };
81
+
82
+ /** Serialize a root element into a UTF-8 XML document string. */
83
+ export const serializeDocument = (root: XmlElement): string =>
84
+ `<?xml version="1.0" encoding="UTF-8"?>\n${serializeElement(root, 0)}\n`;