@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/CHANGELOG.md ADDED
@@ -0,0 +1,168 @@
1
+ # Changelog
2
+
3
+ ## 0.17.0
4
+
5
+ ### Changed
6
+
7
+ - **BREAKING: one UBL model for the parser, the serializer and the build helpers.** `UblInvoice` (root export, re-exported from `@financica/ubl/build`) replaces the build-side `UblDocument`, which remains as a deprecated alias for one release. On the parsed model: `UblParty.endpointId`/`endpointSchemeId` → `endpoint: { value, scheme? }`; `companyId: string` + `companyIdSchemeId` → `companyId: { value, scheme? }`; `UblLine.taxPercent`/`taxCategoryId`/`taxSchemeId` → `taxCategory: { id?, percent?, schemeId?, exemptionReason?, exemptionReasonCode? }` (same object on `UblAllowanceCharge`); `UblTaxSubtotal.taxPercent`/`taxCategoryId`/`taxSchemeId`/`taxExemptionReason` → `category` (same shape); the top-level `taxSubtotals` → `taxTotal: { taxAmount?, subtotals }`, where `taxAmount` is BT-110 as the document states it (never summed from the subtotals); `UblLine.baseQuantity` (BT-149) is now read. On the build side: `supplier`/`customer` → `seller`/`buyer`, `vatNumber` → `vatId`, `legalName` → `registrationName`, `priceAmount` → `unitPrice` (the per-unit price; the serializer writes `PriceAmount = unitPrice × baseQuantity`, and `deriveUnitPrice` returns `{ unitPrice, baseQuantity? }`), line `name` → `description` (written as `cbc:Description`, and as `cbc:Name` unless `itemName` is set), attachment `base64` → `base64Content`, `precedingInvoiceId` → `billingReference.invoiceId`, `UblPeriod` → `UblInvoicePeriod`, `documentType: "invoice" | "creditNote"` → `"Invoice" | "CreditNote"`, and every absent output field is an absent key instead of `null` (`buildCompanyId`, `parsePeppolEndpoint`, `resolveVatEndpoint`, `resolveCompanyIdScheme` return `undefined`; `buildSupplierParty`/`buildCustomerParty`/`normalizeAddress` omit absent keys). Caller-input types (`UblSupplier`, `UblCustomer`, `AddressInput`, `CustomerTaxIdInput`) still accept `null`. `buildTaxTotals` throws `UblBuildError` for a line without a `taxCategory`. `normalizeUblResponse` produces the same `InvoiceExtractionDTO`; only the `extra.tax_subtotals` passthrough changes shape (each entry is now `{ taxableAmount?, taxAmount?, category? }`).
8
+ - **BREAKING: `serializeUblDocument` validates and throws `UblBuildError`.** Also exported as `serializeUblInvoice` (the preferred name). Because the model is permissive, the serializer enforces what EN 16931 / Peppol BIS Billing 3.0 make mandatory and throws the new `UblBuildError` (exported from the root and `/build`, `name` set, `readonly cause?`) naming the BT and model path: document `id`, `issueDate`, `currency`, `seller.name`, `buyer.name`, an `endpoint.scheme` on any endpoint, at least one line, per line `quantity`, `unitCode`, `unitPrice`, `lineExtensionAmount`, `taxCategory.id` (and `taxCategory.percent` unless the category is `O`), `taxTotal.taxAmount`, `monetaryTotal.lineExtensionAmount`/`taxExclusiveAmount`/`taxInclusiveAmount`/`payableAmount`, and per VAT subtotal its `taxableAmount`, `taxAmount` and `category`. An attachment needs `filename`, `mimeCode` and `base64Content`; an attachment with only `externalUri` is written as `cac:ExternalReference`. `customizationId`, `profileId` and `invoiceTypeCode` are written when set (defaulting to the BIS values), so a parsed document re-serializes faithfully.
9
+
10
+ ## 0.16.0
11
+
12
+ ### Changed
13
+
14
+ - **BREAKING: `SupplierVatStatus` is a string union.** `1 | 2 | 3` becomes `"subject" | "not_subject" | "small_business"`; the numbers were Scrada's wire encoding leaking into a generic model. Callers that hold the Scrada code map it at their own boundary.
15
+ - **EAS schemes come from `@financica/peppol` instead of a private copy.** `resolveVatEndpoint` and `resolveCompanyIdScheme` resolve through `getPeppolIdentifierSchemes`, so the three hand-copied tables are one. Routing changes for two countries whose verified profile disagreed with the old copy: Swedish VAT numbers now resolve to `9955` and Italian to `0211` (previously null). Requires `@financica/peppol` ≥ 0.8.0.
16
+ - **BREAKING: parse errors throw `UblParseError`; `null` means "not a UBL invoice".** `parseUblInvoice` returns `null` only when well-formed XML has a root other than a UBL `Invoice`/`CreditNote`; malformed XML and documents missing a mandatory element (`cbc:ID`, `cbc:IssueDate`, `cbc:DocumentCurrencyCode`, a line `cbc:ID`) throw the new `UblParseError` (exported from the root, `cause` set when wrapping). `parsePeppolMessageLevelResponse`, `extractUblEmbeddedAttachments` and `normalizeUblResponse` throw the same class instead of a generic `Error`; `isPeppolMessageLevelResponse` stays a non-throwing sniff.
17
+ - **BREAKING: the parsed model has no sentinel values.** A field the document omits is an absent key instead of `""`/`0`/`"Unknown"`: `UblAddress` (`street`, `city`, `postalZone`, `countryCode`), `UblParty.name`, `UblLine` (`description`, `quantity`, `unitCode`, `unitPrice`, `lineExtensionAmount`), `UblTaxSubtotal` (`taxableAmount`, `taxAmount`, `taxPercent`), every `UblMonetaryTotal` amount, `UblAllowanceCharge.amount`, `UblPaymentMeans.code`, `UblAttachment.id`, `UblDocumentReference.id`, `UblItemProperty.value` and `UblEmbeddedAttachment.id` are now optional, and `PeppolMessageLevelResponse` fields are `?: string` instead of `string | null`. `seller`, `buyer`, `monetaryTotal`, `lines` and `taxSubtotals` are always present. `normalizeUblResponse` reports `null` where it previously reported a manufactured `0` (totals of a document without `LegalMonetaryTotal`, line quantity/price/amount the line does not state), and attachment `sizeBytes` is the exact padding-aware decoded size.
18
+ - **Build-side inputs are typed instead of `unknown`.** `extractCustomerTaxIdentifiers` takes `readonly CustomerTaxIdInput[] | null | undefined` (`{type, value}` pairs, the shape of Stripe's `customer_tax_ids`), and `normalizeAddress` / `UblSupplier.address` take the new `AddressInput` (Stripe `line1`/`postal_code`/`country` and legacy `street`/`zip_code`/`country_code` keys). Both new types are exported from `@financica/ubl/build`. Runtime behaviour is unchanged; callers that passed arbitrary values must now pass the documented shape (or `null`). `listPeppolReceiverIdentifierCandidates` accepts `Partial<CustomerTaxIdentifiers>`, which is the same shape it took before.
19
+
20
+ ### Added
21
+
22
+ - **`coerceLinesForSupplierVatStatus(lines, vatStatus, supplierCountryCode?)`** — the "seller does not charge VAT → every line is `E`/0% with a BT-120 reason" rule now lives here instead of inside the Stripe adapter, so every adapter gets it. The Belgian Article 56bis text is picked by supplier country; other countries get a generic reason.
23
+
24
+ ## 0.15.1
25
+
26
+ ### Fixed
27
+
28
+ - **`extractCustomerTaxIdentifiers` no longer drops non-VAT registration numbers.** An entry was classified by substring of its type (`vat`, `tax`, `peppol`, `gln`), so `ca_gst_hst`, `au_abn`, `us_ein`, `ch_uid` and most of the Stripe taxonomy vanished and a seller with only such an id failed the identifier check. Any other typed entry is now the registration number (BT-30).
29
+
30
+ ## 0.13.0
31
+
32
+ ### Added
33
+
34
+ - **Service periods, end to end.** `UblLine.invoicePeriod` carries a line's own `cac:InvoicePeriod` (BT-134/BT-135), which the parser previously discarded; `normalizeUblResponse` promotes both the document period (BT-73/BT-74) and each line's to first-class `period_start` / `period_end` DTO fields, so consumers no longer have to dig the document one out of `extra.invoice_period` and had no way at all to reach the line ones. The serializer emits `cac:InvoicePeriod` from `UblDocument.invoicePeriod` and `UblLine.invoicePeriod`, at the positions UBL's element sequence requires (after `cbc:BuyerReference` on the document, after `cbc:LineExtensionAmount` on a line). A period with neither bound set is omitted rather than emitted empty, which would fail BR-CO-19.
35
+
36
+ ### Fixed
37
+
38
+ - **A line's period is no longer reported as the document's.** The document-level lookup was a descendant search, so on an invoice that states a period only per line — the normal shape for a subscription bill with prorations — the first line's period surfaced as the whole document's. Both lookups now read direct children only.
39
+
40
+ ## 0.12.0
41
+
42
+ ### Added
43
+
44
+ - **`rounding_total` on the normalized DTO**: `normalizeUblResponse` now surfaces `cbc:PayableRoundingAmount` (BT-114). The parser has always read it into `UblMonetaryTotal`; it simply never reached the DTO, so consumers could not tell a cash-rounded payable from an unexplained gap.
45
+
46
+ ### Fixed
47
+
48
+ - **A rounded payable is no longer mistaken for a prepayment.** With no declared `cbc:PrepaidAmount`, `amount_paid` was inferred from any `TaxInclusiveAmount > PayableAmount` gap — but under BR-CO-16 a rounding amount is exactly such a gap by design. An invoice rounded _down_ (27.17 → 27.15, the Belgian nearest-0.05 cash rule) imported as 0.02 already paid, reporting an untouched invoice as partially settled; one rounded _up_ left the total and the amount due disagreeing with nothing to explain it. The rounding term is now removed before the inference, and the result is rounded to cents before the sign test so the float residue of undoing it cannot pass as a sub-cent prepayment. A declared `PrepaidAmount` is still authoritative and is untouched.
49
+
50
+ ## 0.11.0
51
+
52
+ ### Added
53
+
54
+ - **`deriveUnitPrice` and `UblLine.baseQuantity` (BT-149)**: the serializer now emits `cbc:BaseQuantity` inside `cac:Price`, carrying the quantity's unit code as PEPPOL-EN16931-R130 requires.
55
+
56
+ ### Fixed
57
+
58
+ - **Line prices no longer violate PEPPOL-EN16931-R120.** A line's net price was derived as `net ÷ quantity` rounded to cents, which breaks the rule whenever the division doesn't land on a cent: 940.00 over 14 units gives 67.142857…, and 14 × 67.14 = 939.96 — 0.04 out against a 0.02 tolerance, rejected as a _fatal_ validation error, so the document is never transmitted. `deriveUnitPrice` keeps the cent-rounded unit price only when it reproduces the net exactly, and otherwise prices the line as a whole via BT-149 (`priceAmount` = the net, `baseQuantity` = the quantity). That is exact at any magnitude, rather than merely within tolerance — the residual of a rounded unit price grows with quantity and would eventually breach 0.02 at any fixed precision.
59
+ - **`reconcileLinesToExclTotal` re-derives the price after adjusting a line's net.** It previously re-divided at cent precision, reintroducing the same R120 violation on the very line it had just corrected. It now routes through `deriveUnitPrice` and clears a stale `baseQuantity` when the adjusted net divides evenly.
60
+
61
+ ## 0.10.0
62
+
63
+ ### Added
64
+
65
+ - **Prepayment and rounding on the build side**: `UblMonetaryTotal` gains optional `prepaidAmount` (BT-113, gross/VAT-inclusive) and `payableRoundingAmount` (BT-114), and the serializer emits `cbc:PrepaidAmount` / `cbc:PayableRoundingAmount` in UBL sequence order (before `cbc:PayableAmount`). Both are omitted when absent or zero.
66
+ - **`buildTaxTotals` derives `payableAmount` per BR-CO-16**: an optional second argument (`BuildTaxTotalsOptions`) supplies the prepaid and rounding terms, and BT-115 is computed as `taxInclusiveAmount - prepaidAmount + payableRoundingAmount` rather than hardwired to the gross total. Documents for already-settled invoices — credit notes against paid invoices in particular — no longer present their full gross total as outstanding, which was a double-payment risk. The result is not clamped, so an overpayment surfaces as a negative payable amount instead of being silently hidden. Existing single-argument call sites are unchanged.
67
+
68
+ ## 0.9.0
69
+
70
+ ### Added
71
+
72
+ - **Tax categories K and G**: `taxCategoryFromReasonOrRate` maps intra-community supply to category `K` and export outside the EU to category `G`, both zero-rated with the required EN 16931 exemption reason. Previously both fell through to the generic `E` (exempt).
73
+
74
+ ### Changed
75
+
76
+ - **Toolchain migrated to bun + oxc**: oxlint replaces ESLint, oxfmt replaces Prettier, and tsdown replaces tsup for the dual-entry (`.` and `./build`) build. TypeScript upgraded to 7.0; `bun.lock` replaces `package-lock.json`.
77
+ - **`@xmldom/xmldom` upgraded to 0.9**: 0.9 drops the ambient DOM lib reference and exports its own DOM types, so the parser and MLR reader now import `Element`/`Document` from the package and read `globalThis.DOMParser` through a typed cast. The isomorphic design is unchanged (native browser `DOMParser` preferred, xmldom as the Node fallback).
78
+
79
+ ### Fixed
80
+
81
+ - **Null `documentElement` guard in `parseUblInvoice`**: xmldom 0.9 correctly types `Document.documentElement` as nullable; the missing guard is now in place (`parsePeppolMessageLevelResponse` already had one).
82
+
83
+ ## 0.8.0
84
+
85
+ ### Added
86
+
87
+ - **`extractUblEmbeddedAttachments` and `isPdfLikeAttachment`**: embedded-attachment extraction (base64 content, approximate decoded size, PDF sniffing) moves into the library instead of being reimplemented on top of `parseUblInvoice` by callers. References carrying only an external URI are skipped.
88
+
89
+ ## 0.7.0
90
+
91
+ ### Added
92
+
93
+ - **`buildCustomerParty`**: the buyer-party builder is promoted out of `@financica/stripe-ubl` into the shared build core so every X→UBL adapter resolves the Peppol `EndpointID` identically — explicit Peppol ID → GLN (`0088`) → VAT EAS scheme (e.g. BE → `9925`). A customer known only by VAT number now gets a routable endpoint instead of `null`.
94
+
95
+ ## 0.6.0
96
+
97
+ ### Added
98
+
99
+ - **`resolveVatEndpoint` and qualified receiver candidates**: `listPeppolReceiverIdentifierCandidates` previously returned bare values (e.g. a VAT number `BE0206582284`), but a participant lookup needs a fully-qualified `scheme:value` identifier — fed through `parsePeppolEndpoint` a bare value has no `:` to split on and yielded `null`, so a registered recipient could not be resolved. Candidates are now emitted qualified and in priority order: explicit Peppol ID, GLN (`0088`), VAT (country scheme), the Belgian enterprise-number fallback (`0208`), then a generic tax number. Backed by a country → VAT EAS scheme table from the Peppol Code Lists (Participant Identifier Schemes, BIS Billing 3.0, Nov 2025). Countries that address by organisation number rather than VAT (SE/DK/NO) are intentionally absent.
100
+
101
+ ### Changed
102
+
103
+ - Repository moved to `github.com/financica/ubl-ts`; package metadata and README updated to match.
104
+
105
+ ### Documentation
106
+
107
+ - The README documents the build/serialize API with a complete, type-checked `UblDocument` example alongside the existing parse-side usage.
108
+
109
+ ## 0.5.0
110
+
111
+ ### Added
112
+
113
+ - **UBL build core at `@financica/ubl/build`**: a generic Peppol BIS Billing 3.0 document model, serializer (`serializeUblDocument`), and party/tax/identifier/attachment builders. Extracted from `@financica/stripe-ubl` so any X→UBL adapter shares one core. The build-side types live under the subpath so they do not collide with the parse-side types exported from the package root.
114
+
115
+ ## 0.4.0
116
+
117
+ ### Added
118
+
119
+ - **Peppol Message Level Response parser**: `parsePeppolMessageLevelResponse` and `isPeppolMessageLevelResponse`, plus the `PEPPOL_MLR_*` document-type and process constants. Parses a UBL `ApplicationResponse` (the Peppol transport-level ack), unwrapping an SBDH envelope when present, using the same XXE-safe approach as the invoice parser.
120
+
121
+ ## 0.3.2
122
+
123
+ ### Fixed
124
+
125
+ - **Unit price now divides PriceAmount by BaseQuantity**: When `cac:Price/cbc:BaseQuantity` is present and greater than 1, the effective unit price (BT-146 / BT-149) was previously reported as the raw `PriceAmount`, overstating per-unit cost on invoices that price by a multi-unit basis (e.g. €75.00 per 1.5 hours now correctly reports `unitPrice: 50`, not `75`).
126
+
127
+ ## 0.3.1
128
+
129
+ ### Fixed
130
+
131
+ - **`Price/AllowanceCharge` line discounts**: the parser only collected `AllowanceCharge` elements that were direct children of `InvoiceLine`. UBL also allows `Price/AllowanceCharge` for per-unit discounts (e.g. a 100% discount on a subscription); these were silently ignored, leaving `discount_amount` null. They are now merged into the line's `allowanceCharges` and reflected in `discountAmount`.
132
+
133
+ ## 0.3.0
134
+
135
+ ### Added
136
+
137
+ - **Real-world Peppol invoice features** seen in telco invoices: `AdditionalDocumentReference` without an attachment (text-only references such as terms & conditions), `ExternalReference/URI` for externally hosted attachments, `PaymentMandate/ID` for SEPA Direct Debit mandates, `AdditionalItemProperty` on lines as key-value metadata, multiple `PartyIdentification` elements with scheme IDs, and the `schemeID` attribute on `PartyLegalEntity/CompanyID`.
138
+
139
+ ### Changed
140
+
141
+ - **Package renamed** from `@ingram-tech/ubl` to `@financica/ubl`. 0.3.0 was published under both names — as `@ingram-tech/ubl` on 2026-03-07 (tagged `v0.3.0`), then republished unchanged apart from the rename as `@financica/ubl` on 2026-04-02. `@financica/ubl` starts at 0.3.0; 0.1.0 through 0.2.0 exist only under the old name.
142
+
143
+ ## 0.2.0
144
+
145
+ ### Added
146
+
147
+ - **CreditNote type code support**: `invoiceTypeCode` now correctly reads `cbc:CreditNoteTypeCode` for CreditNote documents (previously only read `cbc:InvoiceTypeCode`, which is absent on credit notes).
148
+ - **Billing reference parsing**: New `UblBillingReference` type and `billingReference` field on `UblInvoice`. Extracts the original invoice ID and issue date from `cac:BillingReference/cac:InvoiceDocumentReference` -- essential for credit notes that reference the invoice being corrected.
149
+ - **DTO billing reference**: `normalizeUblResponse()` now includes `billing_reference` in the `extra` object with `invoice_id` and `invoice_issue_date`.
150
+
151
+ ## 0.1.1
152
+
153
+ Published as `@ingram-tech/ubl` from an uncommitted version bump, so no commit
154
+ carries this version and it has no release tag.
155
+
156
+ ### Changed
157
+
158
+ - Added `prepack` script to ensure build runs before publish. (Committed later, with 0.2.0.)
159
+
160
+ ## 0.1.0
161
+
162
+ ### Added
163
+
164
+ - Initial release.
165
+ - `parseUblInvoice(xml)` -- parse UBL 2.1 Invoice and CreditNote XML into typed objects.
166
+ - `normalizeUblResponse(xml, documentId)` -- normalize parsed UBL into a flat `InvoiceExtractionDTO`.
167
+ - `parseUblInvoiceDocument({ bytes, documentId, mimeType })` -- parse from raw bytes with BOM handling.
168
+ - Full type exports for all UBL structures.
package/README.md CHANGED
@@ -5,7 +5,7 @@ TypeScript toolkit for [UBL (Universal Business Language)](https://www.oasis-ope
5
5
  The package is split into two entry points:
6
6
 
7
7
  - `@financica/ubl` — the parse side: read UBL XML into typed objects (`parseUblInvoice`, `normalizeUblResponse`, MLR parsing).
8
- - `@financica/ubl/build` — the build side: assemble a `UblDocument` and serialize it to Peppol BIS Billing 3.0 XML.
8
+ - `@financica/ubl/build` — the build side: assemble a `UblInvoice` (the same model the parser produces) and serialize it to Peppol BIS Billing 3.0 XML.
9
9
 
10
10
  ## Installation
11
11
 
@@ -62,59 +62,55 @@ Handles UTF-8 BOM stripping automatically.
62
62
 
63
63
  ### Build UBL XML
64
64
 
65
- Construct a `UblDocument`, a vendor-neutral mirror of the Peppol BIS Billing 3.0
66
- fields, and serialize it with `serializeUblDocument`.
65
+ Construct a `UblInvoice` — the same model `parseUblInvoice` returns — and
66
+ serialize it with `serializeUblInvoice`. The model is permissive (the parser
67
+ reads whatever a document states); the serializer enforces what EN 16931 /
68
+ Peppol BIS make mandatory and throws `UblBuildError`, naming the field, when
69
+ something is missing.
67
70
 
68
71
  ```typescript
69
- import { serializeUblDocument, type UblDocument } from "@financica/ubl/build";
72
+ import { serializeUblInvoice, type UblInvoice } from "@financica/ubl/build";
70
73
 
71
- const doc: UblDocument = {
72
- documentType: "invoice",
74
+ const doc: UblInvoice = {
75
+ documentType: "Invoice",
73
76
  id: "INV-001",
74
77
  issueDate: "2026-01-15",
75
78
  dueDate: "2026-02-14",
76
- note: null,
77
79
  currency: "EUR",
78
- buyerReference: null,
79
- precedingInvoiceId: null,
80
- supplier: {
80
+ seller: {
81
81
  endpoint: { scheme: "0208", value: "0800279001" },
82
82
  name: "Acme BV",
83
- legalName: "Acme BV",
84
- vatNumber: "BE0800279001",
83
+ registrationName: "Acme BV",
84
+ vatId: "BE0800279001",
85
85
  companyId: { value: "0800279001", scheme: "0208" },
86
86
  address: {
87
87
  street: "Rue de la Loi 1",
88
- additionalStreet: null,
89
88
  city: "Brussels",
90
89
  postalZone: "1000",
91
- countrySubentity: null,
92
90
  countryCode: "BE",
93
91
  },
94
92
  },
95
- customer: {
93
+ buyer: {
96
94
  endpoint: { scheme: "0208", value: "0123456789" },
97
95
  name: "Globex SA",
98
- legalName: "Globex SA",
99
- vatNumber: "BE0123456789",
96
+ registrationName: "Globex SA",
97
+ vatId: "BE0123456789",
100
98
  companyId: { value: "0123456789", scheme: "0208" },
101
99
  address: {
102
100
  street: "Avenue Louise 50",
103
- additionalStreet: null,
104
101
  city: "Brussels",
105
102
  postalZone: "1050",
106
- countrySubentity: null,
107
103
  countryCode: "BE",
108
104
  },
109
105
  },
110
106
  lines: [
111
107
  {
112
108
  id: "1",
113
- name: "Consulting services",
109
+ description: "Consulting services",
114
110
  quantity: 1,
115
111
  unitCode: "C62",
116
112
  lineExtensionAmount: 100,
117
- priceAmount: 100,
113
+ unitPrice: 100,
118
114
  taxCategory: { id: "S", percent: 21 },
119
115
  },
120
116
  ],
@@ -130,14 +126,13 @@ const doc: UblDocument = {
130
126
  taxInclusiveAmount: 121,
131
127
  payableAmount: 121,
132
128
  },
133
- attachments: [],
134
129
  };
135
130
 
136
- const xml = serializeUblDocument(doc);
131
+ const xml = serializeUblInvoice(doc);
137
132
  ```
138
133
 
139
- Set `documentType: "creditNote"` (with `precedingInvoiceId` referencing the
140
- original invoice) to emit a `CreditNote` instead.
134
+ Set `documentType: "CreditNote"` (with `billingReference: { invoiceId }`
135
+ referencing the original invoice) to emit a `CreditNote` instead.
141
136
 
142
137
  For a document that is already paid, pass the settled gross amount as
143
138
  `prepaidAmount` (BT-113) so `payableAmount` (BT-115) reports what is actually