@financica/ubl 0.17.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.
package/dist/index.js CHANGED
@@ -75,6 +75,15 @@ function cbcDirectNumber(parent, tag) {
75
75
  return toNumber(cbcDirectText$1(parent, tag));
76
76
  }
77
77
  const attribute = (el, name) => trimmed$1(el?.getAttribute(name));
78
+ /** A direct `cbc:<tag>` child with its `@schemeID`. */
79
+ function cbcDirectSchemedId(parent, tag) {
80
+ const element = childElementsByTagNs(parent, CBC_NS, tag)[0];
81
+ const value = trimmed$1(element?.textContent);
82
+ return value !== void 0 ? {
83
+ value,
84
+ scheme: attribute(element, "schemeID")
85
+ } : void 0;
86
+ }
78
87
  function cacDirectElement(parent, tag) {
79
88
  return childElementsByTagNs(parent, "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", tag)[0] ?? null;
80
89
  }
@@ -129,9 +138,21 @@ function parsePartyIdentifications(party) {
129
138
  return result;
130
139
  }
131
140
  function parseParty(root, role) {
132
- const wrapper = cacElement$1(root, role);
141
+ const wrapper = cacDirectElement(root, role);
133
142
  const party = wrapper ? cacElement$1(wrapper, "Party") : null;
134
- if (!party) return {};
143
+ return party ? parsePartyElement(party) : {};
144
+ }
145
+ /**
146
+ * `cac:PayeeParty` (BG-10) and `cac:TaxRepresentativeParty` (BG-11) carry the
147
+ * party children directly, without a `cac:Party` wrapper.
148
+ */
149
+ function parseUnwrappedParty(root, tag) {
150
+ const party = cacDirectElement(root, tag);
151
+ if (!party) return void 0;
152
+ const parsed = parsePartyElement(party);
153
+ return Object.values(parsed).some((value) => value !== void 0) ? parsed : void 0;
154
+ }
155
+ function parsePartyElement(party) {
135
156
  const partyName = cacElement$1(party, "PartyName");
136
157
  const legalEntity = cacElement$1(party, "PartyLegalEntity");
137
158
  const taxScheme = cacElement$1(party, "PartyTaxScheme");
@@ -195,9 +216,11 @@ function parseTaxSubtotalsFromTaxTotal(taxTotal) {
195
216
  function parseTaxTotal(root) {
196
217
  const taxTotals = cacDirectElements(root, "TaxTotal");
197
218
  const first = taxTotals[0];
219
+ const second = taxTotals[1];
198
220
  return {
199
221
  taxAmount: first ? cbcDirectNumber(first, "TaxAmount") : void 0,
200
- subtotals: taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal)
222
+ subtotals: taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal),
223
+ taxAmountInTaxCurrency: second ? cbcDirectNumber(second, "TaxAmount") : void 0
201
224
  };
202
225
  }
203
226
  function parseAllowanceCharge(charge) {
@@ -246,10 +269,14 @@ function parseLines(root, isCreditNote) {
246
269
  const taxCategory = mergeTaxCategories(subtotalCategory, classifiedCategory);
247
270
  const taxPercent = taxCategory?.percent;
248
271
  const computedTaxAmount = taxPercent !== void 0 && lineExtensionAmount !== void 0 ? Number((lineExtensionAmount * taxPercent / 100).toFixed(2)) : void 0;
249
- const lineAllowanceCharges = parseAllowanceCharges(line);
250
- const priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];
251
- const allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];
252
- const discountAmount = allowanceCharges.reduce((sum, charge) => charge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0), 0);
272
+ const allowanceCharges = parseAllowanceCharges(line);
273
+ const priceAllowanceElement = price ? parseAllowanceCharges(price).find((charge) => !charge.chargeIndicator) : void 0;
274
+ const priceAllowance = priceAllowanceElement ? {
275
+ amount: priceAllowanceElement.amount,
276
+ baseAmount: priceAllowanceElement.baseAmount,
277
+ reason: priceAllowanceElement.reason
278
+ } : void 0;
279
+ const discountAmount = allowanceCharges.reduce((sum, charge) => charge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0), 0) + Math.abs(priceAllowance?.amount ?? 0);
253
280
  const chargeAmount = allowanceCharges.reduce((sum, charge) => charge.chargeIndicator ? sum + Math.abs(charge.amount ?? 0) : sum, 0);
