@financica/ubl 0.15.1 → 0.17.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,154 @@
1
+ import { UblBuildError } from "../errors";
2
+ import type {
3
+ UblLine,
4
+ UblMonetaryTotal,
5
+ UblTaxCategory,
6
+ UblTaxSubtotal,
7
+ UblTaxTotal,
8
+ } from "../types";
9
+ import { deriveUnitPrice, roundCurrency } from "./numeric";
10
+ import { compact } from "./utils";
11
+
12
+ const lineNet = (line: UblLine): number => line.lineExtensionAmount ?? 0;
13
+
14
+ /**
15
+ * Adjust the largest line's net amount so the line nets sum to the
16
+ * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).
17
+ *
18
+ * Reconciling at the *line* level — rather than directly on the VAT breakdown —
19
+ * keeps the document consistent bottom-up: the VAT category taxable amounts
20
+ * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the
21
+ * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level
22
+ * coupon; larger ones indicate a real upstream data problem.
23
+ */
24
+ export const reconcileLinesToExclTotal = (
25
+ lines: UblLine[],
26
+ authoritativeTotalExclVat: number,
27
+ ): UblLine[] => {
28
+ if (lines.length === 0) return lines;
29
+ const computed = roundCurrency(lines.reduce((sum, line) => sum + lineNet(line), 0));
30
+ const diff = roundCurrency(authoritativeTotalExclVat - computed);
31
+ if (diff === 0) return lines;
32
+
33
+ const largestIdx = lines.reduce(
34
+ (maxIdx, line, idx, arr) =>
35
+ lineNet(line) > lineNet(arr[maxIdx] ?? line) ? idx : maxIdx,
36
+ 0,
37
+ );
38
+
39
+ return lines.map((line, idx) => {
40
+ if (idx !== largestIdx) return line;
41
+ const adjusted = roundCurrency(lineNet(line) + 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 { unitPrice, baseQuantity } = deriveUnitPrice(
47
+ adjusted,
48
+ line.quantity ?? 0,
49
+ );
50
+ return compact({
51
+ ...line,
52
+ lineExtensionAmount: adjusted,
53
+ unitPrice,
54
+ baseQuantity,
55
+ });
56
+ });
57
+ };
58
+
59
+ const categoryKey = (category: UblTaxCategory): string =>
60
+ `${category.id ?? ""}:${category.percent ?? ""}`;
61
+
62
+ export interface BuildTaxTotalsResult {
63
+ taxTotal: UblTaxTotal;
64
+ monetaryTotal: UblMonetaryTotal;
65
+ }
66
+
67
+ export interface BuildTaxTotalsOptions {
68
+ /**
69
+ * BT-113 — amount already paid, **gross (VAT-inclusive)**. Subtracted from
70
+ * BT-112 to derive the outstanding `payableAmount` (BR-CO-16). Pass the full
71
+ * gross total for a settled document so it reports a payable amount of 0.
72
+ */
73
+ prepaidAmount?: number;
74
+ /** BT-114 — rounding applied to the payable amount. */
75
+ payableRoundingAmount?: number;
76
+ }
77
+
78
+ /**
79
+ * Group lines by `(category, percent)` into a VAT breakdown and compute the
80
+ * document monetary totals.
81
+ *
82
+ * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,
83
+ * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the
84
+ * upstream per-line tax cents. This guarantees the breakdown is internally
85
+ * consistent and passes validation; it can differ by a cent from the figure a
86
+ * payment processor reported, which is an unavoidable artifact of representing
87
+ * a cents-rounded system as a rate-based VAT breakdown.
88
+ *
89
+ * `payableAmount` is derived per BR-CO-16 (`BT-112 − BT-113 + BT-114`) so the
90
+ * invariant holds by construction. The result is *not* clamped: a prepayment
91
+ * exceeding the total yields a negative payable amount, surfacing the upstream
92
+ * overpayment rather than hiding it.
93
+ *
94
+ * @throws {UblBuildError} for a line without a `taxCategory` — there is no
95
+ * VAT breakdown to put it in.
96
+ */
97
+ export const buildTaxTotals = (
98
+ lines: UblLine[],
99
+ options?: BuildTaxTotalsOptions,
100
+ ): BuildTaxTotalsResult => {
101
+ const groups = new Map<
102
+ string,
103
+ { category: UblTaxCategory; taxableAmount: number }
104
+ >();
105
+
106
+ for (const line of lines) {
107
+ if (!line.taxCategory) {
108
+ throw new UblBuildError(
109
+ `Line ${line.id} has no taxCategory (BT-151); cannot build the VAT breakdown`,
110
+ );
111
+ }
112
+ const key = categoryKey(line.taxCategory);
113
+ const current = groups.get(key) ?? {
114
+ category: line.taxCategory,
115
+ taxableAmount: 0,
116
+ };
117
+ current.taxableAmount = roundCurrency(current.taxableAmount + lineNet(line));
118
+ groups.set(key, current);
119
+ }
120
+
121
+ const subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({
122
+ taxableAmount: group.taxableAmount,
123
+ taxAmount: roundCurrency(
124
+ (group.taxableAmount * (group.category.percent ?? 0)) / 100,
125
+ ),
126
+ category: group.category,
127
+ }));
128
+
129
+ const lineExtensionAmount = roundCurrency(
130
+ lines.reduce((sum, line) => sum + lineNet(line), 0),
131
+ );
132
+ const taxAmount = roundCurrency(
133
+ subtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0),
134
+ );
135
+ const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
136
+
137
+ const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
138
+ const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
139
+ const payableAmount = roundCurrency(
140
+ taxInclusiveAmount - prepaidAmount + payableRoundingAmount,
141
+ );
142
+
143
+ return {
144
+ taxTotal: { taxAmount, subtotals },
145
+ monetaryTotal: {
146
+ lineExtensionAmount,
147
+ taxExclusiveAmount: lineExtensionAmount,
148
+ taxInclusiveAmount,
149
+ ...(prepaidAmount ? { prepaidAmount } : {}),
150
+ ...(payableRoundingAmount ? { payableRoundingAmount } : {}),
151
+ payableAmount,
152
+ },
153
+ };
154
+ };
@@ -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,437 @@
1
+ import { UblBuildError } from "../../errors";
2
+ import type {
3
+ UblAddress,
4
+ UblAttachment,
5
+ UblBillingReference,
6
+ UblInvoice,
7
+ UblInvoicePeriod,
8
+ UblLine,
9
+ UblParty,
10
+ UblTaxCategory,
11
+ UblTaxSubtotal,
12
+ } from "../../types";
13
+ import { el, serializeDocument, type XmlElement } from "../xml";
14
+ import {
15
+ COUNTRY_CODE_LIST_ID,
16
+ CREDIT_NOTE_TYPE_CODE,
17
+ INVOICE_TYPE_CODE,
18
+ NS_CAC,
19
+ NS_CBC,
20
+ NS_CREDIT_NOTE,
21
+ NS_INVOICE,
22
+ UBL_CUSTOMIZATION_ID,
23
+ UBL_PROFILE_ID,
24
+ VAT_TAX_SCHEME_ID,
25
+ } from "./constants";
26
+
27
+ // ── Validation ─────────────────────────────────────────────────────────
28
+ //
29
+ // The model is permissive (the parser reads whatever a document states); the
30
+ // serializer is where EN 16931 / Peppol BIS Billing 3.0 mandatory fields are
31
+ // enforced. Each check names the BT and the model path in its message.
32
+
33
+ const missing = (what: string, path: string): UblBuildError =>
34
+ new UblBuildError(`Missing ${what} (${path})`);
35
+
36
+ function required<T>(value: T | undefined, what: string, path: string): NonNullable<T> {
37
+ if (value === undefined || value === null || value === "") {
38
+ throw missing(what, path);
39
+ }
40
+ return value as NonNullable<T>;
41
+ }
42
+
43
+ /** Category `O` (outside scope) is the one category BR-O-05 forbids a percent on. */
44
+ const requiresPercent = (categoryId: string): boolean => categoryId !== "O";
45
+
46
+ const validateTaxCategory = (
47
+ category: UblTaxCategory | undefined,
48
+ path: string,
49
+ ): UblTaxCategory & { id: string } => {
50
+ const present = required(category, "VAT category (BT-151/BT-118)", path);
51
+ const id = required(present.id, "VAT category code (BT-151/BT-118)", `${path}.id`);
52
+ if (requiresPercent(id) && present.percent === undefined) {
53
+ throw missing(`VAT rate (BT-152/BT-119) for category ${id}`, `${path}.percent`);
54
+ }
55
+ return { ...present, id };
56
+ };
57
+
58
+ const validateLine = (line: UblLine, index: number): void => {
59
+ const path = `lines[${index}]`;
60
+ required(line.id, "line identifier (BT-126)", `${path}.id`);
61
+ required(line.quantity, "invoiced quantity (BT-129)", `${path}.quantity`);
62
+ required(line.unitCode, "unit code (BT-130)", `${path}.unitCode`);
63
+ required(line.unitPrice, "net unit price (BT-146)", `${path}.unitPrice`);
64
+ required(
65
+ line.lineExtensionAmount,
66
+ "line net amount (BT-131)",
67
+ `${path}.lineExtensionAmount`,
68
+ );
69
+ validateTaxCategory(line.taxCategory, `${path}.taxCategory`);
70
+ };
71
+
72
+ const isExternalOnly = (attachment: UblAttachment): boolean =>
73
+ attachment.externalUri !== undefined && attachment.base64Content === undefined;
74
+
75
+ const validateAttachment = (attachment: UblAttachment, index: number): void => {
76
+ if (isExternalOnly(attachment)) return;
77
+ const path = `attachments[${index}]`;
78
+ required(attachment.filename, "attachment filename (BT-125-2)", `${path}.filename`);
79
+ required(
80
+ attachment.mimeCode,
81
+ "attachment MIME code (BT-125-1)",
82
+ `${path}.mimeCode`,
83
+ );
84
+ required(
85
+ attachment.base64Content,
86
+ "attachment content (BT-125)",
87
+ `${path}.base64Content`,
88
+ );
89
+ };
90
+
91
+ const validateInvoice = (doc: UblInvoice): void => {
92
+ required(doc.id, "document identifier (BT-1)", "id");
93
+ required(doc.issueDate, "issue date (BT-2)", "issueDate");
94
+ required(doc.currency, "document currency (BT-5)", "currency");
95
+ required(doc.seller.name, "seller name (BT-27)", "seller.name");
96
+ required(doc.buyer.name, "buyer name (BT-44)", "buyer.name");
97
+ if (doc.seller.endpoint && doc.seller.endpoint.scheme === undefined) {
98
+ throw missing("seller endpoint scheme (BT-34-1)", "seller.endpoint.scheme");
99
+ }
100
+ if (doc.buyer.endpoint && doc.buyer.endpoint.scheme === undefined) {
101
+ throw missing("buyer endpoint scheme (BT-49-1)", "buyer.endpoint.scheme");
102
+ }
103
+ if (doc.lines.length === 0) {
104
+ throw new UblBuildError("A document needs at least one line (BG-25, lines)");
105
+ }
106
+ doc.lines.forEach(validateLine);
107
+ required(doc.taxTotal.taxAmount, "total VAT amount (BT-110)", "taxTotal.taxAmount");
108
+ const total = doc.monetaryTotal;
109
+ required(
110
+ total.lineExtensionAmount,
111
+ "sum of line net amounts (BT-106)",
112
+ "monetaryTotal.lineExtensionAmount",
113
+ );
114
+ required(
115
+ total.taxExclusiveAmount,
116
+ "total without VAT (BT-109)",
117
+ "monetaryTotal.taxExclusiveAmount",
118
+ );
119
+ required(
120
+ total.taxInclusiveAmount,
121
+ "total with VAT (BT-112)",
122
+ "monetaryTotal.taxInclusiveAmount",
123
+ );
124
+ required(total.payableAmount, "amount due (BT-115)", "monetaryTotal.payableAmount");
125
+ (doc.attachments ?? []).forEach(validateAttachment);
126
+ };
127
+
128
+ // ── Formatting ─────────────────────────────────────────────────────────
129
+
130
+ /** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */
131
+ const amount = (value: number): string => value.toFixed(2);
132
+
133
+ /** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */
134
+ const percent = (value: number): string => {
135
+ const rounded = Math.round(value * 100) / 100;
136
+ return Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);
137
+ };
138
+
139
+ const money = (name: string, value: number, currency: string): XmlElement =>
140
+ el(name, { currencyID: currency }, amount(value));
141
+
142
+ const text = (name: string, value: string | undefined): XmlElement | null =>
143
+ value !== undefined ? el(name, null, value) : null;
144
+
145
+ const taxScheme = (schemeId: string | undefined): XmlElement =>
146
+ el("cac:TaxScheme", null, [el("cbc:ID", null, schemeId ?? VAT_TAX_SCHEME_ID)]);
147
+
148
+ /**
149
+ * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)
150
+ * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption
151
+ * reason for the non-charging categories (E/AE/O/K/G).
152
+ */
153
+ const taxCategory = (
154
+ name: string,
155
+ category: UblTaxCategory,
156
+ path: string,
157
+ ): XmlElement => {
158
+ const valid = validateTaxCategory(category, path);
159
+ return el(name, null, [
160
+ el("cbc:ID", null, valid.id),
161
+ valid.percent !== undefined
162
+ ? el("cbc:Percent", null, percent(valid.percent))
163
+ : null,
164
+ text("cbc:TaxExemptionReason", valid.exemptionReason),
165
+ taxScheme(valid.schemeId),
166
+ ]);
167
+ };
168
+
169
+ const postalAddress = (address: UblAddress): XmlElement =>
170
+ el("cac:PostalAddress", null, [
171
+ text("cbc:StreetName", address.street),
172
+ text("cbc:AdditionalStreetName", address.additionalStreet),
173
+ text("cbc:CityName", address.city),
174
+ text("cbc:PostalZone", address.postalZone),
175
+ text("cbc:CountrySubentity", address.countrySubentity),
176
+ address.countryCode !== undefined
177
+ ? el("cac:Country", null, [
178
+ el(
179
+ "cbc:IdentificationCode",
180
+ { listID: COUNTRY_CODE_LIST_ID },
181
+ address.countryCode,
182
+ ),
183
+ ])
184
+ : null,
185
+ ]);
186
+
187
+ const party = (source: UblParty, name: string): XmlElement =>
188
+ el("cac:Party", null, [
189
+ source.endpoint
190
+ ? el(
191
+ "cbc:EndpointID",
192
+ { schemeID: source.endpoint.scheme ?? "" },
193
+ source.endpoint.value,
194
+ )
195
+ : null,
196
+ el("cac:PartyName", null, [el("cbc:Name", null, name)]),
197
+ source.address ? postalAddress(source.address) : null,
198
+ source.vatId !== undefined
199
+ ? el("cac:PartyTaxScheme", null, [
200
+ el("cbc:CompanyID", null, source.vatId),
201
+ taxScheme(source.taxSchemeId),
202
+ ])
203
+ : null,
204
+ el("cac:PartyLegalEntity", null, [
205
+ el("cbc:RegistrationName", null, source.registrationName ?? name),
206
+ source.companyId
207
+ ? el(
208
+ "cbc:CompanyID",
209
+ source.companyId.scheme !== undefined
210
+ ? { schemeID: source.companyId.scheme }
211
+ : null,
212
+ source.companyId.value,
213
+ )
214
+ : null,
215
+ ]),
216
+ ]);
217
+
218
+ const taxSubtotal = (
219
+ subtotal: UblTaxSubtotal,
220
+ currency: string,
221
+ index: number,
222
+ ): XmlElement => {
223
+ const path = `taxTotal.subtotals[${index}]`;
224
+ return el("cac:TaxSubtotal", null, [
225
+ money(
226
+ "cbc:TaxableAmount",
227
+ required(
228
+ subtotal.taxableAmount,
229
+ "taxable amount (BT-116)",
230
+ `${path}.taxableAmount`,
231
+ ),
232
+ currency,
233
+ ),
234
+ money(
235
+ "cbc:TaxAmount",
236
+ required(subtotal.taxAmount, "VAT amount (BT-117)", `${path}.taxAmount`),
237
+ currency,
238
+ ),
239
+ taxCategory(
240
+ "cac:TaxCategory",
241
+ required(subtotal.category, "VAT category (BT-118)", `${path}.category`),
242
+ `${path}.category`,
243
+ ),
244
+ ]);
245
+ };
246
+
247
+ /**
248
+ * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`
249
+ * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`
250
+ * — emitting them after it produces schema-invalid XML. BT-113/BT-114 are
251
+ * omitted when absent or zero.
252
+ */
253
+ const legalMonetaryTotalChildren = (doc: UblInvoice): XmlElement[] => {
254
+ const { currency, monetaryTotal: total } = doc;
255
+ const children: (XmlElement | null)[] = [
256
+ money("cbc:LineExtensionAmount", total.lineExtensionAmount ?? 0, currency),
257
+ money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount ?? 0, currency),
258
+ money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount ?? 0, currency),
259
+ total.prepaidAmount
260
+ ? money("cbc:PrepaidAmount", total.prepaidAmount, currency)
261
+ : null,
262
+ total.payableRoundingAmount
263
+ ? money("cbc:PayableRoundingAmount", total.payableRoundingAmount, currency)
264
+ : null,
265
+ money("cbc:PayableAmount", total.payableAmount ?? 0, currency),
266
+ ];
267
+ return children.filter((child): child is XmlElement => Boolean(child));
268
+ };
269
+
270
+ /**
271
+ * `cac:InvoicePeriod`. Null when neither bound is set — an empty period element
272
+ * fails BR-CO-19, which requires at least one of the two dates.
273
+ */
274
+ const invoicePeriod = (period: UblInvoicePeriod | undefined): XmlElement | null => {
275
+ if (!period || (period.startDate === undefined && period.endDate === undefined)) {
276
+ return null;
277
+ }
278
+ return el("cac:InvoicePeriod", null, [
279
+ text("cbc:StartDate", period.startDate),
280
+ text("cbc:EndDate", period.endDate),
281
+ ]);
282
+ };
283
+
284
+ const line = (
285
+ source: UblLine,
286
+ currency: string,
287
+ documentType: UblInvoice["documentType"],
288
+ ): XmlElement => {
289
+ const isCreditNote = documentType === "CreditNote";
290
+ const lineElementName = isCreditNote ? "cac:CreditNoteLine" : "cac:InvoiceLine";
291
+ const quantityElementName = isCreditNote
292
+ ? "cbc:CreditedQuantity"
293
+ : "cbc:InvoicedQuantity";
294
+ const unitCode = source.unitCode ?? "";
295
+ // BT-146 covers BT-149 units; the model holds the per-unit price.
296
+ const priceAmount = (source.unitPrice ?? 0) * (source.baseQuantity ?? 1);
297
+
298
+ return el(lineElementName, null, [
299
+ el("cbc:ID", null, source.id),
300
+ el(quantityElementName, { unitCode }, String(source.quantity ?? 0)),
301
+ money("cbc:LineExtensionAmount", source.lineExtensionAmount ?? 0, currency),
302
+ invoicePeriod(source.invoicePeriod),
303
+ el("cac:Item", null, [
304
+ text("cbc:Description", source.description),
305
+ // BT-153 is mandatory; BT-154 stands in when the line has no name.
306
+ el("cbc:Name", null, source.itemName ?? source.description ?? source.id),
307
+ taxCategory(
308
+ "cac:ClassifiedTaxCategory",
309
+ source.taxCategory ?? {},
310
+ `lines[${source.id}].taxCategory`,
311
+ ),
312
+ ]),
313
+ // BT-149's unit code must match the invoiced/credited quantity's
314
+ // (PEPPOL-EN16931-R130).
315
+ el("cac:Price", null, [
316
+ money("cbc:PriceAmount", priceAmount, currency),
317
+ source.baseQuantity !== undefined
318
+ ? el("cbc:BaseQuantity", { unitCode }, String(source.baseQuantity))
319
+ : null,
320
+ ]),
321
+ ]);
322
+ };
323
+
324
+ const attachmentReference = (attachment: UblAttachment): XmlElement =>
325
+ el("cac:AdditionalDocumentReference", null, [
326
+ el(
327
+ "cbc:ID",
328
+ null,
329
+ attachment.id ?? attachment.filename ?? attachment.externalUri ?? "",
330
+ ),
331
+ el("cac:Attachment", null, [
332
+ isExternalOnly(attachment)
333
+ ? el("cac:ExternalReference", null, [
334
+ el("cbc:URI", null, attachment.externalUri ?? ""),
335
+ ])
336
+ : el(
337
+ "cbc:EmbeddedDocumentBinaryObject",
338
+ {
339
+ mimeCode: attachment.mimeCode ?? "",
340
+ filename: attachment.filename ?? "",
341
+ },
342
+ attachment.base64Content ?? "",
343
+ ),
344
+ ]),
345
+ ]);
346
+
347
+ const billingReference = (reference: UblBillingReference): XmlElement | null => {
348
+ if (reference.invoiceId === undefined) return null;
349
+ return el("cac:BillingReference", null, [
350
+ el("cac:InvoiceDocumentReference", null, [
351
+ el("cbc:ID", null, reference.invoiceId),
352
+ ]),
353
+ ]);
354
+ };
355
+
356
+ /**
357
+ * Serialize a {@link UblInvoice} into a Peppol BIS Billing 3.0 XML string.
358
+ *
359
+ * Emits the subset of the model a Peppol BIS Billing 3.0 document needs:
360
+ * header (`customizationId`, `profileId` and `invoiceTypeCode` default to the
361
+ * BIS values), note, buyer reference, invoice period, billing reference,
362
+ * attachments, parties, payment terms, VAT breakdown, monetary totals and
363
+ * lines with their price and classified VAT category. Payment means,
364
+ * allowances/charges, delivery and the document references are not emitted.
365
+ *
366
+ * @throws {UblBuildError} when a field EN 16931 / Peppol BIS makes mandatory is
367
+ * missing: document id, issue date, currency, seller and buyer name, an
368
+ * endpoint without a scheme, at least one line, per line the quantity, unit
369
+ * code, unit price, net amount and VAT category (id, plus the rate unless the
370
+ * category is `O`), the total VAT amount, the four monetary totals, and for an
371
+ * embedded attachment its filename, MIME code and content.
372
+ */
373
+ export const serializeUblInvoice = (doc: UblInvoice): string => {
374
+ validateInvoice(doc);
375
+
376
+ const isCreditNote = doc.documentType === "CreditNote";
377
+ const rootName = isCreditNote ? "CreditNote" : "Invoice";
378
+ const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
379
+ const typeCodeElement = isCreditNote
380
+ ? el(
381
+ "cbc:CreditNoteTypeCode",
382
+ null,
383
+ doc.invoiceTypeCode ?? CREDIT_NOTE_TYPE_CODE,
384
+ )
385
+ : el("cbc:InvoiceTypeCode", null, doc.invoiceTypeCode ?? INVOICE_TYPE_CODE);
386
+
387
+ const children: (XmlElement | null | false)[] = [
388
+ el("cbc:CustomizationID", null, doc.customizationId ?? UBL_CUSTOMIZATION_ID),
389
+ el("cbc:ProfileID", null, doc.profileId ?? UBL_PROFILE_ID),
390
+ el("cbc:ID", null, doc.id),
391
+ el("cbc:IssueDate", null, doc.issueDate),
392
+ // CreditNote has no DueDate element in the UBL sequence.
393
+ !isCreditNote ? text("cbc:DueDate", doc.dueDate) : null,
394
+ typeCodeElement,
395
+ text("cbc:Note", doc.note),
396
+ el("cbc:DocumentCurrencyCode", null, doc.currency),
397
+ text("cbc:BuyerReference", doc.buyerReference),
398
+ invoicePeriod(doc.invoicePeriod),
399
+ doc.billingReference ? billingReference(doc.billingReference) : null,
400
+ ...(doc.attachments ?? []).map(attachmentReference),
401
+ el("cac:AccountingSupplierParty", null, [
402
+ party(doc.seller, doc.seller.name ?? ""),
403
+ ]),
404
+ el("cac:AccountingCustomerParty", null, [
405
+ party(doc.buyer, doc.buyer.name ?? ""),
406
+ ]),
407
+ // BT-20. In both the Invoice and CreditNote sequences PaymentTerms sits
408
+ // after the parties (and PaymentMeans, which we do not emit) and before
409
+ // TaxTotal.
410
+ doc.paymentTermsNote !== undefined
411
+ ? el("cac:PaymentTerms", null, [el("cbc:Note", null, doc.paymentTermsNote)])
412
+ : null,
413
+ el("cac:TaxTotal", null, [
414
+ money("cbc:TaxAmount", doc.taxTotal.taxAmount ?? 0, doc.currency),
415
+ ...doc.taxTotal.subtotals.map((subtotal, index) =>
416
+ taxSubtotal(subtotal, doc.currency, index),
417
+ ),
418
+ ]),
419
+ el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
420
+ ...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),
421
+ ];
422
+
423
+ const root = el(
424
+ rootName,
425
+ {
426
+ xmlns: rootNamespace,
427
+ "xmlns:cac": NS_CAC,
428
+ "xmlns:cbc": NS_CBC,
429
+ },
430
+ children.filter((child): child is XmlElement => Boolean(child)),
431
+ );
432
+
433
+ return serializeDocument(root);
434
+ };
435
+
436
+ /** Alias of {@link serializeUblInvoice}, kept under the historical name. */
437
+ export const serializeUblDocument = serializeUblInvoice;
@@ -0,0 +1,14 @@
1
+ /** Trim a string; `undefined` when missing or blank. */
2
+ export const normalizeString = (
3
+ value: string | null | undefined,
4
+ ): string | undefined => {
5
+ if (typeof value !== "string") return undefined;
6
+ const normalized = value.trim();
7
+ return normalized.length > 0 ? normalized : undefined;
8
+ };
9
+
10
+ /** Drop `undefined`-valued keys so an absent field is an absent key. */
11
+ export const compact = <T extends object>(value: T): T =>
12
+ Object.fromEntries(
13
+ Object.entries(value).filter(([, entry]) => entry !== undefined),
14
+ ) as T;