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