254
281
  const additionalItemProperties = [];
255
282
  if (item) for (const prop of cacElements(item, "AdditionalItemProperty")) {
@@ -263,8 +290,27 @@ function parseLines(root, isCreditNote) {
263
290
  const priceAmount = price ? cbcNumber(price, "PriceAmount") : void 0;
264
291
  const priceBaseQuantity = price ? cbcDirectNumber(price, "BaseQuantity") : void 0;
265
292
  const unitPrice = priceAmount !== void 0 && priceBaseQuantity && priceBaseQuantity > 0 ? priceAmount / priceBaseQuantity : priceAmount;
293
+ const orderLineReference = cacDirectElement(line, "OrderLineReference");
294
+ const lineDocumentReference = cacDirectElements(line, "DocumentReference").find((reference) => cbcDirectText$1(reference, "DocumentTypeCode") === "130");
295
+ const standardId = item ? cacDirectElement(item, "StandardItemIdentification") : null;
296
+ const originCountry = item ? cacDirectElement(item, "OriginCountry") : null;
297
+ const commodityClassifications = [];
298
+ for (const classification of item ? cacDirectElements(item, "CommodityClassification") : []) {
299
+ const codeElement = childElementsByTagNs(classification, CBC_NS, "ItemClassificationCode")[0];
300
+ const value = trimmed$1(codeElement?.textContent);
301
+ if (value === void 0) continue;
302
+ commodityClassifications.push({
303
+ value,
304
+ listId: attribute(codeElement, "listID"),
305
+ listVersionId: attribute(codeElement, "listVersionID")
306
+ });
307
+ }
266
308
  return {
267
309
  id: requiredCbcText(line, "ID", `${lineTag} identifier`),
310
+ note: cbcDirectText$1(line, "Note"),
311
+ objectIdentifier: lineDocumentReference ? cbcDirectSchemedId(lineDocumentReference, "ID") : void 0,
312
+ orderLineReference: orderLineReference ? cbcDirectText$1(orderLineReference, "LineID") : void 0,
313
+ accountingCost: cbcDirectText$1(line, "AccountingCost"),
268
314
  description: item ? cbcText$1(item, "Description") : void 0,
269
315
  quantity: cbcNumber(line, qtyTag),
270
316
  unitCode: attribute(qtyEl, "unitCode"),
@@ -275,11 +321,15 @@ function parseLines(root, isCreditNote) {
275
321
  taxAmount: taxAmountFromLineTotal ?? (lineTaxSubtotals.length > 0 ? taxAmountFromSubtotals : computedTaxAmount),
276
322
  taxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : void 0,
277
323
  allowanceCharges: allowanceCharges.length > 0 ? allowanceCharges : void 0,
324
+ priceAllowance,
278
325
  discountAmount: discountAmount > 0 ? discountAmount : void 0,
279
326
  chargeAmount: chargeAmount > 0 ? chargeAmount : void 0,
280
327
  itemName: item ? cbcText$1(item, "Name") : void 0,
281
328
  sellersItemId: sellersId ? cbcText$1(sellersId, "ID") : void 0,
282
329
  buyersItemId: buyersId ? cbcText$1(buyersId, "ID") : void 0,
330
+ standardItemId: standardId ? cbcDirectSchemedId(standardId, "ID") : void 0,
331
+ commodityClassifications: commodityClassifications.length > 0 ? commodityClassifications : void 0,
332
+ originCountryCode: originCountry ? cbcDirectText$1(originCountry, "IdentificationCode") : void 0,
283
333
  additionalItemProperties: additionalItemProperties.length > 0 ? additionalItemProperties : void 0,
284
334
  invoicePeriod: parseInvoicePeriod(line)
285
335
  };
@@ -304,6 +354,8 @@ function parsePaymentMeansElement(pm) {
304
354
  const branch = account ? cacElement$1(account, "FinancialInstitutionBranch") : null;
305
355
  const paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, "PaymentMeansCode")[0];
306
356
  const mandate = cacElement$1(pm, "PaymentMandate");
357
+ const debitedAccount = mandate ? cacElement$1(mandate, "PayerFinancialAccount") : null;
358
+ const card = cacElement$1(pm, "CardAccount");
307
359
  return {
308
360
  code: cbcText$1(pm, "PaymentMeansCode"),
309
361
  codeName: attribute(paymentMeansCodeEl, "name"),
@@ -311,7 +363,10 @@ function parsePaymentMeansElement(pm) {
311
363
  iban: account ? cbcText$1(account, "ID") : void 0,
312
364
  bic: branch ? cbcText$1(branch, "ID") : void 0,
313
365
  accountName: account ? cbcText$1(account, "Name") : void 0,
314
- mandateId: mandate ? cbcText$1(mandate, "ID") : void 0
366
+ mandateId: mandate ? cbcDirectText$1(mandate, "ID") : void 0,
367
+ debitedAccount: debitedAccount ? cbcText$1(debitedAccount, "ID") : void 0,
368
+ cardNumber: card ? cbcText$1(card, "PrimaryAccountNumberID") : void 0,
369
+ cardHolder: card ? cbcText$1(card, "HolderName") : void 0
315
370
  };
316
371
  }
317
372
  function parsePaymentMeansList(root) {
@@ -340,11 +395,16 @@ function parseDelivery(root) {
340
395
  if (!delivery) return void 0;
341
396
  const actualDeliveryDate = cbcText$1(delivery, "ActualDeliveryDate");
342
397
  const deliveryLocation = cacElement$1(delivery, "DeliveryLocation");
398
+ const locationId = deliveryLocation ? cbcDirectSchemedId(deliveryLocation, "ID") : void 0;
343
399
  const address = parseAddressFromElement(deliveryLocation ? cacElement$1(deliveryLocation, "Address") : null);
344
- if (!actualDeliveryDate && !address) return void 0;
400
+ const deliveryParty = cacElement$1(delivery, "DeliveryParty");
401
+ const partyName = deliveryParty ? cbcText$1(deliveryParty, "Name") : void 0;
402
+ if (!actualDeliveryDate && !locationId && !address && !partyName) return void 0;
345
403
  return {
346
404
  actualDeliveryDate,
347
- address
405
+ locationId,
406
+ address,
407
+ partyName
348
408
  };
349
409
  }
350
410
  function parsePaymentTermsNote(root) {
@@ -365,14 +425,31 @@ function parseNotes(root) {
365
425
  }
366
426
  return notes.length > 0 ? notes.join("\n") : void 0;
367
427
  }
428
+ /**
429
+ * `cac:AdditionalDocumentReference` (BG-24), plus the two references EN 16931
430
+ * types by `cbc:DocumentTypeCode`: 130 is the invoiced object (BT-18) and 50
431
+ * is the tender or lot (BT-17), which on a credit note stands in for the
432
+ * project reference (BT-11) UBL's CreditNote has no element for.
433
+ */
368
434
  function parseAttachments(root) {
369
- const refs = cacElements(root, "AdditionalDocumentReference");
435
+ const refs = cacDirectElements(root, "AdditionalDocumentReference");
370
436
  const attachments = [];
371
437
  const documentReferences = [];
438
+ let invoicedObjectId;
439
+ let typeCode50Reference;
372
440
  for (const ref of refs) {
373
441
  const attachment = cacElement$1(ref, "Attachment");
374
442
  const refId = cbcText$1(ref, "ID");
375
443
  const description = cbcText$1(ref, "DocumentDescription");
444
+ const typeCode = cbcDirectText$1(ref, "DocumentTypeCode");
445
+ if (typeCode === "130" && !attachment) {
446
+ invoicedObjectId ??= cbcDirectSchemedId(ref, "ID");
447
+ continue;
448
+ }
449
+ if (typeCode === "50" && !attachment) {
450
+ typeCode50Reference ??= refId;
451
+ continue;
452
+ }
376
453
  if (!attachment) {
377
454
  if (refId || description) documentReferences.push({
378
455
  id: refId,
@@ -402,7 +479,9 @@ function parseAttachments(root) {
402
479
  }
403
480
  return {
404
481
  attachments: attachments.length > 0 ? attachments : void 0,
405
- documentReferences: documentReferences.length > 0 ? documentReferences : void 0
482
+ documentReferences: documentReferences.length > 0 ? documentReferences : void 0,
483
+ invoicedObjectId,
484
+ typeCode50Reference
406
485
  };
407
486
  }
408
487
  function parseBillingReference(root) {
@@ -454,9 +533,15 @@ function parseUblInvoice(xml) {
454
533
  const currency = requiredCbcText(root, "DocumentCurrencyCode", "currency code");
455
534
  const paymentMeansList = parsePaymentMeansList(root);
456
535
  const orderReference = cacElement$1(root, "OrderReference");
457
- const contractReference = cacElement$1(root, "ContractDocumentReference");
458
- const projectReference = cacElement$1(root, "ProjectReference");
459
- const { attachments, documentReferences } = parseAttachments(root);
536
+ const contractReference = cacDirectElement(root, "ContractDocumentReference");
537
+ const projectReference = cacDirectElement(root, "ProjectReference");
538
+ const despatchReference = cacDirectElement(root, "DespatchDocumentReference");
539
+ const receiptReference = cacDirectElement(root, "ReceiptDocumentReference");
540
+ const { attachments, documentReferences, invoicedObjectId, typeCode50Reference } = parseAttachments(root);
541
+ const paymentDueDate = (() => {
542
+ const first = cacDirectElements(root, "PaymentMeans")[0];
543
+ return first ? cbcDirectText$1(first, "PaymentDueDate") : void 0;
544
+ })();
460
545
  return omitUndefined({
461
546
  documentType,
462
547
  customizationId: cbcText$1(root, "CustomizationID"),
@@ -464,17 +549,25 @@ function parseUblInvoice(xml) {
464
549
  id,
465
550
  invoiceTypeCode: cbcText$1(root, "InvoiceTypeCode") ?? cbcText$1(root, "CreditNoteTypeCode"),
466
551
  issueDate,
467
- dueDate: cbcText$1(root, "DueDate"),
468
- taxPointDate: cbcText$1(root, "TaxPointDate"),
552
+ dueDate: cbcDirectText$1(root, "DueDate") ?? paymentDueDate,
553
+ taxPointDate: cbcDirectText$1(root, "TaxPointDate"),
469
554
  currency,
555
+ taxCurrency: cbcDirectText$1(root, "TaxCurrencyCode"),
556
+ accountingCost: cbcDirectText$1(root, "AccountingCost"),
470
557
  buyerReference: cbcText$1(root, "BuyerReference"),
471
558
  orderReference: orderReference ? cbcText$1(orderReference, "ID") : void 0,
472
559
  salesOrderId: orderReference ? cbcText$1(orderReference, "SalesOrderID") : void 0,
473
560
  contractReference: contractReference ? cbcText$1(contractReference, "ID") : void 0,
474
- projectReference: projectReference ? cbcText$1(projectReference, "ID") : void 0,
561
+ projectReference: projectReference ? cbcText$1(projectReference, "ID") : isCreditNote ? typeCode50Reference : void 0,
562
+ receivingAdviceReference: receiptReference ? cbcDirectText$1(receiptReference, "ID") : void 0,
563
+ despatchReference: despatchReference ? cbcDirectText$1(despatchReference, "ID") : void 0,
564
+ tenderReference: isCreditNote ? void 0 : typeCode50Reference,
565
+ invoicedObjectId,
475
566
  billingReference: parseBillingReference(root),
476
567
  seller: parseParty(root, "AccountingSupplierParty"),
477
568
  buyer: parseParty(root, "AccountingCustomerParty"),
569
+ payee: parseUnwrappedParty(root, "PayeeParty"),
570
+ taxRepresentative: parseUnwrappedParty(root, "TaxRepresentativeParty"),
478
571
  delivery: parseDelivery(root),
479
572
  lines: parseLines(root, isCreditNote),
480
573
  taxTotal: parseTaxTotal(root),
@@ -779,7 +872,10 @@ const normalizeUblResponse = (xml, documentId) => {
779
872
  tax_category_id: normalizeText(line.taxCategory?.id),
780
873
  tax_scheme_id: normalizeText(line.taxCategory?.schemeId),
781
874
  tax_subtotals: line.taxSubtotals ?? [],
782
- allowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),
875
+ allowance_charges: sanitizeAllowanceCharges([...line.allowanceCharges ?? [], ...line.priceAllowance ? [{
876
+ chargeIndicator: false,
877
+ ...line.priceAllowance
878
+ }] : []]),
783
879
  charge_amount: toNumberOrNull(line.chargeAmount),
784
880
  metadata: line.additionalItemProperties ? Object.fromEntries(line.additionalItemProperties.map((p) => [p.name, p.value])) : null
785
881
  }