@financica/ubl 0.16.0 → 0.18.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,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";
package/src/normalize.ts CHANGED
@@ -110,9 +110,9 @@ const sanitizeAllowanceCharges = (charges?: UblAllowanceCharge[]) =>
110
110
  multiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),
111
111
  reason: normalizeText(charge.reason),
112
112
  reason_code: normalizeText(charge.reasonCode),
113
- tax_percent: toNumberOrNull(charge.taxPercent),
114
- tax_category_id: normalizeText(charge.taxCategoryId),
115
- tax_scheme_id: normalizeText(charge.taxSchemeId),
113
+ tax_percent: toNumberOrNull(charge.taxCategory?.percent),
114
+ tax_category_id: normalizeText(charge.taxCategory?.id),
115
+ tax_scheme_id: normalizeText(charge.taxCategory?.schemeId),
116
116
  }));
117
117
 
118
118
  const sanitizeRawUbl = (ubl: UblInvoice) => ({
@@ -124,11 +124,12 @@ const sanitizeRawUbl = (ubl: UblInvoice) => ({
124
124
  // --- Summation helpers ---
125
125
 
126
126
  const sumTaxTotal = (ubl: UblInvoice): number | null => {
127
- const subtotalSum = ubl.taxSubtotals.reduce(
127
+ const { subtotals } = ubl.taxTotal;
128
+ const subtotalSum = subtotals.reduce(
128
129
  (sum, subtotal) => sum + (subtotal.taxAmount ?? 0),
129
130
  0,
130
131
  );
131
- if (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) {
132
+ if (subtotals.length > 0 && Number.isFinite(subtotalSum)) {
132
133
  return subtotalSum;
133
134
  }
134
135
  const { taxInclusiveAmount, taxExclusiveAmount } = ubl.monetaryTotal;
@@ -217,7 +218,7 @@ export const normalizeUblResponse = (
217
218
  unit_price: toNumberOrNull(line.unitPrice),
218
219
  amount: toNumberOrNull(line.lineExtensionAmount),
219
220
  tax_amount: toNumberOrNull(line.taxAmount),
220
- tax_rate: toNumberOrNull(line.taxPercent),
221
+ tax_rate: toNumberOrNull(line.taxCategory?.percent),
221
222
  product_code:
222
223
  normalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),
223
224
  discount_amount: toNumberOrNull(line.discountAmount),
@@ -228,10 +229,15 @@ export const normalizeUblResponse = (
228
229
  item_name: normalizeText(line.itemName),
229
230
  sellers_item_id: normalizeText(line.sellersItemId),
230
231
  buyers_item_id: normalizeText(line.buyersItemId),
231
- tax_category_id: normalizeText(line.taxCategoryId),
232
- tax_scheme_id: normalizeText(line.taxSchemeId),
232
+ tax_category_id: normalizeText(line.taxCategory?.id),
233
+ tax_scheme_id: normalizeText(line.taxCategory?.schemeId),
233
234
  tax_subtotals: line.taxSubtotals ?? [],
234
- allowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),
235
+ allowance_charges: sanitizeAllowanceCharges([
236
+ ...(line.allowanceCharges ?? []),
237
+ ...(line.priceAllowance
238
+ ? [{ chargeIndicator: false, ...line.priceAllowance }]
239
+ : []),
240
+ ]),
235
241
  charge_amount: toNumberOrNull(line.chargeAmount),
236
242
  metadata: line.additionalItemProperties
237
243
  ? Object.fromEntries(
@@ -286,7 +292,7 @@ export const normalizeUblResponse = (
286
292
  address: supplierAddress,
287
293
  tax_id:
288
294
  normalizeText(ubl.seller.vatId) ??
289
- normalizeText(ubl.seller.companyId),
295
+ normalizeText(ubl.seller.companyId?.value),
290
296
  iban: normalizeText(ubl.paymentMeans?.iban),
291
297
  bic: normalizeText(ubl.paymentMeans?.bic),
292
298
  },
@@ -297,7 +303,7 @@ export const normalizeUblResponse = (
297
303
  address: receiverAddress,
298
304
  tax_id:
299
305
  normalizeText(ubl.buyer.vatId) ??
300
- normalizeText(ubl.buyer.companyId),
306
+ normalizeText(ubl.buyer.companyId?.value),
301
307
  },
302
308
  extra: {
303
309
  document_type: ubl.documentType,
@@ -333,11 +339,11 @@ export const normalizeUblResponse = (
333
339
  }
334
340
  : null,
335
341
  supplier: {
336
- endpoint_id: normalizeText(ubl.seller.endpointId),
337
- endpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),
342
+ endpoint_id: normalizeText(ubl.seller.endpoint?.value),
343
+ endpoint_scheme_id: normalizeText(ubl.seller.endpoint?.scheme),
338
344
  registration_name: normalizeText(ubl.seller.registrationName),
339
345
  company_legal_form: normalizeText(ubl.seller.companyLegalForm),
340
- company_id_scheme_id: normalizeText(ubl.seller.companyIdSchemeId),
346
+ company_id_scheme_id: normalizeText(ubl.seller.companyId?.scheme),
341
347
  tax_scheme_id: normalizeText(ubl.seller.taxSchemeId),
342
348
  party_identifications: ubl.seller.partyIdentifications ?? [],
343
349
  contact_name: normalizeText(ubl.seller.contact?.name),
@@ -345,11 +351,11 @@ export const normalizeUblResponse = (
345
351
  contact_email: normalizeText(ubl.seller.contact?.email),
346
352
  },
347
353
  receiver: {
348
- endpoint_id: normalizeText(ubl.buyer.endpointId),
349
- endpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),
354
+ endpoint_id: normalizeText(ubl.buyer.endpoint?.value),
355
+ endpoint_scheme_id: normalizeText(ubl.buyer.endpoint?.scheme),
350
356
  registration_name: normalizeText(ubl.buyer.registrationName),
351
357
  company_legal_form: normalizeText(ubl.buyer.companyLegalForm),
352
- company_id_scheme_id: normalizeText(ubl.buyer.companyIdSchemeId),
358
+ company_id_scheme_id: normalizeText(ubl.buyer.companyId?.scheme),
353
359
  tax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),
354
360
  party_identifications: ubl.buyer.partyIdentifications ?? [],
355
361
  contact_name: normalizeText(ubl.buyer.contact?.name),
@@ -358,7 +364,7 @@ export const normalizeUblResponse = (
358
364
  },
359
365
  supplier_address_structured: supplierAddressStructured,
360
366
  receiver_address_structured: receiverAddressStructured,
361
- tax_subtotals: ubl.taxSubtotals,
367
+ tax_subtotals: ubl.taxTotal.subtotals,
362
368
  allowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),
363
369
  attachments: attachmentMetadata,
364
370
  document_references: ubl.documentReferences ?? [],
package/src/parser.ts CHANGED
@@ -4,6 +4,7 @@ import type {
4
4
  UblAllowanceCharge,
5
5
  UblAttachment,
6
6
  UblBillingReference,
7
+ UblCommodityClassification,
7
8
  UblContact,
8
9
  UblDelivery,
9
10
  UblDocumentReference,
@@ -15,7 +16,10 @@ import type {
15
16
  UblParty,
16
17
  UblPartyIdentification,
17
18
  UblPaymentMeans,
19
+ UblSchemedId,
20
+ UblTaxCategory,
18
21
  UblTaxSubtotal,
22
+ UblTaxTotal,
19
23
  } from "./types.js";
20
24
  import { UblParseError } from "./errors.js";
21
25
  import { CAC_NS, CBC_NS, parseXmlDocument } from "./xml-dom.js";
@@ -86,6 +90,15 @@ function cbcDirectNumber(parent: Element, tag: string): number | undefined {
86
90
  const attribute = (el: Element | null | undefined, name: string): string | undefined =>
87
91
  trimmed(el?.getAttribute(name));
88
92
 
93
+ /** A direct `cbc:<tag>` child with its `@schemeID`. */
94
+ function cbcDirectSchemedId(parent: Element, tag: string): UblSchemedId | undefined {
95
+ const element = childElementsByTagNs(parent, CBC_NS, tag)[0];
96
+ const value = trimmed(element?.textContent);
97
+ return value !== undefined
98
+ ? { value, scheme: attribute(element, "schemeID") }
99
+ : undefined;
100
+ }
101
+
89
102
  function cacDirectElement(parent: Element, tag: string): Element | null {
90
103
  return childElementsByTagNs(parent, CAC_NS, tag)[0] ?? null;
91
104
  }
@@ -149,10 +162,25 @@ function parsePartyIdentifications(party: Element): UblPartyIdentification[] {
149
162
  }
150
163
 
151
164
  function parseParty(root: Element, role: string): UblParty {
152
- const wrapper = cacElement(root, role);
165
+ const wrapper = cacDirectElement(root, role);
153
166
  const party = wrapper ? cacElement(wrapper, "Party") : null;
154
- if (!party) return {};
167
+ return party ? parsePartyElement(party) : {};
168
+ }
169
+
170
+ /**
171
+ * `cac:PayeeParty` (BG-10) and `cac:TaxRepresentativeParty` (BG-11) carry the
172
+ * party children directly, without a `cac:Party` wrapper.
173
+ */
174
+ function parseUnwrappedParty(root: Element, tag: string): UblParty | undefined {
175
+ const party = cacDirectElement(root, tag);
176
+ if (!party) return undefined;
177
+ const parsed = parsePartyElement(party);
178
+ return Object.values(parsed).some((value) => value !== undefined)
179
+ ? parsed
180
+ : undefined;
181
+ }
155
182
 
183
+ function parsePartyElement(party: Element): UblParty {
156
184
  const partyName = cacElement(party, "PartyName");
157
185
  const legalEntity = cacElement(party, "PartyLegalEntity");
158
186
  const taxScheme = cacElement(party, "PartyTaxScheme");
@@ -163,6 +191,13 @@ function parseParty(root: Element, role: string): UblParty {
163
191
  ? legalEntity.getElementsByTagNameNS(CBC_NS, "CompanyID")[0]
164
192
  : null;
165
193
 
194
+ const endpointValue = trimmed(endpointEl?.textContent);
195
+ const companyIdValue = companyIdEl
196
+ ? trimmed(companyIdEl.textContent)
197
+ : partyId
198
+ ? cbcText(partyId, "ID")
199
+ : undefined;
200
+
166
201
  return {
167
202
  name: partyName ? cbcText(partyName, "Name") : undefined,
168
203
  registrationName: legalEntity
@@ -173,14 +208,14 @@ function parseParty(root: Element, role: string): UblParty {
173
208
  : undefined,
174
209
  vatId: taxScheme ? cbcText(taxScheme, "CompanyID") : undefined,
175
210
  taxSchemeId: parseTaxSchemeId(taxScheme),
176
- companyId: companyIdEl
177
- ? trimmed(companyIdEl.textContent)
178
- : partyId
179
- ? cbcText(partyId, "ID")
211
+ companyId:
212
+ companyIdValue !== undefined
213
+ ? { value: companyIdValue, scheme: attribute(companyIdEl, "schemeID") }
214
+ : undefined,
215
+ endpoint:
216
+ endpointValue !== undefined
217
+ ? { value: endpointValue, scheme: attribute(endpointEl, "schemeID") }
180
218
  : undefined,
181
- companyIdSchemeId: attribute(companyIdEl, "schemeID"),
182
- endpointId: trimmed(endpointEl?.textContent),
183
- endpointSchemeId: attribute(endpointEl, "schemeID"),
184
219
  partyIdentifications:
185
220
  partyIdentifications.length > 0 ? partyIdentifications : undefined,
186
221
  address: parseAddress(party),
@@ -188,16 +223,40 @@ function parseParty(root: Element, role: string): UblParty {
188
223
  };
189
224
  }
190
225
 
226
+ /**
227
+ * `cac:TaxCategory` / `cac:ClassifiedTaxCategory`. Emitted whenever the
228
+ * element states anything; `percentFallback` covers the E-FFF habit of putting
229
+ * `cbc:Percent` on the subtotal instead of inside the category.
230
+ */
231
+ function parseTaxCategory(
232
+ cat: Element | null,
233
+ percentFallback?: Element,
234
+ ): UblTaxCategory | undefined {
235
+ const percentFromParent = percentFallback
236
+ ? cbcDirectNumber(percentFallback, "Percent")
237
+ : undefined;
238
+ if (!cat) {
239
+ return percentFromParent !== undefined
240
+ ? { percent: percentFromParent }
241
+ : undefined;
242
+ }
243
+ const category: UblTaxCategory = {
244
+ id: cbcText(cat, "ID"),
245
+ percent: cbcNumber(cat, "Percent") ?? percentFromParent,
246
+ schemeId: parseTaxSchemeId(cat),
247
+ exemptionReason: cbcText(cat, "TaxExemptionReason"),
248
+ exemptionReasonCode: cbcText(cat, "TaxExemptionReasonCode"),
249
+ };
250
+ return Object.values(category).some((value) => value !== undefined)
251
+ ? category
252
+ : undefined;
253
+ }
254
+
191
255
  function parseTaxSubtotal(sub: Element): UblTaxSubtotal {
192
- const cat = cacElement(sub, "TaxCategory");
193
256
  return {
194
257
  taxableAmount: cbcNumber(sub, "TaxableAmount"),
195
258
  taxAmount: cbcNumber(sub, "TaxAmount"),
196
- taxPercent:
197
- (cat ? cbcNumber(cat, "Percent") : undefined) ?? cbcNumber(sub, "Percent"),
198
- taxCategoryId: cat ? cbcText(cat, "ID") : undefined,
199
- taxSchemeId: parseTaxSchemeId(cat),
200
- taxExemptionReason: cat ? cbcText(cat, "TaxExemptionReason") : undefined,
259
+ category: parseTaxCategory(cacElement(sub, "TaxCategory"), sub),
201
260
  };
202
261
  }
203
262
 
@@ -205,10 +264,22 @@ function parseTaxSubtotalsFromTaxTotal(taxTotal: Element): UblTaxSubtotal[] {
205
264
  return cacDirectElements(taxTotal, "TaxSubtotal").map(parseTaxSubtotal);
206
265
  }
207
266
 
208
- function parseTaxSubtotals(root: Element): UblTaxSubtotal[] {
267
+ /**
268
+ * `cac:TaxTotal` (BG-22). BT-110 is read from the first `cac:TaxTotal` as
269
+ * stated, never summed from the subtotals; the subtotals of every `TaxTotal`
270
+ * (a second one carries the accounting-currency figure) are concatenated.
271
+ */
272
+ function parseTaxTotal(root: Element): UblTaxTotal {
209
273
  const taxTotals = cacDirectElements(root, "TaxTotal");
210
- if (taxTotals.length === 0) return [];
211
- return taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal);
274
+ const first = taxTotals[0];
275
+ const second = taxTotals[1];
276
+ return {
277
+ taxAmount: first ? cbcDirectNumber(first, "TaxAmount") : undefined,
278
+ subtotals: taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal),
279
+ taxAmountInTaxCurrency: second
280
+ ? cbcDirectNumber(second, "TaxAmount")
281
+ : undefined,
282
+ };
212
283
  }
213
284
 
214
285
  function parseAllowanceCharge(charge: Element): UblAllowanceCharge {
@@ -222,9 +293,7 @@ function parseAllowanceCharge(charge: Element): UblAllowanceCharge {
222
293
  multiplierFactorNumeric: cbcDirectNumber(charge, "MultiplierFactorNumeric"),
223
294
  reason: cbcText(charge, "AllowanceChargeReason"),
224
295
  reasonCode: cbcText(charge, "AllowanceChargeReasonCode"),
225
- taxPercent: taxCategory ? cbcNumber(taxCategory, "Percent") : undefined,
226
- taxCategoryId: taxCategory ? cbcText(taxCategory, "ID") : undefined,
227
- taxSchemeId: parseTaxSchemeId(taxCategory),
296
+ taxCategory: parseTaxCategory(taxCategory),
228
297
  };
229
298
  }
230
299
 
@@ -232,6 +301,22 @@ function parseAllowanceCharges(parent: Element): UblAllowanceCharge[] {
232
301
  return cacDirectElements(parent, "AllowanceCharge").map(parseAllowanceCharge);
233
302
  }
234
303
 
304
+ function mergeTaxCategories(
305
+ preferred: UblTaxCategory | undefined,
306
+ fallback: UblTaxCategory | undefined,
307
+ ): UblTaxCategory | undefined {
308
+ if (!preferred) return fallback;
309
+ if (!fallback) return preferred;
310
+ return {
311
+ id: preferred.id ?? fallback.id,
312
+ percent: preferred.percent ?? fallback.percent,
313
+ schemeId: preferred.schemeId ?? fallback.schemeId,
314
+ exemptionReason: preferred.exemptionReason ?? fallback.exemptionReason,
315
+ exemptionReasonCode:
316
+ preferred.exemptionReasonCode ?? fallback.exemptionReasonCode,
317
+ };
318
+ }
319
+
235
320
  function parseLines(root: Element, isCreditNote: boolean): UblLine[] {
236
321
  const qtyTag = isCreditNote ? "CreditedQuantity" : "InvoicedQuantity";
237
322
  const lineTag = isCreditNote ? "CreditNoteLine" : "InvoiceLine";
@@ -239,7 +324,9 @@ function parseLines(root: Element, isCreditNote: boolean): UblLine[] {
239
324
  return cacElements(root, lineTag).map((line) => {
240
325
  const item = cacElement(line, "Item");
241
326
  const price = cacElement(line, "Price");
242
- const taxCategory = item ? cacElement(item, "ClassifiedTaxCategory") : null;
327
+ const classifiedCategory = parseTaxCategory(
328
+ item ? cacElement(item, "ClassifiedTaxCategory") : null,
329
+ );
243
330
  const sellersId = item ? cacElement(item, "SellersItemIdentification") : null;
244
331
  const buyersId = item ? cacElement(item, "BuyersItemIdentification") : null;
245
332
  const qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];
@@ -255,21 +342,33 @@ function parseLines(root: Element, isCreditNote: boolean): UblLine[] {
255
342
  const taxAmountFromLineTotal = lineTaxTotal
256
343
  ? cbcDirectNumber(lineTaxTotal, "TaxAmount")
257
344
  : undefined;
258
- const taxPercent =
259
- lineTaxSubtotals[0]?.taxPercent ??
260
- (taxCategory ? cbcNumber(taxCategory, "Percent") : undefined);
345
+ // A line-level TaxSubtotal (E-FFF) wins over the classified category,
346
+ // field by field.
347
+ const subtotalCategory = lineTaxSubtotals[0]?.category;
348
+ const taxCategory = mergeTaxCategories(subtotalCategory, classifiedCategory);
349
+ const taxPercent = taxCategory?.percent;
261
350
  const computedTaxAmount =
262
351
  taxPercent !== undefined && lineExtensionAmount !== undefined
263
352
  ? Number(((lineExtensionAmount * taxPercent) / 100).toFixed(2))
264
353
  : undefined;
265
- const lineAllowanceCharges = parseAllowanceCharges(line);
266
- const priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];
267
- const allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];
268
- const discountAmount = allowanceCharges.reduce(
269
- (sum, charge) =>
270
- charge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0),
271
- 0,
272
- );
354
+ const allowanceCharges = parseAllowanceCharges(line);
355
+ // BT-147/BT-148: the one allowance UBL permits under cac:Price.
356
+ const priceAllowanceElement = price
357
+ ? parseAllowanceCharges(price).find((charge) => !charge.chargeIndicator)
358
+ : undefined;
359
+ const priceAllowance = priceAllowanceElement
360
+ ? {
361
+ amount: priceAllowanceElement.amount,
362
+ baseAmount: priceAllowanceElement.baseAmount,
363
+ reason: priceAllowanceElement.reason,
364
+ }
365
+ : undefined;
366
+ const discountAmount =
367
+ allowanceCharges.reduce(
368
+ (sum, charge) =>
369
+ charge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0),
370
+ 0,
371
+ ) + Math.abs(priceAllowance?.amount ?? 0);
273
372
  const chargeAmount = allowanceCharges.reduce(
274
373
  (sum, charge) =>
275
374
  charge.chargeIndicator ? sum + Math.abs(charge.amount ?? 0) : sum,
@@ -302,32 +401,73 @@ function parseLines(root: Element, isCreditNote: boolean): UblLine[] {
302
401
  ? priceAmount / priceBaseQuantity
303
402
  : priceAmount;
304
403
 
404
+ const orderLineReference = cacDirectElement(line, "OrderLineReference");
405
+ const lineDocumentReference = cacDirectElements(line, "DocumentReference").find(
406
+ (reference) => cbcDirectText(reference, "DocumentTypeCode") === "130",
407
+ );
408
+ const standardId = item
409
+ ? cacDirectElement(item, "StandardItemIdentification")
410
+ : null;
411
+ const originCountry = item ? cacDirectElement(item, "OriginCountry") : null;
412
+ const commodityClassifications: UblCommodityClassification[] = [];
413
+ for (const classification of item
414
+ ? cacDirectElements(item, "CommodityClassification")
415
+ : []) {
416
+ const codeElement = childElementsByTagNs(
417
+ classification,
418
+ CBC_NS,
419
+ "ItemClassificationCode",
420
+ )[0];
421
+ const value = trimmed(codeElement?.textContent);
422
+ if (value === undefined) continue;
423
+ commodityClassifications.push({
424
+ value,
425
+ listId: attribute(codeElement, "listID"),
426
+ listVersionId: attribute(codeElement, "listVersionID"),
427
+ });
428
+ }
429
+
305
430
  return {
306
431
  id: requiredCbcText(line, "ID", `${lineTag} identifier`),
432
+ note: cbcDirectText(line, "Note"),
433
+ objectIdentifier: lineDocumentReference
434
+ ? cbcDirectSchemedId(lineDocumentReference, "ID")
435
+ : undefined,
436
+ orderLineReference: orderLineReference
437
+ ? cbcDirectText(orderLineReference, "LineID")
438
+ : undefined,
439
+ accountingCost: cbcDirectText(line, "AccountingCost"),
307
440
  description: item ? cbcText(item, "Description") : undefined,
308
441
  quantity: cbcNumber(line, qtyTag),
309
442
  unitCode: attribute(qtyEl, "unitCode"),
310
443
  unitPrice,
311
444
  lineExtensionAmount,
312
- taxPercent,
445
+ baseQuantity: priceBaseQuantity,
446
+ taxCategory,
313
447
  taxAmount:
314
448
  taxAmountFromLineTotal ??
315
449
  (lineTaxSubtotals.length > 0
316
450
  ? taxAmountFromSubtotals
317
451
  : computedTaxAmount),
318
- taxCategoryId:
319
- lineTaxSubtotals[0]?.taxCategoryId ??
320
- (taxCategory ? cbcText(taxCategory, "ID") : undefined),
321
- taxSchemeId:
322
- lineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),
323
452
  taxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : undefined,
324
453
  allowanceCharges:
325
454
  allowanceCharges.length > 0 ? allowanceCharges : undefined,
455
+ priceAllowance,
326
456
  discountAmount: discountAmount > 0 ? discountAmount : undefined,
327
457
  chargeAmount: chargeAmount > 0 ? chargeAmount : undefined,
328
458
  itemName: item ? cbcText(item, "Name") : undefined,
329
459
  sellersItemId: sellersId ? cbcText(sellersId, "ID") : undefined,
330
460
  buyersItemId: buyersId ? cbcText(buyersId, "ID") : undefined,
461
+ standardItemId: standardId
462
+ ? cbcDirectSchemedId(standardId, "ID")
463
+ : undefined,
464
+ commodityClassifications:
465
+ commodityClassifications.length > 0
466
+ ? commodityClassifications
467
+ : undefined,
468
+ originCountryCode: originCountry
469
+ ? cbcDirectText(originCountry, "IdentificationCode")
470
+ : undefined,
331
471
  additionalItemProperties:
332
472
  additionalItemProperties.length > 0
333
473
  ? additionalItemProperties
@@ -357,6 +497,10 @@ function parsePaymentMeansElement(pm: Element): UblPaymentMeans {
357
497
  const branch = account ? cacElement(account, "FinancialInstitutionBranch") : null;
358
498
  const paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, "PaymentMeansCode")[0];
359
499
  const mandate = cacElement(pm, "PaymentMandate");
500
+ const debitedAccount = mandate
501
+ ? cacElement(mandate, "PayerFinancialAccount")
502
+ : null;
503
+ const card = cacElement(pm, "CardAccount");
360
504
 
361
505
  return {
362
506
  code: cbcText(pm, "PaymentMeansCode"),
@@ -365,7 +509,10 @@ function parsePaymentMeansElement(pm: Element): UblPaymentMeans {
365
509
  iban: account ? cbcText(account, "ID") : undefined,
366
510
  bic: branch ? cbcText(branch, "ID") : undefined,
367
511
  accountName: account ? cbcText(account, "Name") : undefined,
368
- mandateId: mandate ? cbcText(mandate, "ID") : undefined,
512
+ mandateId: mandate ? cbcDirectText(mandate, "ID") : undefined,
513
+ debitedAccount: debitedAccount ? cbcText(debitedAccount, "ID") : undefined,
514
+ cardNumber: card ? cbcText(card, "PrimaryAccountNumberID") : undefined,
515
+ cardHolder: card ? cbcText(card, "HolderName") : undefined,
369
516
  };
370
517
  }
371
518
 
@@ -399,13 +546,20 @@ function parseDelivery(root: Element): UblDelivery | undefined {
399
546
  if (!delivery) return undefined;
400
547
  const actualDeliveryDate = cbcText(delivery, "ActualDeliveryDate");
401
548
  const deliveryLocation = cacElement(delivery, "DeliveryLocation");
549
+ const locationId = deliveryLocation
550
+ ? cbcDirectSchemedId(deliveryLocation, "ID")
551
+ : undefined;
402
552
  const address = parseAddressFromElement(
403
553
  deliveryLocation ? cacElement(deliveryLocation, "Address") : null,
404
554
  );
405
- if (!actualDeliveryDate && !address) return undefined;
555
+ const deliveryParty = cacElement(delivery, "DeliveryParty");
556
+ const partyName = deliveryParty ? cbcText(deliveryParty, "Name") : undefined;
557
+ if (!actualDeliveryDate && !locationId && !address && !partyName) return undefined;
406
558
  return {
407
559
  actualDeliveryDate,
560
+ locationId,
408
561
  address,
562
+ partyName,
409
563
  };
410
564
  }
411
565
 
@@ -429,18 +583,38 @@ function parseNotes(root: Element): string | undefined {
429
583
  return notes.length > 0 ? notes.join("\n") : undefined;
430
584
  }
431
585
 
586
+ /**
587
+ * `cac:AdditionalDocumentReference` (BG-24), plus the two references EN 16931
588
+ * types by `cbc:DocumentTypeCode`: 130 is the invoiced object (BT-18) and 50
589
+ * is the tender or lot (BT-17), which on a credit note stands in for the
590
+ * project reference (BT-11) UBL's CreditNote has no element for.
591
+ */
432
592
  function parseAttachments(root: Element): {
433
593
  attachments: UblAttachment[] | undefined;
434
594
  documentReferences: UblDocumentReference[] | undefined;
595
+ invoicedObjectId: UblSchemedId | undefined;
596
+ typeCode50Reference: string | undefined;
435
597
  } {
436
- const refs = cacElements(root, "AdditionalDocumentReference");
598
+ const refs = cacDirectElements(root, "AdditionalDocumentReference");
437
599
  const attachments: UblAttachment[] = [];
438
600
  const documentReferences: UblDocumentReference[] = [];
601
+ let invoicedObjectId: UblSchemedId | undefined;
602
+ let typeCode50Reference: string | undefined;
439
603
 
440
604
  for (const ref of refs) {
441
605
  const attachment = cacElement(ref, "Attachment");
442
606
  const refId = cbcText(ref, "ID");
443
607
  const description = cbcText(ref, "DocumentDescription");
608
+ const typeCode = cbcDirectText(ref, "DocumentTypeCode");
609
+
610
+ if (typeCode === "130" && !attachment) {
611
+ invoicedObjectId ??= cbcDirectSchemedId(ref, "ID");
612
+ continue;
613
+ }
614
+ if (typeCode === "50" && !attachment) {
615
+ typeCode50Reference ??= refId;
616
+ continue;
617
+ }
444
618
 
445
619
  if (!attachment) {
446
620
  // Text-only document reference (e.g. terms & conditions, notices)
@@ -483,6 +657,8 @@ function parseAttachments(root: Element): {
483
657
  attachments: attachments.length > 0 ? attachments : undefined,
484
658
  documentReferences:
485
659
  documentReferences.length > 0 ? documentReferences : undefined,
660
+ invoicedObjectId,
661
+ typeCode50Reference,
486
662
  };
487
663
  }
488
664
 
@@ -551,9 +727,17 @@ export function parseUblInvoice(xml: string): UblInvoice | null {
551
727
  const currency = requiredCbcText(root, "DocumentCurrencyCode", "currency code");
552
728
  const paymentMeansList = parsePaymentMeansList(root);
553
729
  const orderReference = cacElement(root, "OrderReference");
554
- const contractReference = cacElement(root, "ContractDocumentReference");
555
- const projectReference = cacElement(root, "ProjectReference");
556
- const { attachments, documentReferences } = parseAttachments(root);
730
+ const contractReference = cacDirectElement(root, "ContractDocumentReference");
731
+ const projectReference = cacDirectElement(root, "ProjectReference");
732
+ const despatchReference = cacDirectElement(root, "DespatchDocumentReference");
733
+ const receiptReference = cacDirectElement(root, "ReceiptDocumentReference");
734
+ const { attachments, documentReferences, invoicedObjectId, typeCode50Reference } =
735
+ parseAttachments(root);
736
+ // A credit note has no cbc:DueDate; BT-9 travels in the first PaymentMeans.
737
+ const paymentDueDate = (() => {
738
+ const first = cacDirectElements(root, "PaymentMeans")[0];
739
+ return first ? cbcDirectText(first, "PaymentDueDate") : undefined;
740
+ })();
557
741
 
558
742
  return omitUndefined<UblInvoice>({
559
743
  documentType,
@@ -563,9 +747,11 @@ export function parseUblInvoice(xml: string): UblInvoice | null {
563
747
  invoiceTypeCode:
564
748
  cbcText(root, "InvoiceTypeCode") ?? cbcText(root, "CreditNoteTypeCode"),
565
749
  issueDate,
566
- dueDate: cbcText(root, "DueDate"),
567
- taxPointDate: cbcText(root, "TaxPointDate"),
750
+ dueDate: cbcDirectText(root, "DueDate") ?? paymentDueDate,
751
+ taxPointDate: cbcDirectText(root, "TaxPointDate"),
568
752
  currency,
753
+ taxCurrency: cbcDirectText(root, "TaxCurrencyCode"),
754
+ accountingCost: cbcDirectText(root, "AccountingCost"),
569
755
  buyerReference: cbcText(root, "BuyerReference"),
570
756
  orderReference: orderReference ? cbcText(orderReference, "ID") : undefined,
571
757
  salesOrderId: orderReference
@@ -576,13 +762,25 @@ export function parseUblInvoice(xml: string): UblInvoice | null {
576
762
  : undefined,
577
763
  projectReference: projectReference
578
764
  ? cbcText(projectReference, "ID")
765
+ : isCreditNote
766
+ ? typeCode50Reference
767
+ : undefined,
768
+ receivingAdviceReference: receiptReference
769
+ ? cbcDirectText(receiptReference, "ID")
770
+ : undefined,
771
+ despatchReference: despatchReference
772
+ ? cbcDirectText(despatchReference, "ID")
579
773
  : undefined,
774
+ tenderReference: isCreditNote ? undefined : typeCode50Reference,
775
+ invoicedObjectId,
580
776
  billingReference: parseBillingReference(root),
581
777
  seller: parseParty(root, "AccountingSupplierParty"),
582
778
  buyer: parseParty(root, "AccountingCustomerParty"),
779
+ payee: parseUnwrappedParty(root, "PayeeParty"),
780
+ taxRepresentative: parseUnwrappedParty(root, "TaxRepresentativeParty"),
583
781
  delivery: parseDelivery(root),
584
782
  lines: parseLines(root, isCreditNote),
585
- taxSubtotals: parseTaxSubtotals(root),
783
+ taxTotal: parseTaxTotal(root),
586
784
  monetaryTotal: parseMonetaryTotal(root),
587
785
  paymentMeansList,
588
786
  paymentMeans: paymentMeansList?.[0],