@financica/ubl 0.8.0 → 0.9.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
@@ -1,839 +1,835 @@
1
- // src/parser.ts
2
- import { DOMParser as XmlDomParser } from "@xmldom/xmldom";
3
- var CBC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
4
- var CAC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
5
- function cbcText(parent, tag) {
6
- const el = parent.getElementsByTagNameNS(CBC_NS, tag)[0];
7
- return el?.textContent?.trim() ?? "";
1
+ import { DOMParser } from "@xmldom/xmldom";
2
+ //#region src/parser.ts
3
+ const CBC_NS$1 = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
4
+ const CAC_NS$1 = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
5
+ function cbcText$1(parent, tag) {
6
+ return parent.getElementsByTagNameNS(CBC_NS$1, tag)[0]?.textContent?.trim() ?? "";
8
7
  }
9
- function cacElement(parent, tag) {
10
- return parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;
8
+ function cacElement$1(parent, tag) {
9
+ return parent.getElementsByTagNameNS(CAC_NS$1, tag)[0] ?? null;
11
10
  }
12
11
  function cacElements(parent, tag) {
13
- return Array.from(parent.getElementsByTagNameNS(CAC_NS, tag));
12
+ return Array.from(parent.getElementsByTagNameNS(CAC_NS$1, tag));
14
13
  }
15
14
  function cbcNumber(parent, tag) {
16
- const n = Number.parseFloat(cbcText(parent, tag));
17
- return Number.isNaN(n) ? 0 : n;
15
+ const n = Number.parseFloat(cbcText$1(parent, tag));
16
+ return Number.isNaN(n) ? 0 : n;
18
17
  }
19
18
  function childElementsByTagNs(parent, namespace, tag) {
20
- const elements = [];
21
- for (let i = 0; i < parent.childNodes.length; i++) {
22
- const node = parent.childNodes[i];
23
- if (!node || node.nodeType !== 1) continue;
24
- const element = node;
25
- if (element.namespaceURI === namespace && element.localName === tag) {
26
- elements.push(element);
27
- }
28
- }
29
- return elements;
19
+ const elements = [];
20
+ for (let i = 0; i < parent.childNodes.length; i++) {
21
+ const node = parent.childNodes[i];
22
+ if (!node || node.nodeType !== 1) continue;
23
+ const element = node;
24
+ if (element.namespaceURI === namespace && element.localName === tag) elements.push(element);
25
+ }
26
+ return elements;
30
27
  }
31
- function cbcDirectText(parent, tag) {
32
- const el = childElementsByTagNs(parent, CBC_NS, tag)[0];
33
- return el?.textContent?.trim() ?? "";
28
+ function cbcDirectText$1(parent, tag) {
29
+ return childElementsByTagNs(parent, CBC_NS$1, tag)[0]?.textContent?.trim() ?? "";
34
30
  }
35
31
  function cbcDirectNumber(parent, tag) {
36
- const value = cbcDirectText(parent, tag);
37
- if (!value) return null;
38
- const parsed = Number.parseFloat(value);
39
- return Number.isNaN(parsed) ? null : parsed;
32
+ const value = cbcDirectText$1(parent, tag);
33
+ if (!value) return null;
34
+ const parsed = Number.parseFloat(value);
35
+ return Number.isNaN(parsed) ? null : parsed;
40
36
  }
41
37
  function cacDirectElement(parent, tag) {
42
- return childElementsByTagNs(parent, CAC_NS, tag)[0] ?? null;
38
+ return childElementsByTagNs(parent, CAC_NS$1, tag)[0] ?? null;
43
39
  }
44
40
  function cacDirectElements(parent, tag) {
45
- return childElementsByTagNs(parent, CAC_NS, tag);
41
+ return childElementsByTagNs(parent, CAC_NS$1, tag);
46
42
  }
47
43
  function parseAddressFromElement(address) {
48
- if (!address) return void 0;
49
- const country = cacElement(address, "Country");
50
- return {
51
- street: cbcText(address, "StreetName"),
52
- additionalStreet: cbcText(address, "AdditionalStreetName") || void 0,
53
- city: cbcText(address, "CityName"),
54
- postalZone: cbcText(address, "PostalZone"),
55
- countrySubentity: cbcText(address, "CountrySubentity") || void 0,
56
- countryCode: country ? cbcText(country, "IdentificationCode") : ""
57
- };
44
+ if (!address) return void 0;
45
+ const country = cacElement$1(address, "Country");
46
+ return {
47
+ street: cbcText$1(address, "StreetName"),
48
+ additionalStreet: cbcText$1(address, "AdditionalStreetName") || void 0,
49
+ city: cbcText$1(address, "CityName"),
50
+ postalZone: cbcText$1(address, "PostalZone"),
51
+ countrySubentity: cbcText$1(address, "CountrySubentity") || void 0,
52
+ countryCode: country ? cbcText$1(country, "IdentificationCode") : ""
53
+ };
58
54
  }
59
55
  function parseAddress(party) {
60
- const postal = cacElement(party, "PostalAddress");
61
- return parseAddressFromElement(postal);
56
+ return parseAddressFromElement(cacElement$1(party, "PostalAddress"));
62
57
  }
63
58
  function parseTaxSchemeId(parent) {
64
- if (!parent) return void 0;
65
- const taxScheme = cacElement(parent, "TaxScheme");
66
- if (!taxScheme) return void 0;
67
- return cbcText(taxScheme, "ID") || void 0;
59
+ if (!parent) return void 0;
60
+ const taxScheme = cacElement$1(parent, "TaxScheme");
61
+ if (!taxScheme) return void 0;
62
+ return cbcText$1(taxScheme, "ID") || void 0;
68
63
  }
69
64
  function parseContact(party) {
70
- const contact = cacElement(party, "Contact");
71
- if (!contact) return void 0;
72
- const name = cbcText(contact, "Name");
73
- const phone = cbcText(contact, "Telephone");
74
- const email = cbcText(contact, "ElectronicMail");
75
- if (!name && !phone && !email) return void 0;
76
- return {
77
- name: name || void 0,
78
- phone: phone || void 0,
79
- email: email || void 0
80
- };
65
+ const contact = cacElement$1(party, "Contact");
66
+ if (!contact) return void 0;
67
+ const name = cbcText$1(contact, "Name");
68
+ const phone = cbcText$1(contact, "Telephone");
69
+ const email = cbcText$1(contact, "ElectronicMail");
70
+ if (!name && !phone && !email) return void 0;
71
+ return {
72
+ name: name || void 0,
73
+ phone: phone || void 0,
74
+ email: email || void 0
75
+ };
81
76
  }
82
77
  function parsePartyIdentifications(party) {
83
- const ids = cacElements(party, "PartyIdentification");
84
- const result = [];
85
- for (const idEl of ids) {
86
- const idValue = cbcText(idEl, "ID");
87
- if (!idValue) continue;
88
- const schemeIdAttr = idEl.getElementsByTagNameNS(CBC_NS, "ID")[0]?.getAttribute("schemeID");
89
- result.push({
90
- id: idValue,
91
- schemeId: schemeIdAttr || void 0
92
- });
93
- }
94
- return result;
78
+ const ids = cacElements(party, "PartyIdentification");
79
+ const result = [];
80
+ for (const idEl of ids) {
81
+ const idValue = cbcText$1(idEl, "ID");
82
+ if (!idValue) continue;
83
+ const schemeIdAttr = idEl.getElementsByTagNameNS(CBC_NS$1, "ID")[0]?.getAttribute("schemeID");
84
+ result.push({
85
+ id: idValue,
86
+ schemeId: schemeIdAttr || void 0
87
+ });
88
+ }
89
+ return result;
95
90
  }
96
91
  function parseParty(root, role) {
97
- const wrapper = cacElement(root, role);
98
- const party = wrapper ? cacElement(wrapper, "Party") : null;
99
- if (!party) return { name: "Unknown" };
100
- const partyName = cacElement(party, "PartyName");
101
- const legalEntity = cacElement(party, "PartyLegalEntity");
102
- const taxScheme = cacElement(party, "PartyTaxScheme");
103
- const partyId = cacElement(party, "PartyIdentification");
104
- const endpointEl = party.getElementsByTagNameNS(CBC_NS, "EndpointID")[0];
105
- const partyIdentifications = parsePartyIdentifications(party);
106
- const companyIdEl = legalEntity ? legalEntity.getElementsByTagNameNS(CBC_NS, "CompanyID")[0] : null;
107
- return {
108
- name: partyName ? cbcText(partyName, "Name") : "",
109
- registrationName: legalEntity ? cbcText(legalEntity, "RegistrationName") || void 0 : void 0,
110
- companyLegalForm: legalEntity ? cbcText(legalEntity, "CompanyLegalForm") || void 0 : void 0,
111
- vatId: taxScheme ? cbcText(taxScheme, "CompanyID") || void 0 : void 0,
112
- taxSchemeId: parseTaxSchemeId(taxScheme),
113
- companyId: companyIdEl ? companyIdEl.textContent?.trim() || void 0 : partyId ? cbcText(partyId, "ID") || void 0 : void 0,
114
- companyIdSchemeId: companyIdEl?.getAttribute("schemeID") || void 0,
115
- endpointId: endpointEl?.textContent?.trim() || void 0,
116
- endpointSchemeId: endpointEl?.getAttribute("schemeID") || void 0,
117
- partyIdentifications: partyIdentifications.length > 0 ? partyIdentifications : void 0,
118
- address: parseAddress(party),
119
- contact: parseContact(party)
120
- };
92
+ const wrapper = cacElement$1(root, role);
93
+ const party = wrapper ? cacElement$1(wrapper, "Party") : null;
94
+ if (!party) return { name: "Unknown" };
95
+ const partyName = cacElement$1(party, "PartyName");
96
+ const legalEntity = cacElement$1(party, "PartyLegalEntity");
97
+ const taxScheme = cacElement$1(party, "PartyTaxScheme");
98
+ const partyId = cacElement$1(party, "PartyIdentification");
99
+ const endpointEl = party.getElementsByTagNameNS(CBC_NS$1, "EndpointID")[0];
100
+ const partyIdentifications = parsePartyIdentifications(party);
101
+ const companyIdEl = legalEntity ? legalEntity.getElementsByTagNameNS(CBC_NS$1, "CompanyID")[0] : null;
102
+ return {
103
+ name: partyName ? cbcText$1(partyName, "Name") : "",
104
+ registrationName: legalEntity ? cbcText$1(legalEntity, "RegistrationName") || void 0 : void 0,
105
+ companyLegalForm: legalEntity ? cbcText$1(legalEntity, "CompanyLegalForm") || void 0 : void 0,
106
+ vatId: taxScheme ? cbcText$1(taxScheme, "CompanyID") || void 0 : void 0,
107
+ taxSchemeId: parseTaxSchemeId(taxScheme),
108
+ companyId: companyIdEl ? companyIdEl.textContent?.trim() || void 0 : partyId ? cbcText$1(partyId, "ID") || void 0 : void 0,
109
+ companyIdSchemeId: companyIdEl?.getAttribute("schemeID") || void 0,
110
+ endpointId: endpointEl?.textContent?.trim() || void 0,
111
+ endpointSchemeId: endpointEl?.getAttribute("schemeID") || void 0,
112
+ partyIdentifications: partyIdentifications.length > 0 ? partyIdentifications : void 0,
113
+ address: parseAddress(party),
114
+ contact: parseContact(party)
115
+ };
121
116
  }
122
117
  function parseTaxSubtotal(sub) {
123
- const cat = cacElement(sub, "TaxCategory");
124
- return {
125
- taxableAmount: cbcNumber(sub, "TaxableAmount"),
126
- taxAmount: cbcNumber(sub, "TaxAmount"),
127
- taxPercent: (cat ? cbcNumber(cat, "Percent") : 0) || cbcNumber(sub, "Percent"),
128
- taxCategoryId: cat ? cbcText(cat, "ID") || void 0 : void 0,
129
- taxSchemeId: parseTaxSchemeId(cat),
130
- taxExemptionReason: cat ? cbcText(cat, "TaxExemptionReason") || void 0 : void 0
131
- };
118
+ const cat = cacElement$1(sub, "TaxCategory");
119
+ return {
120
+ taxableAmount: cbcNumber(sub, "TaxableAmount"),
121
+ taxAmount: cbcNumber(sub, "TaxAmount"),
122
+ taxPercent: (cat ? cbcNumber(cat, "Percent") : 0) || cbcNumber(sub, "Percent"),
123
+ taxCategoryId: cat ? cbcText$1(cat, "ID") || void 0 : void 0,
124
+ taxSchemeId: parseTaxSchemeId(cat),
125
+ taxExemptionReason: cat ? cbcText$1(cat, "TaxExemptionReason") || void 0 : void 0
126
+ };
132
127
  }
133
128
  function parseTaxSubtotalsFromTaxTotal(taxTotal) {
134
- return cacDirectElements(taxTotal, "TaxSubtotal").map(parseTaxSubtotal);
129
+ return cacDirectElements(taxTotal, "TaxSubtotal").map(parseTaxSubtotal);
135
130
  }
136
131
  function parseTaxSubtotals(root) {
137
- const taxTotals = cacDirectElements(root, "TaxTotal");
138
- if (taxTotals.length === 0) return [];
139
- return taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal);
132
+ const taxTotals = cacDirectElements(root, "TaxTotal");
133
+ if (taxTotals.length === 0) return [];
134
+ return taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal);
140
135
  }
141
136
  function parseAllowanceCharge(charge) {
142
- const taxCategory = cacElement(charge, "TaxCategory");
143
- const indicatorRaw = cbcDirectText(charge, "ChargeIndicator").toLowerCase();
144
- const chargeIndicator = indicatorRaw === "true" || indicatorRaw === "1";
145
- return {
146
- chargeIndicator,
147
- amount: cbcNumber(charge, "Amount"),
148
- baseAmount: cbcDirectNumber(charge, "BaseAmount") ?? void 0,
149
- multiplierFactorNumeric: cbcDirectNumber(charge, "MultiplierFactorNumeric") ?? void 0,
150
- reason: cbcText(charge, "AllowanceChargeReason") || void 0,
151
- reasonCode: cbcText(charge, "AllowanceChargeReasonCode") || void 0,
152
- taxPercent: taxCategory ? cbcNumber(taxCategory, "Percent") : void 0,
153
- taxCategoryId: taxCategory ? cbcText(taxCategory, "ID") || void 0 : void 0,
154
- taxSchemeId: parseTaxSchemeId(taxCategory)
155
- };
137
+ const taxCategory = cacElement$1(charge, "TaxCategory");
138
+ const indicatorRaw = cbcDirectText$1(charge, "ChargeIndicator").toLowerCase();
139
+ return {
140
+ chargeIndicator: indicatorRaw === "true" || indicatorRaw === "1",
141
+ amount: cbcNumber(charge, "Amount"),
142
+ baseAmount: cbcDirectNumber(charge, "BaseAmount") ?? void 0,
143
+ multiplierFactorNumeric: cbcDirectNumber(charge, "MultiplierFactorNumeric") ?? void 0,
144
+ reason: cbcText$1(charge, "AllowanceChargeReason") || void 0,
145
+ reasonCode: cbcText$1(charge, "AllowanceChargeReasonCode") || void 0,
146
+ taxPercent: taxCategory ? cbcNumber(taxCategory, "Percent") : void 0,
147
+ taxCategoryId: taxCategory ? cbcText$1(taxCategory, "ID") || void 0 : void 0,
148
+ taxSchemeId: parseTaxSchemeId(taxCategory)
149
+ };
156
150
  }
157
151
  function parseAllowanceCharges(parent) {
158
- return cacDirectElements(parent, "AllowanceCharge").map(parseAllowanceCharge);
152
+ return cacDirectElements(parent, "AllowanceCharge").map(parseAllowanceCharge);
159
153
  }
160
154
  function parseLines(root, isCreditNote) {
161
- const qtyTag = isCreditNote ? "CreditedQuantity" : "InvoicedQuantity";
162
- const lineTag = isCreditNote ? "CreditNoteLine" : "InvoiceLine";
163
- return cacElements(root, lineTag).map((line) => {
164
- const item = cacElement(line, "Item");
165
- const price = cacElement(line, "Price");
166
- const taxCategory = item ? cacElement(item, "ClassifiedTaxCategory") : null;
167
- const sellersId = item ? cacElement(item, "SellersItemIdentification") : null;
168
- const buyersId = item ? cacElement(item, "BuyersItemIdentification") : null;
169
- const qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];
170
- const lineExtensionAmount = cbcNumber(line, "LineExtensionAmount");
171
- const lineTaxTotal = cacDirectElement(line, "TaxTotal");
172
- const lineTaxSubtotals = lineTaxTotal ? parseTaxSubtotalsFromTaxTotal(lineTaxTotal) : [];
173
- const taxAmountFromSubtotals = lineTaxSubtotals.reduce(
174
- (sum, subtotal) => sum + subtotal.taxAmount,
175
- 0
176
- );
177
- const taxAmountFromLineTotal = lineTaxTotal ? cbcDirectNumber(lineTaxTotal, "TaxAmount") : null;
178
- const taxPercent = lineTaxSubtotals[0]?.taxPercent ?? (taxCategory ? cbcNumber(taxCategory, "Percent") : void 0);
179
- const computedTaxAmount = taxPercent !== void 0 ? Number((lineExtensionAmount * taxPercent / 100).toFixed(2)) : void 0;
180
- const lineAllowanceCharges = parseAllowanceCharges(line);
181
- const priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];
182
- const allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];
183
- const discountAmount = allowanceCharges.reduce(
184
- (sum, charge) => charge.chargeIndicator ? sum : sum + Math.abs(charge.amount),
185
- 0
186
- );
187
- const chargeAmount = allowanceCharges.reduce(
188
- (sum, charge) => charge.chargeIndicator ? sum + Math.abs(charge.amount) : sum,
189
- 0
190
- );
191
- const additionalItemProperties = [];
192
- if (item) {
193
- for (const prop of cacElements(item, "AdditionalItemProperty")) {
194
- const propName = cbcText(prop, "Name");
195
- const propValue = cbcText(prop, "Value");
196
- if (propName) {
197
- additionalItemProperties.push({
198
- name: propName,
199
- value: propValue
200
- });
201
- }
202
- }
203
- }
204
- const priceAmount = price ? cbcNumber(price, "PriceAmount") : 0;
205
- const priceBaseQuantity = price ? cbcDirectNumber(price, "BaseQuantity") : null;
206
- const unitPrice = priceBaseQuantity && priceBaseQuantity > 0 ? priceAmount / priceBaseQuantity : priceAmount;
207
- return {
208
- id: cbcText(line, "ID"),
209
- description: item ? cbcText(item, "Description") : "",
210
- quantity: cbcNumber(line, qtyTag),
211
- unitCode: qtyEl?.getAttribute("unitCode") ?? "",
212
- unitPrice,
213
- lineExtensionAmount,
214
- taxPercent,
215
- taxAmount: taxAmountFromLineTotal ?? (lineTaxSubtotals.length > 0 ? taxAmountFromSubtotals : computedTaxAmount),
216
- taxCategoryId: lineTaxSubtotals[0]?.taxCategoryId ?? (taxCategory ? cbcText(taxCategory, "ID") || void 0 : void 0),
217
- taxSchemeId: lineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),
218
- taxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : void 0,
219
- allowanceCharges: allowanceCharges.length > 0 ? allowanceCharges : void 0,
220
- discountAmount: discountAmount > 0 ? discountAmount : void 0,
221
- chargeAmount: chargeAmount > 0 ? chargeAmount : void 0,
222
- itemName: item ? cbcText(item, "Name") || void 0 : void 0,
223
- sellersItemId: sellersId ? cbcText(sellersId, "ID") || void 0 : void 0,
224
- buyersItemId: buyersId ? cbcText(buyersId, "ID") || void 0 : void 0,
225
- additionalItemProperties: additionalItemProperties.length > 0 ? additionalItemProperties : void 0
226
- };
227
- });
155
+ const qtyTag = isCreditNote ? "CreditedQuantity" : "InvoicedQuantity";
156
+ return cacElements(root, isCreditNote ? "CreditNoteLine" : "InvoiceLine").map((line) => {
157
+ const item = cacElement$1(line, "Item");
158
+ const price = cacElement$1(line, "Price");
159
+ const taxCategory = item ? cacElement$1(item, "ClassifiedTaxCategory") : null;
160
+ const sellersId = item ? cacElement$1(item, "SellersItemIdentification") : null;
161
+ const buyersId = item ? cacElement$1(item, "BuyersItemIdentification") : null;
162
+ const qtyEl = line.getElementsByTagNameNS(CBC_NS$1, qtyTag)[0];
163
+ const lineExtensionAmount = cbcNumber(line, "LineExtensionAmount");
164
+ const lineTaxTotal = cacDirectElement(line, "TaxTotal");
165
+ const lineTaxSubtotals = lineTaxTotal ? parseTaxSubtotalsFromTaxTotal(lineTaxTotal) : [];
166
+ const taxAmountFromSubtotals = lineTaxSubtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0);
167
+ const taxAmountFromLineTotal = lineTaxTotal ? cbcDirectNumber(lineTaxTotal, "TaxAmount") : null;
168
+ const taxPercent = lineTaxSubtotals[0]?.taxPercent ?? (taxCategory ? cbcNumber(taxCategory, "Percent") : void 0);
169
+ const computedTaxAmount = taxPercent !== void 0 ? Number((lineExtensionAmount * taxPercent / 100).toFixed(2)) : void 0;
170
+ const lineAllowanceCharges = parseAllowanceCharges(line);
171
+ const priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];
172
+ const allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];
173
+ const discountAmount = allowanceCharges.reduce((sum, charge) => charge.chargeIndicator ? sum : sum + Math.abs(charge.amount), 0);
174
+ const chargeAmount = allowanceCharges.reduce((sum, charge) => charge.chargeIndicator ? sum + Math.abs(charge.amount) : sum, 0);
175
+ const additionalItemProperties = [];
176
+ if (item) for (const prop of cacElements(item, "AdditionalItemProperty")) {
177
+ const propName = cbcText$1(prop, "Name");
178
+ const propValue = cbcText$1(prop, "Value");
179
+ if (propName) additionalItemProperties.push({
180
+ name: propName,
181
+ value: propValue
182
+ });
183
+ }
184
+ const priceAmount = price ? cbcNumber(price, "PriceAmount") : 0;
185
+ const priceBaseQuantity = price ? cbcDirectNumber(price, "BaseQuantity") : null;
186
+ const unitPrice = priceBaseQuantity && priceBaseQuantity > 0 ? priceAmount / priceBaseQuantity : priceAmount;
187
+ return {
188
+ id: cbcText$1(line, "ID"),
189
+ description: item ? cbcText$1(item, "Description") : "",
190
+ quantity: cbcNumber(line, qtyTag),
191
+ unitCode: qtyEl?.getAttribute("unitCode") ?? "",
192
+ unitPrice,
193
+ lineExtensionAmount,
194
+ taxPercent,
195
+ taxAmount: taxAmountFromLineTotal ?? (lineTaxSubtotals.length > 0 ? taxAmountFromSubtotals : computedTaxAmount),
196
+ taxCategoryId: lineTaxSubtotals[0]?.taxCategoryId ?? (taxCategory ? cbcText$1(taxCategory, "ID") || void 0 : void 0),
197
+ taxSchemeId: lineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),
198
+ taxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : void 0,
199
+ allowanceCharges: allowanceCharges.length > 0 ? allowanceCharges : void 0,
200
+ discountAmount: discountAmount > 0 ? discountAmount : void 0,
201
+ chargeAmount: chargeAmount > 0 ? chargeAmount : void 0,
202
+ itemName: item ? cbcText$1(item, "Name") || void 0 : void 0,
203
+ sellersItemId: sellersId ? cbcText$1(sellersId, "ID") || void 0 : void 0,
204
+ buyersItemId: buyersId ? cbcText$1(buyersId, "ID") || void 0 : void 0,
205
+ additionalItemProperties: additionalItemProperties.length > 0 ? additionalItemProperties : void 0
206
+ };
207
+ });
228
208
  }
