@financica/ubl 0.16.0 → 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.
@@ -1,3 +1,15 @@
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";
1
13
  import { el, serializeDocument, type XmlElement } from "../xml";
2
14
  import {
3
15
  COUNTRY_CODE_LIST_ID,
@@ -11,16 +23,109 @@ import {
11
23
  UBL_PROFILE_ID,
12
24
  VAT_TAX_SCHEME_ID,
13
25
  } from "./constants";
14
- import type {
15
- UblAddress,
16
- UblAttachment,
17
- UblDocument,
18
- UblLine,
19
- UblParty,
20
- UblPeriod,
21
- UblTaxCategory,
22
- UblTaxSubtotal,
23
- } from "./types";
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 ─────────────────────────────────────────────────────────
24
129
 
25
130
  /** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */
26
131
  const amount = (value: number): string => value.toFixed(2);
@@ -34,36 +139,41 @@ const percent = (value: number): string => {
34
139
  const money = (name: string, value: number, currency: string): XmlElement =>
35
140
  el(name, { currencyID: currency }, amount(value));
36
141
 
37
- const vatTaxScheme = (): XmlElement =>
38
- el("cac:TaxScheme", null, [el("cbc:ID", null, VAT_TAX_SCHEME_ID)]);
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)]);
39
147
 
40
148
  /**
41
149
  * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)
42
150
  * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption
43
151
  * reason for the non-charging categories (E/AE/O/K/G).
44
152
  */
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)
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))
51
163
  : null,
52
- vatTaxScheme(),
164
+ text("cbc:TaxExemptionReason", valid.exemptionReason),
165
+ taxScheme(valid.schemeId),
53
166
  ]);
167
+ };
54
168
 
55
169
  const postalAddress = (address: UblAddress): XmlElement =>
56
170
  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
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
67
177
  ? el("cac:Country", null, [
68
178
  el(
69
179
  "cbc:IdentificationCode",
@@ -74,29 +184,29 @@ const postalAddress = (address: UblAddress): XmlElement =>
74
184
  : null,
75
185
  ]);
76
186
 
77
- const party = (source: UblParty): XmlElement =>
187
+ const party = (source: UblParty, name: string): XmlElement =>
78
188
  el("cac:Party", null, [
79
189
  source.endpoint
80
190
  ? el(
81
191
  "cbc:EndpointID",
82
- { schemeID: source.endpoint.scheme },
192
+ { schemeID: source.endpoint.scheme ?? "" },
83
193
  source.endpoint.value,
84
194
  )
85
195
  : null,
86
- el("cac:PartyName", null, [el("cbc:Name", null, source.name)]),
87
- postalAddress(source.address),
88
- source.vatNumber
196
+ el("cac:PartyName", null, [el("cbc:Name", null, name)]),
197
+ source.address ? postalAddress(source.address) : null,
198
+ source.vatId !== undefined
89
199
  ? el("cac:PartyTaxScheme", null, [
90
- el("cbc:CompanyID", null, source.vatNumber),
91
- vatTaxScheme(),
200
+ el("cbc:CompanyID", null, source.vatId),
201
+ taxScheme(source.taxSchemeId),
92
202
  ])
93
203
  : null,
94
204
  el("cac:PartyLegalEntity", null, [
95
- el("cbc:RegistrationName", null, source.legalName ?? source.name),
205
+ el("cbc:RegistrationName", null, source.registrationName ?? name),
96
206
  source.companyId
97
207
  ? el(
98
208
  "cbc:CompanyID",
99
- source.companyId.scheme
209
+ source.companyId.scheme !== undefined
100
210
  ? { schemeID: source.companyId.scheme }
101
211
  : null,
102
212
  source.companyId.value,
@@ -105,31 +215,54 @@ const party = (source: UblParty): XmlElement =>
105
215
  ]),
106
216
  ]);
107
217
 
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),
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
+ ),
113
244
  ]);
245
+ };
114
246
 
115
247
  /**
116
248
  * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`
117
249
  * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`
118
- * — emitting them after it produces schema-invalid XML.
250
+ * — emitting them after it produces schema-invalid XML. BT-113/BT-114 are
251
+ * omitted when absent or zero.
119
252
  */
120
- const legalMonetaryTotalChildren = (doc: UblDocument): XmlElement[] => {
253
+ const legalMonetaryTotalChildren = (doc: UblInvoice): XmlElement[] => {
121
254
  const { currency, monetaryTotal: total } = doc;
122
255
  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),
256
+ money("cbc:LineExtensionAmount", total.lineExtensionAmount ?? 0, currency),
257
+ money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount ?? 0, currency),
258
+ money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount ?? 0, currency),
126
259
  total.prepaidAmount
