@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.
@@ -1,4 +1,6 @@
1
- import { normalizeParticipantValue } from "@financica/peppol/identifiers";
1
+ import { t as UblBuildError } from "../errors-C9YYJ1xR.js";
2
+ import { getPeppolIdentifierSchemes } from "@financica/peppol/countries";
3
+ import { countryFromVatNumber, normalizeParticipantValue } from "@financica/peppol/identifiers";
2
4
  //#region src/build/ubl/constants.ts
3
5
  /** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */
4
6
  /** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */
@@ -31,13 +33,13 @@ const NS_CBC = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponen
31
33
  const el = (name, attrs, content) => {
32
34
  if (Array.isArray(content)) return {
33
35
  name,
34
- attrs: attrs ?? void 0,
36
+ ...attrs ? { attrs } : {},
35
37
  children: content.filter((c) => Boolean(c))
36
38
  };
37
39
  return {
38
40
  name,
39
- attrs: attrs ?? void 0,
40
- text: content ?? void 0
41
+ ...attrs ? { attrs } : {},
42
+ ...content !== void 0 ? { text: content } : {}
41
43
  };
42
44
  };
43
45
  const escapeText = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
@@ -59,6 +61,57 @@ const serializeElement = (node, indentLevel) => {
59
61
  const serializeDocument = (root) => `<?xml version="1.0" encoding="UTF-8"?>\n${serializeElement(root, 0)}\n`;
60
62
  //#endregion
61
63
  //#region src/build/ubl/serialize.ts
64
+ const missing = (what, path) => new UblBuildError(`Missing ${what} (${path})`);
65
+ function required(value, what, path) {
66
+ if (value === void 0 || value === null || value === "") throw missing(what, path);
67
+ return value;
68
+ }
69
+ /** Category `O` (outside scope) is the one category BR-O-05 forbids a percent on. */
70
+ const requiresPercent = (categoryId) => categoryId !== "O";
71
+ const validateTaxCategory = (category, path) => {
72
+ const present = required(category, "VAT category (BT-151/BT-118)", path);
73
+ const id = required(present.id, "VAT category code (BT-151/BT-118)", `${path}.id`);
74
+ if (requiresPercent(id) && present.percent === void 0) throw missing(`VAT rate (BT-152/BT-119) for category ${id}`, `${path}.percent`);
75
+ return {
76
+ ...present,
77
+ id
78
+ };
79
+ };
80
+ const validateLine = (line, index) => {
81
+ const path = `lines[${index}]`;
82
+ required(line.id, "line identifier (BT-126)", `${path}.id`);
83
+ required(line.quantity, "invoiced quantity (BT-129)", `${path}.quantity`);
84
+ required(line.unitCode, "unit code (BT-130)", `${path}.unitCode`);
85
+ required(line.unitPrice, "net unit price (BT-146)", `${path}.unitPrice`);
86
+ required(line.lineExtensionAmount, "line net amount (BT-131)", `${path}.lineExtensionAmount`);
87
+ validateTaxCategory(line.taxCategory, `${path}.taxCategory`);
88
+ };
89
+ const isExternalOnly = (attachment) => attachment.externalUri !== void 0 && attachment.base64Content === void 0;
90
+ const validateAttachment = (attachment, index) => {
91
+ if (isExternalOnly(attachment)) return;
92
+ const path = `attachments[${index}]`;
93
+ required(attachment.filename, "attachment filename (BT-125-2)", `${path}.filename`);
94
+ required(attachment.mimeCode, "attachment MIME code (BT-125-1)", `${path}.mimeCode`);
95
+ required(attachment.base64Content, "attachment content (BT-125)", `${path}.base64Content`);
96
+ };
97
+ const validateInvoice = (doc) => {
98
+ required(doc.id, "document identifier (BT-1)", "id");
99
+ required(doc.issueDate, "issue date (BT-2)", "issueDate");
100
+ required(doc.currency, "document currency (BT-5)", "currency");
101
+ required(doc.seller.name, "seller name (BT-27)", "seller.name");
102
+ required(doc.buyer.name, "buyer name (BT-44)", "buyer.name");
103
+ if (doc.seller.endpoint && doc.seller.endpoint.scheme === void 0) throw missing("seller endpoint scheme (BT-34-1)", "seller.endpoint.scheme");
104
+ if (doc.buyer.endpoint && doc.buyer.endpoint.scheme === void 0) throw missing("buyer endpoint scheme (BT-49-1)", "buyer.endpoint.scheme");
105
+ if (doc.lines.length === 0) throw new UblBuildError("A document needs at least one line (BG-25, lines)");
106
+ doc.lines.forEach(validateLine);
107
+ required(doc.taxTotal.taxAmount, "total VAT amount (BT-110)", "taxTotal.taxAmount");
108
+ const total = doc.monetaryTotal;
109
+ required(total.lineExtensionAmount, "sum of line net amounts (BT-106)", "monetaryTotal.lineExtensionAmount");
110
+ required(total.taxExclusiveAmount, "total without VAT (BT-109)", "monetaryTotal.taxExclusiveAmount");
111
+ required(total.taxInclusiveAmount, "total with VAT (BT-112)", "monetaryTotal.taxInclusiveAmount");
112
+ required(total.payableAmount, "amount due (BT-115)", "monetaryTotal.payableAmount");
113
+ (doc.attachments ?? []).forEach(validateAttachment);
114
+ };
62
115
  /** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */
63
116
  const amount = (value) => value.toFixed(2);
64
117
  /** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */
@@ -67,52 +120,60 @@ const percent = (value) => {
67
120
  return Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);
68
121
  };
69
122
  const money = (name, value, currency) => el(name, { currencyID: currency }, amount(value));
70
- const vatTaxScheme = () => el("cac:TaxScheme", null, [el("cbc:ID", null, "VAT")]);
123
+ const text = (name, value) => value !== void 0 ? el(name, null, value) : null;
124
+ const taxScheme = (schemeId) => el("cac:TaxScheme", null, [el("cbc:ID", null, schemeId ?? "VAT")]);
71
125
  /**
72
126
  * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)
73
127
  * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption
74
128
  * reason for the non-charging categories (E/AE/O/K/G).
75
129
  */
