@financica/ubl 0.16.0 → 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,3 +1,4 @@
1
+ import { t as UblBuildError } from "../errors-C9YYJ1xR.js";
1
2
  import { getPeppolIdentifierSchemes } from "@financica/peppol/countries";
2
3
  import { countryFromVatNumber, normalizeParticipantValue } from "@financica/peppol/identifiers";
3
4
  //#region src/build/ubl/constants.ts
@@ -60,6 +61,57 @@ const serializeElement = (node, indentLevel) => {
60
61
  const serializeDocument = (root) => `<?xml version="1.0" encoding="UTF-8"?>\n${serializeElement(root, 0)}\n`;
61
62
  //#endregion
62
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
+ };
63
115
  /** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */
64
116
  const amount = (value) => value.toFixed(2);
65
117
  /** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */
@@ -68,52 +120,60 @@ const percent = (value) => {
68
120
  return Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);
69
121
  };
70
122
  const money = (name, value, currency) => el(name, { currencyID: currency }, amount(value));
71
- 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")]);
72
125
  /**
73
126
  * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)
74
127
  * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption
75
128
  * reason for the non-charging categories (E/AE/O/K/G).
76
129
  */
77
- const taxCategory = (name, category) => el(name, null, [
78
- el("cbc:ID", null, category.id),
79
- el("cbc:Percent", null, percent(category.percent)),
80
- category.exemptionReason ? el("cbc:TaxExemptionReason", null, category.exemptionReason) : null,
81
- vatTaxScheme()
82
- ]);
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
+ };
83
139
  const postalAddress = (address) => el("cac:PostalAddress", null, [
84
- address.street ? el("cbc:StreetName", null, address.street) : null,
85
- address.additionalStreet ? el("cbc:AdditionalStreetName", null, address.additionalStreet) : null,
86
- address.city ? el("cbc:CityName", null, address.city) : null,
87
- address.postalZone ? el("cbc:PostalZone", null, address.postalZone) : null,
88
- address.countrySubentity ? el("cbc:CountrySubentity", null, address.countrySubentity) : null,
89
- address.countryCode ? el("cac:Country", null, [el("cbc:IdentificationCode", { listID: COUNTRY_CODE_LIST_ID }, address.countryCode)]) : null
90
- ]);
91
- const party = (source) => el("cac:Party", null, [
92
- source.endpoint ? el("cbc:EndpointID", { schemeID: source.endpoint.scheme }, source.endpoint.value) : null,
93
- el("cac:PartyName", null, [el("cbc:Name", null, source.name)]),
94
- postalAddress(source.address),
95
- source.vatNumber ? el("cac:PartyTaxScheme", null, [el("cbc:CompanyID", null, source.vatNumber), vatTaxScheme()]) : null,
96
- 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
97
146
  ]);
98
- const taxSubtotal = (subtotal, currency) => el("cac:TaxSubtotal", null, [
99
- money("cbc:TaxableAmount", subtotal.taxableAmount, currency),
100
- money("cbc:TaxAmount", subtotal.taxAmount, currency),
101
- 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])
102
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
+ };
103
162
  /**
104
163
  * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`
105
164
  * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`
106
- * — 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.
107
167
  */
108
168
  const legalMonetaryTotalChildren = (doc) => {
109
169
  const { currency, monetaryTotal: total } = doc;
110
170
  return [
111
- money("cbc:LineExtensionAmount", total.lineExtensionAmount, currency),
112
- money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount, currency),
113
- 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),
114
174
  total.prepaidAmount ? money("cbc:PrepaidAmount", total.prepaidAmount, currency) : null,
115
175
  total.payableRoundingAmount ? money("cbc:PayableRoundingAmount", total.payableRoundingAmount, currency) : null,
116
- money("cbc:PayableAmount", total.payableAmount, currency)
176
+ money("cbc:PayableAmount", total.payableAmount ?? 0, currency)
117
177
  ].filter((child) => Boolean(child));
118
178
  };
119
179
  /**
@@ -121,49 +181,76 @@ const legalMonetaryTotalChildren = (doc) => {
121
181
  * fails BR-CO-19, which requires at least one of the two dates.
122
182
  */
123
183
  const invoicePeriod = (period) => {
124
- if (!period || !period.startDate && !period.endDate) return null;
125
- 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)]);
126
186
  };