229
209
  function parseMonetaryTotal(root) {
230
- const total = cacDirectElement(root, "LegalMonetaryTotal");
231
- if (!total) {
232
- return {
233
- lineExtensionAmount: 0,
234
- taxExclusiveAmount: 0,
235
- taxInclusiveAmount: 0,
236
- payableAmount: 0
237
- };
238
- }
239
- return {
240
- lineExtensionAmount: cbcNumber(total, "LineExtensionAmount"),
241
- taxExclusiveAmount: cbcNumber(total, "TaxExclusiveAmount"),
242
- taxInclusiveAmount: cbcNumber(total, "TaxInclusiveAmount"),
243
- allowanceTotalAmount: cbcNumber(total, "AllowanceTotalAmount") || void 0,
244
- chargeTotalAmount: cbcNumber(total, "ChargeTotalAmount") || void 0,
245
- prepaidAmount: cbcNumber(total, "PrepaidAmount") || void 0,
246
- payableRoundingAmount: cbcNumber(total, "PayableRoundingAmount") || void 0,
247
- payableAmount: cbcNumber(total, "PayableAmount")
248
- };
210
+ const total = cacDirectElement(root, "LegalMonetaryTotal");
211
+ if (!total) return {
212
+ lineExtensionAmount: 0,
213
+ taxExclusiveAmount: 0,
214
+ taxInclusiveAmount: 0,
215
+ payableAmount: 0
216
+ };
217
+ return {
218
+ lineExtensionAmount: cbcNumber(total, "LineExtensionAmount"),
219
+ taxExclusiveAmount: cbcNumber(total, "TaxExclusiveAmount"),
220
+ taxInclusiveAmount: cbcNumber(total, "TaxInclusiveAmount"),
221
+ allowanceTotalAmount: cbcNumber(total, "AllowanceTotalAmount") || void 0,
222
+ chargeTotalAmount: cbcNumber(total, "ChargeTotalAmount") || void 0,
223
+ prepaidAmount: cbcNumber(total, "PrepaidAmount") || void 0,
224
+ payableRoundingAmount: cbcNumber(total, "PayableRoundingAmount") || void 0,
225
+ payableAmount: cbcNumber(total, "PayableAmount")
226
+ };
249
227
  }