76
- const taxCategory = (name, category) => el(name, null, [
77
- el("cbc:ID", null, category.id),
78
- el("cbc:Percent", null, percent(category.percent)),
79
- category.exemptionReason ? el("cbc:TaxExemptionReason", null, category.exemptionReason) : null,
80
- vatTaxScheme()
81
- ]);
130
+ const taxCategory = (name, category, path) => {
131
+ const valid = validateTaxCategory(category, path);
132
+ return el(name, null, [
133
+ el("cbc:ID", null, valid.id),
134
+ valid.percent !== void 0 ? el("cbc:Percent", null, percent(valid.percent)) : null,
135
+ text("cbc:TaxExemptionReason", valid.exemptionReason),
136
+ taxScheme(valid.schemeId)
137
+ ]);
138
+ };
82
139
  const postalAddress = (address) => el("cac:PostalAddress", null, [
83
- address.street ? el("cbc:StreetName", null, address.street) : null,
84
- address.additionalStreet ? el("cbc:AdditionalStreetName", null, address.additionalStreet) : null,
85
- address.city ? el("cbc:CityName", null, address.city) : null,
86
- address.postalZone ? el("cbc:PostalZone", null, address.postalZone) : null,
87
- address.countrySubentity ? el("cbc:CountrySubentity", null, address.countrySubentity) : null,
88
- address.countryCode ? el("cac:Country", null, [el("cbc:IdentificationCode", { listID: COUNTRY_CODE_LIST_ID }, address.countryCode)]) : null
89
- ]);
90
- const party = (source) => el("cac:Party", null, [
91
- source.endpoint ? el("cbc:EndpointID", { schemeID: source.endpoint.scheme }, source.endpoint.value) : null,
92
- el("cac:PartyName", null, [el("cbc:Name", null, source.name)]),
93
- postalAddress(source.address),
94
- source.vatNumber ? el("cac:PartyTaxScheme", null, [el("cbc:CompanyID", null, source.vatNumber), vatTaxScheme()]) : null,
95
- el("cac:PartyLegalEntity", null, [el("cbc:RegistrationName", null, source.legalName ?? source.name), source.companyId ? el("cbc:CompanyID", source.companyId.scheme ? { schemeID: source.companyId.scheme } : null, source.companyId.value) : null])
140
+ text("cbc:StreetName", address.street),
141
+ text("cbc:AdditionalStreetName", address.additionalStreet),
142
+ text("cbc:CityName", address.city),
143
+ text("cbc:PostalZone", address.postalZone),
144
+ text("cbc:CountrySubentity", address.countrySubentity),
145
+ address.countryCode !== void 0 ? el("cac:Country", null, [el("cbc:IdentificationCode", { listID: COUNTRY_CODE_LIST_ID }, address.countryCode)]) : null
96
146
  ]);
97
- const taxSubtotal = (subtotal, currency) => el("cac:TaxSubtotal", null, [
98
- money("cbc:TaxableAmount", subtotal.taxableAmount, currency),
99
- money("cbc:TaxAmount", subtotal.taxAmount, currency),
100
- taxCategory("cac:TaxCategory", subtotal.category)
147
+ const party = (source, name) => el("cac:Party", null, [
148
+ source.endpoint ? el("cbc:EndpointID", { schemeID: source.endpoint.scheme ?? "" }, source.endpoint.value) : null,
149
+ el("cac:PartyName", null, [el("cbc:Name", null, name)]),
150
+ source.address ? postalAddress(source.address) : null,
151
+ source.vatId !== void 0 ? el("cac:PartyTaxScheme", null, [el("cbc:CompanyID", null, source.vatId), taxScheme(source.taxSchemeId)]) : null,
152
+ el("cac:PartyLegalEntity", null, [el("cbc:RegistrationName", null, source.registrationName ?? name), source.companyId ? el("cbc:CompanyID", source.companyId.scheme !== void 0 ? { schemeID: source.companyId.scheme } : null, source.companyId.value) : null])
101
153
  ]);
154
+ const taxSubtotal = (subtotal, currency, index) => {
155
+ const path = `taxTotal.subtotals[${index}]`;
156
+ return el("cac:TaxSubtotal", null, [
157
+ money("cbc:TaxableAmount", required(subtotal.taxableAmount, "taxable amount (BT-116)", `${path}.taxableAmount`), currency),
158
+ money("cbc:TaxAmount", required(subtotal.taxAmount, "VAT amount (BT-117)", `${path}.taxAmount`), currency),
159
+ taxCategory("cac:TaxCategory", required(subtotal.category, "VAT category (BT-118)", `${path}.category`), `${path}.category`)
160
+ ]);
161
+ };
102
162
  /**
103
163
  * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`
104
164
  * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`
105
- * — emitting them after it produces schema-invalid XML.
165
+ * — emitting them after it produces schema-invalid XML. BT-113/BT-114 are
166
+ * omitted when absent or zero.
106
167
  */
107
168
  const legalMonetaryTotalChildren = (doc) => {
108
169
  const { currency, monetaryTotal: total } = doc;
109
170
  return [
110
- money("cbc:LineExtensionAmount", total.lineExtensionAmount, currency),
111
- money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount, currency),
112
- money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount, currency),
171
+ money("cbc:LineExtensionAmount", total.lineExtensionAmount ?? 0, currency),
172
+ money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount ?? 0, currency),
173
+ money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount ?? 0, currency),
113
174
  total.prepaidAmount ? money("cbc:PrepaidAmount", total.prepaidAmount, currency) : null,
114
175
  total.payableRoundingAmount ? money("cbc:PayableRoundingAmount", total.payableRoundingAmount, currency) : null,
115
- money("cbc:PayableAmount", total.payableAmount, currency)
176
+ money("cbc:PayableAmount", total.payableAmount ?? 0, currency)
116
177
  ].filter((child) => Boolean(child));
117
178
  };
118
179
  /**
@@ -120,49 +181,76 @@ const legalMonetaryTotalChildren = (doc) => {
120
181
  * fails BR-CO-19, which requires at least one of the two dates.
121
182
  */
122
183
  const invoicePeriod = (period) => {
123
- if (!period || !period.startDate && !period.endDate) return null;
124
- return el("cac:InvoicePeriod", null, [period.startDate ? el("cbc:StartDate", null, period.startDate) : null, period.endDate ? el("cbc:EndDate", null, period.endDate) : null].filter((child) => Boolean(child)));
184
+ if (!period || period.startDate === void 0 && period.endDate === void 0) return null;
185
+ return el("cac:InvoicePeriod", null, [text("cbc:StartDate", period.startDate), text("cbc:EndDate", period.endDate)]);
125
186
  };