127
187
  const line = (source, currency, documentType) => {
128
- const lineElementName = documentType === "creditNote" ? "cac:CreditNoteLine" : "cac:InvoiceLine";
129
- 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);
130
193
  return el(lineElementName, null, [
131
194
  el("cbc:ID", null, source.id),
132
- el(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),
133
- money("cbc:LineExtensionAmount", source.lineExtensionAmount, currency),
195
+ el(quantityElementName, { unitCode }, String(source.quantity ?? 0)),
196
+ money("cbc:LineExtensionAmount", source.lineExtensionAmount ?? 0, currency),
134
197
  invoicePeriod(source.invoicePeriod),
135
- el("cac:Item", null, [el("cbc:Name", null, source.name), taxCategory("cac:ClassifiedTaxCategory", source.taxCategory)]),
136
- 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])
137
204
  ]);
138
205
  };
139
- const attachmentReference = (attachment) => el("cac:AdditionalDocumentReference", null, [el("cbc:ID", null, attachment.id), el("cac:Attachment", null, [el("cbc:EmbeddedDocumentBinaryObject", {
140
- mimeCode: attachment.mimeCode,
141
- filename: attachment.filename
142
- }, attachment.base64)])]);
143
- const billingReference = (precedingInvoiceId) => el("cac:BillingReference", null, [el("cac:InvoiceDocumentReference", null, [el("cbc:ID", null, precedingInvoiceId)])]);
144
- /** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */
145
- const serializeUblDocument = (doc) => {
146
- 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";
147
234
  const rootName = isCreditNote ? "CreditNote" : "Invoice";
148
235
  const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
149
- 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");
150
237
  const children = [
151
- el("cbc:CustomizationID", null, UBL_CUSTOMIZATION_ID),
152
- 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"),
153
240
  el("cbc:ID", null, doc.id),
154
241
  el("cbc:IssueDate", null, doc.issueDate),
155
- !isCreditNote && doc.dueDate ? el("cbc:DueDate", null, doc.dueDate) : null,
242
+ !isCreditNote ? text("cbc:DueDate", doc.dueDate) : null,
156
243
  typeCodeElement,
157
- doc.note ? el("cbc:Note", null, doc.note) : null,
244
+ text("cbc:Note", doc.note),
158
245
  el("cbc:DocumentCurrencyCode", null, doc.currency),
159
- doc.buyerReference ? el("cbc:BuyerReference", null, doc.buyerReference) : null,
246
+ text("cbc:BuyerReference", doc.buyerReference),
160
247
  invoicePeriod(doc.invoicePeriod),
161
- doc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,
162
- ...doc.attachments.map(attachmentReference),
163
- el("cac:AccountingSupplierParty", null, [party(doc.supplier)]),
164
- el("cac:AccountingCustomerParty", null, [party(doc.customer)]),
165
- doc.paymentTermsNote ? el("cac:PaymentTerms", null, [el("cbc:Note", null, doc.paymentTermsNote)]) : null,
166
- 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))]),
167
254
  el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
168
255
  ...doc.lines.map((source) => line(source, doc.currency, doc.documentType))
169
256
  ];
@@ -174,24 +261,28 @@ const serializeUblDocument = (doc) => {
174
261
  }, children.filter((child) => Boolean(child)));
175
262
  return serializeDocument(root);
176
263
  };
264
+ /** Alias of {@link serializeUblInvoice}, kept under the historical name. */
265
+ const serializeUblDocument = serializeUblInvoice;
177
266
  //#endregion
178
267
  //#region src/build/utils.ts
179
- /** Trim a string; `null` when missing or blank. */
268
+ /** Trim a string; `undefined` when missing or blank. */
180
269
  const normalizeString = (value) => {
181
- if (typeof value !== "string") return null;
270
+ if (typeof value !== "string") return void 0;
182
271
  const normalized = value.trim();
183
- return normalized.length > 0 ? normalized : null;
272
+ return normalized.length > 0 ? normalized : void 0;
184
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));
185
276
  //#endregion
186
277
  //#region src/build/address.ts
187
278
  const normalizeCountryCode = (value) => {
188
279
  const trimmed = normalizeString(value);
189
- if (!trimmed) return null;
190
- 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;
191
282
  };
