@financica/ubl 0.15.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,408 @@
1
+ import { base64DecodedSize } from "./attachments.js";
2
+ import { UblParseError } from "./errors.js";
3
+ import { parseUblInvoice } from "./parser.js";
4
+ import type {
5
+ InvoiceExtractionDTO,
6
+ UblAddress,
7
+ UblAllowanceCharge,
8
+ UblAttachment,
9
+ UblInvoice,
10
+ UblPaymentMeans,
11
+ } from "./types.js";
12
+
13
+ // --- Utility helpers ---
14
+
15
+ const UTF8_BOM = 0xfeff;
16
+
17
+ /** `null` for an absent value or an "N/A" placeholder written by the sender. */
18
+ const normalizeText = (value: string | undefined): string | null => {
19
+ if (value === undefined) return null;
20
+ const upper = value.toUpperCase();
21
+ if (upper === "NA" || upper === "N/A") return null;
22
+ return value;
23
+ };
24
+
25
+ const toNumberOrNull = (value: number | undefined): number | null =>
26
+ value !== undefined && Number.isFinite(value) ? value : null;
27
+
28
+ const roundToCents = (value: number): number => Math.round(value * 100) / 100;
29
+
30
+ export const normalizeCurrency = (value?: string | null): string | null => {
31
+ if (!value) return null;
32
+ const trimmed = value.trim();
33
+ if (!trimmed) return null;
34
+ return trimmed.toUpperCase();
35
+ };
36
+
37
+ export const parseDate = (value?: string | null): string | null => {
38
+ if (!value) return null;
39
+ const trimmed = value.trim();
40
+ if (!trimmed) return null;
41
+ const timestamp = Date.parse(trimmed);
42
+ if (Number.isNaN(timestamp)) return null;
43
+ const iso = new Date(timestamp).toISOString();
44
+ return iso.slice(0, 10);
45
+ };
46
+
47
+ const sanitizePaymentMeans = (pm: UblPaymentMeans) => ({
48
+ code: normalizeText(pm.code),
49
+ code_name: normalizeText(pm.codeName),
50
+ payment_id: normalizeText(pm.paymentId),
51
+ iban: normalizeText(pm.iban),
52
+ bic: normalizeText(pm.bic),
53
+ account_name: normalizeText(pm.accountName),
54
+ mandate_id: normalizeText(pm.mandateId),
55
+ });
56
+
57
+ // --- Address helpers ---
58
+
59
+ const present = (part: string | undefined): part is string => part !== undefined;
60
+
61
+ const joinStreet = (address: UblAddress): string =>
62
+ [address.street, address.additionalStreet].filter(present).join(" ");
63
+
64
+ const addressToString = (address?: UblAddress): string | null => {
65
+ if (!address) return null;
66
+ const street = joinStreet(address);
67
+ const cityLine = [address.postalZone, address.city].filter(present).join(" ");
68
+ const countryLine = [address.countrySubentity, address.countryCode]
69
+ .filter(present)
70
+ .join(" ");
71
+ const lines = [street, cityLine, countryLine].filter((line) => line.length > 0);
72
+ return lines.length > 0 ? lines.join("\n") : null;
73
+ };
74
+
75
+ const addressToStructured = (address?: UblAddress) => {
76
+ if (!address) return null;
77
+ const line1 = joinStreet(address);
78
+ const result = {
79
+ line1: line1 ? normalizeText(line1) : null,
80
+ line2: null as string | null,
81
+ city: normalizeText(address.city),
82
+ state: normalizeText(address.countrySubentity),
83
+ postal_code: normalizeText(address.postalZone),
84
+ country: normalizeText(address.countryCode),
85
+ };
86
+ const hasValue = Object.values(result).some((value) => value);
87
+ return hasValue ? result : null;
88
+ };
89
+
90
+ // --- Attachment & charge sanitizers ---
91
+
92
+ const sanitizeAttachments = (attachments?: UblAttachment[]) =>
93
+ (attachments ?? []).map((attachment) => ({
94
+ id: normalizeText(attachment.id),
95
+ filename: normalizeText(attachment.filename),
96
+ mime_code: normalizeText(attachment.mimeCode),
97
+ description: normalizeText(attachment.description),
98
+ size_bytes:
99
+ attachment.base64Content !== undefined
100
+ ? base64DecodedSize(attachment.base64Content)
101
+ : null,
102
+ external_uri: normalizeText(attachment.externalUri),
103
+ }));
104
+
105
+ const sanitizeAllowanceCharges = (charges?: UblAllowanceCharge[]) =>
106
+ (charges ?? []).map((charge) => ({
107
+ charge_indicator: charge.chargeIndicator,
108
+ amount: toNumberOrNull(charge.amount),
109
+ base_amount: toNumberOrNull(charge.baseAmount),
110
+ multiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),
111
+ reason: normalizeText(charge.reason),
112
+ reason_code: normalizeText(charge.reasonCode),
113
+ tax_percent: toNumberOrNull(charge.taxCategory?.percent),
114
+ tax_category_id: normalizeText(charge.taxCategory?.id),
115
+ tax_scheme_id: normalizeText(charge.taxCategory?.schemeId),
116
+ }));
117
+
118
+ const sanitizeRawUbl = (ubl: UblInvoice) => ({
119
+ ...ubl,
120
+ attachments: sanitizeAttachments(ubl.attachments),
121
+ documentReferences: ubl.documentReferences ?? [],
122
+ });
123
+
124
+ // --- Summation helpers ---
125
+
126
+ const sumTaxTotal = (ubl: UblInvoice): number | null => {
127
+ const { subtotals } = ubl.taxTotal;
128
+ const subtotalSum = subtotals.reduce(
129
+ (sum, subtotal) => sum + (subtotal.taxAmount ?? 0),
130
+ 0,
131
+ );
132
+ if (subtotals.length > 0 && Number.isFinite(subtotalSum)) {
133
+ return subtotalSum;
134
+ }
135
+ const { taxInclusiveAmount, taxExclusiveAmount } = ubl.monetaryTotal;
136
+ if (taxInclusiveAmount === undefined || taxExclusiveAmount === undefined) {
137
+ return null;
138
+ }
139
+ return taxInclusiveAmount - taxExclusiveAmount;
140
+ };
141
+
142
+ const sumAllowanceChargesByType = (
143
+ charges: UblAllowanceCharge[] | undefined,
144
+ chargeIndicator: boolean,
145
+ ) =>
146
+ (charges ?? []).reduce((sum, charge) => {
147
+ if (charge.chargeIndicator !== chargeIndicator) return sum;
148
+ return sum + Math.abs(charge.amount ?? 0);
149
+ }, 0);
150
+
151
+ // --- Public API ---
152
+
153
+ /**
154
+ * Decode raw XML bytes, stripping an optional UTF-8 BOM.
155
+ */
156
+ export const decodeXmlBytes = (bytes: Uint8Array): string => {
157
+ const text = new TextDecoder("utf-8").decode(bytes);
158
+ return text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;
159
+ };
160
+
161
+ /**
162
+ * Parse a UBL XML string and normalize it into a flat DTO suitable for
163
+ * database storage or API responses.
164
+ *
165
+ * @throws {UblParseError} when the XML is malformed, not a UBL invoice, or
166
+ * lacks a mandatory element.
167
+ */
168
+ export const normalizeUblResponse = (
169
+ xml: string,
170
+ documentId: string,
171
+ ): {
172
+ extracted: InvoiceExtractionDTO;
173
+ rawPayload: Record<string, unknown>;
174
+ } => {
175
+ const ubl = parseUblInvoice(xml);
176
+ if (!ubl) {
177
+ throw new UblParseError("Document is not a UBL Invoice or CreditNote");
178
+ }
179
+
180
+ const subtotal =
181
+ toNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ??
182
+ toNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);
183
+ const total =
184
+ toNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ??
185
+ toNumberOrNull(ubl.monetaryTotal.payableAmount);
186
+ const amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);
187
+ const prepaidAmount = toNumberOrNull(ubl.monetaryTotal.prepaidAmount);
188
+ const roundingAmount = toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount) ?? 0;
189
+ // BR-CO-16: payable = total - prepaid + rounding. With no declared
190
+ // PrepaidAmount we invert that to infer what was paid, but the rounding
191
+ // term has to come out first — a cash-rounded payable (BT-114) is a
192
+ // total-vs-payable gap by design, and reading it as a prepayment reports
193
+ // an unpaid invoice as partially settled. Rounded before the sign test so
194
+ // the float residue of undoing it cannot pass as a sub-cent prepayment.
195
+ const inferredPaid =
196
+ total !== null && amountDue !== null
197
+ ? roundToCents(total - (amountDue - roundingAmount))
198
+ : null;
199
+ const amountPaid =
200
+ prepaidAmount ??
201
+ (inferredPaid !== null && inferredPaid > 0 ? inferredPaid : null);
202
+ const taxTotal = toNumberOrNull(sumTaxTotal(ubl) ?? undefined);
203
+ const hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;
204
+ const headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);
205
+ const headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);
206
+ const currency = normalizeCurrency(ubl.currency);
207
+ const paymentTerms = normalizeText(ubl.paymentTermsNote);
208
+ const poNumber =
209
+ normalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);
210
+
211
+ const lineItems = ubl.lines.map((line) => ({
212
+ description:
213
+ normalizeText(line.description) ??
214
+ normalizeText(line.itemName) ??
215
+ "Line item",
216
+ quantity: toNumberOrNull(line.quantity),
217
+ unit: normalizeText(line.unitCode),
218
+ unit_price: toNumberOrNull(line.unitPrice),
219
+ amount: toNumberOrNull(line.lineExtensionAmount),
220
+ tax_amount: toNumberOrNull(line.taxAmount),
221
+ tax_rate: toNumberOrNull(line.taxCategory?.percent),
222
+ product_code:
223
+ normalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),
224
+ discount_amount: toNumberOrNull(line.discountAmount),
225
+ period_start: parseDate(line.invoicePeriod?.startDate),
226
+ period_end: parseDate(line.invoicePeriod?.endDate),
227
+ extra: {
228
+ ubl_line_id: normalizeText(line.id),
229
+ item_name: normalizeText(line.itemName),
230
+ sellers_item_id: normalizeText(line.sellersItemId),
231
+ buyers_item_id: normalizeText(line.buyersItemId),
232
+ tax_category_id: normalizeText(line.taxCategory?.id),
233
+ tax_scheme_id: normalizeText(line.taxCategory?.schemeId),
234
+ tax_subtotals: line.taxSubtotals ?? [],
235
+ allowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),
236
+ charge_amount: toNumberOrNull(line.chargeAmount),
237
+ metadata: line.additionalItemProperties
238
+ ? Object.fromEntries(
239
+ line.additionalItemProperties.map((p) => [p.name, p.value]),
240
+ )
241
+ : null,
242
+ },
243
+ }));
244
+
245
+ const supplierAddress = addressToString(ubl.seller.address);
246
+ const receiverAddress = addressToString(ubl.buyer.address);
247
+ const supplierAddressStructured = addressToStructured(ubl.seller.address);
248
+ const receiverAddressStructured = addressToStructured(ubl.buyer.address);
249
+ const attachmentMetadata = sanitizeAttachments(ubl.attachments);
250
+ const paymentMeansList =
251
+ ubl.paymentMeansList && ubl.paymentMeansList.length > 0
252
+ ? ubl.paymentMeansList
253
+ : ubl.paymentMeans
254
+ ? [ubl.paymentMeans]
255
+ : [];
256
+
257
+ const extracted: InvoiceExtractionDTO = {
258
+ provider: "ubl_xml",
259
+ document_id: documentId,
260
+ invoice: {
261
+ invoice_number: normalizeText(ubl.id),
262
+ invoice_date: parseDate(ubl.issueDate),
263
+ due_date: parseDate(ubl.dueDate),
264
+ period_start: parseDate(ubl.invoicePeriod?.startDate),
265
+ period_end: parseDate(ubl.invoicePeriod?.endDate),
266
+ currency,
267
+ subtotal,
268
+ tax_total: taxTotal,
269
+ total,
270
+ amount_due: amountDue,
271
+ amount_paid: amountPaid,
272
+ discount_total:
273
+ toNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ??
274
+ (hasHeaderAllowanceCharges
275
+ ? toNumberOrNull(headerDiscountTotal)
276
+ : null),
277
+ shipping_total:
278
+ toNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ??
279
+ (hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),
280
+ rounding_total: toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount),
281
+ payment_terms: paymentTerms,
282
+ po_number: poNumber,
283
+ supplier: {
284
+ name:
285
+ normalizeText(ubl.seller.name) ??
286
+ normalizeText(ubl.seller.registrationName),
287
+ address: supplierAddress,
288
+ tax_id:
289
+ normalizeText(ubl.seller.vatId) ??
290
+ normalizeText(ubl.seller.companyId?.value),
291
+ iban: normalizeText(ubl.paymentMeans?.iban),
292
+ bic: normalizeText(ubl.paymentMeans?.bic),
293
+ },
294
+ receiver: {
295
+ name:
296
+ normalizeText(ubl.buyer.name) ??
297
+ normalizeText(ubl.buyer.registrationName),
298
+ address: receiverAddress,
299
+ tax_id:
300
+ normalizeText(ubl.buyer.vatId) ??
301
+ normalizeText(ubl.buyer.companyId?.value),
302
+ },
303
+ extra: {
304
+ document_type: ubl.documentType,
305
+ customization_id: normalizeText(ubl.customizationId),
306
+ profile_id: normalizeText(ubl.profileId),
307
+ invoice_type_code: normalizeText(ubl.invoiceTypeCode),
308
+ buyer_reference: normalizeText(ubl.buyerReference),
309
+ order_reference_id: normalizeText(ubl.orderReference),
310
+ sales_order_id: normalizeText(ubl.salesOrderId),
311
+ contract_reference: normalizeText(ubl.contractReference),
312
+ project_reference: normalizeText(ubl.projectReference),
313
+ billing_reference: ubl.billingReference
314
+ ? {
315
+ invoice_id: normalizeText(ubl.billingReference.invoiceId),
316
+ invoice_issue_date: parseDate(
317
+ ubl.billingReference.invoiceIssueDate,
318
+ ),
319
+ }
320
+ : null,
321
+ tax_point_date: parseDate(ubl.taxPointDate),
322
+ invoice_period: ubl.invoicePeriod ?? null,
323
+ note: normalizeText(ubl.note),
324
+ payment_means: ubl.paymentMeans
325
+ ? sanitizePaymentMeans(ubl.paymentMeans)
326
+ : null,
327
+ payment_means_list: paymentMeansList.map(sanitizePaymentMeans),
328
+ delivery: ubl.delivery
329
+ ? {
330
+ actual_delivery_date: parseDate(
331
+ ubl.delivery.actualDeliveryDate,
332
+ ),
333
+ address: addressToStructured(ubl.delivery.address),
334
+ }
335
+ : null,
336
+ supplier: {
337
+ endpoint_id: normalizeText(ubl.seller.endpoint?.value),
338
+ endpoint_scheme_id: normalizeText(ubl.seller.endpoint?.scheme),
339
+ registration_name: normalizeText(ubl.seller.registrationName),
340
+ company_legal_form: normalizeText(ubl.seller.companyLegalForm),
341
+ company_id_scheme_id: normalizeText(ubl.seller.companyId?.scheme),
342
+ tax_scheme_id: normalizeText(ubl.seller.taxSchemeId),
343
+ party_identifications: ubl.seller.partyIdentifications ?? [],
344
+ contact_name: normalizeText(ubl.seller.contact?.name),
345
+ contact_phone: normalizeText(ubl.seller.contact?.phone),
346
+ contact_email: normalizeText(ubl.seller.contact?.email),
347
+ },
348
+ receiver: {
349
+ endpoint_id: normalizeText(ubl.buyer.endpoint?.value),
350
+ endpoint_scheme_id: normalizeText(ubl.buyer.endpoint?.scheme),
351
+ registration_name: normalizeText(ubl.buyer.registrationName),
352
+ company_legal_form: normalizeText(ubl.buyer.companyLegalForm),
353
+ company_id_scheme_id: normalizeText(ubl.buyer.companyId?.scheme),
354
+ tax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),
355
+ party_identifications: ubl.buyer.partyIdentifications ?? [],
356
+ contact_name: normalizeText(ubl.buyer.contact?.name),
357
+ contact_phone: normalizeText(ubl.buyer.contact?.phone),
358
+ contact_email: normalizeText(ubl.buyer.contact?.email),
359
+ },
360
+ supplier_address_structured: supplierAddressStructured,
361
+ receiver_address_structured: receiverAddressStructured,
362
+ tax_subtotals: ubl.taxTotal.subtotals,
363
+ allowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),
364
+ attachments: attachmentMetadata,
365
+ document_references: ubl.documentReferences ?? [],
366
+ },
367
+ },
368
+ line_items: lineItems,
369
+ confidence: {
370
+ overall: 1,
371
+ fields: {
372
+ invoice_id: 1,
373
+ invoice_date: 1,
374
+ due_date: 1,
375
+ total_amount: 1,
376
+ supplier_name: 1,
377
+ },
378
+ },
379
+ };
380
+
381
+ return {
382
+ extracted,
383
+ rawPayload: {
384
+ format: "ubl_xml",
385
+ invoice: sanitizeRawUbl(ubl),
386
+ },
387
+ };
388
+ };
389
+
390
+ /**
391
+ * Parse a UBL invoice from raw bytes and normalize it into a DTO.
392
+ */
393
+ export const parseUblInvoiceDocument = (params: {
394
+ bytes: Uint8Array;
395
+ documentId: string;
396
+ mimeType: string;
397
+ }) => {
398
+ const xml = decodeXmlBytes(params.bytes);
399
+ const { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);
400
+ return {
401
+ rawPayload: {
402
+ ...rawPayload,
403
+ mime_type: params.mimeType,
404
+ },
405
+ extracted,
406
+ providerJobId: null as string | null,
407
+ };
408
+ };