@financica/ubl 0.17.0 → 0.18.1

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,12 +1,16 @@
1
1
  import { UblBuildError } from "../../errors";
2
2
  import type {
3
3
  UblAddress,
4
+ UblAllowanceCharge,
4
5
  UblAttachment,
5
6
  UblBillingReference,
7
+ UblDelivery,
6
8
  UblInvoice,
7
9
  UblInvoicePeriod,
8
10
  UblLine,
9
11
  UblParty,
12
+ UblPaymentMeans,
13
+ UblSchemedId,
10
14
  UblTaxCategory,
11
15
  UblTaxSubtotal,
12
16
  } from "../../types";
@@ -27,8 +31,9 @@ import {
27
31
  // ── Validation ─────────────────────────────────────────────────────────
28
32
  //
29
33
  // 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.
34
+ // serializer is where EN 16931 / Peppol BIS Billing 3.0 mandatory fields and
35
+ // the arithmetic business rules are enforced. Each check names the BT or the
36
+ // rule and the model path in its message.
32
37
 
33
38
  const missing = (what: string, path: string): UblBuildError =>
34
39
  new UblBuildError(`Missing ${what} (${path})`);
@@ -40,6 +45,23 @@ function required<T>(value: T | undefined, what: string, path: string): NonNulla
40
45
  return value as NonNullable<T>;
41
46
  }
42
47
 
48
+ const round2 = (value: number): number => Math.round(value * 100) / 100;
49
+
50
+ /** Sums of cent-rounded amounts must agree to the cent; R120 allows a cent either way. */
51
+ const assertEqual = (
52
+ rule: string,
53
+ actual: number,
54
+ expected: number,
55
+ path: string,
56
+ tolerance = 0.005,
57
+ ): void => {
58
+ if (Math.abs(actual - expected) > tolerance) {
59
+ throw new UblBuildError(
60
+ `${rule}: ${path} is ${actual.toFixed(2)}, expected ${expected.toFixed(2)}`,
61
+ );
62
+ }
63
+ };
64
+
43
65
  /** Category `O` (outside scope) is the one category BR-O-05 forbids a percent on. */
44
66
  const requiresPercent = (categoryId: string): boolean => categoryId !== "O";
45
67
 
@@ -55,18 +77,77 @@ const validateTaxCategory = (
55
77
  return { ...present, id };
56
78
  };
57
79
 
80
+ const validateAllowanceCharge = (
81
+ item: UblAllowanceCharge,
82
+ path: string,
83
+ level: "document" | "line",
84
+ ): void => {
85
+ const kind = item.chargeIndicator ? "charge" : "allowance";
86
+ required(item.amount, `${kind} amount (BT-92/BT-99)`, `${path}.amount`);
87
+ if (item.reason === undefined && item.reasonCode === undefined) {
88
+ throw missing(`${kind} reason or reason code (BT-97/BT-98)`, `${path}.reason`);
89
+ }
90
+ if (item.baseAmount !== undefined && item.multiplierFactorNumeric !== undefined) {
91
+ assertEqual(
92
+ "PEPPOL-EN16931-R040",
93
+ item.amount ?? 0,
94
+ round2((item.baseAmount * item.multiplierFactorNumeric) / 100),
95
+ `${path}.amount`,
96
+ 0.01,
97
+ );
98
+ }
99
+ if (level === "document") {
100
+ validateTaxCategory(item.taxCategory, `${path}.taxCategory`);
101
+ }
102
+ };
103
+
104
+ const lineAllowanceTotal = (line: UblLine, charges: boolean): number =>
105
+ (line.allowanceCharges ?? [])
106
+ .filter((item) => item.chargeIndicator === charges)
107
+ .reduce((sum, item) => sum + (item.amount ?? 0), 0);
108
+
58
109
  const validateLine = (line: UblLine, index: number): void => {
59
110
  const path = `lines[${index}]`;
60
111
  required(line.id, "line identifier (BT-126)", `${path}.id`);
61
- required(line.quantity, "invoiced quantity (BT-129)", `${path}.quantity`);
112
+ const quantity = required(
113
+ line.quantity,
114
+ "invoiced quantity (BT-129)",
115
+ `${path}.quantity`,
116
+ );
62
117
  required(line.unitCode, "unit code (BT-130)", `${path}.unitCode`);
63
- required(line.unitPrice, "net unit price (BT-146)", `${path}.unitPrice`);
64
- required(
118
+ const unitPrice = required(
119
+ line.unitPrice,
120
+ "net unit price (BT-146)",
121
+ `${path}.unitPrice`,
122
+ );
123
+ const net = required(
65
124
  line.lineExtensionAmount,
66
125
  "line net amount (BT-131)",
67
126
  `${path}.lineExtensionAmount`,
68
127
  );
128
+ // A negative line carries its sign on the quantity, never on the price.
129
+ if (unitPrice < 0) {
130
+ throw new UblBuildError(
131
+ `BR-27: ${path}.unitPrice is ${unitPrice}, the item net price shall not be negative`,
132
+ );
133
+ }
69
134
  validateTaxCategory(line.taxCategory, `${path}.taxCategory`);
135
+ (line.allowanceCharges ?? []).forEach((item, itemIndex) =>
136
+ validateAllowanceCharge(item, `${path}.allowanceCharges[${itemIndex}]`, "line"),
137
+ );
138
+ // BT-131 = BT-129 × BT-146 + line charges − line allowances. `unitPrice` is
139
+ // the per-unit figure, so BT-149 is already accounted for.
140
+ assertEqual(
141
+ "PEPPOL-EN16931-R120",
142
+ net,
143
+ round2(
144
+ quantity * unitPrice +
145
+ lineAllowanceTotal(line, true) -
146
+ lineAllowanceTotal(line, false),
147
+ ),
148
+ `${path}.lineExtensionAmount`,
149
+ 0.02,
150
+ );
70
151
  };
71
152
 
72
153
  const isExternalOnly = (attachment: UblAttachment): boolean =>
@@ -88,22 +169,181 @@ const validateAttachment = (attachment: UblAttachment, index: number): void => {
88
169
  );
89
170
  };