250
228
  function parsePaymentMeansElement(pm) {
251
- const account = cacElement(pm, "PayeeFinancialAccount");
252
- const branch = account ? cacElement(account, "FinancialInstitutionBranch") : null;
253
- const paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, "PaymentMeansCode")[0];
254
- const mandate = cacElement(pm, "PaymentMandate");
255
- return {
256
- code: cbcText(pm, "PaymentMeansCode"),
257
- codeName: paymentMeansCodeEl?.getAttribute("name") || void 0,
258
- paymentId: cbcText(pm, "PaymentID") || void 0,
259
- iban: account ? cbcText(account, "ID") || void 0 : void 0,
260
- bic: branch ? cbcText(branch, "ID") || void 0 : void 0,
261
- accountName: account && cbcText(account, "Name") || void 0,
262
- mandateId: mandate ? cbcText(mandate, "ID") || void 0 : void 0
263
- };
229
+ const account = cacElement$1(pm, "PayeeFinancialAccount");
230
+ const branch = account ? cacElement$1(account, "FinancialInstitutionBranch") : null;
231
+ const paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS$1, "PaymentMeansCode")[0];
232
+ const mandate = cacElement$1(pm, "PaymentMandate");
233
+ return {
234
+ code: cbcText$1(pm, "PaymentMeansCode"),
235
+ codeName: paymentMeansCodeEl?.getAttribute("name") || void 0,
236
+ paymentId: cbcText$1(pm, "PaymentID") || void 0,
237
+ iban: account ? cbcText$1(account, "ID") || void 0 : void 0,
238
+ bic: branch ? cbcText$1(branch, "ID") || void 0 : void 0,
239
+ accountName: account && cbcText$1(account, "Name") || void 0,
240
+ mandateId: mandate ? cbcText$1(mandate, "ID") || void 0 : void 0
241
+ };
264
242
  }
265
243
  function parsePaymentMeansList(root) {
266
- const list = cacElements(root, "PaymentMeans").map(parsePaymentMeansElement);
267
- return list.length > 0 ? list : void 0;
244
+ const list = cacElements(root, "PaymentMeans").map(parsePaymentMeansElement);
245
+ return list.length > 0 ? list : void 0;
268
246
  }
269
247
  function parseInvoicePeriod(root) {
270
- const period = cacElement(root, "InvoicePeriod");
271
- if (!period) return void 0;
272
- const start = cbcText(period, "StartDate");
273
- const end = cbcText(period, "EndDate");
274
- if (!start && !end) return void 0;
275
- return {
276
- startDate: start || void 0,
277
- endDate: end || void 0,
278
- descriptionCode: cbcText(period, "DescriptionCode") || void 0
279
- };
248
+ const period = cacElement$1(root, "InvoicePeriod");
249
+ if (!period) return void 0;
250
+ const start = cbcText$1(period, "StartDate");
251
+ const end = cbcText$1(period, "EndDate");
252
+ if (!start && !end) return void 0;
253
+ return {
254
+ startDate: start || void 0,
255
+ endDate: end || void 0,
256
+ descriptionCode: cbcText$1(period, "DescriptionCode") || void 0
257
+ };
280
258
  }
281
259
  function parseDelivery(root) {
282
- const delivery = cacElement(root, "Delivery");
283
- if (!delivery) return void 0;
284
- const actualDeliveryDate = cbcText(delivery, "ActualDeliveryDate") || void 0;
285
- const deliveryLocation = cacElement(delivery, "DeliveryLocation");
286
- const address = parseAddressFromElement(
287
- deliveryLocation ? cacElement(deliveryLocation, "Address") : null
288
- );
289
- if (!actualDeliveryDate && !address) return void 0;
290
- return {
291
- actualDeliveryDate,
292
- address
293
- };
260
+ const delivery = cacElement$1(root, "Delivery");
261
+ if (!delivery) return void 0;
262
+ const actualDeliveryDate = cbcText$1(delivery, "ActualDeliveryDate") || void 0;
263
+ const deliveryLocation = cacElement$1(delivery, "DeliveryLocation");
264
+ const address = parseAddressFromElement(deliveryLocation ? cacElement$1(deliveryLocation, "Address") : null);
265
+ if (!actualDeliveryDate && !address) return void 0;
266
+ return {
267
+ actualDeliveryDate,
268
+ address
269
+ };
294
270
  }
295
271
  function parsePaymentTermsNote(root) {
296
- const paymentTerms = cacElement(root, "PaymentTerms");
297
- if (!paymentTerms) return void 0;
298
- const note = cbcText(paymentTerms, "Note");
299
- return note || void 0;
272
+ const paymentTerms = cacElement$1(root, "PaymentTerms");
273
+ if (!paymentTerms) return void 0;
274
+ return cbcText$1(paymentTerms, "Note") || void 0;
300
275
  }
301
276
  function parseNotes(root) {
302
- const noteEls = root.getElementsByTagNameNS(CBC_NS, "Note");
303
- const notes = [];
304
- for (let i = 0; i < noteEls.length; i++) {
305
- const el = noteEls[i];
306
- if (!el) continue;
307
- if (el.parentElement === root || el.parentNode === root) {
308
- const text = el.textContent?.trim();
309
- if (text) notes.push(text);
310
- }
311
- }
312
- return notes.length > 0 ? notes.join("\n") : void 0;
277
+ const noteEls = root.getElementsByTagNameNS(CBC_NS$1, "Note");
278
+ const notes = [];
279
+ for (let i = 0; i < noteEls.length; i++) {
280
+ const el = noteEls[i];
281
+ if (!el) continue;
282
+ if (el.parentElement === root || el.parentNode === root) {
283
+ const text = el.textContent?.trim();
284
+ if (text) notes.push(text);
285
+ }
286
+ }
287
+ return notes.length > 0 ? notes.join("\n") : void 0;
313
288
  }