192
283
  /**
193
284
  * Normalize a free-form address (Stripe shape, custom shape, or an internal
194
- * shape) into a {@link UblAddress}.
285
+ * shape) into a {@link UblAddress}. An absent part is an absent key.
195
286
  *
196
287
  * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`
197
288
  * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address
@@ -201,14 +292,14 @@ const normalizeCountryCode = (value) => {
201
292
  const normalizeAddress = (address, fallbackCountryCode, fallbackLine) => {
202
293
  const record = address ?? {};
203
294
  const countryCode = normalizeCountryCode(normalizeString(record.country)) ?? normalizeCountryCode(normalizeString(record.country_code)) ?? normalizeCountryCode(fallbackCountryCode);
204
- return {
205
- street: normalizeString(record.line1) ?? normalizeString(record.street) ?? fallbackLine ?? null,
295
+ return compact({
296
+ street: normalizeString(record.line1) ?? normalizeString(record.street) ?? normalizeString(fallbackLine),
206
297
  additionalStreet: normalizeString(record.line2),
207
298
  city: normalizeString(record.city),
208
299
  postalZone: normalizeString(record.postal_code) ?? normalizeString(record.zip_code),
209
300
  countrySubentity: normalizeString(record.state) ?? normalizeString(record.country_subentity),
210
301
  countryCode
211
- };
302
+ });
212
303
  };
213
304
  //#endregion
214
305
  //#region src/build/identifiers.ts
@@ -232,32 +323,32 @@ const normalizeCompanyNumberForCountry = (countryCode, companyNumber) => {
232
323
  * `@financica/peppol`'s country profiles.
233
324
  *
234
325
  * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).
235
- * 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
236
327
  * CompanyID is emitted without a `schemeID` attribute.
237
328
  */
238
329
  const resolveCompanyIdScheme = (params) => {
239
330
  const companyNumber = normalizeString(params.companyNumber);
240
- if (!companyNumber) return null;
241
- const fromCountry = getPeppolIdentifierSchemes(params.countryCode)?.companyIdentifierScheme;
331
+ if (!companyNumber) return void 0;
332
+ const fromCountry = getPeppolIdentifierSchemes(params.countryCode)?.companyIdentifierScheme ?? void 0;
242
333
  if (fromCountry) return fromCountry;
243
334
  const prefix = companyNumber.replace(/[^A-Za-z]/g, "").toUpperCase().slice(0, 2);
244
- return getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? null;
335
+ return getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? void 0;
245
336
  };
246
337
  /**
247
338
  * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the
248
- * 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
249
340
  * company number.
250
341
  */
251
342
  const buildCompanyId = (params) => {
252
343
  const normalized = normalizeString(normalizeCompanyNumberForCountry(params.countryCode, params.companyNumber));
253
- if (!normalized) return null;
254
- return {
344
+ if (!normalized) return void 0;
345
+ return compact({
255
346
  value: normalized,
256
347
  scheme: resolveCompanyIdScheme({
257
348
  countryCode: params.countryCode,
258
349
  companyNumber: normalized
259
350
  })
260
- };
351
+ });
261
352
  };
262
353
  /**
263
354
  * Resolve the Peppol participant identifier for a VAT number, deriving the EAS
@@ -266,21 +357,21 @@ const buildCompanyId = (params) => {
266
357
  * `BE0206582284` → `{ scheme: "9925", value: "BE0206582284" }`
267
358
  *
268
359
  * The scheme comes from `@financica/peppol`'s country resolution, so countries
269
- * that route on their registry number alone (Norway, Denmark) yield `null`
360
+ * that route on their registry number alone (Norway, Denmark) yield `undefined`
270
361
  * here — their VAT number is not a Peppol participant identifier.
271
362
  *
272
363
  * The value keeps its country prefix, matching how participants register (the
273
- * Peppol directory lists this party as `9925:be0206582284`). Returns `null`
364
+ * Peppol directory lists this party as `9925:be0206582284`). Returns `undefined`
274
365
  * when the country has no VAT EAS scheme or the input is empty.
275
366
  */