90
171
 
172
+ /** UNCL4461 codes whose payment means need a mandate (direct debit) or an account (credit transfer). */
173
+ const DIRECT_DEBIT_CODES = new Set(["49", "59"]);
174
+ const CREDIT_TRANSFER_CODES = new Set(["30", "58"]);
175
+
176
+ const validatePaymentMeans = (means: UblPaymentMeans, index: number): void => {
177
+ const path = `paymentMeansList[${index}]`;
178
+ const code = required(means.code, "payment means code (BT-81)", `${path}.code`);
179
+ if (CREDIT_TRANSFER_CODES.has(code)) {
180
+ required(
181
+ means.iban,
182
+ `payment account (BT-84) for code ${code}`,
183
+ `${path}.iban`,
184
+ );
185
+ }
186
+ if (DIRECT_DEBIT_CODES.has(code)) {
187
+ required(
188
+ means.mandateId,
189
+ `mandate reference (BT-89) for code ${code}`,
190
+ `${path}.mandateId`,
191
+ );
192
+ }
193
+ };
194
+
195
+ const validateParty = (party: UblParty, role: string, nameBt: string): void => {
196
+ required(party.name, `${role} name (${nameBt})`, `${role}.name`);
197
+ if (party.endpoint && party.endpoint.scheme === undefined) {
198
+ throw missing(`${role} endpoint scheme`, `${role}.endpoint.scheme`);
199
+ }
200
+ };
201
+
202
+ const paymentMeansList = (doc: UblInvoice): UblPaymentMeans[] =>
203
+ doc.paymentMeansList ?? (doc.paymentMeans ? [doc.paymentMeans] : []);
204
+
205
+ const sumBy = <T>(items: T[], pick: (item: T) => number): number =>
206
+ round2(items.reduce((sum, item) => sum + pick(item), 0));
207
+
208
+ const categoryKey = (category: UblTaxCategory | undefined): string =>
209
+ `${category?.id ?? ""}:${category?.percent ?? ""}`;
210
+
211
+ /**
212
+ * The document arithmetic EN 16931 fixes: BR-CO-10 (line sum), BR-CO-11/12
213
+ * (allowance and charge sums), BR-CO-13 (total without VAT), BR-CO-15 (total
214
+ * with VAT), BR-CO-16 (amount due) and the BR-S-08 family (each VAT category's
215
+ * taxable amount is its line nets minus its allowances plus its charges).
216
+ */
217
+ const validateArithmetic = (doc: UblInvoice): void => {
218
+ const total = doc.monetaryTotal;
219
+ const docItems = doc.allowanceCharges ?? [];
220
+ const allowances = docItems.filter((item) => !item.chargeIndicator);
221
+ const charges = docItems.filter((item) => item.chargeIndicator);
222
+ const lineSum = sumBy(doc.lines, (line) => line.lineExtensionAmount ?? 0);
223
+ const allowanceSum = sumBy(allowances, (item) => item.amount ?? 0);
224
+ const chargeSum = sumBy(charges, (item) => item.amount ?? 0);
225
+
226
+ assertEqual(
227
+ "BR-CO-10",
228
+ total.lineExtensionAmount ?? 0,
229
+ lineSum,
230
+ "monetaryTotal.lineExtensionAmount",
231
+ );
232
+ if (allowances.length > 0 || total.allowanceTotalAmount !== undefined) {
233
+ assertEqual(
234
+ "BR-CO-11",
235
+ total.allowanceTotalAmount ?? 0,
236
+ allowanceSum,
237
+ "monetaryTotal.allowanceTotalAmount",
238
+ );
239
+ }
240
+ if (charges.length > 0 || total.chargeTotalAmount !== undefined) {
241
+ assertEqual(
242
+ "BR-CO-12",
243
+ total.chargeTotalAmount ?? 0,
244
+ chargeSum,
245
+ "monetaryTotal.chargeTotalAmount",
246
+ );
247
+ }
248
+ assertEqual(
249
+ "BR-CO-13",
250
+ total.taxExclusiveAmount ?? 0,
251
+ round2(lineSum - allowanceSum + chargeSum),
252
+ "monetaryTotal.taxExclusiveAmount",
253
+ );
254
+ assertEqual(
255
+ "BR-CO-15",
256
+ total.taxInclusiveAmount ?? 0,
257
+ round2((total.taxExclusiveAmount ?? 0) + (doc.taxTotal.taxAmount ?? 0)),
258
+ "monetaryTotal.taxInclusiveAmount",
259
+ );
260
+ assertEqual(
261
+ "BR-CO-16",
262
+ total.payableAmount ?? 0,
263
+ round2(
264
+ (total.taxInclusiveAmount ?? 0) -
265
+ (total.prepaidAmount ?? 0) +
266
+ (total.payableRoundingAmount ?? 0),
267
+ ),
268
+ "monetaryTotal.payableAmount",
269
+ );
270
+
271
+ const taxableByCategory = new Map<string, number>();
272
+ const add = (category: UblTaxCategory | undefined, amount: number): void => {
273
+ const key = categoryKey(category);
274
+ taxableByCategory.set(key, round2((taxableByCategory.get(key) ?? 0) + amount));
275
+ };
276
+ for (const line of doc.lines) add(line.taxCategory, line.lineExtensionAmount ?? 0);
277
+ for (const item of docItems) {
278
+ add(
279
+ item.taxCategory,
280
+ item.chargeIndicator ? (item.amount ?? 0) : -(item.amount ?? 0),
281
+ );
282
+ }
283
+ doc.taxTotal.subtotals.forEach((subtotal, index) => {
284
+ const key = categoryKey(subtotal.category);
285
+ const expected = taxableByCategory.get(key);
286
+ if (expected === undefined) {
287
+ throw new UblBuildError(
288
+ `BR-S-08: taxTotal.subtotals[${index}] (${key}) has no line, allowance or charge in that category`,
289
+ );
290
+ }
291
+ assertEqual(
292
+ "BR-S-08",
293
+ subtotal.taxableAmount ?? 0,
294
+ expected,
295
+ `taxTotal.subtotals[${index}].taxableAmount`,
296
+ );
297
+ });
298
+ };
299
+
91
300
  const validateInvoice = (doc: UblInvoice): void => {
92
301
  required(doc.id, "document identifier (BT-1)", "id");
93
302
  required(doc.issueDate, "issue date (BT-2)", "issueDate");
94
303
  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");
304
+ if (
305
+ doc.taxPointDate !== undefined &&
306
+ doc.invoicePeriod?.descriptionCode !== undefined
307
+ ) {
308
+ throw new UblBuildError(
309
+ "BR-CO-3: a tax point date (BT-7, taxPointDate) and a tax point date code (BT-8, invoicePeriod.descriptionCode) are mutually exclusive",
310
+ );
99
311
  }
100
- if (doc.buyer.endpoint && doc.buyer.endpoint.scheme === undefined) {
101
- throw missing("buyer endpoint scheme (BT-49-1)", "buyer.endpoint.scheme");
312
+ if (doc.taxCurrency !== undefined) {
313
+ required(
314
+ doc.taxTotal.taxAmountInTaxCurrency,
315
+ "VAT total in the accounting currency (BT-111, BR-53)",
316
+ "taxTotal.taxAmountInTaxCurrency",
317
+ );
318
+ }
319
+ validateParty(doc.seller, "seller", "BT-27");
320
+ validateParty(doc.buyer, "buyer", "BT-44");
321
+ if (doc.payee) required(doc.payee.name, "payee name (BT-59)", "payee.name");
322
+ if (doc.taxRepresentative) {
323
+ required(
324
+ doc.taxRepresentative.name,
325
+ "tax representative name (BT-62)",
326
+ "taxRepresentative.name",
327
+ );
328
+ required(
329
+ doc.taxRepresentative.vatId,
330
+ "tax representative VAT identifier (BT-63)",
331
+ "taxRepresentative.vatId",
332
+ );
333
+ required(
334
+ doc.taxRepresentative.address?.countryCode,
335
+ "tax representative country (BT-69)",
336
+ "taxRepresentative.address.countryCode",
337
+ );
102
338
  }
103
339
  if (doc.lines.length === 0) {
104
340
  throw new UblBuildError("A document needs at least one line (BG-25, lines)");
105
341
  }
106
342
  doc.lines.forEach(validateLine);
343
+ (doc.allowanceCharges ?? []).forEach((item, index) =>
344
+ validateAllowanceCharge(item, `allowanceCharges[${index}]`, "document"),
345
+ );
346
+ paymentMeansList(doc).forEach(validatePaymentMeans);
107
347
  required(doc.taxTotal.taxAmount, "total VAT amount (BT-110)", "taxTotal.taxAmount");
108
348
  const total = doc.monetaryTotal;
109
349
  required(
@@ -123,6 +363,7 @@ const validateInvoice = (doc: UblInvoice): void => {
123
363
  );
124
364
  required(total.payableAmount, "amount due (BT-115)", "monetaryTotal.payableAmount");
125
365
  (doc.attachments ?? []).forEach(validateAttachment);
366
+ validateArithmetic(doc);
126
367
  };
127
368
 
128
369
  // ── Formatting ─────────────────────────────────────────────────────────
@@ -139,16 +380,28 @@ const percent = (value: number): string => {
139
380
  const money = (name: string, value: number, currency: string): XmlElement =>
140
381
  el(name, { currencyID: currency }, amount(value));
141
382
 
383
+ const optionalMoney = (
384
+ name: string,
385
+ value: number | undefined,
386
+ currency: string,
387
+ ): XmlElement | null => (value !== undefined ? money(name, value, currency) : null);
388
+
142
389
  const text = (name: string, value: string | undefined): XmlElement | null =>
143
390
  value !== undefined ? el(name, null, value) : null;
144
391
 
392
+ const schemedId = (name: string, id: UblSchemedId | undefined): XmlElement | null =>
393
+ id !== undefined
394
+ ? el(name, id.scheme !== undefined ? { schemeID: id.scheme } : null, id.value)
395
+ : null;
396
+
145
397
  const taxScheme = (schemeId: string | undefined): XmlElement =>
146
398
  el("cac:TaxScheme", null, [el("cbc:ID", null, schemeId ?? VAT_TAX_SCHEME_ID)]);
147
399
 
148
400
  /**
149
401
  * 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).
402
+ * and `cac:TaxCategory` (in the VAT breakdown and on document allowances and
403
+ * charges). EN 16931 requires an exemption reason for the non-charging
404
+ * categories (E/AE/O/K/G); the code precedes the text in the sequence.
152
405
  */
153
406
  const taxCategory = (
154
407
  name: string,
@@ -161,29 +414,77 @@ const taxCategory = (
161
414
  valid.percent !== undefined
162
415
  ? el("cbc:Percent", null, percent(valid.percent))
163
416
  : null,
417
+ text("cbc:TaxExemptionReasonCode", valid.exemptionReasonCode),
164
418
  text("cbc:TaxExemptionReason", valid.exemptionReason),
165
419
  taxScheme(valid.schemeId),
166
420
  ]);
167
421
  };
168
422
 
423
+ const addressChildren = (address: UblAddress): (XmlElement | null)[] => [
424
+ text("cbc:StreetName", address.street),
425
+ text("cbc:AdditionalStreetName", address.additionalStreet),
426
+ text("cbc:CityName", address.city),
427
+ text("cbc:PostalZone", address.postalZone),
428
+ text("cbc:CountrySubentity", address.countrySubentity),
429
+ address.countryCode !== undefined
430
+ ? el("cac:Country", null, [
431
+ el(
432
+ "cbc:IdentificationCode",
433
+ { listID: COUNTRY_CODE_LIST_ID },
434
+ address.countryCode,
435
+ ),
436
+ ])
437
+ : null,
438
+ ];
439
+
169
440
  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
- ]);
441
+ el("cac:PostalAddress", null, addressChildren(address));
442
+
443
+ const partyIdentifications = (source: UblParty): XmlElement[] =>
444
+ (source.partyIdentifications ?? []).map((identification) =>
445
+ el("cac:PartyIdentification", null, [
446
+ el(
447
+ "cbc:ID",
448
+ identification.schemeId !== undefined
449
+ ? { schemeID: identification.schemeId }
450
+ : null,
451
+ identification.id,
452
+ ),
453
+ ]),
454
+ );
455
+
456
+ const partyName = (name: string): XmlElement =>
457
+ el("cac:PartyName", null, [el("cbc:Name", null, name)]);
458
+
459
+ const partyTaxScheme = (source: UblParty): XmlElement | null =>
460
+ source.vatId !== undefined
461
+ ? el("cac:PartyTaxScheme", null, [
462
+ el("cbc:CompanyID", null, source.vatId),
463
+ taxScheme(source.taxSchemeId),
464
+ ])
465
+ : null;
186
466
 