126
187
  const line = (source, currency, documentType) => {
127
- const lineElementName = documentType === "creditNote" ? "cac:CreditNoteLine" : "cac:InvoiceLine";
128
- const quantityElementName = documentType === "creditNote" ? "cbc:CreditedQuantity" : "cbc:InvoicedQuantity";
188
+ const isCreditNote = documentType === "CreditNote";
189
+ const lineElementName = isCreditNote ? "cac:CreditNoteLine" : "cac:InvoiceLine";
190
+ const quantityElementName = isCreditNote ? "cbc:CreditedQuantity" : "cbc:InvoicedQuantity";
191
+ const unitCode = source.unitCode ?? "";
192
+ const priceAmount = (source.unitPrice ?? 0) * (source.baseQuantity ?? 1);
129
193
  return el(lineElementName, null, [
130
194
  el("cbc:ID", null, source.id),
131
- el(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),
132
- money("cbc:LineExtensionAmount", source.lineExtensionAmount, currency),
195
+ el(quantityElementName, { unitCode }, String(source.quantity ?? 0)),
196
+ money("cbc:LineExtensionAmount", source.lineExtensionAmount ?? 0, currency),
133
197
  invoicePeriod(source.invoicePeriod),
134
- el("cac:Item", null, [el("cbc:Name", null, source.name), taxCategory("cac:ClassifiedTaxCategory", source.taxCategory)]),
135
- el("cac:Price", null, [money("cbc:PriceAmount", source.priceAmount, currency), source.baseQuantity != null ? el("cbc:BaseQuantity", { unitCode: source.unitCode }, String(source.baseQuantity)) : null])
198
+ el("cac:Item", null, [
199
+ text("cbc:Description", source.description),
200
+ el("cbc:Name", null, source.itemName ?? source.description ?? source.id),
201
+ taxCategory("cac:ClassifiedTaxCategory", source.taxCategory ?? {}, `lines[${source.id}].taxCategory`)
202
+ ]),
203
+ el("cac:Price", null, [money("cbc:PriceAmount", priceAmount, currency), source.baseQuantity !== void 0 ? el("cbc:BaseQuantity", { unitCode }, String(source.baseQuantity)) : null])
136
204
  ]);
137
205
  };
138
- const attachmentReference = (attachment) => el("cac:AdditionalDocumentReference", null, [el("cbc:ID", null, attachment.id), el("cac:Attachment", null, [el("cbc:EmbeddedDocumentBinaryObject", {
139
- mimeCode: attachment.mimeCode,
140
- filename: attachment.filename
141
- }, attachment.base64)])]);
142
- const billingReference = (precedingInvoiceId) => el("cac:BillingReference", null, [el("cac:InvoiceDocumentReference", null, [el("cbc:ID", null, precedingInvoiceId)])]);
143
- /** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */
144
- const serializeUblDocument = (doc) => {
145
- const isCreditNote = doc.documentType === "creditNote";
206
+ const attachmentReference = (attachment) => el("cac:AdditionalDocumentReference", null, [el("cbc:ID", null, attachment.id ?? attachment.filename ?? attachment.externalUri ?? ""), el("cac:Attachment", null, [isExternalOnly(attachment) ? el("cac:ExternalReference", null, [el("cbc:URI", null, attachment.externalUri ?? "")]) : el("cbc:EmbeddedDocumentBinaryObject", {
207
+ mimeCode: attachment.mimeCode ?? "",
208
+ filename: attachment.filename ?? ""
209
+ }, attachment.base64Content ?? "")])]);
210
+ const billingReference = (reference) => {
211
+ if (reference.invoiceId === void 0) return null;
212
+ return el("cac:BillingReference", null, [el("cac:InvoiceDocumentReference", null, [el("cbc:ID", null, reference.invoiceId)])]);
213
+ };
214
+ /**
215
+ * Serialize a {@link UblInvoice} into a Peppol BIS Billing 3.0 XML string.
216
+ *
217
+ * Emits the subset of the model a Peppol BIS Billing 3.0 document needs:
218
+ * header (`customizationId`, `profileId` and `invoiceTypeCode` default to the
219
+ * BIS values), note, buyer reference, invoice period, billing reference,
220
+ * attachments, parties, payment terms, VAT breakdown, monetary totals and
221
+ * lines with their price and classified VAT category. Payment means,
222
+ * allowances/charges, delivery and the document references are not emitted.
223
+ *
224
+ * @throws {UblBuildError} when a field EN 16931 / Peppol BIS makes mandatory is
225
+ * missing: document id, issue date, currency, seller and buyer name, an
226
+ * endpoint without a scheme, at least one line, per line the quantity, unit
227
+ * code, unit price, net amount and VAT category (id, plus the rate unless the
228
+ * category is `O`), the total VAT amount, the four monetary totals, and for an
229
+ * embedded attachment its filename, MIME code and content.
230
+ */
231
+ const serializeUblInvoice = (doc) => {
232
+ validateInvoice(doc);
233
+ const isCreditNote = doc.documentType === "CreditNote";
146
234
  const rootName = isCreditNote ? "CreditNote" : "Invoice";
147
235
  const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
148
- const typeCodeElement = isCreditNote ? el("cbc:CreditNoteTypeCode", null, "381") : el("cbc:InvoiceTypeCode", null, "380");
236
+ const typeCodeElement = isCreditNote ? el("cbc:CreditNoteTypeCode", null, doc.invoiceTypeCode ?? "381") : el("cbc:InvoiceTypeCode", null, doc.invoiceTypeCode ?? "380");
149
237
  const children = [
150
- el("cbc:CustomizationID", null, UBL_CUSTOMIZATION_ID),
151
- el("cbc:ProfileID", null, UBL_PROFILE_ID),
238
+ el("cbc:CustomizationID", null, doc.customizationId ?? "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0"),
239
+ el("cbc:ProfileID", null, doc.profileId ?? "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0"),
152
240
  el("cbc:ID", null, doc.id),
153
241
  el("cbc:IssueDate", null, doc.issueDate),
154
- !isCreditNote && doc.dueDate ? el("cbc:DueDate", null, doc.dueDate) : null,
242
+ !isCreditNote ? text("cbc:DueDate", doc.dueDate) : null,
155
243
  typeCodeElement,
156
- doc.note ? el("cbc:Note", null, doc.note) : null,
244
+ text("cbc:Note", doc.note),
157
245
  el("cbc:DocumentCurrencyCode", null, doc.currency),
158
- doc.buyerReference ? el("cbc:BuyerReference", null, doc.buyerReference) : null,
246
+ text("cbc:BuyerReference", doc.buyerReference),
159
247
  invoicePeriod(doc.invoicePeriod),
160
- doc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,
161
- ...doc.attachments.map(attachmentReference),
162
- el("cac:AccountingSupplierParty", null, [party(doc.supplier)]),
163
- el("cac:AccountingCustomerParty", null, [party(doc.customer)]),
164
- doc.paymentTermsNote ? el("cac:PaymentTerms", null, [el("cbc:Note", null, doc.paymentTermsNote)]) : null,
165
- el("cac:TaxTotal", null, [money("cbc:TaxAmount", doc.taxTotal.taxAmount, doc.currency), ...doc.taxTotal.subtotals.map((subtotal) => taxSubtotal(subtotal, doc.currency))]),
248
+ doc.billingReference ? billingReference(doc.billingReference) : null,
249
+ ...(doc.attachments ?? []).map(attachmentReference),
250
+ el("cac:AccountingSupplierParty", null, [party(doc.seller, doc.seller.name ?? "")]),
251
+ el("cac:AccountingCustomerParty", null, [party(doc.buyer, doc.buyer.name ?? "")]),
252
+ doc.paymentTermsNote !== void 0 ? el("cac:PaymentTerms", null, [el("cbc:Note", null, doc.paymentTermsNote)]) : null,
253
+ el("cac:TaxTotal", null, [money("cbc:TaxAmount", doc.taxTotal.taxAmount ?? 0, doc.currency), ...doc.taxTotal.subtotals.map((subtotal, index) => taxSubtotal(subtotal, doc.currency, index))]),
166
254
  el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
167
255
  ...doc.lines.map((source) => line(source, doc.currency, doc.documentType))
168
256
  ];
@@ -173,24 +261,28 @@ const serializeUblDocument = (doc) => {
173
261
  }, children.filter((child) => Boolean(child)));
174
262
  return serializeDocument(root);
175
263
  };