276
367
  const resolveVatEndpoint = (params) => {
277
368
  const value = normalizeString(params.vatNumber);
278
- if (!value) return null;
369
+ if (!value) return void 0;
279
370
  const fromPrefix = countryFromVatNumber(value);
280
371
  const scheme = getPeppolIdentifierSchemes(fromPrefix)?.vatIdentifierScheme ?? getPeppolIdentifierSchemes(params.countryCode)?.vatIdentifierScheme;
281
- if (!scheme) return null;
372
+ if (!scheme) return void 0;
282
373
  const cleaned = normalizeParticipantValue(scheme, value).toUpperCase();
283
- if (!cleaned) return null;
374
+ if (!cleaned) return void 0;
284
375
  return {
285
376
  scheme,
286
377
  value: cleaned
@@ -290,23 +381,23 @@ const resolveVatEndpoint = (params) => {
290
381
  * Parse a Peppol participant identifier into a {@link UblEndpoint}.
291
382
  *
292
383
  * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns
293
- * `null` for values without an explicit scheme, since `cbc:EndpointID` requires
384
+ * `undefined` for values without an explicit scheme, since `cbc:EndpointID` requires
294
385
  * a `schemeID` and guessing one would mis-route the document.
295
386
  */
296
387
  const parsePeppolEndpoint = (peppolId) => {
297
388
  const normalized = normalizeString(peppolId);
298
- if (!normalized) return null;
389
+ if (!normalized) return void 0;
299
390
  const separatorIndex = normalized.indexOf(":");
300
- if (separatorIndex <= 0) return null;
391
+ if (separatorIndex <= 0) return void 0;
301
392
  const scheme = normalized.slice(0, separatorIndex).trim();
302
393
  const value = normalized.slice(separatorIndex + 1).trim();
303
- if (!scheme || !value) return null;
394
+ if (!scheme || !value) return void 0;
304
395
  return {
305
396
  scheme,
306
397
  value
307
398
  };
308
399
  };
309
- const normalizeIdentifierType = (value) => value?.toLowerCase().replace(/[^a-z0-9]+/g, "_") ?? null;
400
+ const normalizeIdentifierType = (value) => value?.toLowerCase().replace(/[^a-z0-9]+/g, "_");
310
401
  /**
311
402
  * Pick the first usable Peppol identifier, GLN, VAT number, and tax number
312
403
  * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).
@@ -393,23 +484,23 @@ const listPeppolReceiverIdentifierCandidates = (customer, countryCode) => {
393
484
  };
394
485
  //#endregion
395
486
  //#region src/build/party.ts
396
- /** Convert a {@link UblSupplier} into the supplier (seller) party. */
487
+ /** Convert a {@link UblSupplier} into the seller party (`cac:AccountingSupplierParty`). */
397
488
  const buildSupplierParty = (supplier) => {
398
489
  const address = normalizeAddress(supplier.address, supplier.countryCode);
399
- return {
490
+ return compact({
400
491
  endpoint: parsePeppolEndpoint(supplier.peppolID),
401
492
  name: supplier.name,
493
+ registrationName: supplier.name,
402
494
  address,
403
- vatNumber: normalizeString(supplier.vatNumber),
404
- legalName: supplier.name,
495
+ vatId: normalizeString(supplier.vatNumber),
405
496
  companyId: buildCompanyId({
406
497
  countryCode: supplier.countryCode,
407
498
  companyNumber: supplier.companyNumber ?? null
408
499
  })
409
- };
500
+ });
410
501
  };
411
502
  /**
412
- * Convert a {@link UblCustomer} into the customer (buyer) party.
503
+ * Convert a {@link UblCustomer} into the buyer party (`cac:AccountingCustomerParty`).
413
504
  *
414
505
  * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in
415
506
  * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered
@@ -420,24 +511,25 @@ const buildSupplierParty = (supplier) => {
420
511
  * document would be unroutable.
421
512
  */
422
513
  const buildCustomerParty = (customer, endpointOverride) => {
423
- const countryCode = normalizeString(customer.countryCode) ?? customer.address.countryCode;
424
- return {
425
- endpoint: endpointOverride ?? parsePeppolEndpoint(customer.peppolID) ?? (customer.glnNumber ? {
426
- scheme: "0088",
427
- value: customer.glnNumber
428
- } : null) ?? resolveVatEndpoint({
429
- vatNumber: customer.vatNumber,
430
- countryCode
431
- }),
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,
432
524
  name: customer.name,
525
+ registrationName: customer.name,
433
526
  address: customer.address,
434
- vatNumber: normalizeString(customer.vatNumber),
435
- legalName: customer.name,
527
+ vatId: normalizeString(customer.vatNumber),
436
528
  companyId: buildCompanyId({
437
529
  countryCode,
438
530
  companyNumber: customer.taxNumber ?? null
439
531
  })
440
- };
532
+ });
441
533
  };
442
534
  //#endregion
443
535
  //#region src/build/attachment.ts
@@ -450,20 +542,20 @@ const buildPdfAttachment = (params) => ({
450
542
  id: params.id ?? params.filename,
451
543
  filename: params.filename,
452
544
  mimeCode: "application/pdf",
453
- base64: Buffer.from(params.bytes).toString("base64")
545
+ base64Content: Buffer.from(params.bytes).toString("base64")
454
546
  });
455
547
  /**
456
548
  * Replace each attachment's base64 payload with `[omitted]` plus a length, so a
457
- * {@link UblDocument} is safe to log or persist for audit.
549
+ * {@link UblInvoice} is safe to log or persist for audit.
458
550
  */
459
551
  const sanitizeUblDocumentForAudit = (doc) => {
460
- if (doc.attachments.length === 0) return doc;
552
+ if (!doc.attachments?.length) return doc;
461
553
  return {
462
554
  ...doc,
463
- attachments: doc.attachments.map((attachment) => ({
555
+ attachments: doc.attachments.map((attachment) => attachment.base64Content === void 0 ? attachment : {
464
556
  ...attachment,
465
- base64: `[omitted ${attachment.base64.length} chars]`
466
- }))
557
+ base64Content: `[omitted ${attachment.base64Content.length} chars]`
558
+ })
467
559
  };
468
560
  };
469
561
  //#endregion
@@ -476,24 +568,26 @@ const centsToDecimal = (cents) => roundCurrency(cents / 100);
476
568
  * Derive the `cac:Price` for a line whose net total is authoritative.
477
569
  *
478
570
  * Peppol rule PEPPOL-EN16931-R120 checks
479
- * `quantity × (priceAmount ÷ baseQuantity)` against the line net amount within
571
+ * `quantity × (PriceAmount ÷ BaseQuantity)` against the line net amount within
480
572
  * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that
481
573
  * whenever the division doesn't land on a cent: 940.00 over 14 units gives
482
574
  * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and
483
575
  * rejected as a fatal validation error.
484
576
  *
485
577
  * So the cent-rounded unit price is only used when it reproduces the net
486
- * exactly. Otherwise the line is priced as a whole via BT-149 (`priceAmount` =
487
- * the net, `baseQuantity` = the quantity), which is exact at any magnitude
488
- * instead of merely within tolerance — the residual of a rounded unit price
489
- * 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.
490
584
  */
491
585
  const deriveUnitPrice = (netTotal, quantity) => {
492
586
  const units = quantity > 0 ? quantity : 1;
493
587
  const perUnit = roundCurrency(netTotal / units);
494
- if (roundCurrency(perUnit * units) === roundCurrency(netTotal)) return { priceAmount: perUnit };
588
+ if (roundCurrency(perUnit * units) === roundCurrency(netTotal)) return { unitPrice: perUnit };
495
589
  return {
496
- priceAmount: roundCurrency(netTotal),
590
+ unitPrice: roundCurrency(netTotal) / units,
497
591
  baseQuantity: units
498
592
  };
499
593
  };
@@ -523,7 +617,7 @@ const EXEMPTION_REASON_TEXT = {
523
617
  not_collecting: "VAT not collected",
524
618
  not_supported: "VAT not applicable"
525
619
  };
526
- const normalizeTaxCategoryId = (value) => normalizeString(value)?.toUpperCase() ?? null;
620
+ const normalizeTaxCategoryId = (value) => normalizeString(value)?.toUpperCase();
527
621
  /**
528
622
  * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a
529
623
  * numeric rate into a {@link UblTaxCategory}.
@@ -556,7 +650,7 @@ const taxCategoryFromReasonOrRate = (params) => {
556
650
  if (categoryHint === "E" || reason && EXEMPT_TAXABILITY_REASONS.has(reason)) return {
557
651
  id: "E",
558
652
  percent: 0,
559
- exemptionReason: (reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? "Exempt from VAT"
653
+ exemptionReason: (reason ? EXEMPTION_REASON_TEXT[reason] : void 0) ?? "Exempt from VAT"
560
654
  };
561
655
  if (categoryHint === "Z" || reason === "zero_rated" || params.rate <= 0) return {
562
656
  id: "Z",
@@ -614,6 +708,7 @@ const coerceLinesForSupplierVatStatus = (lines, vatStatus, supplierCountryCode)
614
708
  };
615
709
  //#endregion
616
710
  //#region src/build/tax-totals.ts
711
+ const lineNet = (line) => line.lineExtensionAmount ?? 0;
617
712
  /**
618
713
  * Adjust the largest line's net amount so the line nets sum to the
619
714
  * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).
@@ -626,23 +721,23 @@ const coerceLinesForSupplierVatStatus = (lines, vatStatus, supplierCountryCode)
626
721
  */
627
722
  const reconcileLinesToExclTotal = (lines, authoritativeTotalExclVat) => {
628
723
  if (lines.length === 0) return lines;
629
- const computed = roundCurrency(lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0));
724
+ const computed = roundCurrency(lines.reduce((sum, line) => sum + lineNet(line), 0));
630
725
  const diff = roundCurrency(authoritativeTotalExclVat - computed);
631
726
  if (diff === 0) return lines;
632
- 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);
633
728
  return lines.map((line, idx) => {
634
729
  if (idx !== largestIdx) return line;
635
- const adjusted = roundCurrency(line.lineExtensionAmount + diff);
636
- const { priceAmount, baseQuantity } = deriveUnitPrice(adjusted, line.quantity);
637
- return {
730
+ const adjusted = roundCurrency(lineNet(line) + diff);
731
+ const { unitPrice, baseQuantity } = deriveUnitPrice(adjusted, line.quantity ?? 0);
732
+ return compact({
638
733
  ...line,
639
734
  lineExtensionAmount: adjusted,
640
- priceAmount,
735
+ unitPrice,
641
736
  baseQuantity
642
- };
737
+ });
643
738
  });
