@financica/ubl 0.15.1 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +161 -0
- package/dist/build/index.d.ts +76 -40
- package/dist/build/index.d.ts.map +1 -1
- package/dist/build/index.js +54 -108
- package/dist/build/index.js.map +1 -1
- package/dist/index.d.ts +149 -121
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +277 -233
- package/dist/index.js.map +1 -1
- package/package.json +16 -7
- package/src/attachments.ts +67 -0
- package/src/build/address.ts +64 -0
- package/src/build/attachment.ts +33 -0
- package/src/build/identifiers.ts +253 -0
- package/src/build/index.ts +69 -0
- package/src/build/numeric.ts +41 -0
- package/src/build/party.ts +127 -0
- package/src/build/tax-category.ts +152 -0
- package/src/build/tax-totals.ts +143 -0
- package/src/build/ubl/constants.ts +30 -0
- package/src/build/ubl/serialize.ts +258 -0
- package/src/build/ubl/types.ts +179 -0
- package/src/build/utils.ts +6 -0
- package/src/build/xml.ts +84 -0
- package/src/errors.ts +15 -0
- package/src/index.ts +40 -0
- package/src/mlr.ts +156 -0
- package/src/normalize.ts +407 -0
- package/src/parser.ts +596 -0
- package/src/types.ts +234 -0
- package/src/xml-dom.ts +37 -0
package/src/errors.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown by the parse side of this package when input is broken: malformed
|
|
3
|
+
* XML, or a UBL document missing an element EN 16931 makes mandatory. A parser
|
|
4
|
+
* returns `null` instead when the input is well-formed but not the document
|
|
5
|
+
* type it parses.
|
|
6
|
+
*/
|
|
7
|
+
export class UblParseError extends Error {
|
|
8
|
+
override readonly cause?: unknown;
|
|
9
|
+
|
|
10
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "UblParseError";
|
|
13
|
+
if (options && "cause" in options) this.cause = options.cause;
|
|
14
|
+
}
|
|
15
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export {
|
|
2
|
+
extractUblEmbeddedAttachments,
|
|
3
|
+
isPdfLikeAttachment,
|
|
4
|
+
type UblEmbeddedAttachment,
|
|
5
|
+
} from "./attachments.js";
|
|
6
|
+
export { UblParseError } from "./errors.js";
|
|
7
|
+
export { parseUblInvoice } from "./parser.js";
|
|
8
|
+
export {
|
|
9
|
+
isPeppolMessageLevelResponse,
|
|
10
|
+
parsePeppolMessageLevelResponse,
|
|
11
|
+
PEPPOL_MLR_DOCUMENT_TYPE_VALUE,
|
|
12
|
+
PEPPOL_MLR_PROCESS_VALUE,
|
|
13
|
+
type PeppolMessageLevelResponse,
|
|
14
|
+
} from "./mlr.js";
|
|
15
|
+
export {
|
|
16
|
+
decodeXmlBytes,
|
|
17
|
+
normalizeCurrency,
|
|
18
|
+
normalizeUblResponse,
|
|
19
|
+
parseDate,
|
|
20
|
+
parseUblInvoiceDocument,
|
|
21
|
+
} from "./normalize.js";
|
|
22
|
+
export type {
|
|
23
|
+
InvoiceExtractionDTO,
|
|
24
|
+
UblAddress,
|
|
25
|
+
UblAllowanceCharge,
|
|
26
|
+
UblAttachment,
|
|
27
|
+
UblBillingReference,
|
|
28
|
+
UblContact,
|
|
29
|
+
UblDelivery,
|
|
30
|
+
UblDocumentReference,
|
|
31
|
+
UblInvoice,
|
|
32
|
+
UblInvoicePeriod,
|
|
33
|
+
UblItemProperty,
|
|
34
|
+
UblLine,
|
|
35
|
+
UblMonetaryTotal,
|
|
36
|
+
UblParty,
|
|
37
|
+
UblPartyIdentification,
|
|
38
|
+
UblPaymentMeans,
|
|
39
|
+
UblTaxSubtotal,
|
|
40
|
+
} from "./types.js";
|
package/src/mlr.ts
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { UblParseError } from "./errors.js";
|
|
3
|
+
import { CAC_NS, CBC_NS, parseXmlDocument } from "./xml-dom.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Peppol BIS MLR (Message Level Response) document-type identifier value
|
|
7
|
+
* (Peppol `busdox-docid-qns` scheme).
|
|
8
|
+
*/
|
|
9
|
+
export const PEPPOL_MLR_DOCUMENT_TYPE_VALUE =
|
|
10
|
+
"urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1";
|
|
11
|
+
|
|
12
|
+
/** Peppol BIS MLR process identifier value. */
|
|
13
|
+
export const PEPPOL_MLR_PROCESS_VALUE = "urn:fdc:peppol.eu:poacc:bis:mlr:3";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A parsed Peppol Message Level Response (a UBL `ApplicationResponse`). Every
|
|
17
|
+
* field is optional: a given MLR may omit any of them, and an omitted field is
|
|
18
|
+
* an absent key.
|
|
19
|
+
*/
|
|
20
|
+
export interface PeppolMessageLevelResponse {
|
|
21
|
+
customizationId?: string | undefined;
|
|
22
|
+
profileId?: string | undefined;
|
|
23
|
+
responseId?: string | undefined;
|
|
24
|
+
issueDate?: string | undefined;
|
|
25
|
+
issueTime?: string | undefined;
|
|
26
|
+
referencedDocumentId?: string | undefined;
|
|
27
|
+
responseCode?: string | undefined;
|
|
28
|
+
description?: string | undefined;
|
|
29
|
+
/** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */
|
|
30
|
+
senderIdentifier?: string | undefined;
|
|
31
|
+
/** Receiver participant id as `schemeID:value`. */
|
|
32
|
+
receiverIdentifier?: string | undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const trimmed = (value: string | null | undefined): string | undefined => {
|
|
36
|
+
const text = value?.trim();
|
|
37
|
+
return text ? text : undefined;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** First descendant CBC element's trimmed text, or undefined. */
|
|
41
|
+
const cbcText = (parent: Element, tag: string): string | undefined =>
|
|
42
|
+
trimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* First direct-child CBC element's trimmed text, or null. Used for the
|
|
46
|
+
* top-level scalars so a nested `cbc:ID` (e.g. inside DocumentReference) cannot
|
|
47
|
+
* shadow the ApplicationResponse's own id.
|
|
48
|
+
*/
|
|
49
|
+
const cbcDirectText = (parent: Element, tag: string): string | undefined => {
|
|
50
|
+
for (let i = 0; i < parent.childNodes.length; i++) {
|
|
51
|
+
const node = parent.childNodes[i];
|
|
52
|
+
if (!node || node.nodeType !== 1) continue;
|
|
53
|
+
const el = node as Element;
|
|
54
|
+
if (el.namespaceURI === CBC_NS && el.localName === tag) {
|
|
55
|
+
return trimmed(el.textContent);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return undefined;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** First descendant CAC element, or null. */
|
|
62
|
+
const cacElement = (parent: Element, tag: string): Element | null =>
|
|
63
|
+
parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The Peppol participant identifier of a SenderParty / ReceiverParty, rendered
|
|
67
|
+
* as `schemeID:value` when the EndpointID carries a scheme and the value does
|
|
68
|
+
* not already include one, otherwise the raw value.
|
|
69
|
+
*/
|
|
70
|
+
const endpointIdentifier = (party: Element | null): string | undefined => {
|
|
71
|
+
if (!party) return undefined;
|
|
72
|
+
const endpoint = party.getElementsByTagNameNS(CBC_NS, "EndpointID")[0];
|
|
73
|
+
if (!endpoint) return undefined;
|
|
74
|
+
const id = trimmed(endpoint.textContent);
|
|
75
|
+
const scheme = endpoint.getAttribute("schemeID");
|
|
76
|
+
if (scheme && id && !id.includes(":")) return `${scheme}:${id}`;
|
|
77
|
+
return id;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Locate the `ApplicationResponse` element, unwrapping a Standard Business
|
|
82
|
+
* Document (SBDH) envelope when present. Returns null when the XML contains no
|
|
83
|
+
* ApplicationResponse; throws {@link UblParseError} when it is malformed.
|
|
84
|
+
*/
|
|
85
|
+
const findApplicationResponse = (xml: string): Element | null => {
|
|
86
|
+
const doc = parseXmlDocument(xml);
|
|
87
|
+
const root = doc.documentElement;
|
|
88
|
+
if (!root) return null;
|
|
89
|
+
if (root.localName === "ApplicationResponse") return root;
|
|
90
|
+
const candidates = root.getElementsByTagName("*");
|
|
91
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
92
|
+
const el = candidates[i];
|
|
93
|
+
if (el?.localName === "ApplicationResponse") return el;
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Whether an inbound document is a Peppol Message Level Response, identified by
|
|
100
|
+
* its document-type value, its process value, or by parsing the XML and finding
|
|
101
|
+
* an `ApplicationResponse` root (SBDH-wrapped or not).
|
|
102
|
+
*/
|
|
103
|
+
export const isPeppolMessageLevelResponse = (params: {
|
|
104
|
+
documentTypeValue?: string | null;
|
|
105
|
+
processValue?: string | null;
|
|
106
|
+
xml?: string | null;
|
|
107
|
+
}): boolean => {
|
|
108
|
+
if (trimmed(params.documentTypeValue) === PEPPOL_MLR_DOCUMENT_TYPE_VALUE) {
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
if (trimmed(params.processValue) === PEPPOL_MLR_PROCESS_VALUE) return true;
|
|
112
|
+
const xml = trimmed(params.xml);
|
|
113
|
+
if (!xml) return false;
|
|
114
|
+
try {
|
|
115
|
+
return findApplicationResponse(xml) !== null;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
// A sniff answers "is this an MLR?"; malformed XML is simply "no".
|
|
118
|
+
if (error instanceof UblParseError) return false;
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping
|
|
125
|
+
* an SBDH envelope when present. Throws {@link UblParseError} when the XML is
|
|
126
|
+
* malformed or is not an ApplicationResponse.
|
|
127
|
+
*/
|
|
128
|
+
export const parsePeppolMessageLevelResponse = (
|
|
129
|
+
xml: string,
|
|
130
|
+
): PeppolMessageLevelResponse => {
|
|
131
|
+
const root = findApplicationResponse(xml);
|
|
132
|
+
if (!root) {
|
|
133
|
+
throw new UblParseError("Document is not a Peppol Message Level Response");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const documentResponse = cacElement(root, "DocumentResponse");
|
|
137
|
+
const response = documentResponse ? cacElement(documentResponse, "Response") : null;
|
|
138
|
+
const documentReference = documentResponse
|
|
139
|
+
? cacElement(documentResponse, "DocumentReference")
|
|
140
|
+
: null;
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
customizationId: cbcDirectText(root, "CustomizationID"),
|
|
144
|
+
profileId: cbcDirectText(root, "ProfileID"),
|
|
145
|
+
responseId: cbcDirectText(root, "ID"),
|
|
146
|
+
issueDate: cbcDirectText(root, "IssueDate"),
|
|
147
|
+
issueTime: cbcDirectText(root, "IssueTime"),
|
|
148
|
+
referencedDocumentId: documentReference
|
|
149
|
+
? cbcText(documentReference, "ID")
|
|
150
|
+
: undefined,
|
|
151
|
+
responseCode: response ? cbcText(response, "ResponseCode") : undefined,
|
|
152
|
+
description: response ? cbcText(response, "Description") : undefined,
|
|
153
|
+
senderIdentifier: endpointIdentifier(cacElement(root, "SenderParty")),
|
|
154
|
+
receiverIdentifier: endpointIdentifier(cacElement(root, "ReceiverParty")),
|
|
155
|
+
};
|
|
156
|
+
};
|
package/src/normalize.ts
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
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.taxPercent),
|
|
114
|
+
tax_category_id: normalizeText(charge.taxCategoryId),
|
|
115
|
+
tax_scheme_id: normalizeText(charge.taxSchemeId),
|
|
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 subtotalSum = ubl.taxSubtotals.reduce(
|
|
128
|
+
(sum, subtotal) => sum + (subtotal.taxAmount ?? 0),
|
|
129
|
+
0,
|
|
130
|
+
);
|
|
131
|
+
if (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) {
|
|
132
|
+
return subtotalSum;
|
|
133
|
+
}
|
|
134
|
+
const { taxInclusiveAmount, taxExclusiveAmount } = ubl.monetaryTotal;
|
|
135
|
+
if (taxInclusiveAmount === undefined || taxExclusiveAmount === undefined) {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
return taxInclusiveAmount - taxExclusiveAmount;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const sumAllowanceChargesByType = (
|
|
142
|
+
charges: UblAllowanceCharge[] | undefined,
|
|
143
|
+
chargeIndicator: boolean,
|
|
144
|
+
) =>
|
|
145
|
+
(charges ?? []).reduce((sum, charge) => {
|
|
146
|
+
if (charge.chargeIndicator !== chargeIndicator) return sum;
|
|
147
|
+
return sum + Math.abs(charge.amount ?? 0);
|
|
148
|
+
}, 0);
|
|
149
|
+
|
|
150
|
+
// --- Public API ---
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Decode raw XML bytes, stripping an optional UTF-8 BOM.
|
|
154
|
+
*/
|
|
155
|
+
export const decodeXmlBytes = (bytes: Uint8Array): string => {
|
|
156
|
+
const text = new TextDecoder("utf-8").decode(bytes);
|
|
157
|
+
return text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Parse a UBL XML string and normalize it into a flat DTO suitable for
|
|
162
|
+
* database storage or API responses.
|
|
163
|
+
*
|
|
164
|
+
* @throws {UblParseError} when the XML is malformed, not a UBL invoice, or
|
|
165
|
+
* lacks a mandatory element.
|
|
166
|
+
*/
|
|
167
|
+
export const normalizeUblResponse = (
|
|
168
|
+
xml: string,
|
|
169
|
+
documentId: string,
|
|
170
|
+
): {
|
|
171
|
+
extracted: InvoiceExtractionDTO;
|
|
172
|
+
rawPayload: Record<string, unknown>;
|
|
173
|
+
} => {
|
|
174
|
+
const ubl = parseUblInvoice(xml);
|
|
175
|
+
if (!ubl) {
|
|
176
|
+
throw new UblParseError("Document is not a UBL Invoice or CreditNote");
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const subtotal =
|
|
180
|
+
toNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ??
|
|
181
|
+
toNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);
|
|
182
|
+
const total =
|
|
183
|
+
toNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ??
|
|
184
|
+
toNumberOrNull(ubl.monetaryTotal.payableAmount);
|
|
185
|
+
const amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);
|
|
186
|
+
const prepaidAmount = toNumberOrNull(ubl.monetaryTotal.prepaidAmount);
|
|
187
|
+
const roundingAmount = toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount) ?? 0;
|
|
188
|
+
// BR-CO-16: payable = total - prepaid + rounding. With no declared
|
|
189
|
+
// PrepaidAmount we invert that to infer what was paid, but the rounding
|
|
190
|
+
// term has to come out first — a cash-rounded payable (BT-114) is a
|
|
191
|
+
// total-vs-payable gap by design, and reading it as a prepayment reports
|
|
192
|
+
// an unpaid invoice as partially settled. Rounded before the sign test so
|
|
193
|
+
// the float residue of undoing it cannot pass as a sub-cent prepayment.
|
|
194
|
+
const inferredPaid =
|
|
195
|
+
total !== null && amountDue !== null
|
|
196
|
+
? roundToCents(total - (amountDue - roundingAmount))
|
|
197
|
+
: null;
|
|
198
|
+
const amountPaid =
|
|
199
|
+
prepaidAmount ??
|
|
200
|
+
(inferredPaid !== null && inferredPaid > 0 ? inferredPaid : null);
|
|
201
|
+
const taxTotal = toNumberOrNull(sumTaxTotal(ubl) ?? undefined);
|
|
202
|
+
const hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;
|
|
203
|
+
const headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);
|
|
204
|
+
const headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);
|
|
205
|
+
const currency = normalizeCurrency(ubl.currency);
|
|
206
|
+
const paymentTerms = normalizeText(ubl.paymentTermsNote);
|
|
207
|
+
const poNumber =
|
|
208
|
+
normalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);
|
|
209
|
+
|
|
210
|
+
const lineItems = ubl.lines.map((line) => ({
|
|
211
|
+
description:
|
|
212
|
+
normalizeText(line.description) ??
|
|
213
|
+
normalizeText(line.itemName) ??
|
|
214
|
+
"Line item",
|
|
215
|
+
quantity: toNumberOrNull(line.quantity),
|
|
216
|
+
unit: normalizeText(line.unitCode),
|
|
217
|
+
unit_price: toNumberOrNull(line.unitPrice),
|
|
218
|
+
amount: toNumberOrNull(line.lineExtensionAmount),
|
|
219
|
+
tax_amount: toNumberOrNull(line.taxAmount),
|
|
220
|
+
tax_rate: toNumberOrNull(line.taxPercent),
|
|
221
|
+
product_code:
|
|
222
|
+
normalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),
|
|
223
|
+
discount_amount: toNumberOrNull(line.discountAmount),
|
|
224
|
+
period_start: parseDate(line.invoicePeriod?.startDate),
|
|
225
|
+
period_end: parseDate(line.invoicePeriod?.endDate),
|
|
226
|
+
extra: {
|
|
227
|
+
ubl_line_id: normalizeText(line.id),
|
|
228
|
+
item_name: normalizeText(line.itemName),
|
|
229
|
+
sellers_item_id: normalizeText(line.sellersItemId),
|
|
230
|
+
buyers_item_id: normalizeText(line.buyersItemId),
|
|
231
|
+
tax_category_id: normalizeText(line.taxCategoryId),
|
|
232
|
+
tax_scheme_id: normalizeText(line.taxSchemeId),
|
|
233
|
+
tax_subtotals: line.taxSubtotals ?? [],
|
|
234
|
+
allowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),
|
|
235
|
+
charge_amount: toNumberOrNull(line.chargeAmount),
|
|
236
|
+
metadata: line.additionalItemProperties
|
|
237
|
+
? Object.fromEntries(
|
|
238
|
+
line.additionalItemProperties.map((p) => [p.name, p.value]),
|
|
239
|
+
)
|
|
240
|
+
: null,
|
|
241
|
+
},
|
|
242
|
+
}));
|
|
243
|
+
|
|
244
|
+
const supplierAddress = addressToString(ubl.seller.address);
|
|
245
|
+
const receiverAddress = addressToString(ubl.buyer.address);
|
|
246
|
+
const supplierAddressStructured = addressToStructured(ubl.seller.address);
|
|
247
|
+
const receiverAddressStructured = addressToStructured(ubl.buyer.address);
|
|
248
|
+
const attachmentMetadata = sanitizeAttachments(ubl.attachments);
|
|
249
|
+
const paymentMeansList =
|
|
250
|
+
ubl.paymentMeansList && ubl.paymentMeansList.length > 0
|
|
251
|
+
? ubl.paymentMeansList
|
|
252
|
+
: ubl.paymentMeans
|
|
253
|
+
? [ubl.paymentMeans]
|
|
254
|
+
: [];
|
|
255
|
+
|
|
256
|
+
const extracted: InvoiceExtractionDTO = {
|
|
257
|
+
provider: "ubl_xml",
|
|
258
|
+
document_id: documentId,
|
|
259
|
+
invoice: {
|
|
260
|
+
invoice_number: normalizeText(ubl.id),
|
|
261
|
+
invoice_date: parseDate(ubl.issueDate),
|
|
262
|
+
due_date: parseDate(ubl.dueDate),
|
|
263
|
+
period_start: parseDate(ubl.invoicePeriod?.startDate),
|
|
264
|
+
period_end: parseDate(ubl.invoicePeriod?.endDate),
|
|
265
|
+
currency,
|
|
266
|
+
subtotal,
|
|
267
|
+
tax_total: taxTotal,
|
|
268
|
+
total,
|
|
269
|
+
amount_due: amountDue,
|
|
270
|
+
amount_paid: amountPaid,
|
|
271
|
+
discount_total:
|
|
272
|
+
toNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ??
|
|
273
|
+
(hasHeaderAllowanceCharges
|
|
274
|
+
? toNumberOrNull(headerDiscountTotal)
|
|
275
|
+
: null),
|
|
276
|
+
shipping_total:
|
|
277
|
+
toNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ??
|
|
278
|
+
(hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),
|
|
279
|
+
rounding_total: toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount),
|
|
280
|
+
payment_terms: paymentTerms,
|
|
281
|
+
po_number: poNumber,
|
|
282
|
+
supplier: {
|
|
283
|
+
name:
|
|
284
|
+
normalizeText(ubl.seller.name) ??
|
|
285
|
+
normalizeText(ubl.seller.registrationName),
|
|
286
|
+
address: supplierAddress,
|
|
287
|
+
tax_id:
|
|
288
|
+
normalizeText(ubl.seller.vatId) ??
|
|
289
|
+
normalizeText(ubl.seller.companyId),
|
|
290
|
+
iban: normalizeText(ubl.paymentMeans?.iban),
|
|
291
|
+
bic: normalizeText(ubl.paymentMeans?.bic),
|
|
292
|
+
},
|
|
293
|
+
receiver: {
|
|
294
|
+
name:
|
|
295
|
+
normalizeText(ubl.buyer.name) ??
|
|
296
|
+
normalizeText(ubl.buyer.registrationName),
|
|
297
|
+
address: receiverAddress,
|
|
298
|
+
tax_id:
|
|
299
|
+
normalizeText(ubl.buyer.vatId) ??
|
|
300
|
+
normalizeText(ubl.buyer.companyId),
|
|
301
|
+
},
|
|
302
|
+
extra: {
|
|
303
|
+
document_type: ubl.documentType,
|
|
304
|
+
customization_id: normalizeText(ubl.customizationId),
|
|
305
|
+
profile_id: normalizeText(ubl.profileId),
|
|
306
|
+
invoice_type_code: normalizeText(ubl.invoiceTypeCode),
|
|
307
|
+
buyer_reference: normalizeText(ubl.buyerReference),
|
|
308
|
+
order_reference_id: normalizeText(ubl.orderReference),
|
|
309
|
+
sales_order_id: normalizeText(ubl.salesOrderId),
|
|
310
|
+
contract_reference: normalizeText(ubl.contractReference),
|
|
311
|
+
project_reference: normalizeText(ubl.projectReference),
|
|
312
|
+
billing_reference: ubl.billingReference
|
|
313
|
+
? {
|
|
314
|
+
invoice_id: normalizeText(ubl.billingReference.invoiceId),
|
|
315
|
+
invoice_issue_date: parseDate(
|
|
316
|
+
ubl.billingReference.invoiceIssueDate,
|
|
317
|
+
),
|
|
318
|
+
}
|
|
319
|
+
: null,
|
|
320
|
+
tax_point_date: parseDate(ubl.taxPointDate),
|
|
321
|
+
invoice_period: ubl.invoicePeriod ?? null,
|
|
322
|
+
note: normalizeText(ubl.note),
|
|
323
|
+
payment_means: ubl.paymentMeans
|
|
324
|
+
? sanitizePaymentMeans(ubl.paymentMeans)
|
|
325
|
+
: null,
|
|
326
|
+
payment_means_list: paymentMeansList.map(sanitizePaymentMeans),
|
|
327
|
+
delivery: ubl.delivery
|
|
328
|
+
? {
|
|
329
|
+
actual_delivery_date: parseDate(
|
|
330
|
+
ubl.delivery.actualDeliveryDate,
|
|
331
|
+
),
|
|
332
|
+
address: addressToStructured(ubl.delivery.address),
|
|
333
|
+
}
|
|
334
|
+
: null,
|
|
335
|
+
supplier: {
|
|
336
|
+
endpoint_id: normalizeText(ubl.seller.endpointId),
|
|
337
|
+
endpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),
|
|
338
|
+
registration_name: normalizeText(ubl.seller.registrationName),
|
|
339
|
+
company_legal_form: normalizeText(ubl.seller.companyLegalForm),
|
|
340
|
+
company_id_scheme_id: normalizeText(ubl.seller.companyIdSchemeId),
|
|
341
|
+
tax_scheme_id: normalizeText(ubl.seller.taxSchemeId),
|
|
342
|
+
party_identifications: ubl.seller.partyIdentifications ?? [],
|
|
343
|
+
contact_name: normalizeText(ubl.seller.contact?.name),
|
|
344
|
+
contact_phone: normalizeText(ubl.seller.contact?.phone),
|
|
345
|
+
contact_email: normalizeText(ubl.seller.contact?.email),
|
|
346
|
+
},
|
|
347
|
+
receiver: {
|
|
348
|
+
endpoint_id: normalizeText(ubl.buyer.endpointId),
|
|
349
|
+
endpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),
|
|
350
|
+
registration_name: normalizeText(ubl.buyer.registrationName),
|
|
351
|
+
company_legal_form: normalizeText(ubl.buyer.companyLegalForm),
|
|
352
|
+
company_id_scheme_id: normalizeText(ubl.buyer.companyIdSchemeId),
|
|
353
|
+
tax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),
|
|
354
|
+
party_identifications: ubl.buyer.partyIdentifications ?? [],
|
|
355
|
+
contact_name: normalizeText(ubl.buyer.contact?.name),
|
|
356
|
+
contact_phone: normalizeText(ubl.buyer.contact?.phone),
|
|
357
|
+
contact_email: normalizeText(ubl.buyer.contact?.email),
|
|
358
|
+
},
|
|
359
|
+
supplier_address_structured: supplierAddressStructured,
|
|
360
|
+
receiver_address_structured: receiverAddressStructured,
|
|
361
|
+
tax_subtotals: ubl.taxSubtotals,
|
|
362
|
+
allowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),
|
|
363
|
+
attachments: attachmentMetadata,
|
|
364
|
+
document_references: ubl.documentReferences ?? [],
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
line_items: lineItems,
|
|
368
|
+
confidence: {
|
|
369
|
+
overall: 1,
|
|
370
|
+
fields: {
|
|
371
|
+
invoice_id: 1,
|
|
372
|
+
invoice_date: 1,
|
|
373
|
+
due_date: 1,
|
|
374
|
+
total_amount: 1,
|
|
375
|
+
supplier_name: 1,
|
|
376
|
+
},
|
|
377
|
+
},
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
return {
|
|
381
|
+
extracted,
|
|
382
|
+
rawPayload: {
|
|
383
|
+
format: "ubl_xml",
|
|
384
|
+
invoice: sanitizeRawUbl(ubl),
|
|
385
|
+
},
|
|
386
|
+
};
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Parse a UBL invoice from raw bytes and normalize it into a DTO.
|
|
391
|
+
*/
|
|
392
|
+
export const parseUblInvoiceDocument = (params: {
|
|
393
|
+
bytes: Uint8Array;
|
|
394
|
+
documentId: string;
|
|
395
|
+
mimeType: string;
|
|
396
|
+
}) => {
|
|
397
|
+
const xml = decodeXmlBytes(params.bytes);
|
|
398
|
+
const { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);
|
|
399
|
+
return {
|
|
400
|
+
rawPayload: {
|
|
401
|
+
...rawPayload,
|
|
402
|
+
mime_type: params.mimeType,
|
|
403
|
+
},
|
|
404
|
+
extracted,
|
|
405
|
+
providerJobId: null as string | null,
|
|
406
|
+
};
|
|
407
|
+
};
|