264
+ /** Alias of {@link serializeUblInvoice}, kept under the historical name. */
265
+ const serializeUblDocument = serializeUblInvoice;
176
266
  //#endregion
177
267
  //#region src/build/utils.ts
178
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
268
+ /** Trim a string; `undefined` when missing or blank. */
179
269
  const normalizeString = (value) => {
180
- if (typeof value !== "string") return null;
270
+ if (typeof value !== "string") return void 0;
181
271
  const normalized = value.trim();
182
- return normalized.length > 0 ? normalized : null;
272
+ return normalized.length > 0 ? normalized : void 0;
183
273
  };
274
+ /** Drop `undefined`-valued keys so an absent field is an absent key. */
275
+ const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
184
276
  //#endregion
185
277
  //#region src/build/address.ts
186
278
  const normalizeCountryCode = (value) => {
187
279
  const trimmed = normalizeString(value);
188
- if (!trimmed) return null;
189
- return trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;
280
+ if (!trimmed) return void 0;
281
+ return trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : void 0;
190
282
  };
191
283
  /**
192
284
  * Normalize a free-form address (Stripe shape, custom shape, or an internal
193
- * shape) into a {@link UblAddress}.
285
+ * shape) into a {@link UblAddress}. An absent part is an absent key.
194
286
  *
195
287
  * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`
196
288
  * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address
@@ -198,16 +290,16 @@ const normalizeCountryCode = (value) => {
198
290
  * `null` when "no country" is the right answer.
199
291
  */
200
292
  const normalizeAddress = (address, fallbackCountryCode, fallbackLine) => {
201
- const record = isRecord(address) ? address : {};
293
+ const record = address ?? {};
202
294
  const countryCode = normalizeCountryCode(normalizeString(record.country)) ?? normalizeCountryCode(normalizeString(record.country_code)) ?? normalizeCountryCode(fallbackCountryCode);
203
- return {
204
- street: normalizeString(record.line1) ?? normalizeString(record.street) ?? fallbackLine ?? null,
295
+ return compact({
296
+ street: normalizeString(record.line1) ?? normalizeString(record.street) ?? normalizeString(fallbackLine),
205
297
  additionalStreet: normalizeString(record.line2),
206
298
  city: normalizeString(record.city),
207
299
  postalZone: normalizeString(record.postal_code) ?? normalizeString(record.zip_code),
208
300
  countrySubentity: normalizeString(record.state) ?? normalizeString(record.country_subentity),
209
301
  countryCode
210
- };
302
+ });
211
303
  };
212
304
  //#endregion
213
305
  //#region src/build/identifiers.ts
@@ -225,101 +317,38 @@ const normalizeCompanyNumberForCountry = (countryCode, companyNumber) => {
225
317
  return companyNumber.trim();
226
318
  };
227
319
  /**
228
- * Country code → Peppol/ISO 6523 ICD scheme for a legal registration number
229
- * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`).
230
- *
231
- * BE → 0208 (Belgian enterprise number, CBE/KBO/BCE)
232
- * NL → 0106 (Netherlands KvK)
233
- * FR → 0002 (France SIRENE)
320
+ * Peppol/ISO 6523 ICD scheme for a legal registration number
321
+ * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`), e.g. BE → `0208`
322
+ * (enterprise number), NL → `0106` (KvK), FR → `0002` (SIRENE). The table is
323
+ * `@financica/peppol`'s country profiles.
234
324
  *
235
325
  * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).
236
- * Returns `null` when the scheme can't be determined, in which case the
326
+ * Returns `undefined` when the scheme can't be determined, in which case the
237
327
  * CompanyID is emitted without a `schemeID` attribute.
238
328
  */
239
329
  const resolveCompanyIdScheme = (params) => {
240
330
  const companyNumber = normalizeString(params.companyNumber);
241
- if (!companyNumber) return null;
242
- const TABLE = {
243
- BE: "0208",
244
- NL: "0106",
245
- FR: "0002"
246
- };
247
- const normalizedCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;
248
- if (normalizedCountry && normalizedCountry in TABLE) return TABLE[normalizedCountry] ?? null;
249
- const countryPrefix = companyNumber.replace(/[^A-Za-z]/g, "").toUpperCase().slice(0, 2);
250
- return countryPrefix in TABLE ? TABLE[countryPrefix] ?? null : null;
331
+ if (!companyNumber) return void 0;
332
+ const fromCountry = getPeppolIdentifierSchemes(params.countryCode)?.companyIdentifierScheme ?? void 0;
333
+ if (fromCountry) return fromCountry;
334
+ const prefix = companyNumber.replace(/[^A-Za-z]/g, "").toUpperCase().slice(0, 2);
335
+ return getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? void 0;
251
336
  };