467
+ const companyId = (source: UblParty): XmlElement | null =>
468
+ source.companyId
469
+ ? el(
470
+ "cbc:CompanyID",
471
+ source.companyId.scheme !== undefined
472
+ ? { schemeID: source.companyId.scheme }
473
+ : null,
474
+ source.companyId.value,
475
+ )
476
+ : null;
477
+
478
+ const contact = (source: UblParty): XmlElement | null =>
479
+ source.contact
480
+ ? el("cac:Contact", null, [
481
+ text("cbc:Name", source.contact.name),
482
+ text("cbc:Telephone", source.contact.phone),
483
+ text("cbc:ElectronicMail", source.contact.email),
484
+ ])
485
+ : null;
486
+
487
+ /** `cac:Party` for the seller and buyer (BG-4, BG-7). */
187
488
  const party = (source: UblParty, name: string): XmlElement =>
188
489
  el("cac:Party", null, [
189
490
  source.endpoint
@@ -193,26 +494,137 @@ const party = (source: UblParty, name: string): XmlElement =>
193
494
  source.endpoint.value,
194
495
  )
195
496
  : null,
196
- el("cac:PartyName", null, [el("cbc:Name", null, name)]),
497
+ ...partyIdentifications(source),
498
+ partyName(name),
197
499
  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,
500
+ partyTaxScheme(source),
204
501
  el("cac:PartyLegalEntity", null, [
205
502
  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,
503
+ companyId(source),
504
+ text("cbc:CompanyLegalForm", source.companyLegalForm),
215
505
  ]),
506
+ contact(source),
507
+ ]);
508
+
509
+ /** `cac:PayeeParty` (BG-10): identification, name and legal entity id, unwrapped. */
510
+ const payeeParty = (source: UblParty): XmlElement =>
511
+ el("cac:PayeeParty", null, [
512
+ ...partyIdentifications(source),
513
+ partyName(source.name ?? ""),
514
+ source.companyId ? el("cac:PartyLegalEntity", null, [companyId(source)]) : null,
515
+ ]);
516
+
517
+ /** `cac:TaxRepresentativeParty` (BG-11): name, address and VAT id, unwrapped. */
518
+ const taxRepresentativeParty = (source: UblParty): XmlElement =>
519
+ el("cac:TaxRepresentativeParty", null, [
520
+ partyName(source.name ?? ""),
521
+ source.address ? postalAddress(source.address) : null,
522
+ partyTaxScheme(source),
523
+ ]);
524
+
525
+ /** `cac:Delivery` (BG-13). */
526
+ const delivery = (source: UblDelivery): XmlElement | null => {
527
+ const location =
528
+ source.locationId !== undefined || source.address !== undefined
529
+ ? el("cac:DeliveryLocation", null, [
530
+ schemedId("cbc:ID", source.locationId),
531
+ source.address
532
+ ? el("cac:Address", null, addressChildren(source.address))
533
+ : null,
534
+ ])
535
+ : null;
536
+ const deliveryParty =
537
+ source.partyName !== undefined
538
+ ? el("cac:DeliveryParty", null, [partyName(source.partyName)])
539
+ : null;
540
+ if (source.actualDeliveryDate === undefined && !location && !deliveryParty)
541
+ return null;
542
+ return el("cac:Delivery", null, [
543
+ text("cbc:ActualDeliveryDate", source.actualDeliveryDate),
544
+ location,
545
+ deliveryParty,
546
+ ]);
547
+ };
548
+
549
+ /**
550
+ * `cac:PaymentMeans` (BG-16). On a credit note BT-9 has no root element and
551
+ * rides in the first payment means as `cbc:PaymentDueDate`. `cbc:NetworkID`
552
+ * is schema-mandatory inside `cac:CardAccount` and carries no business term;
553
+ * the BIS example value is `NA`.
554
+ */
555
+ const paymentMeans = (
556
+ source: UblPaymentMeans,
557
+ dueDate: string | undefined,
558
+ ): XmlElement =>
559
+ el("cac:PaymentMeans", null, [
560
+ el(
561
+ "cbc:PaymentMeansCode",
562
+ source.codeName !== undefined ? { name: source.codeName } : null,
563
+ source.code ?? "",
564
+ ),
565
+ text("cbc:PaymentDueDate", dueDate),
566
+ text("cbc:PaymentID", source.paymentId),
567
+ source.cardNumber !== undefined
568
+ ? el("cac:CardAccount", null, [
569
+ el("cbc:PrimaryAccountNumberID", null, source.cardNumber),
570
+ el("cbc:NetworkID", null, "NA"),
571
+ text("cbc:HolderName", source.cardHolder),
572
+ ])
573
+ : null,
574
+ source.iban !== undefined
575
+ ? el("cac:PayeeFinancialAccount", null, [
576
+ el("cbc:ID", null, source.iban),
577
+ text("cbc:Name", source.accountName),
578
+ source.bic !== undefined
579
+ ? el("cac:FinancialInstitutionBranch", null, [
580
+ el("cbc:ID", null, source.bic),
581
+ ])
582
+ : null,
583
+ ])
584
+ : null,
585
+ source.mandateId !== undefined
586
+ ? el("cac:PaymentMandate", null, [
587
+ el("cbc:ID", null, source.mandateId),
588
+ source.debitedAccount !== undefined
589
+ ? el("cac:PayerFinancialAccount", null, [
590
+ el("cbc:ID", null, source.debitedAccount),
591
+ ])
592
+ : null,
593
+ ])
594
+ : null,
595
+ ]);
596
+
597
+ /**
598
+ * `cac:AllowanceCharge` at document level (BG-20/BG-21, with its VAT
599
+ * category) and line level (BG-27/BG-28, without: the line's category
600
+ * applies).
601
+ */
602
+ const allowanceCharge = (
603
+ item: UblAllowanceCharge,
604
+ currency: string,
605
+ path: string,
606
+ level: "document" | "line",
607
+ ): XmlElement =>
608
+ el("cac:AllowanceCharge", null, [
609
+ el("cbc:ChargeIndicator", null, item.chargeIndicator ? "true" : "false"),
610
+ text("cbc:AllowanceChargeReasonCode", item.reasonCode),
611
+ text("cbc:AllowanceChargeReason", item.reason),
612
+ item.multiplierFactorNumeric !== undefined
613
+ ? el(
614
+ "cbc:MultiplierFactorNumeric",
615
+ null,
616
+ percent(item.multiplierFactorNumeric),
617
+ )
618
+ : null,
619
+ money("cbc:Amount", item.amount ?? 0, currency),
620
+ optionalMoney("cbc:BaseAmount", item.baseAmount, currency),
621
+ level === "document"
622
+ ? taxCategory(
623
+ "cac:TaxCategory",
624
+ item.taxCategory ?? {},
625
+ `${path}.taxCategory`,
626
+ )
627
+ : null,
216
628
  ]);