127
260
  ? money("cbc:PrepaidAmount", total.prepaidAmount, currency)
128
261
  : null,
129
262
  total.payableRoundingAmount
130
263
  ? money("cbc:PayableRoundingAmount", total.payableRoundingAmount, currency)
131
264
  : null,
132
- money("cbc:PayableAmount", total.payableAmount, currency),
265
+ money("cbc:PayableAmount", total.payableAmount ?? 0, currency),
133
266
  ];
134
267
  return children.filter((child): child is XmlElement => Boolean(child));
135
268
  };
@@ -138,47 +271,51 @@ const legalMonetaryTotalChildren = (doc: UblDocument): XmlElement[] => {
138
271
  * `cac:InvoicePeriod`. Null when neither bound is set — an empty period element
139
272
  * fails BR-CO-19, which requires at least one of the two dates.
140
273
  */
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
- );
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
+ ]);
151
282
  };
152
283
 
153
284
  const line = (
154
285
  source: UblLine,
155
286
  currency: string,
156
- documentType: UblDocument["documentType"],
287
+ documentType: UblInvoice["documentType"],
157
288
  ): XmlElement => {
158
- const lineElementName =
159
- documentType === "creditNote" ? "cac:CreditNoteLine" : "cac:InvoiceLine";
160
- const quantityElementName =
161
- documentType === "creditNote" ? "cbc:CreditedQuantity" : "cbc:InvoicedQuantity";
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);
162
297
 
163
298
  return el(lineElementName, null, [
164
299
  el("cbc:ID", null, source.id),
165
- el(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),
166
- money("cbc:LineExtensionAmount", source.lineExtensionAmount, currency),
300
+ el(quantityElementName, { unitCode }, String(source.quantity ?? 0)),
301
+ money("cbc:LineExtensionAmount", source.lineExtensionAmount ?? 0, currency),
167
302
  invoicePeriod(source.invoicePeriod),
168
303
  el("cac:Item", null, [
169
- el("cbc:Name", null, source.name),
170
- taxCategory("cac:ClassifiedTaxCategory", source.taxCategory),
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
+ ),
171
312
  ]),
172
313
  // BT-149's unit code must match the invoiced/credited quantity's
173
314
  // (PEPPOL-EN16931-R130).
174
315
  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
- )
316
+ money("cbc:PriceAmount", priceAmount, currency),
317
+ source.baseQuantity !== undefined
318
+ ? el("cbc:BaseQuantity", { unitCode }, String(source.baseQuantity))
182
319
  : null,
183
320
  ]),
184
321
  ]);
@@ -186,58 +323,97 @@ const line = (
186
323
 
187
324
  const attachmentReference = (attachment: UblAttachment): XmlElement =>
188
325
  el("cac:AdditionalDocumentReference", null, [
189
- el("cbc:ID", null, attachment.id),
326
+ el(
327
+ "cbc:ID",
328
+ null,
329
+ attachment.id ?? attachment.filename ?? attachment.externalUri ?? "",
330
+ ),
190
331
  el("cac:Attachment", null, [
191
- el(
192
- "cbc:EmbeddedDocumentBinaryObject",
193
- { mimeCode: attachment.mimeCode, filename: attachment.filename },
194
- attachment.base64,
195
- ),
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
+ ),
196
344
  ]),
197
345
  ]);
198
346
 
199
- const billingReference = (precedingInvoiceId: string): XmlElement =>
200
- el("cac:BillingReference", null, [
347
+ const billingReference = (reference: UblBillingReference): XmlElement | null => {
348
+ if (reference.invoiceId === undefined) return null;
349
+ return el("cac:BillingReference", null, [
201
350
  el("cac:InvoiceDocumentReference", null, [
202
- el("cbc:ID", null, precedingInvoiceId),
351
+ el("cbc:ID", null, reference.invoiceId),
203
352
  ]),
204
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);
205
375
 
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";
376
+ const isCreditNote = doc.documentType === "CreditNote";
209
377
  const rootName = isCreditNote ? "CreditNote" : "Invoice";
210
378
  const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
211
379
  const typeCodeElement = isCreditNote
212
- ? el("cbc:CreditNoteTypeCode", null, CREDIT_NOTE_TYPE_CODE)
213
- : el("cbc:InvoiceTypeCode", null, INVOICE_TYPE_CODE);
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);
214
386
 
215
387
  const children: (XmlElement | null | false)[] = [
216
- el("cbc:CustomizationID", null, UBL_CUSTOMIZATION_ID),
217
- el("cbc:ProfileID", null, UBL_PROFILE_ID),
388
+ el("cbc:CustomizationID", null, doc.customizationId ?? UBL_CUSTOMIZATION_ID),
389
+ el("cbc:ProfileID", null, doc.profileId ?? UBL_PROFILE_ID),
218
390
  el("cbc:ID", null, doc.id),
219
391
  el("cbc:IssueDate", null, doc.issueDate),
220
392
  // CreditNote has no DueDate element in the UBL sequence.
221
- !isCreditNote && doc.dueDate ? el("cbc:DueDate", null, doc.dueDate) : null,
393
+ !isCreditNote ? text("cbc:DueDate", doc.dueDate) : null,
222
394
  typeCodeElement,
223
- doc.note ? el("cbc:Note", null, doc.note) : null,
395
+ text("cbc:Note", doc.note),
224
396
  el("cbc:DocumentCurrencyCode", null, doc.currency),
225
- doc.buyerReference ? el("cbc:BuyerReference", null, doc.buyerReference) : null,
397
+ text("cbc:BuyerReference", doc.buyerReference),
226
398
  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)]),
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
+ ]),
231
407
  // BT-20. In both the Invoice and CreditNote sequences PaymentTerms sits