252
337
  /**
253
338
  * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the
254
- * country-appropriate ICD scheme when known. Returns `null` when there is no
339
+ * country-appropriate ICD scheme when known. Returns `undefined` when there is no
255
340
  * company number.
256
341
  */
257
342
  const buildCompanyId = (params) => {
258
343
  const normalized = normalizeString(normalizeCompanyNumberForCountry(params.countryCode, params.companyNumber));
259
- if (!normalized) return null;
260
- return {
344
+ if (!normalized) return void 0;
345
+ return compact({
261
346
  value: normalized,
262
347
  scheme: resolveCompanyIdScheme({
263
348
  countryCode: params.countryCode,
264
349
  companyNumber: normalized
265
350
  })
266
- };
267
- };
268
- /**
269
- * Country code → Peppol EAS scheme for a *VAT* identifier, keyed by ISO 3166-1
270
- * alpha-2. Source: Peppol Code Lists – Participant Identifier Schemes (EAS),
271
- * Peppol BIS Billing 3.0 (November 2025 release).
272
- *
273
- * Only countries that publish a VAT-based EAS scheme appear here. Some (e.g.
274
- * SE/DK/NO) address Peppol participants by organisation number rather than VAT
275
- * and are intentionally absent — see {@link resolveCompanyIdScheme}.
276
- */
277
- const VAT_SCHEME_BY_COUNTRY = {
278
- AD: "9922",
279
- AL: "9923",
280
- AT: "9914",
281
- BA: "9924",
282
- BE: "9925",
283
- BG: "9926",
284
- CH: "9927",
285
- CY: "9928",
286
- CZ: "9929",
287
- DE: "9930",
288
- EE: "9931",
289
- ES: "9920",
290
- FI: "0213",
291
- FR: "9957",
292
- GB: "9932",
293
- GR: "9933",
294
- HR: "9934",
295
- HU: "9910",
296
- IE: "9935",
297
- LI: "9936",
298
- LT: "9937",
299
- LU: "9938",
300
- LV: "9939",
301
- MC: "9940",
302
- ME: "9941",
303
- MK: "9942",
304
- MT: "9943",
305
- NL: "9944",
306
- PL: "9945",
307
- PT: "9946",
308
- RO: "9947",
309
- RS: "9948",
310
- SI: "9949",
311
- SK: "9950",
312
- SM: "9951",
313
- TR: "9952",
314
- VA: "9953"
315
- };
316
- /**
317
- * VAT registration prefixes that differ from the ISO 3166-1 alpha-2 country
318
- * code, so a VAT number's leading two letters still resolve to the right scheme.
319
- */
320
- const VAT_PREFIX_TO_COUNTRY = {
321
- EL: "GR",
322
- XI: "GB"
351
+ });
323
352
  };
324
353
  /**
325
354
  * Resolve the Peppol participant identifier for a VAT number, deriving the EAS
@@ -327,21 +356,22 @@ const VAT_PREFIX_TO_COUNTRY = {
327
356
  *
328
357
  * `BE0206582284` → `{ scheme: "9925", value: "BE0206582284" }`
329
358
  *
359
+ * The scheme comes from `@financica/peppol`'s country resolution, so countries
360
+ * that route on their registry number alone (Norway, Denmark) yield `undefined`
361
+ * here — their VAT number is not a Peppol participant identifier.
362
+ *
330
363
  * The value keeps its country prefix, matching how participants register (the
331
- * Peppol directory lists this party as `9925:be0206582284`). Returns `null`
364
+ * Peppol directory lists this party as `9925:be0206582284`). Returns `undefined`
332
365
  * when the country has no VAT EAS scheme or the input is empty.
333
366
  */