314
289
  function parseAttachments(root) {
315
- const refs = cacElements(root, "AdditionalDocumentReference");
316
- const attachments = [];
317
- const documentReferences = [];
318
- for (const ref of refs) {
319
- const attachment = cacElement(ref, "Attachment");
320
- const refId = cbcText(ref, "ID");
321
- const description = cbcText(ref, "DocumentDescription") || void 0;
322
- if (!attachment) {
323
- if (refId || description) {
324
- documentReferences.push({ id: refId, description });
325
- }
326
- continue;
327
- }
328
- const binaryEl = attachment.getElementsByTagNameNS(
329
- CBC_NS,
330
- "EmbeddedDocumentBinaryObject"
331
- )[0];
332
- const externalRef = cacElement(attachment, "ExternalReference");
333
- if (binaryEl) {
334
- const content = binaryEl.textContent?.trim();
335
- if (content) {
336
- attachments.push({
337
- id: refId,
338
- filename: binaryEl.getAttribute("filename") || void 0,
339
- mimeCode: binaryEl.getAttribute("mimeCode") || void 0,
340
- description,
341
- base64Content: content
342
- });
343
- }
344
- } else if (externalRef) {
345
- const uri = cbcText(externalRef, "URI");
346
- if (uri) {
347
- attachments.push({
348
- id: refId,
349
- description,
350
- externalUri: uri
351
- });
352
- }
353
- }
354
- }
355
- return {
356
- attachments: attachments.length > 0 ? attachments : void 0,
357
- documentReferences: documentReferences.length > 0 ? documentReferences : void 0
358
- };
290
+ const refs = cacElements(root, "AdditionalDocumentReference");
291
+ const attachments = [];
292
+ const documentReferences = [];
293
+ for (const ref of refs) {
294
+ const attachment = cacElement$1(ref, "Attachment");
295
+ const refId = cbcText$1(ref, "ID");
296
+ const description = cbcText$1(ref, "DocumentDescription") || void 0;
297
+ if (!attachment) {
298
+ if (refId || description) documentReferences.push({
299
+ id: refId,
300
+ description
301
+ });
302
+ continue;
303
+ }
304
+ const binaryEl = attachment.getElementsByTagNameNS(CBC_NS$1, "EmbeddedDocumentBinaryObject")[0];
305
+ const externalRef = cacElement$1(attachment, "ExternalReference");
306
+ if (binaryEl) {
307
+ const content = binaryEl.textContent?.trim();
308
+ if (content) attachments.push({
309
+ id: refId,
310
+ filename: binaryEl.getAttribute("filename") || void 0,
311
+ mimeCode: binaryEl.getAttribute("mimeCode") || void 0,
312
+ description,
313
+ base64Content: content
314
+ });
315
+ } else if (externalRef) {
316
+ const uri = cbcText$1(externalRef, "URI");
317
+ if (uri) attachments.push({
318
+ id: refId,
319
+ description,
320
+ externalUri: uri
321
+ });
322
+ }
323
+ }
324
+ return {
325
+ attachments: attachments.length > 0 ? attachments : void 0,
326
+ documentReferences: documentReferences.length > 0 ? documentReferences : void 0
327
+ };
359
328
  }
360
329
  function parseBillingReference(root) {
361
- const billingRef = cacElement(root, "BillingReference");
362
- if (!billingRef) return void 0;
363
- const invoiceRef = cacElement(billingRef, "InvoiceDocumentReference");
364
- if (!invoiceRef) return void 0;
365
- const invoiceId = cbcText(invoiceRef, "ID") || void 0;
366
- const invoiceIssueDate = cbcText(invoiceRef, "IssueDate") || void 0;
367
- if (!invoiceId && !invoiceIssueDate) return void 0;
368
- return { invoiceId, invoiceIssueDate };
330
+ const billingRef = cacElement$1(root, "BillingReference");
331
+ if (!billingRef) return void 0;
332
+ const invoiceRef = cacElement$1(billingRef, "InvoiceDocumentReference");
333
+ if (!invoiceRef) return void 0;
334
+ const invoiceId = cbcText$1(invoiceRef, "ID") || void 0;
335
+ const invoiceIssueDate = cbcText$1(invoiceRef, "IssueDate") || void 0;
336
+ if (!invoiceId && !invoiceIssueDate) return void 0;
337
+ return {
338
+ invoiceId,
339
+ invoiceIssueDate
340
+ };
369
341
  }
370
- var stripDoctype = (xml) => xml.replace(/<!DOCTYPE\s[^>[]*(?:\[[^\]]*\])?>/gi, "");
342
+ /**
343
+ * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.
344
+ * @xmldom/xmldom resolves external entities by default, so we remove
345
+ * DOCTYPE blocks (including inline DTD subsets) before parsing.
346
+ */
347
+ const stripDoctype$1 = (xml) => xml.replace(/<!DOCTYPE\s[^>[]*(?:\[[^\]]*\])?>/gi, "");
371
348
  function parseUblInvoice(xml) {
372
- try {
373
- const safeXml = stripDoctype(xml);
374
- const BrowserDomParser = globalThis.DOMParser;
375
- const parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();
376
- const doc = parser.parseFromString(safeXml, "text/xml");
377
- if (doc.getElementsByTagName("parsererror").length > 0) return null;
378
- const root = doc.documentElement;
379
- const localName = root.localName;
380
- let documentType;
381
- if (localName === "Invoice") {
382
- documentType = "Invoice";
383
- } else if (localName === "CreditNote") {
384
- documentType = "CreditNote";
385
- } else {
386
- return null;
387
- }
388
- const isCreditNote = documentType === "CreditNote";
389
- const id = cbcText(root, "ID");
390
- if (!id) return null;
391
- const paymentMeansList = parsePaymentMeansList(root);
392
- const orderReference = cacElement(root, "OrderReference");
393
- const contractReference = cacElement(root, "ContractDocumentReference");
394
- const projectReference = cacElement(root, "ProjectReference");
395
- const { attachments, documentReferences } = parseAttachments(root);
396
- return {
397
- documentType,
398
- customizationId: cbcText(root, "CustomizationID") || void 0,
399
- profileId: cbcText(root, "ProfileID") || void 0,
400
- id,
401
- invoiceTypeCode: cbcText(root, "InvoiceTypeCode") || cbcText(root, "CreditNoteTypeCode") || void 0,
402
- issueDate: cbcText(root, "IssueDate"),
403
- dueDate: cbcText(root, "DueDate") || void 0,
404
- taxPointDate: cbcText(root, "TaxPointDate") || void 0,
405
- currency: cbcText(root, "DocumentCurrencyCode"),
406
- buyerReference: cbcText(root, "BuyerReference") || void 0,
407
- orderReference: orderReference ? cbcText(orderReference, "ID") : void 0,
408
- salesOrderId: orderReference ? cbcText(orderReference, "SalesOrderID") || void 0 : void 0,
409
- contractReference: contractReference ? cbcText(contractReference, "ID") : void 0,
410
- projectReference: projectReference ? cbcText(projectReference, "ID") : void 0,
411
- billingReference: parseBillingReference(root),
412
- seller: parseParty(root, "AccountingSupplierParty"),
413
- buyer: parseParty(root, "AccountingCustomerParty"),
414
- delivery: parseDelivery(root),
415
- lines: parseLines(root, isCreditNote),
416
- taxSubtotals: parseTaxSubtotals(root),
417
- monetaryTotal: parseMonetaryTotal(root),
418
- paymentMeansList,
419
- paymentMeans: paymentMeansList?.[0],
420
- invoicePeriod: parseInvoicePeriod(root),
421
- note: parseNotes(root),
422
- paymentTermsNote: parsePaymentTermsNote(root),
423
- attachments,
424
- documentReferences,
425
- allowanceCharges: parseAllowanceCharges(root)
426
- };
427
- } catch {
428
- return null;
429
- }
349
+ try {
350
+ const safeXml = stripDoctype$1(xml);
351
+ const BrowserDomParser = globalThis.DOMParser;
352
+ const doc = (BrowserDomParser ? new BrowserDomParser() : new DOMParser()).parseFromString(safeXml, "text/xml");
353
+ if (doc.getElementsByTagName("parsererror").length > 0) return null;
354
+ const root = doc.documentElement;
355
+ if (!root) return null;
356
+ const localName = root.localName;
357
+ let documentType;
358
+ if (localName === "Invoice") documentType = "Invoice";
359
+ else if (localName === "CreditNote") documentType = "CreditNote";
360
+ else return null;
361
+ const isCreditNote = documentType === "CreditNote";
362
+ const id = cbcText$1(root, "ID");
363
+ if (!id) return null;
364
+ const paymentMeansList = parsePaymentMeansList(root);
365
+ const orderReference = cacElement$1(root, "OrderReference");
366
+ const contractReference = cacElement$1(root, "ContractDocumentReference");
367
+ const projectReference = cacElement$1(root, "ProjectReference");
368
+ const { attachments, documentReferences } = parseAttachments(root);
369
+ return {
370
+ documentType,
371
+ customizationId: cbcText$1(root, "CustomizationID") || void 0,
372
+ profileId: cbcText$1(root, "ProfileID") || void 0,
373
+ id,
374
+ invoiceTypeCode: cbcText$1(root, "InvoiceTypeCode") || cbcText$1(root, "CreditNoteTypeCode") || void 0,
375
+ issueDate: cbcText$1(root, "IssueDate"),
376
+ dueDate: cbcText$1(root, "DueDate") || void 0,
377
+ taxPointDate: cbcText$1(root, "TaxPointDate") || void 0,
378
+ currency: cbcText$1(root, "DocumentCurrencyCode"),
379
+ buyerReference: cbcText$1(root, "BuyerReference") || void 0,
380
+ orderReference: orderReference ? cbcText$1(orderReference, "ID") : void 0,
381
+ salesOrderId: orderReference ? cbcText$1(orderReference, "SalesOrderID") || void 0 : void 0,
382
+ contractReference: contractReference ? cbcText$1(contractReference, "ID") : void 0,
383
+ projectReference: projectReference ? cbcText$1(projectReference, "ID") : void 0,
384
+ billingReference: parseBillingReference(root),
385
+ seller: parseParty(root, "AccountingSupplierParty"),
386
+ buyer: parseParty(root, "AccountingCustomerParty"),
387
+ delivery: parseDelivery(root),
388
+ lines: parseLines(root, isCreditNote),
389
+ taxSubtotals: parseTaxSubtotals(root),
390
+ monetaryTotal: parseMonetaryTotal(root),
391
+ paymentMeansList,
392
+ paymentMeans: paymentMeansList?.[0],
393
+ invoicePeriod: parseInvoicePeriod(root),
394
+ note: parseNotes(root),
395
+ paymentTermsNote: parsePaymentTermsNote(root),
396
+ attachments,
397
+ documentReferences,
398
+ allowanceCharges: parseAllowanceCharges(root)
399
+ };
400
+ } catch {
401
+ return null;
402
+ }
430
403
  }