232
408
  // after the parties (and PaymentMeans, which we do not emit) and before
233
409
  // TaxTotal.
234
- doc.paymentTermsNote
410
+ doc.paymentTermsNote !== undefined
235
411
  ? el("cac:PaymentTerms", null, [el("cbc:Note", null, doc.paymentTermsNote)])
236
412
  : null,
237
413
  el("cac:TaxTotal", null, [
238
- money("cbc:TaxAmount", doc.taxTotal.taxAmount, doc.currency),
239
- ...doc.taxTotal.subtotals.map((subtotal) =>
240
- taxSubtotal(subtotal, doc.currency),
414
+ money("cbc:TaxAmount", doc.taxTotal.taxAmount ?? 0, doc.currency),
415
+ ...doc.taxTotal.subtotals.map((subtotal, index) =>
416
+ taxSubtotal(subtotal, doc.currency, index),
241
417
  ),
242
418
  ]),
243
419
  el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
@@ -256,3 +432,6 @@ export const serializeUblDocument = (doc: UblDocument): string => {
256
432
 
257
433
  return serializeDocument(root);
258
434
  };
435
+
436
+ /** Alias of {@link serializeUblInvoice}, kept under the historical name. */
437
+ export const serializeUblDocument = serializeUblInvoice;
@@ -1,6 +1,14 @@
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;
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;
4
6
  const normalized = value.trim();
5
- return normalized.length > 0 ? normalized : null;
7
+ return normalized.length > 0 ? normalized : undefined;
6
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;
package/src/errors.ts CHANGED
@@ -13,3 +13,19 @@ export class UblParseError extends Error {
13
13
  if (options && "cause" in options) this.cause = options.cause;
14
14
  }
15
15
  }
16
+
17
+ /**
18
+ * Thrown by the build side when a model cannot be serialized: a field EN 16931
19
+ * / Peppol BIS Billing 3.0 makes mandatory on the wire is missing, or a build
20
+ * helper is handed input it cannot turn into one. The message names the BT /
21
+ * model field.
22
+ */
23
+ export class UblBuildError extends Error {
24
+ override readonly cause?: unknown;
25
+
26
+ constructor(message: string, options?: { cause?: unknown }) {
27
+ super(message);
28
+ this.name = "UblBuildError";
29
+ if (options && "cause" in options) this.cause = options.cause;
30
+ }
31
+ }
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@ export {
3
3
  isPdfLikeAttachment,
4
4
  type UblEmbeddedAttachment,
5
5
  } from "./attachments.js";
6
- export { UblParseError } from "./errors.js";
6
+ export { UblBuildError, UblParseError } from "./errors.js";
7
7
  export { parseUblInvoice } from "./parser.js";
8
8
  export {
9
9
  isPeppolMessageLevelResponse,
@@ -25,9 +25,11 @@ export type {
25
25
  UblAllowanceCharge,
26
26
  UblAttachment,
27
27
  UblBillingReference,
28
+ UblCompanyId,
28
29
  UblContact,
29
30
  UblDelivery,
30
31
  UblDocumentReference,
32
+ UblEndpoint,
31
33
  UblInvoice,
32
34
  UblInvoicePeriod,
33
35
  UblItemProperty,
@@ -36,5 +38,7 @@ export type {
36
38
  UblParty,
37
39
  UblPartyIdentification,
38
40
  UblPaymentMeans,
41
+ UblTaxCategory,
39
42
  UblTaxSubtotal,
43
+ UblTaxTotal,
40
44
  } from "./types.js";