334
367
  const resolveVatEndpoint = (params) => {
335
368
  const value = normalizeString(params.vatNumber);
336
- if (!value) return null;
337
- const prefix = value.replace(/[^A-Za-z0-9]/g, "").toUpperCase().slice(0, 2);
338
- const fromPrefix = /^[A-Z]{2}$/.test(prefix) ? VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix : null;
339
- const fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;
340
- const country = fromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;
341
- const scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : void 0;
342
- if (!scheme) return null;
369
+ if (!value) return void 0;
370
+ const fromPrefix = countryFromVatNumber(value);
371
+ const scheme = getPeppolIdentifierSchemes(fromPrefix)?.vatIdentifierScheme ?? getPeppolIdentifierSchemes(params.countryCode)?.vatIdentifierScheme;
372
+ if (!scheme) return void 0;
343
373
  const cleaned = normalizeParticipantValue(scheme, value).toUpperCase();
344
- if (!cleaned) return null;
374
+ if (!cleaned) return void 0;
345
375
  return {
346
376
  scheme,
347
377
  value: cleaned
@@ -351,23 +381,23 @@ const resolveVatEndpoint = (params) => {
351
381
  * Parse a Peppol participant identifier into a {@link UblEndpoint}.
352
382
  *
353
383
  * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns
354
- * `null` for values without an explicit scheme, since `cbc:EndpointID` requires
384
+ * `undefined` for values without an explicit scheme, since `cbc:EndpointID` requires
355
385
  * a `schemeID` and guessing one would mis-route the document.
356
386
  */
357
387
  const parsePeppolEndpoint = (peppolId) => {
358
388
  const normalized = normalizeString(peppolId);
359
- if (!normalized) return null;
389
+ if (!normalized) return void 0;
360
390
  const separatorIndex = normalized.indexOf(":");
361
- if (separatorIndex <= 0) return null;
391
+ if (separatorIndex <= 0) return void 0;
362
392
  const scheme = normalized.slice(0, separatorIndex).trim();
363
393
  const value = normalized.slice(separatorIndex + 1).trim();
364
- if (!scheme || !value) return null;
394
+ if (!scheme || !value) return void 0;
365
395
  return {
366
396
  scheme,
367
397
  value
368
398
  };
369
399
  };
370
- const normalizeIdentifierType = (value) => value?.toLowerCase().replace(/[^a-z0-9]+/g, "_") ?? null;
400
+ const normalizeIdentifierType = (value) => value?.toLowerCase().replace(/[^a-z0-9]+/g, "_");
371
401
  /**
372
402
  * Pick the first usable Peppol identifier, GLN, VAT number, and tax number
373
403
  * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).
@@ -380,14 +410,7 @@ const extractCustomerTaxIdentifiers = (taxIds) => {
380
410
  let glnNumber = null;
381
411
  let taxNumber = null;
382
412
  let vatNumber = null;
383
- if (!Array.isArray(taxIds)) return {
384
- peppolID,
385
- glnNumber,
386
- taxNumber,
387
- vatNumber
388
- };
389
- for (const entry of taxIds) {
390
- if (!isRecord(entry)) continue;
413
+ for (const entry of taxIds ?? []) {
391
414
  const type = normalizeIdentifierType(normalizeString(entry.type));
392
415
  const value = normalizeString(entry.value);
393
416
  if (!type || !value) continue;
@@ -461,23 +484,23 @@ const listPeppolReceiverIdentifierCandidates = (customer, countryCode) => {
461
484
  };
462
485
  //#endregion
463
486
  //#region src/build/party.ts
464
- /** Convert a {@link UblSupplier} into the supplier (seller) party. */
487
+ /** Convert a {@link UblSupplier} into the seller party (`cac:AccountingSupplierParty`). */
465
488
  const buildSupplierParty = (supplier) => {
466
489
  const address = normalizeAddress(supplier.address, supplier.countryCode);
467
- return {
490
+ return compact({
468
491
  endpoint: parsePeppolEndpoint(supplier.peppolID),
469
492
  name: supplier.name,
493
+ registrationName: supplier.name,
470
494
  address,
471
- vatNumber: normalizeString(supplier.vatNumber),
472
- legalName: supplier.name,
495
+ vatId: normalizeString(supplier.vatNumber),
473
496
  companyId: buildCompanyId({
474
497
  countryCode: supplier.countryCode,
475
498
  companyNumber: supplier.companyNumber ?? null
476
499
  })
477
- };
500
+ });
478
501
  };
479
502
  /**
480
- * Convert a {@link UblCustomer} into the customer (buyer) party.
503
+ * Convert a {@link UblCustomer} into the buyer party (`cac:AccountingCustomerParty`).
481
504
  *
482
505
  * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in
483
506
  * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered
@@ -488,24 +511,25 @@ const buildSupplierParty = (supplier) => {
488
511
  * document would be unroutable.
489
512
  */
490
513
  const buildCustomerParty = (customer, endpointOverride) => {
491
- const countryCode = normalizeString(customer.countryCode) ?? customer.address.countryCode;
492
- return {
493
- endpoint: endpointOverride ?? parsePeppolEndpoint(customer.peppolID) ?? (customer.glnNumber ? {
494
- scheme: "0088",
495
- value: customer.glnNumber
496
- } : null) ?? resolveVatEndpoint({
497
- vatNumber: customer.vatNumber,
498
- countryCode
499
- }),
514
+ const countryCode = normalizeString(customer.countryCode) ?? customer.address.countryCode ?? null;
515
+ const endpoint = endpointOverride ?? parsePeppolEndpoint(customer.peppolID) ?? (customer.glnNumber ? {
516
+ scheme: "0088",
517
+ value: customer.glnNumber
518
+ } : void 0) ?? resolveVatEndpoint({
519
+ vatNumber: customer.vatNumber,
520
+ countryCode
521
+ });
522
+ return compact({
523
+ endpoint,
500
524
  name: customer.name,
525
+ registrationName: customer.name,
501
526
  address: customer.address,
502
- vatNumber: normalizeString(customer.vatNumber),
503
- legalName: customer.name,
527
+ vatId: normalizeString(customer.vatNumber),
504
528
  companyId: buildCompanyId({
505
529
  countryCode,
506
530
  companyNumber: customer.taxNumber ?? null
507
531
  })
508
- };
532
+ });
509
533
  };
510
534
  //#endregion
511
535
  //#region src/build/attachment.ts
@@ -518,20 +542,20 @@ const buildPdfAttachment = (params) => ({
518
542
  id: params.id ?? params.filename,
519
543
  filename: params.filename,
520
544
  mimeCode: "application/pdf",
521
- base64: Buffer.from(params.bytes).toString("base64")
545
+ base64Content: Buffer.from(params.bytes).toString("base64")
522
546
  });
523
547
  /**
524
548
  * Replace each attachment's base64 payload with `[omitted]` plus a length, so a
525
- * {@link UblDocument} is safe to log or persist for audit.
549
+ * {@link UblInvoice} is safe to log or persist for audit.
526
550
  */
527
551
  const sanitizeUblDocumentForAudit = (doc) => {
528
- if (doc.attachments.length === 0) return doc;
552
+ if (!doc.attachments?.length) return doc;
529
553
  return {
530
554
  ...doc,
531
- attachments: doc.attachments.map((attachment) => ({
555
+ attachments: doc.attachments.map((attachment) => attachment.base64Content === void 0 ? attachment : {
532
556
  ...attachment,
533
- base64: `[omitted ${attachment.base64.length} chars]`
534
- }))
557
+ base64Content: `[omitted ${attachment.base64Content.length} chars]`
558
+ })
535
559
  };
536
560
  };
537
561
  //#endregion
@@ -544,24 +568,26 @@ const centsToDecimal = (cents) => roundCurrency(cents / 100);
544
568
  * Derive the `cac:Price` for a line whose net total is authoritative.
545
569
  *
546
570
  * Peppol rule PEPPOL-EN16931-R120 checks
547
- * `quantity × (priceAmount ÷ baseQuantity)` against the line net amount within
571
+ * `quantity × (PriceAmount ÷ BaseQuantity)` against the line net amount within
548
572
  * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that
549
573
  * whenever the division doesn't land on a cent: 940.00 over 14 units gives
550
574
  * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and
551
575
  * rejected as a fatal validation error.
552
576
  *
553
577
  * So the cent-rounded unit price is only used when it reproduces the net
554
- * exactly. Otherwise the line is priced as a whole via BT-149 (`priceAmount` =
555
- * the net, `baseQuantity` = the quantity), which is exact at any magnitude
556
- * instead of merely within tolerance — the residual of a rounded unit price
557
- * grows with quantity and would eventually breach 0.02 at any fixed precision.
578
+ * exactly. Otherwise the line is priced as a whole via BT-149: `unitPrice` is
579
+ * the exact (unrounded) `net ÷ quantity` and `baseQuantity` = the quantity, so
580
+ * the serializer writes `PriceAmount` = the net and `BaseQuantity` = the
581
+ * quantity, which is exact at any magnitude instead of merely within tolerance
582
+ * — the residual of a rounded unit price grows with quantity and would
583
+ * eventually breach 0.02 at any fixed precision.
558
584
  */
559
585
  const deriveUnitPrice = (netTotal, quantity) => {
560
586
  const units = quantity > 0 ? quantity : 1;
561
587
  const perUnit = roundCurrency(netTotal / units);
562
- if (roundCurrency(perUnit * units) === roundCurrency(netTotal)) return { priceAmount: perUnit };
588
+ if (roundCurrency(perUnit * units) === roundCurrency(netTotal)) return { unitPrice: perUnit };
563
589
  return {
564
- priceAmount: roundCurrency(netTotal),
590
+ unitPrice: roundCurrency(netTotal) / units,
565
591
  baseQuantity: units
566
592
  };
567
593
  };
@@ -591,11 +617,7 @@ const EXEMPTION_REASON_TEXT = {
591
617
  not_collecting: "VAT not collected",
592
618
  not_supported: "VAT not applicable"
593
619
  };
594
- const normalizeTaxCategoryId = (value) => {
595
- if (typeof value !== "string") return null;
596
- const normalized = value.trim().toUpperCase();
597
- return normalized.length > 0 ? normalized : null;
598
- };
620
+ const normalizeTaxCategoryId = (value) => normalizeString(value)?.toUpperCase();
599
621
  /**
600
622
  * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a
601
623
  * numeric rate into a {@link UblTaxCategory}.
@@ -613,22 +635,22 @@ const taxCategoryFromReasonOrRate = (params) => {
613
635
  if (categoryHint === "AE" || reason === "reverse_charge") return {
614
636
  id: "AE",
615
637
  percent: 0,
616
- exemptionReason: EXEMPTION_REASON_TEXT.reverse_charge
638
+ exemptionReason: EXEMPTION_REASON_TEXT["reverse_charge"]
617
639
  };
618
640
  if (categoryHint === "K" || reason === "intra_community") return {
619
641
  id: "K",
620
642
  percent: 0,
621
- exemptionReason: EXEMPTION_REASON_TEXT.intra_community
643
+ exemptionReason: EXEMPTION_REASON_TEXT["intra_community"]
622
644
  };
623
645
  if (categoryHint === "G" || reason === "export") return {
624
646
  id: "G",
625
647
  percent: 0,
626
- exemptionReason: EXEMPTION_REASON_TEXT.export
648
+ exemptionReason: EXEMPTION_REASON_TEXT["export"]
627
649
  };
628
650
  if (categoryHint === "E" || reason && EXEMPT_TAXABILITY_REASONS.has(reason)) return {
629
651
  id: "E",
630
652
  percent: 0,
631
- exemptionReason: (reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? "Exempt from VAT"
653
+ exemptionReason: (reason ? EXEMPTION_REASON_TEXT[reason] : void 0) ?? "Exempt from VAT"
632
654
  };
633
655
  if (categoryHint === "Z" || reason === "zero_rated" || params.rate <= 0) return {
634
656
  id: "Z",
@@ -648,26 +670,45 @@ const taxCategoryFromReasonOrRate = (params) => {
648
670
  const resolveTaxCategoryFromTaxAmounts = (taxAmounts, rate) => {
649
671
  for (const ta of taxAmounts) {
650
672
  if (!ta.taxability_reason) continue;
651
- if (ta.taxability_reason === "reverse_charge") return taxCategoryFromReasonOrRate({
652
- taxabilityReason: "reverse_charge",
653
- rate
654
- });
655
- if (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) return taxCategoryFromReasonOrRate({
673
+ if (ta.taxability_reason === "reverse_charge" || ta.taxability_reason === "zero_rated" || EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) return taxCategoryFromReasonOrRate({
656
674
  taxabilityReason: ta.taxability_reason,
657
675
  rate
658
676
  });
659
- if (ta.taxability_reason === "zero_rated") return taxCategoryFromReasonOrRate({
660
- taxabilityReason: "zero_rated",
661
- rate
662
- });
663
677
  }
664
678
  return taxCategoryFromReasonOrRate({
665
679
  taxabilityReason: null,
666
680
  rate
667
681
  });
668
682
  };
683
+ /**
684
+ * BT-120 text for a small-business/franchise exemption, by supplier country.
685
+ * Countries without a specific legal reference fall back to the generic text.
686
+ */
687
+ const SMALL_BUSINESS_EXEMPTION_REASON_BY_COUNTRY = { BE: "Exempt — small business scheme (Article 56bis)" };
688
+ const SMALL_BUSINESS_EXEMPTION_REASON = "Exempt — small business scheme";
689
+ const NOT_SUBJECT_EXEMPTION_REASON = "Seller not subject to VAT";
690
+ /**
691
+ * When the supplier does not charge VAT, coerce every line to a non-charging
692
+ * exempt category (`E`, 0%) with the appropriate BT-120 reason, so the document
693
+ * reports no VAT regardless of what the upstream line tax data implied. Lines
694
+ * are returned untouched for a `subject` supplier.
695
+ */
696
+ const coerceLinesForSupplierVatStatus = (lines, vatStatus, supplierCountryCode) => {
697
+ if (vatStatus === "subject") return lines;
698
+ const country = normalizeString(supplierCountryCode)?.toUpperCase();
699
+ const exemptionReason = vatStatus === "small_business" ? (country && SMALL_BUSINESS_EXEMPTION_REASON_BY_COUNTRY[country]) ?? SMALL_BUSINESS_EXEMPTION_REASON : NOT_SUBJECT_EXEMPTION_REASON;
700
+ return lines.map((line) => ({
701
+ ...line,
702
+ taxCategory: {
703
+ id: "E",
704
+ percent: 0,
705
+ exemptionReason
706
+ }
707
+ }));
708
+ };
669
709
  //#endregion
670
710
  //#region src/build/tax-totals.ts
711
+ const lineNet = (line) => line.lineExtensionAmount ?? 0;
671
712
  /**
672
713
  * Adjust the largest line's net amount so the line nets sum to the
673
714
  * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).
@@ -680,23 +721,23 @@ const resolveTaxCategoryFromTaxAmounts = (taxAmounts, rate) => {
680
721
  */
681
722
  const reconcileLinesToExclTotal = (lines, authoritativeTotalExclVat) => {
682
723
  if (lines.length === 0) return lines;
683
- const computed = roundCurrency(lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0));
724
+ const computed = roundCurrency(lines.reduce((sum, line) => sum + lineNet(line), 0));
684
725
  const diff = roundCurrency(authoritativeTotalExclVat - computed);
685
726
  if (diff === 0) return lines;
686
- const largestIdx = lines.reduce((maxIdx, line, idx, arr) => line.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0) ? idx : maxIdx, 0);
727
+ const largestIdx = lines.reduce((maxIdx, line, idx, arr) => lineNet(line) > lineNet(arr[maxIdx] ?? line) ? idx : maxIdx, 0);
687
728
  return lines.map((line, idx) => {
688
729
  if (idx !== largestIdx) return line;
689
- const adjusted = roundCurrency(line.lineExtensionAmount + diff);
690
- const { priceAmount, baseQuantity } = deriveUnitPrice(adjusted, line.quantity);
691
- return {
730
+ const adjusted = roundCurrency(lineNet(line) + diff);
731
+ const { unitPrice, baseQuantity } = deriveUnitPrice(adjusted, line.quantity ?? 0);
732
+ return compact({
692
733
  ...line,
693
734
  lineExtensionAmount: adjusted,
694
- priceAmount,
735
+ unitPrice,
695
736
  baseQuantity
696
- };
737
+ });
697
738
  });
698
739
  };
699
- const categoryKey = (category) => `${category.id}:${category.percent}`;
740
+ const categoryKey = (category) => `${category.id ?? ""}:${category.percent ?? ""}`;
700
741
  /**
701
742
  * Group lines by `(category, percent)` into a VAT breakdown and compute the
702
743
  * document monetary totals.
@@ -712,25 +753,29 @@ const categoryKey = (category) => `${category.id}:${category.percent}`;
712
753
  * invariant holds by construction. The result is *not* clamped: a prepayment
713
754
  * exceeding the total yields a negative payable amount, surfacing the upstream
714
755
  * overpayment rather than hiding it.
756
+ *
757
+ * @throws {UblBuildError} for a line without a `taxCategory` — there is no
758
+ * VAT breakdown to put it in.
715
759
  */
716
760
  const buildTaxTotals = (lines, options) => {
717
761
  const groups = /* @__PURE__ */ new Map();
718
762
  for (const line of lines) {
763
+ if (!line.taxCategory) throw new UblBuildError(`Line ${line.id} has no taxCategory (BT-151); cannot build the VAT breakdown`);
719
764
  const key = categoryKey(line.taxCategory);
720
765
  const current = groups.get(key) ?? {
721
766
  category: line.taxCategory,
722
767
  taxableAmount: 0
723
768
  };
724
- current.taxableAmount = roundCurrency(current.taxableAmount + line.lineExtensionAmount);
769
+ current.taxableAmount = roundCurrency(current.taxableAmount + lineNet(line));
725
770
  groups.set(key, current);
726
771
  }
727
772
  const subtotals = Array.from(groups.values()).map((group) => ({
728
773
  taxableAmount: group.taxableAmount,
729
- taxAmount: roundCurrency(group.taxableAmount * group.category.percent / 100),
774
+ taxAmount: roundCurrency(group.taxableAmount * (group.category.percent ?? 0) / 100),
730
775
  category: group.category
731
776
  }));
732
- const lineExtensionAmount = roundCurrency(lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0));
733
- const taxAmount = roundCurrency(subtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0));
777
+ const lineExtensionAmount = roundCurrency(lines.reduce((sum, line) => sum + lineNet(line), 0));
778
+ const taxAmount = roundCurrency(subtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0));
734
779
  const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