431
-
432
- // src/attachments.ts
433
- var base64DecodedSize = (base64) => Math.round(base64.length * 3 / 4);
434
- var extractUblEmbeddedAttachments = (xml) => {
435
- const parsed = parseUblInvoice(xml);
436
- if (!parsed?.attachments || parsed.attachments.length === 0) return [];
437
- return parsed.attachments.map((attachment, index) => {
438
- const base64Content = attachment.base64Content?.trim();
439
- if (!base64Content) return null;
440
- return {
441
- id: attachment.id || null,
442
- filename: attachment.filename || `attachment-${index + 1}`,
443
- mimeCode: attachment.mimeCode || "application/octet-stream",
444
- sizeBytes: base64DecodedSize(base64Content),
445
- lineOrder: index,
446
- base64Content
447
- };
448
- }).filter((entry) => entry !== null);
404
+ //#endregion
405
+ //#region src/attachments.ts
406
+ /** Approximate decoded byte length of a base64 string. */
407
+ const base64DecodedSize = (base64) => Math.round(base64.length * 3 / 4);
408
+ /**
409
+ * Extract the embedded attachments (typically the human-readable PDF) from a
410
+ * UBL invoice or credit note XML. Attachments referenced only by external URI
411
+ * (no `EmbeddedDocumentBinaryObject`) are skipped; use {@link parseUblInvoice}
412
+ * directly when those matter.
413
+ */
414
+ const extractUblEmbeddedAttachments = (xml) => {
415
+ const parsed = parseUblInvoice(xml);
416
+ if (!parsed?.attachments || parsed.attachments.length === 0) return [];
417
+ return parsed.attachments.map((attachment, index) => {
418
+ const base64Content = attachment.base64Content?.trim();
419
+ if (!base64Content) return null;
420
+ return {
421
+ id: attachment.id || null,
422
+ filename: attachment.filename || `attachment-${index + 1}`,
423
+ mimeCode: attachment.mimeCode || "application/octet-stream",
424
+ sizeBytes: base64DecodedSize(base64Content),
425
+ lineOrder: index,
426
+ base64Content
427
+ };
428
+ }).filter((entry) => entry !== null);
449
429
  };
450
- var isPdfLikeAttachment = (attachment) => {
451
- const mimeCode = attachment.mimeCode?.toLowerCase() ?? "";
452
- if (mimeCode === "application/pdf" || mimeCode.endsWith("/pdf")) return true;
453
- return attachment.filename?.toLowerCase().endsWith(".pdf") ?? false;
430
+ /**
431
+ * Whether an attachment looks like a PDF, by MIME type first and filename
432
+ * extension as a fallback.
433
+ */
434
+ const isPdfLikeAttachment = (attachment) => {
435
+ const mimeCode = attachment.mimeCode?.toLowerCase() ?? "";
436
+ if (mimeCode === "application/pdf" || mimeCode.endsWith("/pdf")) return true;
437
+ return attachment.filename?.toLowerCase().endsWith(".pdf") ?? false;
454
438
  };
455
-
456
- // src/mlr.ts
457
- import { DOMParser as XmlDomParser2 } from "@xmldom/xmldom";
458
- var CBC_NS2 = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
459
- var CAC_NS2 = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
460
- var PEPPOL_MLR_DOCUMENT_TYPE_VALUE = "urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1";
461
- var PEPPOL_MLR_PROCESS_VALUE = "urn:fdc:peppol.eu:poacc:bis:mlr:3";
462
- var stripDoctype2 = (xml) => xml.replace(/<!DOCTYPE\s[^>[]*(?:\[[^\]]*\])?>/gi, "");
463
- var parseXmlDocument = (xml) => {
464
- const safeXml = stripDoctype2(xml);
465
- const BrowserDomParser = globalThis.DOMParser;
466
- const parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser2();
467
- const doc = parser.parseFromString(safeXml, "text/xml");
468
- if (doc.getElementsByTagName("parsererror").length > 0) return null;
469
- return doc;
439
+ //#endregion
440
+ //#region src/mlr.ts
441
+ const CBC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
442
+ const CAC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
443
+ /**
444
+ * Peppol BIS MLR (Message Level Response) document-type identifier value
445
+ * (Peppol `busdox-docid-qns` scheme).
446
+ */
447
+ const PEPPOL_MLR_DOCUMENT_TYPE_VALUE = "urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1";
448
+ /** Peppol BIS MLR process identifier value. */
449
+ const PEPPOL_MLR_PROCESS_VALUE = "urn:fdc:peppol.eu:poacc:bis:mlr:3";
450
+ /**
451
+ * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.
452
+ * @xmldom/xmldom resolves external entities by default, so we remove DOCTYPE
453
+ * blocks (including inline DTD subsets) before parsing.
454
+ */
455
+ const stripDoctype = (xml) => xml.replace(/<!DOCTYPE\s[^>[]*(?:\[[^\]]*\])?>/gi, "");
456
+ const parseXmlDocument = (xml) => {
457
+ const safeXml = stripDoctype(xml);
458
+ const BrowserDomParser = globalThis.DOMParser;
459
+ const doc = (BrowserDomParser ? new BrowserDomParser() : new DOMParser()).parseFromString(safeXml, "text/xml");
460
+ if (doc.getElementsByTagName("parsererror").length > 0) return null;
461
+ return doc;
470
462
  };
471
- var trimmed = (value) => {
472
- const text = value?.trim();
473
- return text ? text : null;
463
+ const trimmed = (value) => {
464
+ const text = value?.trim();
465
+ return text ? text : null;
474
466
  };
475
- var cbcText2 = (parent, tag) => trimmed(parent.getElementsByTagNameNS(CBC_NS2, tag)[0]?.textContent);
476
- var cbcDirectText2 = (parent, tag) => {
477
- for (let i = 0; i < parent.childNodes.length; i++) {
478
- const node = parent.childNodes[i];
479
- if (!node || node.nodeType !== 1) continue;
480
- const el = node;
481
- if (el.namespaceURI === CBC_NS2 && el.localName === tag) {
482
- return trimmed(el.textContent);
483
- }
484
- }
485
- return null;
467
+ /** First descendant CBC element's trimmed text, or null. */
468
+ const cbcText = (parent, tag) => trimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);
469
+ /**
470
+ * First direct-child CBC element's trimmed text, or null. Used for the
471
+ * top-level scalars so a nested `cbc:ID` (e.g. inside DocumentReference) cannot
472
+ * shadow the ApplicationResponse's own id.
473
+ */
474
+ const cbcDirectText = (parent, tag) => {
475
+ for (let i = 0; i < parent.childNodes.length; i++) {
476
+ const node = parent.childNodes[i];
477
+ if (!node || node.nodeType !== 1) continue;
478
+ const el = node;
479
+ if (el.namespaceURI === CBC_NS && el.localName === tag) return trimmed(el.textContent);
480
+ }
481
+ return null;
486
482
  };
487
- var cacElement2 = (parent, tag) => parent.getElementsByTagNameNS(CAC_NS2, tag)[0] ?? null;
488
- var endpointIdentifier = (party) => {
489
- if (!party) return null;
490
- const endpoint = party.getElementsByTagNameNS(CBC_NS2, "EndpointID")[0];
491
- if (!endpoint) return null;
492
- const id = trimmed(endpoint.textContent);
493
- const scheme = endpoint.getAttribute("schemeID");
494
- if (scheme && id && !id.includes(":")) return `${scheme}:${id}`;
495
- return id;
483
+ /** First descendant CAC element, or null. */
484
+ const cacElement = (parent, tag) => parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;
485
+ /**
486
+ * The Peppol participant identifier of a SenderParty / ReceiverParty, rendered
487
+ * as `schemeID:value` when the EndpointID carries a scheme and the value does
488
+ * not already include one, otherwise the raw value.
489
+ */
490
+ const endpointIdentifier = (party) => {
491
+ if (!party) return null;
492
+ const endpoint = party.getElementsByTagNameNS(CBC_NS, "EndpointID")[0];
493
+ if (!endpoint) return null;
494
+ const id = trimmed(endpoint.textContent);
495
+ const scheme = endpoint.getAttribute("schemeID");
496
+ if (scheme && id && !id.includes(":")) return `${scheme}:${id}`;
497
+ return id;
496
498
  };
497
- var findApplicationResponse = (xml) => {
498
- let doc;
499
- try {
500
- doc = parseXmlDocument(xml);
501
- } catch {
502
- return null;
503
- }
504
- const root = doc?.documentElement;
505
- if (!root) return null;
506
- if (root.localName === "ApplicationResponse") return root;
507
- const candidates = root.getElementsByTagName("*");
508
- for (let i = 0; i < candidates.length; i++) {
509
- const el = candidates[i];
510
- if (el?.localName === "ApplicationResponse") return el;
511
- }
512
- return null;
499
+ /**
500
+ * Locate the `ApplicationResponse` element, unwrapping a Standard Business
501
+ * Document (SBDH) envelope when present. Returns null when the XML is not
502
+ * parseable or contains no ApplicationResponse.
503
+ */
504
+ const findApplicationResponse = (xml) => {
505
+ let doc;
506
+ try {
507
+ doc = parseXmlDocument(xml);
508
+ } catch {
509
+ return null;
510
+ }
511
+ const root = doc?.documentElement;
512
+ if (!root) return null;
513
+ if (root.localName === "ApplicationResponse") return root;
514
+ const candidates = root.getElementsByTagName("*");
515
+ for (let i = 0; i < candidates.length; i++) {
516
+ const el = candidates[i];
517
+ if (el?.localName === "ApplicationResponse") return el;
518
+ }
519
+ return null;
513
520
  };
514
- var isPeppolMessageLevelResponse = (params) => {
515
- if (trimmed(params.documentTypeValue) === PEPPOL_MLR_DOCUMENT_TYPE_VALUE) {
516
- return true;
517
- }
518
- if (trimmed(params.processValue) === PEPPOL_MLR_PROCESS_VALUE) return true;
519
- const xml = trimmed(params.xml);
520
- if (!xml) return false;
521
- return findApplicationResponse(xml) !== null;
521
+ /**
522
+ * Whether an inbound document is a Peppol Message Level Response, identified by
523
+ * its document-type value, its process value, or by parsing the XML and finding
524
+ * an `ApplicationResponse` root (SBDH-wrapped or not).
525
+ */
526
+ const isPeppolMessageLevelResponse = (params) => {
527
+ if (trimmed(params.documentTypeValue) === "urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1") return true;
528
+ if (trimmed(params.processValue) === "urn:fdc:peppol.eu:poacc:bis:mlr:3") return true;
529
+ const xml = trimmed(params.xml);
530
+ if (!xml) return false;
531
+ return findApplicationResponse(xml) !== null;
522
532
  };
523
- var parsePeppolMessageLevelResponse = (xml) => {
524
- const root = findApplicationResponse(xml);
525
- if (!root) {
526
- throw new Error("Document is not a Peppol Message Level Response");
527
- }
528
- const documentResponse = cacElement2(root, "DocumentResponse");
529
- const response = documentResponse ? cacElement2(documentResponse, "Response") : null;
530
- const documentReference = documentResponse ? cacElement2(documentResponse, "DocumentReference") : null;
531
- return {
532
- customizationId: cbcDirectText2(root, "CustomizationID"),
533
- profileId: cbcDirectText2(root, "ProfileID"),
534
- responseId: cbcDirectText2(root, "ID"),
535
- issueDate: cbcDirectText2(root, "IssueDate"),
536
- issueTime: cbcDirectText2(root, "IssueTime"),
537
- referencedDocumentId: documentReference ? cbcText2(documentReference, "ID") : null,
538
- responseCode: response ? cbcText2(response, "ResponseCode") : null,
539
- description: response ? cbcText2(response, "Description") : null,
540
- senderIdentifier: endpointIdentifier(cacElement2(root, "SenderParty")),
541
- receiverIdentifier: endpointIdentifier(cacElement2(root, "ReceiverParty"))
542
- };
533
+ /**
534
+ * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping
535
+ * an SBDH envelope when present. Throws when the XML is not an
536
+ * ApplicationResponse.
537
+ */
538
+ const parsePeppolMessageLevelResponse = (xml) => {
539
+ const root = findApplicationResponse(xml);
540
+ if (!root) throw new Error("Document is not a Peppol Message Level Response");
541
+ const documentResponse = cacElement(root, "DocumentResponse");
542
+ const response = documentResponse ? cacElement(documentResponse, "Response") : null;
543
+ const documentReference = documentResponse ? cacElement(documentResponse, "DocumentReference") : null;
544
+ return {
545
+ customizationId: cbcDirectText(root, "CustomizationID"),
546
+ profileId: cbcDirectText(root, "ProfileID"),
547
+ responseId: cbcDirectText(root, "ID"),
548
+ issueDate: cbcDirectText(root, "IssueDate"),
549
+ issueTime: cbcDirectText(root, "IssueTime"),
550
+ referencedDocumentId: documentReference ? cbcText(documentReference, "ID") : null,
551
+ responseCode: response ? cbcText(response, "ResponseCode") : null,
552
+ description: response ? cbcText(response, "Description") : null,
553
+ senderIdentifier: endpointIdentifier(cacElement(root, "SenderParty")),
554
+ receiverIdentifier: endpointIdentifier(cacElement(root, "ReceiverParty"))
555
+ };
543
556
  };
544
-
545
- // src/normalize.ts
546
- var UTF8_BOM = 65279;
547
- var normalizeText = (value) => {
548
- if (!value) return null;
549
- const trimmed2 = value.trim();
550
- if (!trimmed2) return null;
551
- const upper = trimmed2.toUpperCase();
552
- if (upper === "NA" || upper === "N/A") return null;
553
- return trimmed2;
557
+ //#endregion
558
+ //#region src/normalize.ts
559
+ const UTF8_BOM = 65279;
560
+ const normalizeText = (value) => {
561
+ if (!value) return null;
562
+ const trimmed = value.trim();
563
+ if (!trimmed) return null;
564
+ const upper = trimmed.toUpperCase();
565
+ if (upper === "NA" || upper === "N/A") return null;
566
+ return trimmed;
554
567
  };
555
- var toNumberOrNull = (value) => Number.isFinite(value ?? Number.NaN) ? value : null;
556
- var normalizeCurrency = (value) => {
557
- if (!value) return null;
558
- const trimmed2 = value.trim();
559
- if (!trimmed2) return null;
560
- return trimmed2.toUpperCase();
568
+ const toNumberOrNull = (value) => Number.isFinite(value ?? NaN) ? value : null;
569
+ const normalizeCurrency = (value) => {
570
+ if (!value) return null;
571
+ const trimmed = value.trim();
572
+ if (!trimmed) return null;
573
+ return trimmed.toUpperCase();
561
574
  };
562
- var parseDate = (value) => {
563
- if (!value) return null;
564
- const trimmed2 = value.trim();
565
- if (!trimmed2) return null;
566
- const timestamp = Date.parse(trimmed2);
567
- if (Number.isNaN(timestamp)) return null;
568
- const iso = new Date(timestamp).toISOString();
569
- return iso.slice(0, 10);
575
+ const parseDate = (value) => {
576
+ if (!value) return null;
577
+ const trimmed = value.trim();
578
+ if (!trimmed) return null;
579
+ const timestamp = Date.parse(trimmed);
580
+ if (Number.isNaN(timestamp)) return null;
581
+ return new Date(timestamp).toISOString().slice(0, 10);
570
582
  };
571
- var addressToString = (address) => {
572
- if (!address) return null;
573
- const street = [address.street, address.additionalStreet].filter((part) => part && part.trim().length > 0).join(" ");
574
- const cityLine = [address.postalZone, address.city].filter((part) => part && part.trim().length > 0).join(" ");
575
- const countryLine = [address.countrySubentity, address.countryCode].filter((part) => part && part.trim().length > 0).join(" ");
576
- const lines = [street, cityLine, countryLine].filter((line) => line.length > 0);
577
- return lines.length > 0 ? lines.join("\n") : null;
583
+ const addressToString = (address) => {
584
+ if (!address) return null;
585
+ const lines = [
586
+ [address.street, address.additionalStreet].filter((part) => part && part.trim().length > 0).join(" "),
587
+ [address.postalZone, address.city].filter((part) => part && part.trim().length > 0).join(" "),
588
+ [address.countrySubentity, address.countryCode].filter((part) => part && part.trim().length > 0).join(" ")
589
+ ].filter((line) => line.length > 0);
590
+ return lines.length > 0 ? lines.join("\n") : null;
578
591
  };
579
- var addressToStructured = (address) => {
580
- if (!address) return null;
581
- const line1 = [address.street, address.additionalStreet].filter((part) => part && part.trim().length > 0).join(" ");
582
- const result = {
583
- line1: normalizeText(line1),
584
- line2: null,
585
- city: normalizeText(address.city),
586
- state: normalizeText(address.countrySubentity),
587
- postal_code: normalizeText(address.postalZone),
588
- country: normalizeText(address.countryCode)
589
- };
590
- const hasValue = Object.values(result).some((value) => value);
591
- return hasValue ? result : null;
592
+ const addressToStructured = (address) => {
593
+ if (!address) return null;
594
+ const line1 = [address.street, address.additionalStreet].filter((part) => part && part.trim().length > 0).join(" ");
595
+ const result = {
596
+ line1: normalizeText(line1),
597
+ line2: null,
598
+ city: normalizeText(address.city),
599
+ state: normalizeText(address.countrySubentity),
600
+ postal_code: normalizeText(address.postalZone),
601
+ country: normalizeText(address.countryCode)
602
+ };
603
+ return Object.values(result).some((value) => value) ? result : null;
592
604
  };
593
- var base64ByteLength = (content) => {
594
- const sanitized = content.replace(/\s+/g, "");
595
- if (!sanitized) return 0;
596
- const paddingLength = sanitized.endsWith("==") ? 2 : sanitized.endsWith("=") ? 1 : 0;
597
- return Math.floor(sanitized.length * 3 / 4) - paddingLength;
605
+ const base64ByteLength = (content) => {
606
+ const sanitized = content.replace(/\s+/g, "");
607
+ if (!sanitized) return 0;
608
+ const paddingLength = sanitized.endsWith("==") ? 2 : sanitized.endsWith("=") ? 1 : 0;
609
+ return Math.floor(sanitized.length * 3 / 4) - paddingLength;
598
610
  };
599
- var sanitizeAttachments = (attachments) => (attachments ?? []).map((attachment) => ({
600
- id: normalizeText(attachment.id),
601
- filename: normalizeText(attachment.filename),
602
- mime_code: normalizeText(attachment.mimeCode),
603
- description: normalizeText(attachment.description),
604
- size_bytes: attachment.base64Content ? base64ByteLength(attachment.base64Content) : null,
605
- external_uri: normalizeText(attachment.externalUri)
611
+ const sanitizeAttachments = (attachments) => (attachments ?? []).map((attachment) => ({
612
+ id: normalizeText(attachment.id),
613
+ filename: normalizeText(attachment.filename),
614
+ mime_code: normalizeText(attachment.mimeCode),
615
+ description: normalizeText(attachment.description),
616
+ size_bytes: attachment.base64Content ? base64ByteLength(attachment.base64Content) : null,
617
+ external_uri: normalizeText(attachment.externalUri)
606
618
  }));
607
- var sanitizeAllowanceCharges = (charges) => (charges ?? []).map((charge) => ({
608
- charge_indicator: charge.chargeIndicator,
609
- amount: toNumberOrNull(charge.amount),
610
- base_amount: toNumberOrNull(charge.baseAmount),
611
- multiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),
612
- reason: normalizeText(charge.reason),
613
- reason_code: normalizeText(charge.reasonCode),
614
- tax_percent: toNumberOrNull(charge.taxPercent),
615
- tax_category_id: normalizeText(charge.taxCategoryId),
616
- tax_scheme_id: normalizeText(charge.taxSchemeId)
619
+ const sanitizeAllowanceCharges = (charges) => (charges ?? []).map((charge) => ({
620
+ charge_indicator: charge.chargeIndicator,
621
+ amount: toNumberOrNull(charge.amount),
622
+ base_amount: toNumberOrNull(charge.baseAmount),
623
+ multiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),
624
+ reason: normalizeText(charge.reason),
625
+ reason_code: normalizeText(charge.reasonCode),
626
+ tax_percent: toNumberOrNull(charge.taxPercent),
627
+ tax_category_id: normalizeText(charge.taxCategoryId),
628
+ tax_scheme_id: normalizeText(charge.taxSchemeId)
617
629
  }));
618
- var sanitizeRawUbl = (ubl) => ({
619
- ...ubl,
620
- attachments: sanitizeAttachments(ubl.attachments),
621
- documentReferences: ubl.documentReferences ?? []
630
+ const sanitizeRawUbl = (ubl) => ({
631
+ ...ubl,
632
+ attachments: sanitizeAttachments(ubl.attachments),
633
+ documentReferences: ubl.documentReferences ?? []
622
634
  });
623
- var sumTaxTotal = (ubl) => {
624
- const subtotalSum = ubl.taxSubtotals.reduce(
625
- (sum, subtotal) => sum + subtotal.taxAmount,
626
- 0
627
- );
628
- if (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) {
629
- return subtotalSum;
630
- }
631
- return ubl.monetaryTotal.taxInclusiveAmount - ubl.monetaryTotal.taxExclusiveAmount;
635
+ const sumTaxTotal = (ubl) => {
636
+ const subtotalSum = ubl.taxSubtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0);
637
+ if (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) return subtotalSum;
638
+ return ubl.monetaryTotal.taxInclusiveAmount - ubl.monetaryTotal.taxExclusiveAmount;
632
639
  };
633
- var sumAllowanceChargesByType = (charges, chargeIndicator) => (charges ?? []).reduce((sum, charge) => {
634
- if (charge.chargeIndicator !== chargeIndicator) return sum;
635
- return sum + Math.abs(charge.amount);
640
+ const sumAllowanceChargesByType = (charges, chargeIndicator) => (charges ?? []).reduce((sum, charge) => {
641
+ if (charge.chargeIndicator !== chargeIndicator) return sum;
642
+ return sum + Math.abs(charge.amount);
636
643
  }, 0);
637
- var decodeXmlBytes = (bytes) => {
638
- const text = new TextDecoder("utf-8").decode(bytes);
639
- return text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;
644
+ /**
645
+ * Decode raw XML bytes, stripping an optional UTF-8 BOM.
646
+ */
647
+ const decodeXmlBytes = (bytes) => {
648
+ const text = new TextDecoder("utf-8").decode(bytes);
649
+ return text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;
640
650
  };
641
- var normalizeUblResponse = (xml, documentId) => {
642
- const ubl = parseUblInvoice(xml);
643
- if (!ubl) {
644
- throw new Error("Failed to parse UBL invoice XML");
645
- }
646
- const subtotal = toNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ?? toNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);
647
- const total = toNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ?? toNumberOrNull(ubl.monetaryTotal.payableAmount);
648
- const amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);
649
- const prepaidAmount = toNumberOrNull(ubl.monetaryTotal.prepaidAmount);
650
- const amountPaid = prepaidAmount ?? (total !== null && amountDue !== null && total > amountDue ? toNumberOrNull(total - amountDue) : null);
651
- const taxTotal = toNumberOrNull(sumTaxTotal(ubl));
652
- const hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;
653
- const headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);
654
- const headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);
655
- const currency = normalizeCurrency(ubl.currency);
656
- const paymentTerms = normalizeText(ubl.paymentTermsNote);
657
- const poNumber = normalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);
658
- const lineItems = ubl.lines.map((line) => ({
659
- description: normalizeText(line.description) ?? normalizeText(line.itemName) ?? "Line item",
660
- quantity: toNumberOrNull(line.quantity),
661
- unit: normalizeText(line.unitCode),
662
- unit_price: toNumberOrNull(line.unitPrice),
663
- amount: toNumberOrNull(line.lineExtensionAmount),
664
- tax_amount: toNumberOrNull(line.taxAmount),
665
- tax_rate: toNumberOrNull(line.taxPercent),
666
- product_code: normalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),
667
- discount_amount: toNumberOrNull(line.discountAmount),
668
- extra: {
669
- ubl_line_id: normalizeText(line.id),
670
- item_name: normalizeText(line.itemName),
671
- sellers_item_id: normalizeText(line.sellersItemId),
672
- buyers_item_id: normalizeText(line.buyersItemId),
673
- tax_category_id: normalizeText(line.taxCategoryId),
674
- tax_scheme_id: normalizeText(line.taxSchemeId),
675
- tax_subtotals: line.taxSubtotals ?? [],
676
- allowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),
677
- charge_amount: toNumberOrNull(line.chargeAmount),
678
- metadata: line.additionalItemProperties ? Object.fromEntries(
679
- line.additionalItemProperties.map((p) => [p.name, p.value])
680
- ) : null
681
- }
682
- }));
683
- const supplierAddress = addressToString(ubl.seller.address);
684
- const receiverAddress = addressToString(ubl.buyer.address);
685
- const supplierAddressStructured = addressToStructured(ubl.seller.address);
686
- const receiverAddressStructured = addressToStructured(ubl.buyer.address);
687
- const attachmentMetadata = sanitizeAttachments(ubl.attachments);
688
- const paymentMeansList = ubl.paymentMeansList && ubl.paymentMeansList.length > 0 ? ubl.paymentMeansList : ubl.paymentMeans ? [ubl.paymentMeans] : [];
689
- const extracted = {
690
- provider: "ubl_xml",
691
- document_id: documentId,
692
- invoice: {
693
- invoice_number: normalizeText(ubl.id),
694
- invoice_date: parseDate(ubl.issueDate),
695
- due_date: parseDate(ubl.dueDate),
696
- currency,
697
- subtotal,
698
- tax_total: taxTotal,
699
- total,
700
- amount_due: amountDue,
701
- amount_paid: amountPaid,
702
- discount_total: toNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ?? (hasHeaderAllowanceCharges ? toNumberOrNull(headerDiscountTotal) : null),
703
- shipping_total: toNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ?? (hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),
704
- payment_terms: paymentTerms,
705
- po_number: poNumber,
706
- supplier: {
707
- name: normalizeText(ubl.seller.name) ?? normalizeText(ubl.seller.registrationName),
708
- address: supplierAddress,
709
- tax_id: normalizeText(ubl.seller.vatId) ?? normalizeText(ubl.seller.companyId),
710
- iban: normalizeText(ubl.paymentMeans?.iban),
711
- bic: normalizeText(ubl.paymentMeans?.bic)
712
- },
713
- receiver: {
714
- name: normalizeText(ubl.buyer.name) ?? normalizeText(ubl.buyer.registrationName),
715
- address: receiverAddress,
716
- tax_id: normalizeText(ubl.buyer.vatId) ?? normalizeText(ubl.buyer.companyId)
717
- },
718
- extra: {
719
- document_type: ubl.documentType,
720
- customization_id: normalizeText(ubl.customizationId),
721
- profile_id: normalizeText(ubl.profileId),
722
- invoice_type_code: normalizeText(ubl.invoiceTypeCode),
723
- buyer_reference: normalizeText(ubl.buyerReference),
724
- order_reference_id: normalizeText(ubl.orderReference),
725
- sales_order_id: normalizeText(ubl.salesOrderId),
726
- contract_reference: normalizeText(ubl.contractReference),
727
- project_reference: normalizeText(ubl.projectReference),
728
- billing_reference: ubl.billingReference ? {
729
- invoice_id: normalizeText(ubl.billingReference.invoiceId),
730
- invoice_issue_date: parseDate(
731
- ubl.billingReference.invoiceIssueDate
732
- )
733
- } : null,
734
- tax_point_date: parseDate(ubl.taxPointDate),
735
- invoice_period: ubl.invoicePeriod ?? null,
736
- note: normalizeText(ubl.note),
737
- payment_means: ubl.paymentMeans ? {
738
- code: normalizeText(ubl.paymentMeans.code),
739
- code_name: normalizeText(ubl.paymentMeans.codeName),
740
- payment_id: normalizeText(ubl.paymentMeans.paymentId),
741
- iban: normalizeText(ubl.paymentMeans.iban),
742
- bic: normalizeText(ubl.paymentMeans.bic),
743
- account_name: normalizeText(ubl.paymentMeans.accountName),
744
- mandate_id: normalizeText(ubl.paymentMeans.mandateId)
745
- } : null,
746
- payment_means_list: paymentMeansList.map((item) => ({
747
- code: normalizeText(item.code),
748
- code_name: normalizeText(item.codeName),
749
- payment_id: normalizeText(item.paymentId),
750
- iban: normalizeText(item.iban),
751
- bic: normalizeText(item.bic),
752
- account_name: normalizeText(item.accountName),
753
- mandate_id: normalizeText(item.mandateId)
754
- })),
755
- delivery: ubl.delivery ? {
756
- actual_delivery_date: parseDate(
757
- ubl.delivery.actualDeliveryDate
758
- ),
759
- address: addressToStructured(ubl.delivery.address)
760
- } : null,
761
- supplier: {
762
- endpoint_id: normalizeText(ubl.seller.endpointId),
763
- endpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),
764
- registration_name: normalizeText(ubl.seller.registrationName),
765
- company_legal_form: normalizeText(ubl.seller.companyLegalForm),
766
- company_id_scheme_id: normalizeText(ubl.seller.companyIdSchemeId),
767
- tax_scheme_id: normalizeText(ubl.seller.taxSchemeId),
768
- party_identifications: ubl.seller.partyIdentifications ?? [],
769
- contact_name: normalizeText(ubl.seller.contact?.name),
770
- contact_phone: normalizeText(ubl.seller.contact?.phone),
771
- contact_email: normalizeText(ubl.seller.contact?.email)
772
- },
773
- receiver: {
774
- endpoint_id: normalizeText(ubl.buyer.endpointId),
775
- endpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),
776
- registration_name: normalizeText(ubl.buyer.registrationName),
777
- company_legal_form: normalizeText(ubl.buyer.companyLegalForm),
778
- company_id_scheme_id: normalizeText(ubl.buyer.companyIdSchemeId),
779
- tax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),
780
- party_identifications: ubl.buyer.partyIdentifications ?? [],
781
- contact_name: normalizeText(ubl.buyer.contact?.name),
782
- contact_phone: normalizeText(ubl.buyer.contact?.phone),
783
- contact_email: normalizeText(ubl.buyer.contact?.email)
784
- },
785
- supplier_address_structured: supplierAddressStructured,
786
- receiver_address_structured: receiverAddressStructured,
787
- tax_subtotals: ubl.taxSubtotals,
788
- allowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),
789
- attachments: attachmentMetadata,
790
- document_references: ubl.documentReferences ?? []
791
- }
792
- },
793
- line_items: lineItems,
794
- confidence: {
795
- overall: 1,
796
- fields: {
797
- invoice_id: 1,
798
- invoice_date: 1,
799
- due_date: 1,
800
- total_amount: 1,
801
- supplier_name: 1
802
- }
803
- }
804
- };
805
- return {
806
- extracted,
807
- rawPayload: {
808
- format: "ubl_xml",
809
- invoice: sanitizeRawUbl(ubl)
810
- }
811
- };
651
+ /**
652
+ * Parse a UBL XML string and normalize it into a flat DTO suitable for
653
+ * database storage or API responses.
654
+ */
655
+ const normalizeUblResponse = (xml, documentId) => {
656
+ const ubl = parseUblInvoice(xml);
657
+ if (!ubl) throw new Error("Failed to parse UBL invoice XML");
658
+ const subtotal = toNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ?? toNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);
659
+ const total = toNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ?? toNumberOrNull(ubl.monetaryTotal.payableAmount);
660
+ const amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);
661
+ const amountPaid = toNumberOrNull(ubl.monetaryTotal.prepaidAmount) ?? (total !== null && amountDue !== null && total > amountDue ? toNumberOrNull(total - amountDue) : null);
662
+ const taxTotal = toNumberOrNull(sumTaxTotal(ubl));
663
+ const hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;
664
+ const headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);
665
+ const headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);
666
+ const currency = normalizeCurrency(ubl.currency);
667
+ const paymentTerms = normalizeText(ubl.paymentTermsNote);
668
+ const poNumber = normalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);
669
+ const lineItems = ubl.lines.map((line) => ({
670
+ description: normalizeText(line.description) ?? normalizeText(line.itemName) ?? "Line item",
671
+ quantity: toNumberOrNull(line.quantity),
672
+ unit: normalizeText(line.unitCode),
673
+ unit_price: toNumberOrNull(line.unitPrice),
674
+ amount: toNumberOrNull(line.lineExtensionAmount),
675
+ tax_amount: toNumberOrNull(line.taxAmount),
676
+ tax_rate: toNumberOrNull(line.taxPercent),
677
+ product_code: normalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),
678
+ discount_amount: toNumberOrNull(line.discountAmount),
679
+ extra: {
680
+ ubl_line_id: normalizeText(line.id),
681
+ item_name: normalizeText(line.itemName),
682
+ sellers_item_id: normalizeText(line.sellersItemId),
683
+ buyers_item_id: normalizeText(line.buyersItemId),
684
+ tax_category_id: normalizeText(line.taxCategoryId),
685
+ tax_scheme_id: normalizeText(line.taxSchemeId),
686
+ tax_subtotals: line.taxSubtotals ?? [],
687
+ allowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),
688
+ charge_amount: toNumberOrNull(line.chargeAmount),
689
+ metadata: line.additionalItemProperties ? Object.fromEntries(line.additionalItemProperties.map((p) => [p.name, p.value])) : null
690
+ }
691
+ }));
692
+ const supplierAddress = addressToString(ubl.seller.address);
693
+ const receiverAddress = addressToString(ubl.buyer.address);
694
+ const supplierAddressStructured = addressToStructured(ubl.seller.address);
695
+ const receiverAddressStructured = addressToStructured(ubl.buyer.address);
696
+ const attachmentMetadata = sanitizeAttachments(ubl.attachments);
697
+ const paymentMeansList = ubl.paymentMeansList && ubl.paymentMeansList.length > 0 ? ubl.paymentMeansList : ubl.paymentMeans ? [ubl.paymentMeans] : [];
698
+ return {
699
+ extracted: {
700
+ provider: "ubl_xml",
701
+ document_id: documentId,
702
+ invoice: {
703
+ invoice_number: normalizeText(ubl.id),
704
+ invoice_date: parseDate(ubl.issueDate),
705
+ due_date: parseDate(ubl.dueDate),
706
+ currency,
707
+ subtotal,
708
+ tax_total: taxTotal,
709
+ total,
710
+ amount_due: amountDue,
711
+ amount_paid: amountPaid,
712
+ discount_total: toNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ?? (hasHeaderAllowanceCharges ? toNumberOrNull(headerDiscountTotal) : null),
713
+ shipping_total: toNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ?? (hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),
714
+ payment_terms: paymentTerms,
715
+ po_number: poNumber,
716
+ supplier: {
717
+ name: normalizeText(ubl.seller.name) ?? normalizeText(ubl.seller.registrationName),
718
+ address: supplierAddress,
719
+ tax_id: normalizeText(ubl.seller.vatId) ?? normalizeText(ubl.seller.companyId),
720
+ iban: normalizeText(ubl.paymentMeans?.iban),
721
+ bic: normalizeText(ubl.paymentMeans?.bic)
722
+ },
723
+ receiver: {
724
+ name: normalizeText(ubl.buyer.name) ?? normalizeText(ubl.buyer.registrationName),
725
+ address: receiverAddress,
726
+ tax_id: normalizeText(ubl.buyer.vatId) ?? normalizeText(ubl.buyer.companyId)
727
+ },
728
+ extra: {
729
+ document_type: ubl.documentType,
730
+ customization_id: normalizeText(ubl.customizationId),
731
+ profile_id: normalizeText(ubl.profileId),
732
+ invoice_type_code: normalizeText(ubl.invoiceTypeCode),
733
+ buyer_reference: normalizeText(ubl.buyerReference),
734
+ order_reference_id: normalizeText(ubl.orderReference),
735
+ sales_order_id: normalizeText(ubl.salesOrderId),
736
+ contract_reference: normalizeText(ubl.contractReference),
737
+ project_reference: normalizeText(ubl.projectReference),
738
+ billing_reference: ubl.billingReference ? {
739
+ invoice_id: normalizeText(ubl.billingReference.invoiceId),
740
+ invoice_issue_date: parseDate(ubl.billingReference.invoiceIssueDate)
741
+ } : null,
742
+ tax_point_date: parseDate(ubl.taxPointDate),
743
+ invoice_period: ubl.invoicePeriod ?? null,
744
+ note: normalizeText(ubl.note),
745
+ payment_means: ubl.paymentMeans ? {
746
+ code: normalizeText(ubl.paymentMeans.code),
747
+ code_name: normalizeText(ubl.paymentMeans.codeName),
748
+ payment_id: normalizeText(ubl.paymentMeans.paymentId),
749
+ iban: normalizeText(ubl.paymentMeans.iban),
750
+ bic: normalizeText(ubl.paymentMeans.bic),
751
+ account_name: normalizeText(ubl.paymentMeans.accountName),
752
+ mandate_id: normalizeText(ubl.paymentMeans.mandateId)
753
+ } : null,
754
+ payment_means_list: paymentMeansList.map((item) => ({
755
+ code: normalizeText(item.code),
756
+ code_name: normalizeText(item.codeName),
757
+ payment_id: normalizeText(item.paymentId),
758
+ iban: normalizeText(item.iban),
759
+ bic: normalizeText(item.bic),
760
+ account_name: normalizeText(item.accountName),
761
+ mandate_id: normalizeText(item.mandateId)
762
+ })),
763
+ delivery: ubl.delivery ? {
764
+ actual_delivery_date: parseDate(ubl.delivery.actualDeliveryDate),
765
+ address: addressToStructured(ubl.delivery.address)
766
+ } : null,
767
+ supplier: {
768
+ endpoint_id: normalizeText(ubl.seller.endpointId),
769
+ endpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),
770
+ registration_name: normalizeText(ubl.seller.registrationName),
771
+ company_legal_form: normalizeText(ubl.seller.companyLegalForm),
772
+ company_id_scheme_id: normalizeText(ubl.seller.companyIdSchemeId),
773
+ tax_scheme_id: normalizeText(ubl.seller.taxSchemeId),
774
+ party_identifications: ubl.seller.partyIdentifications ?? [],
775
+ contact_name: normalizeText(ubl.seller.contact?.name),
776
+ contact_phone: normalizeText(ubl.seller.contact?.phone),
777
+ contact_email: normalizeText(ubl.seller.contact?.email)
778
+ },
779
+ receiver: {
780
+ endpoint_id: normalizeText(ubl.buyer.endpointId),
781
+ endpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),
782
+ registration_name: normalizeText(ubl.buyer.registrationName),
783
+ company_legal_form: normalizeText(ubl.buyer.companyLegalForm),
784
+ company_id_scheme_id: normalizeText(ubl.buyer.companyIdSchemeId),
785
+ tax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),
786
+ party_identifications: ubl.buyer.partyIdentifications ?? [],
787
+ contact_name: normalizeText(ubl.buyer.contact?.name),
788
+ contact_phone: normalizeText(ubl.buyer.contact?.phone),
789
+ contact_email: normalizeText(ubl.buyer.contact?.email)
790
+ },
791
+ supplier_address_structured: supplierAddressStructured,
792
+ receiver_address_structured: receiverAddressStructured,
793
+ tax_subtotals: ubl.taxSubtotals,
794
+ allowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),
795
+ attachments: attachmentMetadata,
796
+ document_references: ubl.documentReferences ?? []
797
+ }
798
+ },
799
+ line_items: lineItems,
800
+ confidence: {
801
+ overall: 1,
802
+ fields: {
803
+ invoice_id: 1,
804
+ invoice_date: 1,
805
+ due_date: 1,
806
+ total_amount: 1,
807
+ supplier_name: 1
808
+ }
809
+ }
810
+ },
811
+ rawPayload: {
812
+ format: "ubl_xml",
813
+ invoice: sanitizeRawUbl(ubl)
814
+ }
815
+ };
812
816
  };
813
- var parseUblInvoiceDocument = (params) => {
814
- const xml = decodeXmlBytes(params.bytes);
815
- const { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);
816
- return {
817
- rawPayload: {
818
- ...rawPayload,
819
- mime_type: params.mimeType
820
- },
821
- extracted,
822
- providerJobId: null
823
- };
824
- };
825
- export {
826
- PEPPOL_MLR_DOCUMENT_TYPE_VALUE,
827
- PEPPOL_MLR_PROCESS_VALUE,
828
- decodeXmlBytes,
829
- extractUblEmbeddedAttachments,
830
- isPdfLikeAttachment,
831
- isPeppolMessageLevelResponse,
832
- normalizeCurrency,
833
- normalizeUblResponse,
834
- parseDate,
835
- parsePeppolMessageLevelResponse,
836
- parseUblInvoice,
837
- parseUblInvoiceDocument
817
+ /**
818
+ * Parse a UBL invoice from raw bytes and normalize it into a DTO.
819
+ */
820
+ const parseUblInvoiceDocument = (params) => {
821
+ const xml = decodeXmlBytes(params.bytes);
822
+ const { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);
823
+ return {
824
+ rawPayload: {
825
+ ...rawPayload,
826
+ mime_type: params.mimeType
827
+ },
828
+ extracted,
829
+ providerJobId: null
830
+ };
838
831
  };
832
+ //#endregion
833
+ export { PEPPOL_MLR_DOCUMENT_TYPE_VALUE, PEPPOL_MLR_PROCESS_VALUE, decodeXmlBytes, extractUblEmbeddedAttachments, isPdfLikeAttachment, isPeppolMessageLevelResponse, normalizeCurrency, normalizeUblResponse, parseDate, parsePeppolMessageLevelResponse, parseUblInvoice, parseUblInvoiceDocument };
834
+
839
835
  //# sourceMappingURL=index.js.map