@financica/ubl 0.15.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/parser.ts ADDED
@@ -0,0 +1,651 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import type {
3
+ UblAddress,
4
+ UblAllowanceCharge,
5
+ UblAttachment,
6
+ UblBillingReference,
7
+ UblContact,
8
+ UblDelivery,
9
+ UblDocumentReference,
10
+ UblInvoice,
11
+ UblInvoicePeriod,
12
+ UblItemProperty,
13
+ UblLine,
14
+ UblMonetaryTotal,
15
+ UblParty,
16
+ UblPartyIdentification,
17
+ UblPaymentMeans,
18
+ UblTaxCategory,
19
+ UblTaxSubtotal,
20
+ UblTaxTotal,
21
+ } from "./types.js";
22
+ import { UblParseError } from "./errors.js";
23
+ import { CAC_NS, CBC_NS, parseXmlDocument } from "./xml-dom.js";
24
+
25
+ // --- DOM helpers ---
26
+
27
+ const trimmed = (value: string | null | undefined): string | undefined => {
28
+ const text = value?.trim();
29
+ return text ? text : undefined;
30
+ };
31
+
32
+ /** First descendant CBC element's trimmed text; absent or blank is `undefined`. */
33
+ function cbcText(parent: Element, tag: string): string | undefined {
34
+ return trimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);
35
+ }
36
+
37
+ /** Like {@link cbcText} but throws: the element is mandatory in EN 16931. */
38
+ function requiredCbcText(parent: Element, tag: string, what: string): string {
39
+ const value = cbcText(parent, tag);
40
+ if (value === undefined) throw new UblParseError(`Missing ${what} (cbc:${tag})`);
41
+ return value;
42
+ }
43
+
44
+ const toNumber = (value: string | undefined): number | undefined => {
45
+ if (value === undefined) return undefined;
46
+ const parsed = Number.parseFloat(value);
47
+ return Number.isNaN(parsed) ? undefined : parsed;
48
+ };
49
+
50
+ function cacElement(parent: Element, tag: string): Element | null {
51
+ return parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;
52
+ }
53
+
54
+ function cacElements(parent: Element, tag: string): Element[] {
55
+ return Array.from(parent.getElementsByTagNameNS(CAC_NS, tag));
56
+ }
57
+
58
+ /** First descendant CBC element as a number; absent or non-numeric is `undefined`. */
59
+ function cbcNumber(parent: Element, tag: string): number | undefined {
60
+ return toNumber(cbcText(parent, tag));
61
+ }
62
+
63
+ function childElementsByTagNs(
64
+ parent: Element,
65
+ namespace: string,
66
+ tag: string,
67
+ ): Element[] {
68
+ const elements: Element[] = [];
69
+ for (let i = 0; i < parent.childNodes.length; i++) {
70
+ const node = parent.childNodes[i];
71
+ if (!node || node.nodeType !== 1) continue;
72
+ const element = node as Element;
73
+ if (element.namespaceURI === namespace && element.localName === tag) {
74
+ elements.push(element);
75
+ }
76
+ }
77
+ return elements;
78
+ }
79
+
80
+ function cbcDirectText(parent: Element, tag: string): string | undefined {
81
+ return trimmed(childElementsByTagNs(parent, CBC_NS, tag)[0]?.textContent);
82
+ }
83
+
84
+ function cbcDirectNumber(parent: Element, tag: string): number | undefined {
85
+ return toNumber(cbcDirectText(parent, tag));
86
+ }
87
+
88
+ const attribute = (el: Element | null | undefined, name: string): string | undefined =>
89
+ trimmed(el?.getAttribute(name));
90
+
91
+ function cacDirectElement(parent: Element, tag: string): Element | null {
92
+ return childElementsByTagNs(parent, CAC_NS, tag)[0] ?? null;
93
+ }
94
+
95
+ function cacDirectElements(parent: Element, tag: string): Element[] {
96
+ return childElementsByTagNs(parent, CAC_NS, tag);
97
+ }
98
+
99
+ // --- Section parsers ---
100
+
101
+ function parseAddressFromElement(address: Element | null): UblAddress | undefined {
102
+ if (!address) return undefined;
103
+ const country = cacElement(address, "Country");
104
+ return {
105
+ street: cbcText(address, "StreetName"),
106
+ additionalStreet: cbcText(address, "AdditionalStreetName"),
107
+ city: cbcText(address, "CityName"),
108
+ postalZone: cbcText(address, "PostalZone"),
109
+ countrySubentity: cbcText(address, "CountrySubentity"),
110
+ countryCode: country ? cbcText(country, "IdentificationCode") : undefined,
111
+ };
112
+ }
113
+
114
+ function parseAddress(party: Element): UblAddress | undefined {
115
+ const postal = cacElement(party, "PostalAddress");
116
+ return parseAddressFromElement(postal);
117
+ }
118
+
119
+ function parseTaxSchemeId(parent: Element | null): string | undefined {
120
+ if (!parent) return undefined;
121
+ const taxScheme = cacElement(parent, "TaxScheme");
122
+ if (!taxScheme) return undefined;
123
+ return cbcText(taxScheme, "ID");
124
+ }
125
+
126
+ function parseContact(party: Element): UblContact | undefined {
127
+ const contact = cacElement(party, "Contact");
128
+ if (!contact) return undefined;
129
+ const name = cbcText(contact, "Name");
130
+ const phone = cbcText(contact, "Telephone");
131
+ const email = cbcText(contact, "ElectronicMail");
132
+ if (!name && !phone && !email) return undefined;
133
+ return { name, phone, email };
134
+ }
135
+
136
+ function parsePartyIdentifications(party: Element): UblPartyIdentification[] {
137
+ const ids = cacElements(party, "PartyIdentification");
138
+ const result: UblPartyIdentification[] = [];
139
+ for (const idEl of ids) {
140
+ const idValue = cbcText(idEl, "ID");
141
+ if (!idValue) continue;
142
+ result.push({
143
+ id: idValue,
144
+ schemeId: attribute(
145
+ idEl.getElementsByTagNameNS(CBC_NS, "ID")[0],
146
+ "schemeID",
147
+ ),
148
+ });
149
+ }
150
+ return result;
151
+ }
152
+
153
+ function parseParty(root: Element, role: string): UblParty {
154
+ const wrapper = cacElement(root, role);
155
+ const party = wrapper ? cacElement(wrapper, "Party") : null;
156
+ if (!party) return {};
157
+
158
+ const partyName = cacElement(party, "PartyName");
159
+ const legalEntity = cacElement(party, "PartyLegalEntity");
160
+ const taxScheme = cacElement(party, "PartyTaxScheme");
161
+ const partyId = cacElement(party, "PartyIdentification");
162
+ const endpointEl = party.getElementsByTagNameNS(CBC_NS, "EndpointID")[0];
163
+ const partyIdentifications = parsePartyIdentifications(party);
164
+ const companyIdEl = legalEntity
165
+ ? legalEntity.getElementsByTagNameNS(CBC_NS, "CompanyID")[0]
166
+ : null;
167
+
168
+ const endpointValue = trimmed(endpointEl?.textContent);
169
+ const companyIdValue = companyIdEl
170
+ ? trimmed(companyIdEl.textContent)
171
+ : partyId
172
+ ? cbcText(partyId, "ID")
173
+ : undefined;
174
+
175
+ return {
176
+ name: partyName ? cbcText(partyName, "Name") : undefined,
177
+ registrationName: legalEntity
178
+ ? cbcText(legalEntity, "RegistrationName")
179
+ : undefined,
180
+ companyLegalForm: legalEntity
181
+ ? cbcText(legalEntity, "CompanyLegalForm")
182
+ : undefined,
183
+ vatId: taxScheme ? cbcText(taxScheme, "CompanyID") : undefined,
184
+ taxSchemeId: parseTaxSchemeId(taxScheme),
185
+ companyId:
186
+ companyIdValue !== undefined
187
+ ? { value: companyIdValue, scheme: attribute(companyIdEl, "schemeID") }
188
+ : undefined,
189
+ endpoint:
190
+ endpointValue !== undefined
191
+ ? { value: endpointValue, scheme: attribute(endpointEl, "schemeID") }
192
+ : undefined,
193
+ partyIdentifications:
194
+ partyIdentifications.length > 0 ? partyIdentifications : undefined,
195
+ address: parseAddress(party),
196
+ contact: parseContact(party),
197
+ };
198
+ }
199
+
200
+ /**
201
+ * `cac:TaxCategory` / `cac:ClassifiedTaxCategory`. Emitted whenever the
202
+ * element states anything; `percentFallback` covers the E-FFF habit of putting
203
+ * `cbc:Percent` on the subtotal instead of inside the category.
204
+ */
205
+ function parseTaxCategory(
206
+ cat: Element | null,
207
+ percentFallback?: Element,
208
+ ): UblTaxCategory | undefined {
209
+ const percentFromParent = percentFallback
210
+ ? cbcDirectNumber(percentFallback, "Percent")
211
+ : undefined;
212
+ if (!cat) {
213
+ return percentFromParent !== undefined
214
+ ? { percent: percentFromParent }
215
+ : undefined;
216
+ }
217
+ const category: UblTaxCategory = {
218
+ id: cbcText(cat, "ID"),
219
+ percent: cbcNumber(cat, "Percent") ?? percentFromParent,
220
+ schemeId: parseTaxSchemeId(cat),
221
+ exemptionReason: cbcText(cat, "TaxExemptionReason"),
222
+ exemptionReasonCode: cbcText(cat, "TaxExemptionReasonCode"),
223
+ };
224
+ return Object.values(category).some((value) => value !== undefined)
225
+ ? category
226
+ : undefined;
227
+ }
228
+
229
+ function parseTaxSubtotal(sub: Element): UblTaxSubtotal {
230
+ return {
231
+ taxableAmount: cbcNumber(sub, "TaxableAmount"),
232
+ taxAmount: cbcNumber(sub, "TaxAmount"),
233
+ category: parseTaxCategory(cacElement(sub, "TaxCategory"), sub),
234
+ };
235
+ }
236
+
237
+ function parseTaxSubtotalsFromTaxTotal(taxTotal: Element): UblTaxSubtotal[] {
238
+ return cacDirectElements(taxTotal, "TaxSubtotal").map(parseTaxSubtotal);
239
+ }
240
+
241
+ /**
242
+ * `cac:TaxTotal` (BG-22). BT-110 is read from the first `cac:TaxTotal` as
243
+ * stated, never summed from the subtotals; the subtotals of every `TaxTotal`
244
+ * (a second one carries the accounting-currency figure) are concatenated.
245
+ */
246
+ function parseTaxTotal(root: Element): UblTaxTotal {
247
+ const taxTotals = cacDirectElements(root, "TaxTotal");
248
+ const first = taxTotals[0];
249
+ return {
250
+ taxAmount: first ? cbcDirectNumber(first, "TaxAmount") : undefined,
251
+ subtotals: taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal),
252
+ };
253
+ }
254
+
255
+ function parseAllowanceCharge(charge: Element): UblAllowanceCharge {
256
+ const taxCategory = cacElement(charge, "TaxCategory");
257
+ const indicatorRaw = cbcDirectText(charge, "ChargeIndicator")?.toLowerCase();
258
+ const chargeIndicator = indicatorRaw === "true" || indicatorRaw === "1";
259
+ return {
260
+ chargeIndicator,
261
+ amount: cbcNumber(charge, "Amount"),
262
+ baseAmount: cbcDirectNumber(charge, "BaseAmount"),
263
+ multiplierFactorNumeric: cbcDirectNumber(charge, "MultiplierFactorNumeric"),
264
+ reason: cbcText(charge, "AllowanceChargeReason"),
265
+ reasonCode: cbcText(charge, "AllowanceChargeReasonCode"),
266
+ taxCategory: parseTaxCategory(taxCategory),
267
+ };
268
+ }
269
+
270
+ function parseAllowanceCharges(parent: Element): UblAllowanceCharge[] {
271
+ return cacDirectElements(parent, "AllowanceCharge").map(parseAllowanceCharge);
272
+ }
273
+
274
+ function mergeTaxCategories(
275
+ preferred: UblTaxCategory | undefined,
276
+ fallback: UblTaxCategory | undefined,
277
+ ): UblTaxCategory | undefined {
278
+ if (!preferred) return fallback;
279
+ if (!fallback) return preferred;
280
+ return {
281
+ id: preferred.id ?? fallback.id,
282
+ percent: preferred.percent ?? fallback.percent,
283
+ schemeId: preferred.schemeId ?? fallback.schemeId,
284
+ exemptionReason: preferred.exemptionReason ?? fallback.exemptionReason,
285
+ exemptionReasonCode:
286
+ preferred.exemptionReasonCode ?? fallback.exemptionReasonCode,
287
+ };
288
+ }
289
+
290
+ function parseLines(root: Element, isCreditNote: boolean): UblLine[] {
291
+ const qtyTag = isCreditNote ? "CreditedQuantity" : "InvoicedQuantity";
292
+ const lineTag = isCreditNote ? "CreditNoteLine" : "InvoiceLine";
293
+
294
+ return cacElements(root, lineTag).map((line) => {
295
+ const item = cacElement(line, "Item");
296
+ const price = cacElement(line, "Price");
297
+ const classifiedCategory = parseTaxCategory(
298
+ item ? cacElement(item, "ClassifiedTaxCategory") : null,
299
+ );
300
+ const sellersId = item ? cacElement(item, "SellersItemIdentification") : null;
301
+ const buyersId = item ? cacElement(item, "BuyersItemIdentification") : null;
302
+ const qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];
303
+ const lineExtensionAmount = cbcNumber(line, "LineExtensionAmount");
304
+ const lineTaxTotal = cacDirectElement(line, "TaxTotal");
305
+ const lineTaxSubtotals = lineTaxTotal
306
+ ? parseTaxSubtotalsFromTaxTotal(lineTaxTotal)
307
+ : [];
308
+ const taxAmountFromSubtotals = lineTaxSubtotals.reduce(
309
+ (sum, subtotal) => sum + (subtotal.taxAmount ?? 0),
310
+ 0,
311
+ );
312
+ const taxAmountFromLineTotal = lineTaxTotal
313
+ ? cbcDirectNumber(lineTaxTotal, "TaxAmount")
314
+ : undefined;
315
+ // A line-level TaxSubtotal (E-FFF) wins over the classified category,
316
+ // field by field.
317
+ const subtotalCategory = lineTaxSubtotals[0]?.category;
318
+ const taxCategory = mergeTaxCategories(subtotalCategory, classifiedCategory);
319
+ const taxPercent = taxCategory?.percent;
320
+ const computedTaxAmount =
321
+ taxPercent !== undefined && lineExtensionAmount !== undefined
322
+ ? Number(((lineExtensionAmount * taxPercent) / 100).toFixed(2))
323
+ : undefined;
324
+ const lineAllowanceCharges = parseAllowanceCharges(line);
325
+ const priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];
326
+ const allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];
327
+ const discountAmount = allowanceCharges.reduce(
328
+ (sum, charge) =>
329
+ charge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0),
330
+ 0,
331
+ );
332
+ const chargeAmount = allowanceCharges.reduce(
333
+ (sum, charge) =>
334
+ charge.chargeIndicator ? sum + Math.abs(charge.amount ?? 0) : sum,
335
+ 0,
336
+ );
337
+
338
+ const additionalItemProperties: UblItemProperty[] = [];
339
+ if (item) {
340
+ for (const prop of cacElements(item, "AdditionalItemProperty")) {
341
+ const propName = cbcText(prop, "Name");
342
+ const propValue = cbcText(prop, "Value");
343
+ if (propName) {
344
+ additionalItemProperties.push({
345
+ name: propName,
346
+ value: propValue,
347
+ });
348
+ }
349
+ }
350
+ }
351
+
352
+ // EN16931 BT-146 (PriceAmount) is the price for BT-149 (BaseQuantity) units
353
+ // of the item, not necessarily for one unit. Effective unit price is
354
+ // PriceAmount / BaseQuantity, with BaseQuantity defaulting to 1 when absent.
355
+ const priceAmount = price ? cbcNumber(price, "PriceAmount") : undefined;
356
+ const priceBaseQuantity = price
357
+ ? cbcDirectNumber(price, "BaseQuantity")
358
+ : undefined;
359
+ const unitPrice =
360
+ priceAmount !== undefined && priceBaseQuantity && priceBaseQuantity > 0
361
+ ? priceAmount / priceBaseQuantity
362
+ : priceAmount;
363
+
364
+ return {
365
+ id: requiredCbcText(line, "ID", `${lineTag} identifier`),
366
+ description: item ? cbcText(item, "Description") : undefined,
367
+ quantity: cbcNumber(line, qtyTag),
368
+ unitCode: attribute(qtyEl, "unitCode"),
369
+ unitPrice,
370
+ lineExtensionAmount,
371
+ baseQuantity: priceBaseQuantity,
372
+ taxCategory,
373
+ taxAmount:
374
+ taxAmountFromLineTotal ??
375
+ (lineTaxSubtotals.length > 0
376
+ ? taxAmountFromSubtotals
377
+ : computedTaxAmount),
378
+ taxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : undefined,
379
+ allowanceCharges:
380
+ allowanceCharges.length > 0 ? allowanceCharges : undefined,
381
+ discountAmount: discountAmount > 0 ? discountAmount : undefined,
382
+ chargeAmount: chargeAmount > 0 ? chargeAmount : undefined,
383
+ itemName: item ? cbcText(item, "Name") : undefined,
384
+ sellersItemId: sellersId ? cbcText(sellersId, "ID") : undefined,
385
+ buyersItemId: buyersId ? cbcText(buyersId, "ID") : undefined,
386
+ additionalItemProperties:
387
+ additionalItemProperties.length > 0
388
+ ? additionalItemProperties
389
+ : undefined,
390
+ invoicePeriod: parseInvoicePeriod(line),
391
+ };
392
+ });
393
+ }
394
+
395
+ function parseMonetaryTotal(root: Element): UblMonetaryTotal {
396
+ const total = cacDirectElement(root, "LegalMonetaryTotal");
397
+ if (!total) return {};
398
+ return {
399
+ lineExtensionAmount: cbcNumber(total, "LineExtensionAmount"),
400
+ taxExclusiveAmount: cbcNumber(total, "TaxExclusiveAmount"),
401
+ taxInclusiveAmount: cbcNumber(total, "TaxInclusiveAmount"),
402
+ allowanceTotalAmount: cbcNumber(total, "AllowanceTotalAmount"),
403
+ chargeTotalAmount: cbcNumber(total, "ChargeTotalAmount"),
404
+ prepaidAmount: cbcNumber(total, "PrepaidAmount"),
405
+ payableRoundingAmount: cbcNumber(total, "PayableRoundingAmount"),
406
+ payableAmount: cbcNumber(total, "PayableAmount"),
407
+ };
408
+ }
409
+
410
+ function parsePaymentMeansElement(pm: Element): UblPaymentMeans {
411
+ const account = cacElement(pm, "PayeeFinancialAccount");
412
+ const branch = account ? cacElement(account, "FinancialInstitutionBranch") : null;
413
+ const paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, "PaymentMeansCode")[0];
414
+ const mandate = cacElement(pm, "PaymentMandate");
415
+
416
+ return {
417
+ code: cbcText(pm, "PaymentMeansCode"),
418
+ codeName: attribute(paymentMeansCodeEl, "name"),
419
+ paymentId: cbcText(pm, "PaymentID"),
420
+ iban: account ? cbcText(account, "ID") : undefined,
421
+ bic: branch ? cbcText(branch, "ID") : undefined,
422
+ accountName: account ? cbcText(account, "Name") : undefined,
423
+ mandateId: mandate ? cbcText(mandate, "ID") : undefined,
424
+ };
425
+ }
426
+
427
+ function parsePaymentMeansList(root: Element): UblPaymentMeans[] | undefined {
428
+ const list = cacElements(root, "PaymentMeans").map(parsePaymentMeansElement);
429
+ return list.length > 0 ? list : undefined;
430
+ }
431
+
432
+ /**
433
+ * BT-73/BT-74 on a document, BT-134/BT-135 on a line. Direct children only:
434
+ * a descendant search on the document root would report the first line's
435
+ * period as the document's whenever the document states none of its own.
436
+ */
437
+ function parseInvoicePeriod(parent: Element): UblInvoicePeriod | undefined {
438
+ const period = cacDirectElement(parent, "InvoicePeriod");
439
+ if (!period) return undefined;
440
+
441
+ const start = cbcText(period, "StartDate");
442
+ const end = cbcText(period, "EndDate");
443
+ if (!start && !end) return undefined;
444
+
445
+ return {
446
+ startDate: start,
447
+ endDate: end,
448
+ descriptionCode: cbcText(period, "DescriptionCode"),
449
+ };
450
+ }
451
+
452
+ function parseDelivery(root: Element): UblDelivery | undefined {
453
+ const delivery = cacElement(root, "Delivery");
454
+ if (!delivery) return undefined;
455
+ const actualDeliveryDate = cbcText(delivery, "ActualDeliveryDate");
456
+ const deliveryLocation = cacElement(delivery, "DeliveryLocation");
457
+ const address = parseAddressFromElement(
458
+ deliveryLocation ? cacElement(deliveryLocation, "Address") : null,
459
+ );
460
+ if (!actualDeliveryDate && !address) return undefined;
461
+ return {
462
+ actualDeliveryDate,
463
+ address,
464
+ };
465
+ }
466
+
467
+ function parsePaymentTermsNote(root: Element): string | undefined {
468
+ const paymentTerms = cacElement(root, "PaymentTerms");
469
+ if (!paymentTerms) return undefined;
470
+ return cbcText(paymentTerms, "Note");
471
+ }
472
+
473
+ function parseNotes(root: Element): string | undefined {
474
+ const noteEls = root.getElementsByTagNameNS(CBC_NS, "Note");
475
+ const notes: string[] = [];
476
+ for (let i = 0; i < noteEls.length; i++) {
477
+ const el = noteEls[i];
478
+ if (!el) continue;
479
+ if (el.parentElement === root || el.parentNode === root) {
480
+ const text = el.textContent?.trim();
481
+ if (text) notes.push(text);
482
+ }
483
+ }
484
+ return notes.length > 0 ? notes.join("\n") : undefined;
485
+ }
486
+
487
+ function parseAttachments(root: Element): {
488
+ attachments: UblAttachment[] | undefined;
489
+ documentReferences: UblDocumentReference[] | undefined;
490
+ } {
491
+ const refs = cacElements(root, "AdditionalDocumentReference");
492
+ const attachments: UblAttachment[] = [];
493
+ const documentReferences: UblDocumentReference[] = [];
494
+
495
+ for (const ref of refs) {
496
+ const attachment = cacElement(ref, "Attachment");
497
+ const refId = cbcText(ref, "ID");
498
+ const description = cbcText(ref, "DocumentDescription");
499
+
500
+ if (!attachment) {
501
+ // Text-only document reference (e.g. terms & conditions, notices)
502
+ if (refId || description) {
503
+ documentReferences.push({ id: refId, description });
504
+ }
505
+ continue;
506
+ }
507
+
508
+ const binaryEl = attachment.getElementsByTagNameNS(
509
+ CBC_NS,
510
+ "EmbeddedDocumentBinaryObject",
511
+ )[0];
512
+ const externalRef = cacElement(attachment, "ExternalReference");
513
+
514
+ if (binaryEl) {
515
+ const content = binaryEl.textContent?.trim();
516
+ if (content) {
517
+ attachments.push({
518
+ id: refId,
519
+ filename: attribute(binaryEl, "filename"),
520
+ mimeCode: attribute(binaryEl, "mimeCode"),
521
+ description,
522
+ base64Content: content,
523
+ });
524
+ }
525
+ } else if (externalRef) {
526
+ const uri = cbcText(externalRef, "URI");
527
+ if (uri) {
528
+ attachments.push({
529
+ id: refId,
530
+ description,
531
+ externalUri: uri,
532
+ });
533
+ }
534
+ }
535
+ }
536
+
537
+ return {
538
+ attachments: attachments.length > 0 ? attachments : undefined,
539
+ documentReferences:
540
+ documentReferences.length > 0 ? documentReferences : undefined,
541
+ };
542
+ }
543
+
544
+ function parseBillingReference(root: Element): UblBillingReference | undefined {
545
+ const billingRef = cacElement(root, "BillingReference");
546
+ if (!billingRef) return undefined;
547
+ const invoiceRef = cacElement(billingRef, "InvoiceDocumentReference");
548
+ if (!invoiceRef) return undefined;
549
+ const invoiceId = cbcText(invoiceRef, "ID");
550
+ const invoiceIssueDate = cbcText(invoiceRef, "IssueDate");
551
+ if (!invoiceId && !invoiceIssueDate) return undefined;
552
+ return { invoiceId, invoiceIssueDate };
553
+ }
554
+
555
+ // --- Main parser ---
556
+
557
+ /**
558
+ * Drop `undefined`-valued keys recursively so an absent field is an absent
559
+ * key, not a key holding `undefined`. Arrays keep their order and length.
560
+ */
561
+ function omitUndefined<T>(value: T): T {
562
+ if (Array.isArray(value)) {
563
+ return value.map(omitUndefined) as T;
564
+ }
565
+ if (value !== null && typeof value === "object") {
566
+ const out: Record<string, unknown> = {};
567
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
568
+ if (entry !== undefined) out[key] = omitUndefined(entry);
569
+ }
570
+ return out as T;
571
+ }
572
+ return value;
573
+ }
574
+
575
+ const INVOICE_NS = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
576
+ const CREDIT_NOTE_NS = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
577
+
578
+ /**
579
+ * Parse a UBL 2.1 Invoice or CreditNote.
580
+ *
581
+ * Returns `null` when the XML is well-formed but its root is not a UBL
582
+ * `Invoice`/`CreditNote`. Throws {@link UblParseError} when the XML is
583
+ * malformed or the document lacks an element EN 16931 makes mandatory
584
+ * (document id, issue date, currency, line id).
585
+ */
586
+ export function parseUblInvoice(xml: string): UblInvoice | null {
587
+ const doc = parseXmlDocument(xml);
588
+ const root = doc.documentElement;
589
+ if (!root) return null;
590
+
591
+ let documentType: "Invoice" | "CreditNote";
592
+ if (root.localName === "Invoice" && root.namespaceURI === INVOICE_NS) {
593
+ documentType = "Invoice";
594
+ } else if (
595
+ root.localName === "CreditNote" &&
596
+ root.namespaceURI === CREDIT_NOTE_NS
597
+ ) {
598
+ documentType = "CreditNote";
599
+ } else {
600
+ return null;
601
+ }
602
+
603
+ const isCreditNote = documentType === "CreditNote";
604
+ const id = requiredCbcText(root, "ID", "document identifier");
605
+ const issueDate = requiredCbcText(root, "IssueDate", "issue date");
606
+ const currency = requiredCbcText(root, "DocumentCurrencyCode", "currency code");
607
+ const paymentMeansList = parsePaymentMeansList(root);
608
+ const orderReference = cacElement(root, "OrderReference");
609
+ const contractReference = cacElement(root, "ContractDocumentReference");
610
+ const projectReference = cacElement(root, "ProjectReference");
611
+ const { attachments, documentReferences } = parseAttachments(root);
612
+
613
+ return omitUndefined<UblInvoice>({
614
+ documentType,
615
+ customizationId: cbcText(root, "CustomizationID"),
616
+ profileId: cbcText(root, "ProfileID"),
617
+ id,
618
+ invoiceTypeCode:
619
+ cbcText(root, "InvoiceTypeCode") ?? cbcText(root, "CreditNoteTypeCode"),
620
+ issueDate,
621
+ dueDate: cbcText(root, "DueDate"),
622
+ taxPointDate: cbcText(root, "TaxPointDate"),
623
+ currency,
624
+ buyerReference: cbcText(root, "BuyerReference"),
625
+ orderReference: orderReference ? cbcText(orderReference, "ID") : undefined,
626
+ salesOrderId: orderReference
627
+ ? cbcText(orderReference, "SalesOrderID")
628
+ : undefined,
629
+ contractReference: contractReference
630
+ ? cbcText(contractReference, "ID")
631
+ : undefined,
632
+ projectReference: projectReference
633
+ ? cbcText(projectReference, "ID")
634
+ : undefined,
635
+ billingReference: parseBillingReference(root),
636
+ seller: parseParty(root, "AccountingSupplierParty"),
637
+ buyer: parseParty(root, "AccountingCustomerParty"),
638
+ delivery: parseDelivery(root),
639
+ lines: parseLines(root, isCreditNote),
640
+ taxTotal: parseTaxTotal(root),
641
+ monetaryTotal: parseMonetaryTotal(root),
642
+ paymentMeansList,
643
+ paymentMeans: paymentMeansList?.[0],
644
+ invoicePeriod: parseInvoicePeriod(root),
645
+ note: parseNotes(root),
646
+ paymentTermsNote: parsePaymentTermsNote(root),
647
+ attachments,
648
+ documentReferences,
649
+ allowanceCharges: parseAllowanceCharges(root),
650
+ });
651
+ }