735
780
  const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
736
781
  const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
@@ -751,6 +796,6 @@ const buildTaxTotals = (lines, options) => {
751
796
  };
752
797
  };
753
798
  //#endregion
754
- export { COUNTRY_CODE_LIST_ID, CREDIT_NOTE_TYPE_CODE, DEFAULT_UNIT_CODE, EXEMPT_TAXABILITY_REASONS, INVOICE_TYPE_CODE, NS_CAC, NS_CBC, NS_CREDIT_NOTE, NS_INVOICE, UBL_CUSTOMIZATION_ID, UBL_PROFILE_ID, VAT_TAX_SCHEME_ID, buildCompanyId, buildCustomerParty, buildPdfAttachment, buildSupplierParty, buildTaxTotals, centsToDecimal, deriveUnitPrice, el, extractCustomerTaxIdentifiers, listPeppolReceiverIdentifierCandidates, normalizeAddress, normalizeCompanyNumberForCountry, parsePeppolEndpoint, reconcileLinesToExclTotal, resolveCompanyIdScheme, resolveTaxCategoryFromTaxAmounts, resolveVatEndpoint, roundCurrency, sanitizeUblDocumentForAudit, serializeDocument, serializeUblDocument, taxCategoryFromReasonOrRate };
799
+ export { COUNTRY_CODE_LIST_ID, CREDIT_NOTE_TYPE_CODE, DEFAULT_UNIT_CODE, EXEMPT_TAXABILITY_REASONS, INVOICE_TYPE_CODE, NS_CAC, NS_CBC, NS_CREDIT_NOTE, NS_INVOICE, UBL_CUSTOMIZATION_ID, UBL_PROFILE_ID, UblBuildError, VAT_TAX_SCHEME_ID, buildCompanyId, buildCustomerParty, buildPdfAttachment, buildSupplierParty, buildTaxTotals, centsToDecimal, coerceLinesForSupplierVatStatus, deriveUnitPrice, el, extractCustomerTaxIdentifiers, listPeppolReceiverIdentifierCandidates, normalizeAddress, normalizeCompanyNumberForCountry, parsePeppolEndpoint, reconcileLinesToExclTotal, resolveCompanyIdScheme, resolveTaxCategoryFromTaxAmounts, resolveVatEndpoint, roundCurrency, sanitizeUblDocumentForAudit, serializeDocument, serializeUblDocument, serializeUblInvoice, taxCategoryFromReasonOrRate };
755
800
 
756
801
  //# sourceMappingURL=index.js.map