@financica/ubl 0.15.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/types.ts ADDED
@@ -0,0 +1,398 @@
1
+ // --- UBL document model ---
2
+ //
3
+ // One model, used by the parser, the serializer and the build helpers. It is a
4
+ // vendor-neutral mirror of the UBL 2.1 / Peppol BIS Billing 3.0 fields this
5
+ // package reads and writes, not a full UBL object graph.
6
+ //
7
+ // The parser reads everything the document states: a field the document omits
8
+ // is an absent key (never `""`/`0`/`"S"` to fill a gap). Only the fields
9
+ // EN 16931 makes mandatory for *parsing* (document id, issue date, currency,
10
+ // line id) are required on the type; a document that lacks one is rejected
11
+ // with `UblParseError`. Containers the consumer iterates (`lines`,
12
+ // `taxTotal.subtotals`) and the `seller`/`buyer`/`taxTotal`/`monetaryTotal`
13
+ // objects are always present.
14
+ //
15
+ // The serializer is the validator: `serializeUblInvoice` throws `UblBuildError`
16
+ // when a field EN 16931 / Peppol BIS makes mandatory on the wire is missing.
17
+
18
+ export interface UblAddress {
19
+ /** `cbc:StreetName` (BT-35). */
20
+ street?: string | undefined;
21
+ /** `cbc:AdditionalStreetName` (BT-36). */
22
+ additionalStreet?: string | undefined;
23
+ /** `cbc:CityName` (BT-37). */
24
+ city?: string | undefined;
25
+ /** `cbc:PostalZone` (BT-38). */
26
+ postalZone?: string | undefined;
27
+ /** `cbc:CountrySubentity` (BT-39). */
28
+ countrySubentity?: string | undefined;
29
+ /** `cac:Country/cbc:IdentificationCode` (BT-40) — ISO 3166-1 alpha-2. */
30
+ countryCode?: string | undefined;
31
+ }
32
+
33
+ export interface UblContact {
34
+ /** `cac:Contact/cbc:Name` (BT-41/BT-56). */
35
+ name?: string | undefined;
36
+ /** `cac:Contact/cbc:Telephone` (BT-42/BT-57). */
37
+ phone?: string | undefined;
38
+ /** `cac:Contact/cbc:ElectronicMail` (BT-43/BT-58). */
39
+ email?: string | undefined;
40
+ }
41
+
42
+ /**
43
+ * Peppol participant identifier (`cbc:EndpointID` + `@schemeID`), e.g. scheme
44
+ * `0208`, value `0800279001`. A document may state the value without a scheme;
45
+ * the serializer requires both.
46
+ */
47
+ export interface UblEndpoint {
48
+ value: string;
49
+ /** EAS scheme (`@schemeID`), e.g. `0208`. */
50
+ scheme?: string | undefined;
51
+ }
52
+
53
+ /**
54
+ * Legal registration identifier (`cac:PartyLegalEntity/cbc:CompanyID` +
55
+ * `@schemeID`), e.g. a Belgian enterprise number.
56
+ */
57
+ export interface UblCompanyId {
58
+ value: string;
59
+ /** ISO 6523 ICD scheme (`@schemeID`, e.g. `0208` for the Belgian CBE), when known. */
60
+ scheme?: string | undefined;
61
+ }
62
+
63
+ /** `cac:PartyIdentification/cbc:ID` (BT-29/BT-46) with its `@schemeID`. */
64
+ export interface UblPartyIdentification {
65
+ id: string;
66
+ schemeId?: string | undefined;
67
+ }
68
+
69
+ export interface UblParty {
70
+ /** `cac:PartyName/cbc:Name` (BT-28/BT-45). */
71
+ name?: string | undefined;
72
+ /** `cac:PartyLegalEntity/cbc:RegistrationName` (BT-27/BT-44). */
73
+ registrationName?: string | undefined;
74
+ /** `cac:PartyLegalEntity/cbc:CompanyLegalForm` (BT-33). */
75
+ companyLegalForm?: string | undefined;
76
+ /** `cac:PartyTaxScheme/cbc:CompanyID` (BT-31/BT-48) — the VAT identifier. */
77
+ vatId?: string | undefined;
78
+ /** `cac:PartyTaxScheme/cac:TaxScheme/cbc:ID`, normally `VAT`. */
79
+ taxSchemeId?: string | undefined;
80
+ /** `cac:PartyLegalEntity/cbc:CompanyID` (BT-30/BT-47). */
81
+ companyId?: UblCompanyId | undefined;
82
+ /** `cbc:EndpointID` (BT-34/BT-49) — the Peppol routing identifier. */
83
+ endpoint?: UblEndpoint | undefined;
84
+ partyIdentifications?: UblPartyIdentification[] | undefined;
85
+ address?: UblAddress | undefined;
86
+ contact?: UblContact | undefined;
87
+ }
88
+
89
+ /**
90
+ * VAT category (`cac:ClassifiedTaxCategory` on a line, `cac:TaxCategory` in
91
+ * the VAT breakdown and on an allowance/charge). `id` is a UNCL5305 code:
92
+ * - `S` Standard rate
93
+ * - `Z` Zero-rated goods
94
+ * - `E` Exempt from VAT
95
+ * - `AE` VAT reverse charge
96
+ * - `O` Services outside scope of tax
97
+ * - `K` Intra-community supply
98
+ * - `G` Export outside the EU
99
+ */
100
+ export interface UblTaxCategory {
101
+ /** `cbc:ID` (BT-151/BT-118/BT-95/BT-102). */
102
+ id?: string | undefined;
103
+ /** `cbc:Percent` (BT-152/BT-119/BT-96/BT-103); absent for `O` and when the document omits it. */
104
+ percent?: number | undefined;
105
+ /** `cac:TaxScheme/cbc:ID`, normally `VAT`. */
106
+ schemeId?: string | undefined;
107
+ /** `cbc:TaxExemptionReason` (BT-120). Required by EN 16931 for non-charging categories. */
108
+ exemptionReason?: string | undefined;
109
+ /** `cbc:TaxExemptionReasonCode` (BT-121). */
110
+ exemptionReasonCode?: string | undefined;
111
+ }
112
+
113
+ export interface UblItemProperty {
114
+ /** `cac:AdditionalItemProperty/cbc:Name` (BT-160). */
115
+ name: string;
116
+ /** `cac:AdditionalItemProperty/cbc:Value` (BT-161). */
117
+ value?: string | undefined;
118
+ }
119
+
120
+ export interface UblLine {
121
+ /** `cbc:ID` (BT-126) — line identifier. */
122
+ id: string;
123
+ /** `cac:Item/cbc:Description` (BT-154). */
124
+ description?: string | undefined;
125
+ /** `cbc:InvoicedQuantity` / `cbc:CreditedQuantity` (BT-129). */
126
+ quantity?: number | undefined;
127
+ /** UN/ECE Rec 20 unit code (BT-130). */
128
+ unitCode?: string | undefined;
129
+ /**
130
+ * Net price of one unit: `cac:Price/cbc:PriceAmount` (BT-146) divided by
131
+ * `cbc:BaseQuantity` (BT-149, default 1).
132
+ */
133
+ unitPrice?: number | undefined;
134
+ /** `cbc:LineExtensionAmount` (BT-131) — net of VAT, after line discounts. */
135
+ lineExtensionAmount?: number | undefined;
136
+ /**
137
+ * `cac:Price/cbc:BaseQuantity` (BT-149) — the number of units BT-146
138
+ * covers. Omitted means 1. Set it when the net doesn't divide evenly into
139
+ * cents, so `quantity × unitPrice` reproduces the line net exactly
140
+ * (PEPPOL-EN16931-R120); see `deriveUnitPrice`. The serializer emits
141
+ * `PriceAmount = unitPrice × baseQuantity`.
142
+ */
143
+ baseQuantity?: number | undefined;
144
+ /** `cac:Item/cac:ClassifiedTaxCategory` (BT-151/BT-152). */
145
+ taxCategory?: UblTaxCategory | undefined;
146
+ /** Line VAT amount: `cac:TaxTotal/cbc:TaxAmount` when stated, else derived from the rate. */
147
+ taxAmount?: number | undefined;
148
+ /** Line-level `cac:TaxTotal/cac:TaxSubtotal` (not used by BIS Billing, seen in the wild). */
149
+ taxSubtotals?: UblTaxSubtotal[] | undefined;
150
+ allowanceCharges?: UblAllowanceCharge[] | undefined;
151
+ /** Sum of line-level allowances (absolute). */
152
+ discountAmount?: number | undefined;
153
+ /** Sum of line-level charges (absolute). */
154
+ chargeAmount?: number | undefined;
155
+ /** `cac:Item/cbc:Name` (BT-153). */
156
+ itemName?: string | undefined;
157
+ /** `cac:Item/cac:SellersItemIdentification/cbc:ID` (BT-155). */
158
+ sellersItemId?: string | undefined;
159
+ /** `cac:Item/cac:BuyersItemIdentification/cbc:ID` (BT-156). */
160
+ buyersItemId?: string | undefined;
161
+ additionalItemProperties?: UblItemProperty[] | undefined;
162
+ /** `cac:InvoicePeriod` (BT-134/BT-135) — the line's own service period. */
163
+ invoicePeriod?: UblInvoicePeriod | undefined;
164
+ }
165
+
166
+ export interface UblAllowanceCharge {
167
+ /** `cbc:ChargeIndicator` — `true` for a charge, `false` for an allowance. */
168
+ chargeIndicator: boolean;
169
+ /** `cbc:Amount` (BT-92/BT-99). */
170
+ amount?: number | undefined;
171
+ /** `cbc:BaseAmount` (BT-93/BT-100). */
172
+ baseAmount?: number | undefined;
173
+ /** `cbc:MultiplierFactorNumeric` (BT-94/BT-101). */
174
+ multiplierFactorNumeric?: number | undefined;
175
+ /** `cbc:AllowanceChargeReason` (BT-97/BT-104). */
176
+ reason?: string | undefined;
177
+ /** `cbc:AllowanceChargeReasonCode` (BT-98/BT-105). */
178
+ reasonCode?: string | undefined;
179
+ /** `cac:TaxCategory` (BT-95/BT-96, BT-102/BT-103). */
180
+ taxCategory?: UblTaxCategory | undefined;
181
+ }
182
+
183
+ export interface UblTaxSubtotal {
184
+ /** `cbc:TaxableAmount` (BT-116). */
185
+ taxableAmount?: number | undefined;
186
+ /** `cbc:TaxAmount` (BT-117). */
187
+ taxAmount?: number | undefined;
188
+ /** `cac:TaxCategory` (BT-118/BT-119/BT-120/BT-121). */
189
+ category?: UblTaxCategory | undefined;
190
+ }
191
+
192
+ export interface UblTaxTotal {
193
+ /** `cac:TaxTotal/cbc:TaxAmount` (BT-110). Read as stated; never summed from the subtotals. */
194
+ taxAmount?: number | undefined;
195
+ /** `cac:TaxSubtotal` (BG-23) — the VAT breakdown. */
196
+ subtotals: UblTaxSubtotal[];
197
+ }
198
+
199
+ export interface UblMonetaryTotal {
200
+ /** BT-106 — sum of line net amounts. */
201
+ lineExtensionAmount?: number | undefined;
202
+ /** BT-109 — total without VAT. */
203
+ taxExclusiveAmount?: number | undefined;
204
+ /** BT-112 — total with VAT. */
205
+ taxInclusiveAmount?: number | undefined;
206
+ /** BT-107 — sum of document-level allowances. */
207
+ allowanceTotalAmount?: number | undefined;
208
+ /** BT-108 — sum of document-level charges. */
209
+ chargeTotalAmount?: number | undefined;
210
+ /**
211
+ * BT-113 — sum of amounts paid in advance. **Gross (VAT-inclusive)**, since
212
+ * BR-CO-16 subtracts it directly from BT-112.
213
+ */
214
+ prepaidAmount?: number | undefined;
215
+ /** BT-114 — rounding applied to the payable amount. */
216
+ payableRoundingAmount?: number | undefined;
217
+ /**
218
+ * BT-115 — amount due for payment, i.e. the *outstanding* amount.
219
+ * BR-CO-16: `BT-115 = BT-112 − BT-113 + BT-114`.
220
+ */
221
+ payableAmount?: number | undefined;
222
+ }
223
+
224
+ export interface UblPaymentMeans {
225
+ /** `cbc:PaymentMeansCode` (BT-81). */
226
+ code?: string | undefined;
227
+ /** `cbc:PaymentMeansCode/@name` (BT-82). */
228
+ codeName?: string | undefined;
229
+ /** `cbc:PaymentID` (BT-83). */
230
+ paymentId?: string | undefined;
231
+ /** `cac:PayeeFinancialAccount/cbc:ID` (BT-84). */
232
+ iban?: string | undefined;
233
+ /** `cac:FinancialInstitutionBranch/cbc:ID` (BT-86). */
234
+ bic?: string | undefined;
235
+ /** `cac:PayeeFinancialAccount/cbc:Name` (BT-85). */
236
+ accountName?: string | undefined;
237
+ /** `cac:PaymentMandate/cbc:ID` (BT-89). */
238
+ mandateId?: string | undefined;
239
+ }
240
+
241
+ /**
242
+ * A service period: BT-73/BT-74 on the document, BT-134/BT-135 on a line.
243
+ * Either bound may stand alone — UBL allows a half-open period — but a period
244
+ * with neither is omitted entirely.
245
+ */
246
+ export interface UblInvoicePeriod {
247
+ /** `cbc:StartDate`, `YYYY-MM-DD`. */
248
+ startDate?: string | undefined;
249
+ /** `cbc:EndDate`, `YYYY-MM-DD`, inclusive. */
250
+ endDate?: string | undefined;
251
+ /** `cbc:DescriptionCode` (BT-8). */
252
+ descriptionCode?: string | undefined;
253
+ }
254
+
255
+ /** A supporting document (BG-24): embedded (`base64Content`) or external (`externalUri`). */
256
+ export interface UblAttachment {
257
+ /** `cac:AdditionalDocumentReference/cbc:ID` (BT-122). */
258
+ id?: string | undefined;
259
+ /** `cbc:EmbeddedDocumentBinaryObject/@filename` (BT-125-2). */
260
+ filename?: string | undefined;
261
+ /** MIME type (BT-125-1), e.g. `application/pdf`. */
262
+ mimeCode?: string | undefined;
263
+ /** `cbc:DocumentDescription` (BT-123). */
264
+ description?: string | undefined;
265
+ /** Base64-encoded document bytes (BT-125). */
266
+ base64Content?: string | undefined;
267
+ /** `cac:ExternalReference/cbc:URI` (BT-124). */
268
+ externalUri?: string | undefined;
269
+ }
270
+
271
+ /** A text-only `cac:AdditionalDocumentReference` (no attachment). */
272
+ export interface UblDocumentReference {
273
+ id?: string | undefined;
274
+ description?: string | undefined;
275
+ }
276
+
277
+ export interface UblDelivery {
278
+ /** `cbc:ActualDeliveryDate` (BT-72). */
279
+ actualDeliveryDate?: string | undefined;
280
+ /** `cac:DeliveryLocation/cac:Address` (BG-15). */
281
+ address?: UblAddress | undefined;
282
+ }
283
+
284
+ /** `cac:BillingReference/cac:InvoiceDocumentReference` (BT-25/BT-26). */
285
+ export interface UblBillingReference {
286
+ invoiceId?: string | undefined;
287
+ invoiceIssueDate?: string | undefined;
288
+ }
289
+
290
+ export interface UblInvoice {
291
+ documentType: "Invoice" | "CreditNote";
292
+ /** `cbc:CustomizationID` (BT-24). The serializer defaults to Peppol BIS Billing 3.0. */
293
+ customizationId?: string | undefined;
294
+ /** `cbc:ProfileID` (BT-23). The serializer defaults to the Peppol billing process. */
295
+ profileId?: string | undefined;
296
+ /** Invoice / credit note number (BT-1). */
297
+ id: string;
298
+ /** `cbc:InvoiceTypeCode` / `cbc:CreditNoteTypeCode` (BT-3). The serializer defaults to 380/381. */
299
+ invoiceTypeCode?: string | undefined;
300
+ /** Issue date (BT-2), `YYYY-MM-DD`. */
301
+ issueDate: string;
302
+ /** Payment due date (BT-9). Invoices only. */
303
+ dueDate?: string | undefined;
304
+ /** `cbc:TaxPointDate` (BT-7). */
305
+ taxPointDate?: string | undefined;
306
+ /** Document currency (BT-5). */
307
+ currency: string;
308
+ /** Buyer reference (BT-10). */
309
+ buyerReference?: string | undefined;
310
+ /** `cac:OrderReference/cbc:ID` (BT-13). */
311
+ orderReference?: string | undefined;
312
+ /** `cac:OrderReference/cbc:SalesOrderID` (BT-14). */
313
+ salesOrderId?: string | undefined;
314
+ /** `cac:ContractDocumentReference/cbc:ID` (BT-12). */
315
+ contractReference?: string | undefined;
316
+ /** `cac:ProjectReference/cbc:ID` (BT-11). */
317
+ projectReference?: string | undefined;
318
+ /** For credit notes: the referenced original invoice (BT-25). */
319
+ billingReference?: UblBillingReference | undefined;
320
+ seller: UblParty;
321
+ buyer: UblParty;
322
+ delivery?: UblDelivery | undefined;
323
+ lines: UblLine[];
324
+ taxTotal: UblTaxTotal;
325
+ monetaryTotal: UblMonetaryTotal;
326
+ /** The first entry of `paymentMeansList`. */
327
+ paymentMeans?: UblPaymentMeans | undefined;
328
+ paymentMeansList?: UblPaymentMeans[] | undefined;
329
+ /** Invoicing period (BT-73/BT-74). */
330
+ invoicePeriod?: UblInvoicePeriod | undefined;
331
+ /** Free-text note (BT-22). */
332
+ note?: string | undefined;
333
+ /** Payment terms note (BT-20, `cac:PaymentTerms/cbc:Note`). */
334
+ paymentTermsNote?: string | undefined;
335
+ attachments?: UblAttachment[] | undefined;
336
+ documentReferences?: UblDocumentReference[] | undefined;
337
+ /** Document-level allowances and charges (BG-20/BG-21). */
338
+ allowanceCharges?: UblAllowanceCharge[] | undefined;
339
+ }
340
+
341
+ // --- Normalized DTO types ---
342
+
343
+ export interface InvoiceExtractionDTO {
344
+ provider: string;
345
+ document_id: string;
346
+ invoice: {
347
+ invoice_number: string | null;
348
+ invoice_date: string | null;
349
+ due_date: string | null;
350
+ /** EN 16931 BT-73/BT-74: the period the document bills for. */
351
+ period_start: string | null;
352
+ period_end: string | null;
353
+ currency: string | null;
354
+ subtotal: number | null;
355
+ tax_total: number | null;
356
+ total: number | null;
357
+ amount_due: number | null;
358
+ amount_paid: number | null;
359
+ discount_total: number | null;
360
+ shipping_total: number | null;
361
+ /** EN 16931 BT-114, signed. Outside the VAT breakdown (BR-CO-16). */
362
+ rounding_total: number | null;
363
+ payment_terms: string | null;
364
+ po_number: string | null;
365
+ supplier: {
366
+ name: string | null;
367
+ address: string | null;
368
+ tax_id: string | null;
369
+ iban: string | null;
370
+ bic: string | null;
371
+ };
372
+ receiver: {
373
+ name: string | null;
374
+ address: string | null;
375
+ tax_id: string | null;
376
+ };
377
+ extra: Record<string, unknown>;
378
+ };
379
+ line_items: Array<{
380
+ description: string;
381
+ quantity: number | null;
382
+ unit: string | null;
383
+ unit_price: number | null;
384
+ amount: number | null;
385
+ tax_amount: number | null;
386
+ tax_rate: number | null;
387
+ product_code: string | null;
388
+ discount_amount: number | null;
389
+ /** EN 16931 BT-134/BT-135: the line's own service period. */
390
+ period_start: string | null;
391
+ period_end: string | null;
392
+ extra: Record<string, unknown>;
393
+ }>;
394
+ confidence: {
395
+ overall: number | null;
396
+ fields: Record<string, number>;
397
+ };
398
+ }
package/src/xml-dom.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { type Document, DOMParser as XmlDomParser } from "@xmldom/xmldom";
2
+ import { UblParseError } from "./errors.js";
3
+
4
+ export const CBC_NS =
5
+ "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
6
+ export const CAC_NS =
7
+ "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
8
+
9
+ /**
10
+ * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.
11
+ * @xmldom/xmldom resolves external entities by default, so we remove DOCTYPE
12
+ * blocks (including inline DTD subsets) before parsing.
13
+ */
14
+ export const stripDoctype = (xml: string): string =>
15
+ xml.replace(/<!DOCTYPE\s[^>[]*(?:\[[^\]]*\])?>/gi, "");
16
+
17
+ /**
18
+ * Parse XML into a DOM, preferring the host's `DOMParser` (browsers) and
19
+ * falling back to @xmldom/xmldom. Throws {@link UblParseError} when the XML
20
+ * is malformed.
21
+ */
22
+ export const parseXmlDocument = (xml: string): Document => {
23
+ const safeXml = stripDoctype(xml);
24
+ const BrowserDomParser = (globalThis as { DOMParser?: typeof XmlDomParser })
25
+ .DOMParser;
26
+ const parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();
27
+ let doc: Document;
28
+ try {
29
+ doc = parser.parseFromString(safeXml, "text/xml");
30
+ } catch (cause) {
31
+ throw new UblParseError("Malformed XML", { cause });
32
+ }
33
+ if (doc.getElementsByTagName("parsererror").length > 0 || !doc.documentElement) {
34
+ throw new UblParseError("Malformed XML");
35
+ }
36
+ return doc;
37
+ };