217
629
 
218
630
  const taxSubtotal = (
@@ -245,17 +657,32 @@ const taxSubtotal = (
245
657
  };
246
658
 
247
659
  /**
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.
660
+ * `cac:LegalMonetaryTotal` children, in UBL sequence order. BT-107/BT-108 are
661
+ * written when the document carries allowances or charges; BT-113 and BT-114
662
+ * are omitted when absent or zero.
252
663
  */
253
664
  const legalMonetaryTotalChildren = (doc: UblInvoice): XmlElement[] => {
254
665
  const { currency, monetaryTotal: total } = doc;
666
+ const hasAllowances = (doc.allowanceCharges ?? []).some(
667
+ (item) => !item.chargeIndicator,
668
+ );
669
+ const hasCharges = (doc.allowanceCharges ?? []).some(
670
+ (item) => item.chargeIndicator,
671
+ );
255
672
  const children: (XmlElement | null)[] = [
256
673
  money("cbc:LineExtensionAmount", total.lineExtensionAmount ?? 0, currency),
257
674
  money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount ?? 0, currency),
258
675
  money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount ?? 0, currency),
676
+ hasAllowances || total.allowanceTotalAmount
677
+ ? money(
678
+ "cbc:AllowanceTotalAmount",
679
+ total.allowanceTotalAmount ?? 0,
680
+ currency,
681
+ )
682
+ : null,
683
+ hasCharges || total.chargeTotalAmount
684
+ ? money("cbc:ChargeTotalAmount", total.chargeTotalAmount ?? 0, currency)
685
+ : null,
259
686
  total.prepaidAmount
260
687
  ? money("cbc:PrepaidAmount", total.prepaidAmount, currency)
261
688
  : null,
@@ -269,7 +696,8 @@ const legalMonetaryTotalChildren = (doc: UblInvoice): XmlElement[] => {
269
696
 
270
697
  /**
271
698
  * `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.
699
+ * fails BR-CO-19, which requires at least one of the two dates. BT-8 (the tax
700
+ * point date code) is only meaningful on the document period.
273
701
  */
274
702
  const invoicePeriod = (period: UblInvoicePeriod | undefined): XmlElement | null => {
275
703
  if (!period || (period.startDate === undefined && period.endDate === undefined)) {
@@ -278,9 +706,60 @@ const invoicePeriod = (period: UblInvoicePeriod | undefined): XmlElement | null
278
706
  return el("cac:InvoicePeriod", null, [
279
707
  text("cbc:StartDate", period.startDate),
280
708
  text("cbc:EndDate", period.endDate),
709
+ text("cbc:DescriptionCode", period.descriptionCode),
281
710
  ]);
282
711
  };
283
712
 
713
+ const item = (source: UblLine): XmlElement =>
714
+ el("cac:Item", null, [
715
+ text("cbc:Description", source.description),
716
+ // BT-153 is mandatory; BT-154 stands in when the line has no name.
717
+ el("cbc:Name", null, source.itemName ?? source.description ?? source.id),
718
+ source.buyersItemId !== undefined
719
+ ? el("cac:BuyersItemIdentification", null, [
720
+ el("cbc:ID", null, source.buyersItemId),
721
+ ])
722
+ : null,
723
+ source.sellersItemId !== undefined
724
+ ? el("cac:SellersItemIdentification", null, [
725
+ el("cbc:ID", null, source.sellersItemId),
726
+ ])
727
+ : null,
728
+ source.standardItemId !== undefined
729
+ ? el("cac:StandardItemIdentification", null, [
730
+ schemedId("cbc:ID", source.standardItemId),
731
+ ])
732
+ : null,
733
+ source.originCountryCode !== undefined
734
+ ? el("cac:OriginCountry", null, [
735
+ el("cbc:IdentificationCode", null, source.originCountryCode),
736
+ ])
737
+ : null,
738
+ ...(source.commodityClassifications ?? []).map((classification) =>
739
+ el("cac:CommodityClassification", null, [
740
+ el(
741
+ "cbc:ItemClassificationCode",
742
+ {
743
+ listID: classification.listId,
744
+ listVersionID: classification.listVersionId,
745
+ },
746
+ classification.value,
747
+ ),
748
+ ]),
749
+ ),
750
+ taxCategory(
751
+ "cac:ClassifiedTaxCategory",
752
+ source.taxCategory ?? {},
753
+ `lines[${source.id}].taxCategory`,
754
+ ),
755
+ ...(source.additionalItemProperties ?? []).map((property) =>
756
+ el("cac:AdditionalItemProperty", null, [
757
+ el("cbc:Name", null, property.name),
758
+ el("cbc:Value", null, property.value ?? ""),
759
+ ]),
760
+ ),
761
+ ]);
762
+
284
763
  const line = (
285
764
  source: UblLine,
286
765
  currency: string,
@@ -297,19 +776,31 @@ const line = (
297
776
 
298
777
  return el(lineElementName, null, [
299
778
  el("cbc:ID", null, source.id),
779
+ text("cbc:Note", source.note),
300
780
  el(quantityElementName, { unitCode }, String(source.quantity ?? 0)),
301
781
  money("cbc:LineExtensionAmount", source.lineExtensionAmount ?? 0, currency),
782
+ text("cbc:AccountingCost", source.accountingCost),
302
783
  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`,
784
+ source.orderLineReference !== undefined
785
+ ? el("cac:OrderLineReference", null, [
786
+ el("cbc:LineID", null, source.orderLineReference),
787
+ ])
788
+ : null,
789
+ source.objectIdentifier !== undefined
790
+ ? el("cac:DocumentReference", null, [
791
+ schemedId("cbc:ID", source.objectIdentifier),
792
+ el("cbc:DocumentTypeCode", null, "130"),
793
+ ])
794
+ : null,
795
+ ...(source.allowanceCharges ?? []).map((entry, index) =>
796
+ allowanceCharge(
797
+ entry,
798
+ currency,
799
+ `lines[${source.id}].allowanceCharges[${index}]`,
800
+ "line",
311
801
  ),
312
- ]),
802
+ ),
803
+ item(source),
313
804
  // BT-149's unit code must match the invoiced/credited quantity's
314
805
  // (PEPPOL-EN16931-R130).
315
806
  el("cac:Price", null, [
@@ -317,6 +808,21 @@ const line = (
317
808
  source.baseQuantity !== undefined
318
809
  ? el("cbc:BaseQuantity", { unitCode }, String(source.baseQuantity))
319
810
  : null,
811
+ source.priceAllowance !== undefined
812
+ ? el("cac:AllowanceCharge", null, [
813
+ el("cbc:ChargeIndicator", null, "false"),
814
+ money(
815
+ "cbc:Amount",
816
+ source.priceAllowance.amount ?? 0,
817
+ currency,
818
+ ),
819
+ optionalMoney(
820
+ "cbc:BaseAmount",
821
+ source.priceAllowance.baseAmount,
822
+ currency,
823
+ ),
824
+ ])
825
+ : null,
320
826
  ]),
321
827
  ]);
322
828
  };
@@ -328,6 +834,7 @@ const attachmentReference = (attachment: UblAttachment): XmlElement =>
328
834
  null,
329
835
  attachment.id ?? attachment.filename ?? attachment.externalUri ?? "",
330
836
  ),
837
+ text("cbc:DocumentDescription", attachment.description),
331
838
  el("cac:Attachment", null, [
332
839
  isExternalOnly(attachment)
333
840
  ? el("cac:ExternalReference", null, [
@@ -344,11 +851,34 @@ const attachmentReference = (attachment: UblAttachment): XmlElement =>
344
851
  ]),
345
852
  ]);
346
853
 
854
+ /** A typed `cac:AdditionalDocumentReference` without attachment (BT-17, BT-18, BT-11 on a credit note). */
855
+ const typedDocumentReference = (id: UblSchemedId, typeCode: string): XmlElement =>
856
+ el("cac:AdditionalDocumentReference", null, [
857
+ schemedId("cbc:ID", id),
858
+ el("cbc:DocumentTypeCode", null, typeCode),
859
+ ]);
860
+
861
+ const documentReference = (name: string, id: string | undefined): XmlElement | null =>
862
+ id !== undefined ? el(name, null, [el("cbc:ID", null, id)]) : null;
863
+
864
+ /**
865
+ * `cac:OrderReference`. BT-13 (the buyer's order number) is the element's
866
+ * mandatory child, so a sales order id (BT-14) alone is not emitted.
867
+ */
868
+ const orderReference = (doc: UblInvoice): XmlElement | null => {
869
+ if (doc.orderReference === undefined) return null;
870
+ return el("cac:OrderReference", null, [
871
+ el("cbc:ID", null, doc.orderReference),
872
+ text("cbc:SalesOrderID", doc.salesOrderId),
873
+ ]);
874
+ };
875
+
347
876
  const billingReference = (reference: UblBillingReference): XmlElement | null => {
348
877
  if (reference.invoiceId === undefined) return null;
349
878
  return el("cac:BillingReference", null, [
350
879
  el("cac:InvoiceDocumentReference", null, [
351
880
  el("cbc:ID", null, reference.invoiceId),
881
+ text("cbc:IssueDate", reference.invoiceIssueDate),
352
882
  ]),
353
883
  ]);
354
884
  };
@@ -356,19 +886,21 @@ const billingReference = (reference: UblBillingReference): XmlElement | null =>
356
886
  /**
357
887
  * Serialize a {@link UblInvoice} into a Peppol BIS Billing 3.0 XML string.
358
888
  *
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.
889
+ * Writes every EN 16931 business term the model holds, at its position in the
890
+ * UBL 2.1 sequence: the header terms (`customizationId`, `profileId` and
891
+ * `invoiceTypeCode` default to the BIS values), the references (BT-10 to
892
+ * BT-19), the parties with identifications, legal form and contacts, the
893
+ * payee and tax representative, delivery, payment means, payment terms,
894
+ * document and line allowances and charges, the VAT breakdown (plus BT-111 in
895
+ * the accounting currency), the monetary totals, attachments and document
896
+ * references, and lines with their item identifiers, classifications,
897
+ * properties, price discount and classified VAT category. Line-level tax
898
+ * totals are not emitted: BIS Billing 3.0 forbids them.
365
899
  *
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.
900
+ * @throws {UblBuildError} when a field EN 16931 / Peppol BIS makes mandatory
901
+ * is missing (naming the BT and the model path), or when the document's
902
+ * arithmetic breaks a business rule: BR-CO-3, BR-CO-10 to BR-CO-13, BR-CO-15,
903
+ * BR-CO-16, BR-53, the BR-S-08 family, PEPPOL-EN16931-R040 and R120.
372
904
  */
373
905
  export const serializeUblInvoice = (doc: UblInvoice): string => {
374
906
  validateInvoice(doc);
@@ -383,39 +915,94 @@ export const serializeUblInvoice = (doc: UblInvoice): string => {
383
915
  doc.invoiceTypeCode ?? CREDIT_NOTE_TYPE_CODE,
384
916
  )
385
917
  : el("cbc:InvoiceTypeCode", null, doc.invoiceTypeCode ?? INVOICE_TYPE_CODE);
918
+ const taxPointDate = text("cbc:TaxPointDate", doc.taxPointDate);
919
+ const means = paymentMeansList(doc);
920
+ // A credit note has no cbc:DueDate: BT-9 goes in the first PaymentMeans.
921
+ const creditNoteDueDate =
922
+ isCreditNote && means.length > 0 ? doc.dueDate : undefined;
386
923
 
387
924
  const children: (XmlElement | null | false)[] = [
388
925
  el("cbc:CustomizationID", null, doc.customizationId ?? UBL_CUSTOMIZATION_ID),
389
926
  el("cbc:ProfileID", null, doc.profileId ?? UBL_PROFILE_ID),
390
927
  el("cbc:ID", null, doc.id),
391
928
  el("cbc:IssueDate", null, doc.issueDate),
392
- // CreditNote has no DueDate element in the UBL sequence.
393
929
  !isCreditNote ? text("cbc:DueDate", doc.dueDate) : null,
930
+ // The CreditNote sequence puts BT-7 before the type code, Invoice after the note.
931
+ isCreditNote ? taxPointDate : null,
394
932
  typeCodeElement,
395
933
  text("cbc:Note", doc.note),
934
+ !isCreditNote ? taxPointDate : null,
396
935
  el("cbc:DocumentCurrencyCode", null, doc.currency),
936
+ text("cbc:TaxCurrencyCode", doc.taxCurrency),
937
+ text("cbc:AccountingCost", doc.accountingCost),
397
938
  text("cbc:BuyerReference", doc.buyerReference),
398
939
  invoicePeriod(doc.invoicePeriod),
940
+ orderReference(doc),
399
941
  doc.billingReference ? billingReference(doc.billingReference) : null,
942
+ documentReference("cac:DespatchDocumentReference", doc.despatchReference),
943
+ documentReference("cac:ReceiptDocumentReference", doc.receivingAdviceReference),
944
+ documentReference("cac:ContractDocumentReference", doc.contractReference),
400
945
  ...(doc.attachments ?? []).map(attachmentReference),
946
+ ...(doc.documentReferences ?? []).map((reference) =>
947
+ el("cac:AdditionalDocumentReference", null, [
948
+ el("cbc:ID", null, reference.id ?? ""),
949
+ text("cbc:DocumentDescription", reference.description),
950
+ ]),
951
+ ),
952
+ doc.invoicedObjectId !== undefined
953
+ ? typedDocumentReference(doc.invoicedObjectId, "130")
954
+ : null,
955
+ !isCreditNote && doc.tenderReference !== undefined
956
+ ? typedDocumentReference({ value: doc.tenderReference }, "50")
957
+ : null,
958
+ // UBL's CreditNote has no cac:ProjectReference; BIS uses type code 50.
959
+ isCreditNote && doc.projectReference !== undefined
960
+ ? typedDocumentReference({ value: doc.projectReference }, "50")
961
+ : null,
962
+ !isCreditNote
963
+ ? documentReference("cac:ProjectReference", doc.projectReference)
964
+ : null,
401
965
  el("cac:AccountingSupplierParty", null, [
402
966
  party(doc.seller, doc.seller.name ?? ""),
403
967
  ]),
404
968
  el("cac:AccountingCustomerParty", null, [
405
969
  party(doc.buyer, doc.buyer.name ?? ""),
406
970
  ]),
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.
971
+ doc.payee ? payeeParty(doc.payee) : null,
972
+ doc.taxRepresentative ? taxRepresentativeParty(doc.taxRepresentative) : null,
973
+ doc.delivery ? delivery(doc.delivery) : null,
974
+ ...means.map((entry, index) =>
975
+ paymentMeans(entry, index === 0 ? creditNoteDueDate : undefined),
976
+ ),
977
+ // BT-20. In both sequences PaymentTerms sits after PaymentMeans and
978
+ // before AllowanceCharge and TaxTotal.
410
979
  doc.paymentTermsNote !== undefined
411
980
  ? el("cac:PaymentTerms", null, [el("cbc:Note", null, doc.paymentTermsNote)])
412
981
  : null,
982
+ ...(doc.allowanceCharges ?? []).map((entry, index) =>
983
+ allowanceCharge(
984
+ entry,
985
+ doc.currency,
986
+ `allowanceCharges[${index}]`,
987
+ "document",
988
+ ),
989
+ ),
413
990
  el("cac:TaxTotal", null, [
414
991
  money("cbc:TaxAmount", doc.taxTotal.taxAmount ?? 0, doc.currency),
415
992
  ...doc.taxTotal.subtotals.map((subtotal, index) =>
416
993
  taxSubtotal(subtotal, doc.currency, index),
417
994
  ),
418
995
  ]),
996
+ // BT-111: a second TaxTotal carrying only the VAT total in BT-6.
997
+ doc.taxCurrency !== undefined
998
+ ? el("cac:TaxTotal", null, [
999
+ money(
1000
+ "cbc:TaxAmount",
1001
+ doc.taxTotal.taxAmountInTaxCurrency ?? 0,
1002
+ doc.taxCurrency,
1003
+ ),
1004
+ ])
1005
+ : null,
419
1006
  el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
420
1007
  ...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),
421
1008
  ];