644
739
  };
645
- const categoryKey = (category) => `${category.id}:${category.percent}`;
740
+ const categoryKey = (category) => `${category.id ?? ""}:${category.percent ?? ""}`;
646
741
  /**
647
742
  * Group lines by `(category, percent)` into a VAT breakdown and compute the
648
743
  * document monetary totals.
@@ -658,25 +753,29 @@ const categoryKey = (category) => `${category.id}:${category.percent}`;
658
753
  * invariant holds by construction. The result is *not* clamped: a prepayment
659
754
  * exceeding the total yields a negative payable amount, surfacing the upstream
660
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.
661
759
  */
662
760
  const buildTaxTotals = (lines, options) => {
663
761
  const groups = /* @__PURE__ */ new Map();
664
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`);
665
764
  const key = categoryKey(line.taxCategory);
666
765
  const current = groups.get(key) ?? {
667
766
  category: line.taxCategory,
668
767
  taxableAmount: 0
669
768
  };
670
- current.taxableAmount = roundCurrency(current.taxableAmount + line.lineExtensionAmount);
769
+ current.taxableAmount = roundCurrency(current.taxableAmount + lineNet(line));
671
770
  groups.set(key, current);
672
771
  }
673
772
  const subtotals = Array.from(groups.values()).map((group) => ({
674
773
  taxableAmount: group.taxableAmount,
675
- taxAmount: roundCurrency(group.taxableAmount * group.category.percent / 100),
774
+ taxAmount: roundCurrency(group.taxableAmount * (group.category.percent ?? 0) / 100),
676
775
  category: group.category
677
776
  }));
678
- const lineExtensionAmount = roundCurrency(lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0));
679
- 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));
680
779
  const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
681
780
  const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
682
781
  const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
@@ -697,6 +796,6 @@ const buildTaxTotals = (lines, options) => {
697
796
  };
698
797
  };
699
798
  //#endregion
700
- 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, coerceLinesForSupplierVatStatus, 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 };
701
800
 
702
801
  //# sourceMappingURL=index.js.map