@financica/ubl 0.16.0 → 0.18.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,131 @@ 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
+ const round2 = (value) => Math.round(value * 100) / 100;
70
+ /** Sums of cent-rounded amounts must agree to the cent; R120 allows a cent either way. */
71
+ const assertEqual = (rule, actual, expected, path, tolerance = .005) => {
72
+ if (Math.abs(actual - expected) > tolerance) throw new UblBuildError(`${rule}: ${path} is ${actual.toFixed(2)}, expected ${expected.toFixed(2)}`);
73
+ };
74
+ /** Category `O` (outside scope) is the one category BR-O-05 forbids a percent on. */
75
+ const requiresPercent = (categoryId) => categoryId !== "O";
76
+ const validateTaxCategory = (category, path) => {
77
+ const present = required(category, "VAT category (BT-151/BT-118)", path);
78
+ const id = required(present.id, "VAT category code (BT-151/BT-118)", `${path}.id`);
79
+ if (requiresPercent(id) && present.percent === void 0) throw missing(`VAT rate (BT-152/BT-119) for category ${id}`, `${path}.percent`);
80
+ return {
81
+ ...present,
82
+ id
83
+ };
84
+ };
85
+ const validateAllowanceCharge = (item, path, level) => {
86
+ const kind = item.chargeIndicator ? "charge" : "allowance";
87
+ required(item.amount, `${kind} amount (BT-92/BT-99)`, `${path}.amount`);
88
+ if (item.reason === void 0 && item.reasonCode === void 0) throw missing(`${kind} reason or reason code (BT-97/BT-98)`, `${path}.reason`);
89
+ if (item.baseAmount !== void 0 && item.multiplierFactorNumeric !== void 0) assertEqual("PEPPOL-EN16931-R040", item.amount ?? 0, round2(item.baseAmount * item.multiplierFactorNumeric / 100), `${path}.amount`, .01);
90
+ if (level === "document") validateTaxCategory(item.taxCategory, `${path}.taxCategory`);
91
+ };
92
+ const lineAllowanceTotal = (line, charges) => (line.allowanceCharges ?? []).filter((item) => item.chargeIndicator === charges).reduce((sum, item) => sum + (item.amount ?? 0), 0);
93
+ const validateLine = (line, index) => {
94
+ const path = `lines[${index}]`;
95
+ required(line.id, "line identifier (BT-126)", `${path}.id`);
96
+ const quantity = required(line.quantity, "invoiced quantity (BT-129)", `${path}.quantity`);
97
+ required(line.unitCode, "unit code (BT-130)", `${path}.unitCode`);
98
+ const unitPrice = required(line.unitPrice, "net unit price (BT-146)", `${path}.unitPrice`);
99
+ const net = required(line.lineExtensionAmount, "line net amount (BT-131)", `${path}.lineExtensionAmount`);
100
+ validateTaxCategory(line.taxCategory, `${path}.taxCategory`);
101
+ (line.allowanceCharges ?? []).forEach((item, itemIndex) => validateAllowanceCharge(item, `${path}.allowanceCharges[${itemIndex}]`, "line"));
102
+ assertEqual("PEPPOL-EN16931-R120", net, round2(quantity * unitPrice + lineAllowanceTotal(line, true) - lineAllowanceTotal(line, false)), `${path}.lineExtensionAmount`, .02);
103
+ };
104
+ const isExternalOnly = (attachment) => attachment.externalUri !== void 0 && attachment.base64Content === void 0;
105
+ const validateAttachment = (attachment, index) => {
106
+ if (isExternalOnly(attachment)) return;
107
+ const path = `attachments[${index}]`;
108
+ required(attachment.filename, "attachment filename (BT-125-2)", `${path}.filename`);
109
+ required(attachment.mimeCode, "attachment MIME code (BT-125-1)", `${path}.mimeCode`);
110
+ required(attachment.base64Content, "attachment content (BT-125)", `${path}.base64Content`);
111
+ };
112
+ /** UNCL4461 codes whose payment means need a mandate (direct debit) or an account (credit transfer). */
113
+ const DIRECT_DEBIT_CODES = /* @__PURE__ */ new Set(["49", "59"]);
114
+ const CREDIT_TRANSFER_CODES = /* @__PURE__ */ new Set(["30", "58"]);
115
+ const validatePaymentMeans = (means, index) => {
116
+ const path = `paymentMeansList[${index}]`;
117
+ const code = required(means.code, "payment means code (BT-81)", `${path}.code`);
118
+ if (CREDIT_TRANSFER_CODES.has(code)) required(means.iban, `payment account (BT-84) for code ${code}`, `${path}.iban`);
119
+ if (DIRECT_DEBIT_CODES.has(code)) required(means.mandateId, `mandate reference (BT-89) for code ${code}`, `${path}.mandateId`);
120
+ };
121
+ const validateParty = (party, role, nameBt) => {
122
+ required(party.name, `${role} name (${nameBt})`, `${role}.name`);
123
+ if (party.endpoint && party.endpoint.scheme === void 0) throw missing(`${role} endpoint scheme`, `${role}.endpoint.scheme`);
124
+ };
125
+ const paymentMeansList = (doc) => doc.paymentMeansList ?? (doc.paymentMeans ? [doc.paymentMeans] : []);
126
+ const sumBy = (items, pick) => round2(items.reduce((sum, item) => sum + pick(item), 0));
127
+ const categoryKey$1 = (category) => `${category?.id ?? ""}:${category?.percent ?? ""}`;
128
+ /**
129
+ * The document arithmetic EN 16931 fixes: BR-CO-10 (line sum), BR-CO-11/12
130
+ * (allowance and charge sums), BR-CO-13 (total without VAT), BR-CO-15 (total
131
+ * with VAT), BR-CO-16 (amount due) and the BR-S-08 family (each VAT category's
132
+ * taxable amount is its line nets minus its allowances plus its charges).
133
+ */
134
+ const validateArithmetic = (doc) => {
135
+ const total = doc.monetaryTotal;
136
+ const docItems = doc.allowanceCharges ?? [];
137
+ const allowances = docItems.filter((item) => !item.chargeIndicator);
138
+ const charges = docItems.filter((item) => item.chargeIndicator);
139
+ const lineSum = sumBy(doc.lines, (line) => line.lineExtensionAmount ?? 0);
140
+ const allowanceSum = sumBy(allowances, (item) => item.amount ?? 0);
141
+ const chargeSum = sumBy(charges, (item) => item.amount ?? 0);
142
+ assertEqual("BR-CO-10", total.lineExtensionAmount ?? 0, lineSum, "monetaryTotal.lineExtensionAmount");
143
+ if (allowances.length > 0 || total.allowanceTotalAmount !== void 0) assertEqual("BR-CO-11", total.allowanceTotalAmount ?? 0, allowanceSum, "monetaryTotal.allowanceTotalAmount");
144
+ if (charges.length > 0 || total.chargeTotalAmount !== void 0) assertEqual("BR-CO-12", total.chargeTotalAmount ?? 0, chargeSum, "monetaryTotal.chargeTotalAmount");
145
+ assertEqual("BR-CO-13", total.taxExclusiveAmount ?? 0, round2(lineSum - allowanceSum + chargeSum), "monetaryTotal.taxExclusiveAmount");
146
+ assertEqual("BR-CO-15", total.taxInclusiveAmount ?? 0, round2((total.taxExclusiveAmount ?? 0) + (doc.taxTotal.taxAmount ?? 0)), "monetaryTotal.taxInclusiveAmount");
147
+ assertEqual("BR-CO-16", total.payableAmount ?? 0, round2((total.taxInclusiveAmount ?? 0) - (total.prepaidAmount ?? 0) + (total.payableRoundingAmount ?? 0)), "monetaryTotal.payableAmount");
148
+ const taxableByCategory = /* @__PURE__ */ new Map();
149
+ const add = (category, amount) => {
150
+ const key = categoryKey$1(category);
151
+ taxableByCategory.set(key, round2((taxableByCategory.get(key) ?? 0) + amount));
152
+ };
153
+ for (const line of doc.lines) add(line.taxCategory, line.lineExtensionAmount ?? 0);
154
+ for (const item of docItems) add(item.taxCategory, item.chargeIndicator ? item.amount ?? 0 : -(item.amount ?? 0));
155
+ doc.taxTotal.subtotals.forEach((subtotal, index) => {
156
+ const key = categoryKey$1(subtotal.category);
157
+ const expected = taxableByCategory.get(key);
158
+ if (expected === void 0) throw new UblBuildError(`BR-S-08: taxTotal.subtotals[${index}] (${key}) has no line, allowance or charge in that category`);
159
+ assertEqual("BR-S-08", subtotal.taxableAmount ?? 0, expected, `taxTotal.subtotals[${index}].taxableAmount`);
160
+ });
161
+ };
162
+ const validateInvoice = (doc) => {
163
+ required(doc.id, "document identifier (BT-1)", "id");
164
+ required(doc.issueDate, "issue date (BT-2)", "issueDate");
165
+ required(doc.currency, "document currency (BT-5)", "currency");
166
+ if (doc.taxPointDate !== void 0 && doc.invoicePeriod?.descriptionCode !== void 0) throw new UblBuildError("BR-CO-3: a tax point date (BT-7, taxPointDate) and a tax point date code (BT-8, invoicePeriod.descriptionCode) are mutually exclusive");
167
+ if (doc.taxCurrency !== void 0) required(doc.taxTotal.taxAmountInTaxCurrency, "VAT total in the accounting currency (BT-111, BR-53)", "taxTotal.taxAmountInTaxCurrency");
168
+ validateParty(doc.seller, "seller", "BT-27");
169
+ validateParty(doc.buyer, "buyer", "BT-44");
170
+ if (doc.payee) required(doc.payee.name, "payee name (BT-59)", "payee.name");
171
+ if (doc.taxRepresentative) {
172
+ required(doc.taxRepresentative.name, "tax representative name (BT-62)", "taxRepresentative.name");
173
+ required(doc.taxRepresentative.vatId, "tax representative VAT identifier (BT-63)", "taxRepresentative.vatId");
174
+ required(doc.taxRepresentative.address?.countryCode, "tax representative country (BT-69)", "taxRepresentative.address.countryCode");
175
+ }
176
+ if (doc.lines.length === 0) throw new UblBuildError("A document needs at least one line (BG-25, lines)");
177
+ doc.lines.forEach(validateLine);
178
+ (doc.allowanceCharges ?? []).forEach((item, index) => validateAllowanceCharge(item, `allowanceCharges[${index}]`, "document"));
179
+ paymentMeansList(doc).forEach(validatePaymentMeans);
180
+ required(doc.taxTotal.taxAmount, "total VAT amount (BT-110)", "taxTotal.taxAmount");
181
+ const total = doc.monetaryTotal;
182
+ required(total.lineExtensionAmount, "sum of line net amounts (BT-106)", "monetaryTotal.lineExtensionAmount");
183
+ required(total.taxExclusiveAmount, "total without VAT (BT-109)", "monetaryTotal.taxExclusiveAmount");
184
+ required(total.taxInclusiveAmount, "total with VAT (BT-112)", "monetaryTotal.taxInclusiveAmount");
185
+ required(total.payableAmount, "amount due (BT-115)", "monetaryTotal.payableAmount");
186
+ (doc.attachments ?? []).forEach(validateAttachment);
187
+ validateArithmetic(doc);
188
+ };
63
189
  /** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */
64
190
  const amount = (value) => value.toFixed(2);
65
191
  /** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */
@@ -68,102 +194,287 @@ const percent = (value) => {
68
194
  return Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);
69
195
  };
70
196
  const money = (name, value, currency) => el(name, { currencyID: currency }, amount(value));
71
- const vatTaxScheme = () => el("cac:TaxScheme", null, [el("cbc:ID", null, "VAT")]);
197
+ const optionalMoney = (name, value, currency) => value !== void 0 ? money(name, value, currency) : null;
198
+ const text = (name, value) => value !== void 0 ? el(name, null, value) : null;
199
+ const schemedId = (name, id) => id !== void 0 ? el(name, id.scheme !== void 0 ? { schemeID: id.scheme } : null, id.value) : null;
200
+ const taxScheme = (schemeId) => el("cac:TaxScheme", null, [el("cbc:ID", null, schemeId ?? "VAT")]);
72
201
  /**
73
202
  * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)
74
- * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption
75
- * reason for the non-charging categories (E/AE/O/K/G).
203
+ * and `cac:TaxCategory` (in the VAT breakdown and on document allowances and
204
+ * charges). EN 16931 requires an exemption reason for the non-charging
205
+ * categories (E/AE/O/K/G); the code precedes the text in the sequence.
76
206
  */
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()
207
+ const taxCategory = (name, category, path) => {
208
+ const valid = validateTaxCategory(category, path);
209
+ return el(name, null, [
210
+ el("cbc:ID", null, valid.id),
211
+ valid.percent !== void 0 ? el("cbc:Percent", null, percent(valid.percent)) : null,
212
+ text("cbc:TaxExemptionReasonCode", valid.exemptionReasonCode),
213
+ text("cbc:TaxExemptionReason", valid.exemptionReason),
214
+ taxScheme(valid.schemeId)
215
+ ]);
216
+ };
217
+ const addressChildren = (address) => [
218
+ text("cbc:StreetName", address.street),
219
+ text("cbc:AdditionalStreetName", address.additionalStreet),
220
+ text("cbc:CityName", address.city),
221
+ text("cbc:PostalZone", address.postalZone),
222
+ text("cbc:CountrySubentity", address.countrySubentity),
223
+ address.countryCode !== void 0 ? el("cac:Country", null, [el("cbc:IdentificationCode", { listID: COUNTRY_CODE_LIST_ID }, address.countryCode)]) : null
224
+ ];
225
+ const postalAddress = (address) => el("cac:PostalAddress", null, addressChildren(address));
226
+ const partyIdentifications = (source) => (source.partyIdentifications ?? []).map((identification) => el("cac:PartyIdentification", null, [el("cbc:ID", identification.schemeId !== void 0 ? { schemeID: identification.schemeId } : null, identification.id)]));
227
+ const partyName = (name) => el("cac:PartyName", null, [el("cbc:Name", null, name)]);
228
+ const partyTaxScheme = (source) => source.vatId !== void 0 ? el("cac:PartyTaxScheme", null, [el("cbc:CompanyID", null, source.vatId), taxScheme(source.taxSchemeId)]) : null;
229
+ const companyId = (source) => source.companyId ? el("cbc:CompanyID", source.companyId.scheme !== void 0 ? { schemeID: source.companyId.scheme } : null, source.companyId.value) : null;
230
+ const contact = (source) => source.contact ? el("cac:Contact", null, [
231
+ text("cbc:Name", source.contact.name),
232
+ text("cbc:Telephone", source.contact.phone),
233
+ text("cbc:ElectronicMail", source.contact.email)
234
+ ]) : null;
235
+ /** `cac:Party` for the seller and buyer (BG-4, BG-7). */
236
+ const party = (source, name) => el("cac:Party", null, [
237
+ source.endpoint ? el("cbc:EndpointID", { schemeID: source.endpoint.scheme ?? "" }, source.endpoint.value) : null,
238
+ ...partyIdentifications(source),
239
+ partyName(name),
240
+ source.address ? postalAddress(source.address) : null,
241
+ partyTaxScheme(source),
242
+ el("cac:PartyLegalEntity", null, [
243
+ el("cbc:RegistrationName", null, source.registrationName ?? name),
244
+ companyId(source),
245
+ text("cbc:CompanyLegalForm", source.companyLegalForm)
246
+ ]),
247
+ contact(source)
82
248
  ]);
83
- 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
249
+ /** `cac:PayeeParty` (BG-10): identification, name and legal entity id, unwrapped. */
250
+ const payeeParty = (source) => el("cac:PayeeParty", null, [
251
+ ...partyIdentifications(source),
252
+ partyName(source.name ?? ""),
253
+ source.companyId ? el("cac:PartyLegalEntity", null, [companyId(source)]) : null
90
254
  ]);
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])
255
+ /** `cac:TaxRepresentativeParty` (BG-11): name, address and VAT id, unwrapped. */
256
+ const taxRepresentativeParty = (source) => el("cac:TaxRepresentativeParty", null, [
257
+ partyName(source.name ?? ""),
258
+ source.address ? postalAddress(source.address) : null,
259
+ partyTaxScheme(source)
97
260
  ]);
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)
261
+ /** `cac:Delivery` (BG-13). */
262
+ const delivery = (source) => {
263
+ const location = source.locationId !== void 0 || source.address !== void 0 ? el("cac:DeliveryLocation", null, [schemedId("cbc:ID", source.locationId), source.address ? el("cac:Address", null, addressChildren(source.address)) : null]) : null;
264
+ const deliveryParty = source.partyName !== void 0 ? el("cac:DeliveryParty", null, [partyName(source.partyName)]) : null;
265
+ if (source.actualDeliveryDate === void 0 && !location && !deliveryParty) return null;
266
+ return el("cac:Delivery", null, [
267
+ text("cbc:ActualDeliveryDate", source.actualDeliveryDate),
268
+ location,
269
+ deliveryParty
270
+ ]);
271
+ };
272
+ /**
273
+ * `cac:PaymentMeans` (BG-16). On a credit note BT-9 has no root element and
274
+ * rides in the first payment means as `cbc:PaymentDueDate`. `cbc:NetworkID`
275
+ * is schema-mandatory inside `cac:CardAccount` and carries no business term;
276
+ * the BIS example value is `NA`.
277
+ */
278
+ const paymentMeans = (source, dueDate) => el("cac:PaymentMeans", null, [
279
+ el("cbc:PaymentMeansCode", source.codeName !== void 0 ? { name: source.codeName } : null, source.code ?? ""),
280
+ text("cbc:PaymentDueDate", dueDate),
281
+ text("cbc:PaymentID", source.paymentId),
282
+ source.cardNumber !== void 0 ? el("cac:CardAccount", null, [
283
+ el("cbc:PrimaryAccountNumberID", null, source.cardNumber),
284
+ el("cbc:NetworkID", null, "NA"),
285
+ text("cbc:HolderName", source.cardHolder)
286
+ ]) : null,
287
+ source.iban !== void 0 ? el("cac:PayeeFinancialAccount", null, [
288
+ el("cbc:ID", null, source.iban),
289
+ text("cbc:Name", source.accountName),
290
+ source.bic !== void 0 ? el("cac:FinancialInstitutionBranch", null, [el("cbc:ID", null, source.bic)]) : null
291
+ ]) : null,
292
+ source.mandateId !== void 0 ? el("cac:PaymentMandate", null, [el("cbc:ID", null, source.mandateId), source.debitedAccount !== void 0 ? el("cac:PayerFinancialAccount", null, [el("cbc:ID", null, source.debitedAccount)]) : null]) : null
293
+ ]);
294
+ /**
295
+ * `cac:AllowanceCharge` at document level (BG-20/BG-21, with its VAT
296
+ * category) and line level (BG-27/BG-28, without: the line's category
297
+ * applies).
298
+ */
299
+ const allowanceCharge = (item, currency, path, level) => el("cac:AllowanceCharge", null, [
300
+ el("cbc:ChargeIndicator", null, item.chargeIndicator ? "true" : "false"),
301
+ text("cbc:AllowanceChargeReasonCode", item.reasonCode),
302
+ text("cbc:AllowanceChargeReason", item.reason),
303
+ item.multiplierFactorNumeric !== void 0 ? el("cbc:MultiplierFactorNumeric", null, percent(item.multiplierFactorNumeric)) : null,
304
+ money("cbc:Amount", item.amount ?? 0, currency),
305
+ optionalMoney("cbc:BaseAmount", item.baseAmount, currency),
306
+ level === "document" ? taxCategory("cac:TaxCategory", item.taxCategory ?? {}, `${path}.taxCategory`) : null
102
307
  ]);
308
+ const taxSubtotal = (subtotal, currency, index) => {
309
+ const path = `taxTotal.subtotals[${index}]`;
310
+ return el("cac:TaxSubtotal", null, [
311
+ money("cbc:TaxableAmount", required(subtotal.taxableAmount, "taxable amount (BT-116)", `${path}.taxableAmount`), currency),
312
+ money("cbc:TaxAmount", required(subtotal.taxAmount, "VAT amount (BT-117)", `${path}.taxAmount`), currency),
313
+ taxCategory("cac:TaxCategory", required(subtotal.category, "VAT category (BT-118)", `${path}.category`), `${path}.category`)
314
+ ]);
315
+ };
103
316
  /**
104
- * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`
105
- * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`
106
- * — emitting them after it produces schema-invalid XML.
317
+ * `cac:LegalMonetaryTotal` children, in UBL sequence order. BT-107/BT-108 are
318
+ * written when the document carries allowances or charges; BT-113 and BT-114
319
+ * are omitted when absent or zero.
107
320
  */
108
321
  const legalMonetaryTotalChildren = (doc) => {
109
322
  const { currency, monetaryTotal: total } = doc;
323
+ const hasAllowances = (doc.allowanceCharges ?? []).some((item) => !item.chargeIndicator);
324
+ const hasCharges = (doc.allowanceCharges ?? []).some((item) => item.chargeIndicator);
110
325
  return [
111
- money("cbc:LineExtensionAmount", total.lineExtensionAmount, currency),
112
- money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount, currency),
113
- money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount, currency),
326
+ money("cbc:LineExtensionAmount", total.lineExtensionAmount ?? 0, currency),
327
+ money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount ?? 0, currency),
328
+ money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount ?? 0, currency),
329
+ hasAllowances || total.allowanceTotalAmount ? money("cbc:AllowanceTotalAmount", total.allowanceTotalAmount ?? 0, currency) : null,
330
+ hasCharges || total.chargeTotalAmount ? money("cbc:ChargeTotalAmount", total.chargeTotalAmount ?? 0, currency) : null,
114
331
  total.prepaidAmount ? money("cbc:PrepaidAmount", total.prepaidAmount, currency) : null,
115
332
  total.payableRoundingAmount ? money("cbc:PayableRoundingAmount", total.payableRoundingAmount, currency) : null,
116
- money("cbc:PayableAmount", total.payableAmount, currency)
333
+ money("cbc:PayableAmount", total.payableAmount ?? 0, currency)
117
334
  ].filter((child) => Boolean(child));
118
335
  };
119
336
  /**
120
337
  * `cac:InvoicePeriod`. Null when neither bound is set — an empty period element
121
- * fails BR-CO-19, which requires at least one of the two dates.
338
+ * fails BR-CO-19, which requires at least one of the two dates. BT-8 (the tax
339
+ * point date code) is only meaningful on the document period.
122
340
  */
123
341
  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)));
342
+ if (!period || period.startDate === void 0 && period.endDate === void 0) return null;
343
+ return el("cac:InvoicePeriod", null, [
344
+ text("cbc:StartDate", period.startDate),
345
+ text("cbc:EndDate", period.endDate),
346
+ text("cbc:DescriptionCode", period.descriptionCode)
347
+ ]);
126
348
  };
349
+ const item = (source) => el("cac:Item", null, [
350
+ text("cbc:Description", source.description),
351
+ el("cbc:Name", null, source.itemName ?? source.description ?? source.id),
352
+ source.buyersItemId !== void 0 ? el("cac:BuyersItemIdentification", null, [el("cbc:ID", null, source.buyersItemId)]) : null,
353
+ source.sellersItemId !== void 0 ? el("cac:SellersItemIdentification", null, [el("cbc:ID", null, source.sellersItemId)]) : null,
354
+ source.standardItemId !== void 0 ? el("cac:StandardItemIdentification", null, [schemedId("cbc:ID", source.standardItemId)]) : null,
355
+ source.originCountryCode !== void 0 ? el("cac:OriginCountry", null, [el("cbc:IdentificationCode", null, source.originCountryCode)]) : null,
356
+ ...(source.commodityClassifications ?? []).map((classification) => el("cac:CommodityClassification", null, [el("cbc:ItemClassificationCode", {
357
+ listID: classification.listId,
358
+ listVersionID: classification.listVersionId
359
+ }, classification.value)])),
360
+ taxCategory("cac:ClassifiedTaxCategory", source.taxCategory ?? {}, `lines[${source.id}].taxCategory`),
361
+ ...(source.additionalItemProperties ?? []).map((property) => el("cac:AdditionalItemProperty", null, [el("cbc:Name", null, property.name), el("cbc:Value", null, property.value ?? "")]))
362
+ ]);
127
363
  const line = (source, currency, documentType) => {
128
- const lineElementName = documentType === "creditNote" ? "cac:CreditNoteLine" : "cac:InvoiceLine";
129
- const quantityElementName = documentType === "creditNote" ? "cbc:CreditedQuantity" : "cbc:InvoicedQuantity";
364
+ const isCreditNote = documentType === "CreditNote";
365
+ const lineElementName = isCreditNote ? "cac:CreditNoteLine" : "cac:InvoiceLine";
366
+ const quantityElementName = isCreditNote ? "cbc:CreditedQuantity" : "cbc:InvoicedQuantity";
367
+ const unitCode = source.unitCode ?? "";
368
+ const priceAmount = (source.unitPrice ?? 0) * (source.baseQuantity ?? 1);
130
369
  return el(lineElementName, null, [
131
370
  el("cbc:ID", null, source.id),
132
- el(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),
133
- money("cbc:LineExtensionAmount", source.lineExtensionAmount, currency),
371
+ text("cbc:Note", source.note),
372
+ el(quantityElementName, { unitCode }, String(source.quantity ?? 0)),
373
+ money("cbc:LineExtensionAmount", source.lineExtensionAmount ?? 0, currency),
374
+ text("cbc:AccountingCost", source.accountingCost),
134
375
  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])
376
+ source.orderLineReference !== void 0 ? el("cac:OrderLineReference", null, [el("cbc:LineID", null, source.orderLineReference)]) : null,
377
+ source.objectIdentifier !== void 0 ? el("cac:DocumentReference", null, [schemedId("cbc:ID", source.objectIdentifier), el("cbc:DocumentTypeCode", null, "130")]) : null,
378
+ ...(source.allowanceCharges ?? []).map((entry, index) => allowanceCharge(entry, currency, `lines[${source.id}].allowanceCharges[${index}]`, "line")),
379
+ item(source),
380
+ el("cac:Price", null, [
381
+ money("cbc:PriceAmount", priceAmount, currency),
382
+ source.baseQuantity !== void 0 ? el("cbc:BaseQuantity", { unitCode }, String(source.baseQuantity)) : null,
383
+ source.priceAllowance !== void 0 ? el("cac:AllowanceCharge", null, [
384
+ el("cbc:ChargeIndicator", null, "false"),
385
+ money("cbc:Amount", source.priceAllowance.amount ?? 0, currency),
386
+ optionalMoney("cbc:BaseAmount", source.priceAllowance.baseAmount, currency)
387
+ ]) : null
388
+ ])
137
389
  ]);
138
390
  };
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";
391
+ const attachmentReference = (attachment) => el("cac:AdditionalDocumentReference", null, [
392
+ el("cbc:ID", null, attachment.id ?? attachment.filename ?? attachment.externalUri ?? ""),
393
+ text("cbc:DocumentDescription", attachment.description),
394
+ el("cac:Attachment", null, [isExternalOnly(attachment) ? el("cac:ExternalReference", null, [el("cbc:URI", null, attachment.externalUri ?? "")]) : el("cbc:EmbeddedDocumentBinaryObject", {
395
+ mimeCode: attachment.mimeCode ?? "",
396
+ filename: attachment.filename ?? ""
397
+ }, attachment.base64Content ?? "")])
398
+ ]);
399
+ /** A typed `cac:AdditionalDocumentReference` without attachment (BT-17, BT-18, BT-11 on a credit note). */
400
+ const typedDocumentReference = (id, typeCode) => el("cac:AdditionalDocumentReference", null, [schemedId("cbc:ID", id), el("cbc:DocumentTypeCode", null, typeCode)]);
401
+ const documentReference = (name, id) => id !== void 0 ? el(name, null, [el("cbc:ID", null, id)]) : null;
402
+ /**
403
+ * `cac:OrderReference`. BT-13 (the buyer's order number) is the element's
404
+ * mandatory child, so a sales order id (BT-14) alone is not emitted.
405
+ */
406
+ const orderReference = (doc) => {
407
+ if (doc.orderReference === void 0) return null;
408
+ return el("cac:OrderReference", null, [el("cbc:ID", null, doc.orderReference), text("cbc:SalesOrderID", doc.salesOrderId)]);
409
+ };
410
+ const billingReference = (reference) => {
411
+ if (reference.invoiceId === void 0) return null;
412
+ return el("cac:BillingReference", null, [el("cac:InvoiceDocumentReference", null, [el("cbc:ID", null, reference.invoiceId), text("cbc:IssueDate", reference.invoiceIssueDate)])]);
413
+ };
414
+ /**
415
+ * Serialize a {@link UblInvoice} into a Peppol BIS Billing 3.0 XML string.
416
+ *
417
+ * Writes every EN 16931 business term the model holds, at its position in the
418
+ * UBL 2.1 sequence: the header terms (`customizationId`, `profileId` and
419
+ * `invoiceTypeCode` default to the BIS values), the references (BT-10 to
420
+ * BT-19), the parties with identifications, legal form and contacts, the
421
+ * payee and tax representative, delivery, payment means, payment terms,
422
+ * document and line allowances and charges, the VAT breakdown (plus BT-111 in
423
+ * the accounting currency), the monetary totals, attachments and document
424
+ * references, and lines with their item identifiers, classifications,
425
+ * properties, price discount and classified VAT category. Line-level tax
426
+ * totals are not emitted: BIS Billing 3.0 forbids them.
427
+ *
428
+ * @throws {UblBuildError} when a field EN 16931 / Peppol BIS makes mandatory
429
+ * is missing (naming the BT and the model path), or when the document's
430
+ * arithmetic breaks a business rule: BR-CO-3, BR-CO-10 to BR-CO-13, BR-CO-15,
431
+ * BR-CO-16, BR-53, the BR-S-08 family, PEPPOL-EN16931-R040 and R120.
432
+ */
433
+ const serializeUblInvoice = (doc) => {
434
+ validateInvoice(doc);
435
+ const isCreditNote = doc.documentType === "CreditNote";
147
436
  const rootName = isCreditNote ? "CreditNote" : "Invoice";
148
437
  const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
149
- const typeCodeElement = isCreditNote ? el("cbc:CreditNoteTypeCode", null, "381") : el("cbc:InvoiceTypeCode", null, "380");
438
+ const typeCodeElement = isCreditNote ? el("cbc:CreditNoteTypeCode", null, doc.invoiceTypeCode ?? "381") : el("cbc:InvoiceTypeCode", null, doc.invoiceTypeCode ?? "380");
439
+ const taxPointDate = text("cbc:TaxPointDate", doc.taxPointDate);
440
+ const means = paymentMeansList(doc);
441
+ const creditNoteDueDate = isCreditNote && means.length > 0 ? doc.dueDate : void 0;
150
442
  const children = [
151
- el("cbc:CustomizationID", null, UBL_CUSTOMIZATION_ID),
152
- el("cbc:ProfileID", null, UBL_PROFILE_ID),
443
+ el("cbc:CustomizationID", null, doc.customizationId ?? "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0"),
444
+ el("cbc:ProfileID", null, doc.profileId ?? "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0"),
153
445
  el("cbc:ID", null, doc.id),
154
446
  el("cbc:IssueDate", null, doc.issueDate),
155
- !isCreditNote && doc.dueDate ? el("cbc:DueDate", null, doc.dueDate) : null,
447
+ !isCreditNote ? text("cbc:DueDate", doc.dueDate) : null,
448
+ isCreditNote ? taxPointDate : null,
156
449
  typeCodeElement,
157
- doc.note ? el("cbc:Note", null, doc.note) : null,
450
+ text("cbc:Note", doc.note),
451
+ !isCreditNote ? taxPointDate : null,
158
452
  el("cbc:DocumentCurrencyCode", null, doc.currency),
159
- doc.buyerReference ? el("cbc:BuyerReference", null, doc.buyerReference) : null,
453
+ text("cbc:TaxCurrencyCode", doc.taxCurrency),
454
+ text("cbc:AccountingCost", doc.accountingCost),
455
+ text("cbc:BuyerReference", doc.buyerReference),
160
456
  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))]),
457
+ orderReference(doc),
458
+ doc.billingReference ? billingReference(doc.billingReference) : null,
459
+ documentReference("cac:DespatchDocumentReference", doc.despatchReference),
460
+ documentReference("cac:ReceiptDocumentReference", doc.receivingAdviceReference),
461
+ documentReference("cac:ContractDocumentReference", doc.contractReference),
462
+ ...(doc.attachments ?? []).map(attachmentReference),
463
+ ...(doc.documentReferences ?? []).map((reference) => el("cac:AdditionalDocumentReference", null, [el("cbc:ID", null, reference.id ?? ""), text("cbc:DocumentDescription", reference.description)])),
464
+ doc.invoicedObjectId !== void 0 ? typedDocumentReference(doc.invoicedObjectId, "130") : null,
465
+ !isCreditNote && doc.tenderReference !== void 0 ? typedDocumentReference({ value: doc.tenderReference }, "50") : null,
466
+ isCreditNote && doc.projectReference !== void 0 ? typedDocumentReference({ value: doc.projectReference }, "50") : null,
467
+ !isCreditNote ? documentReference("cac:ProjectReference", doc.projectReference) : null,
468
+ el("cac:AccountingSupplierParty", null, [party(doc.seller, doc.seller.name ?? "")]),
469
+ el("cac:AccountingCustomerParty", null, [party(doc.buyer, doc.buyer.name ?? "")]),
470
+ doc.payee ? payeeParty(doc.payee) : null,
471
+ doc.taxRepresentative ? taxRepresentativeParty(doc.taxRepresentative) : null,
472
+ doc.delivery ? delivery(doc.delivery) : null,
473
+ ...means.map((entry, index) => paymentMeans(entry, index === 0 ? creditNoteDueDate : void 0)),
474
+ doc.paymentTermsNote !== void 0 ? el("cac:PaymentTerms", null, [el("cbc:Note", null, doc.paymentTermsNote)]) : null,
475
+ ...(doc.allowanceCharges ?? []).map((entry, index) => allowanceCharge(entry, doc.currency, `allowanceCharges[${index}]`, "document")),
476
+ el("cac:TaxTotal", null, [money("cbc:TaxAmount", doc.taxTotal.taxAmount ?? 0, doc.currency), ...doc.taxTotal.subtotals.map((subtotal, index) => taxSubtotal(subtotal, doc.currency, index))]),
477
+ doc.taxCurrency !== void 0 ? el("cac:TaxTotal", null, [money("cbc:TaxAmount", doc.taxTotal.taxAmountInTaxCurrency ?? 0, doc.taxCurrency)]) : null,
167
478
  el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
168
479
  ...doc.lines.map((source) => line(source, doc.currency, doc.documentType))
169
480
  ];
@@ -174,24 +485,28 @@ const serializeUblDocument = (doc) => {
174
485
  }, children.filter((child) => Boolean(child)));
175
486
  return serializeDocument(root);
176
487
  };
488
+ /** Alias of {@link serializeUblInvoice}, kept under the historical name. */
489
+ const serializeUblDocument = serializeUblInvoice;
177
490
  //#endregion
178
491
  //#region src/build/utils.ts
179
- /** Trim a string; `null` when missing or blank. */
492
+ /** Trim a string; `undefined` when missing or blank. */
180
493
  const normalizeString = (value) => {
181
- if (typeof value !== "string") return null;
494
+ if (typeof value !== "string") return void 0;
182
495
  const normalized = value.trim();
183
- return normalized.length > 0 ? normalized : null;
496
+ return normalized.length > 0 ? normalized : void 0;
184
497
  };
498
+ /** Drop `undefined`-valued keys so an absent field is an absent key. */
499
+ const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
185
500
  //#endregion
186
501
  //#region src/build/address.ts
187
502
  const normalizeCountryCode = (value) => {
188
503
  const trimmed = normalizeString(value);
189
- if (!trimmed) return null;
190
- return trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;
504
+ if (!trimmed) return void 0;
505
+ return trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : void 0;
191
506
  };
192
507
  /**
193
508
  * Normalize a free-form address (Stripe shape, custom shape, or an internal
194
- * shape) into a {@link UblAddress}.
509
+ * shape) into a {@link UblAddress}. An absent part is an absent key.
195
510
  *
196
511
  * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`
197
512
  * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address
@@ -201,14 +516,14 @@ const normalizeCountryCode = (value) => {
201
516
  const normalizeAddress = (address, fallbackCountryCode, fallbackLine) => {
202
517
  const record = address ?? {};
203
518
  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,
519
+ return compact({
520
+ street: normalizeString(record.line1) ?? normalizeString(record.street) ?? normalizeString(fallbackLine),
206
521
  additionalStreet: normalizeString(record.line2),
207
522
  city: normalizeString(record.city),
208
523
  postalZone: normalizeString(record.postal_code) ?? normalizeString(record.zip_code),
209
524
  countrySubentity: normalizeString(record.state) ?? normalizeString(record.country_subentity),
210
525
  countryCode
211
- };
526
+ });
212
527
  };
213
528
  //#endregion
214
529
  //#region src/build/identifiers.ts
@@ -232,32 +547,32 @@ const normalizeCompanyNumberForCountry = (countryCode, companyNumber) => {
232
547
  * `@financica/peppol`'s country profiles.
233
548
  *
234
549
  * 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
550
+ * Returns `undefined` when the scheme can't be determined, in which case the
236
551
  * CompanyID is emitted without a `schemeID` attribute.
237
552
  */
238
553
  const resolveCompanyIdScheme = (params) => {
239
554
  const companyNumber = normalizeString(params.companyNumber);
240
- if (!companyNumber) return null;
241
- const fromCountry = getPeppolIdentifierSchemes(params.countryCode)?.companyIdentifierScheme;
555
+ if (!companyNumber) return void 0;
556
+ const fromCountry = getPeppolIdentifierSchemes(params.countryCode)?.companyIdentifierScheme ?? void 0;
242
557
  if (fromCountry) return fromCountry;
243
558
  const prefix = companyNumber.replace(/[^A-Za-z]/g, "").toUpperCase().slice(0, 2);
244
- return getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? null;
559
+ return getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? void 0;
245
560
  };
246
561
  /**
247
562
  * 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
563
+ * country-appropriate ICD scheme when known. Returns `undefined` when there is no
249
564
  * company number.
250
565
  */
251
566
  const buildCompanyId = (params) => {
252
567
  const normalized = normalizeString(normalizeCompanyNumberForCountry(params.countryCode, params.companyNumber));
253
- if (!normalized) return null;
254
- return {
568
+ if (!normalized) return void 0;
569
+ return compact({
255
570
  value: normalized,
256
571
  scheme: resolveCompanyIdScheme({
257
572
  countryCode: params.countryCode,
258
573
  companyNumber: normalized
259
574
  })
260
- };
575
+ });
261
576
  };
262
577
  /**
263
578
  * Resolve the Peppol participant identifier for a VAT number, deriving the EAS
@@ -266,21 +581,21 @@ const buildCompanyId = (params) => {
266
581
  * `BE0206582284` → `{ scheme: "9925", value: "BE0206582284" }`
267
582
  *
268
583
  * The scheme comes from `@financica/peppol`'s country resolution, so countries
269
- * that route on their registry number alone (Norway, Denmark) yield `null`
584
+ * that route on their registry number alone (Norway, Denmark) yield `undefined`
270
585
  * here — their VAT number is not a Peppol participant identifier.
271
586
  *
272
587
  * The value keeps its country prefix, matching how participants register (the
273
- * Peppol directory lists this party as `9925:be0206582284`). Returns `null`
588
+ * Peppol directory lists this party as `9925:be0206582284`). Returns `undefined`
274
589
  * when the country has no VAT EAS scheme or the input is empty.
275
590
  */
276
591
  const resolveVatEndpoint = (params) => {
277
592
  const value = normalizeString(params.vatNumber);
278
- if (!value) return null;
593
+ if (!value) return void 0;
279
594
  const fromPrefix = countryFromVatNumber(value);
280
595
  const scheme = getPeppolIdentifierSchemes(fromPrefix)?.vatIdentifierScheme ?? getPeppolIdentifierSchemes(params.countryCode)?.vatIdentifierScheme;
281
- if (!scheme) return null;
596
+ if (!scheme) return void 0;
282
597
  const cleaned = normalizeParticipantValue(scheme, value).toUpperCase();
283
- if (!cleaned) return null;
598
+ if (!cleaned) return void 0;
284
599
  return {
285
600
  scheme,
286
601
  value: cleaned
@@ -290,23 +605,23 @@ const resolveVatEndpoint = (params) => {
290
605
  * Parse a Peppol participant identifier into a {@link UblEndpoint}.
291
606
  *
292
607
  * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns
293
- * `null` for values without an explicit scheme, since `cbc:EndpointID` requires
608
+ * `undefined` for values without an explicit scheme, since `cbc:EndpointID` requires
294
609
  * a `schemeID` and guessing one would mis-route the document.
295
610
  */
296
611
  const parsePeppolEndpoint = (peppolId) => {
297
612
  const normalized = normalizeString(peppolId);
298
- if (!normalized) return null;
613
+ if (!normalized) return void 0;
299
614
  const separatorIndex = normalized.indexOf(":");
300
- if (separatorIndex <= 0) return null;
615
+ if (separatorIndex <= 0) return void 0;
301
616
  const scheme = normalized.slice(0, separatorIndex).trim();
302
617
  const value = normalized.slice(separatorIndex + 1).trim();
303
- if (!scheme || !value) return null;
618
+ if (!scheme || !value) return void 0;
304
619
  return {
305
620
  scheme,
306
621
  value
307
622
  };
308
623
  };
309
- const normalizeIdentifierType = (value) => value?.toLowerCase().replace(/[^a-z0-9]+/g, "_") ?? null;
624
+ const normalizeIdentifierType = (value) => value?.toLowerCase().replace(/[^a-z0-9]+/g, "_");
310
625
  /**
311
626
  * Pick the first usable Peppol identifier, GLN, VAT number, and tax number
312
627
  * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).
@@ -393,23 +708,23 @@ const listPeppolReceiverIdentifierCandidates = (customer, countryCode) => {
393
708
  };
394
709
  //#endregion
395
710
  //#region src/build/party.ts
396
- /** Convert a {@link UblSupplier} into the supplier (seller) party. */
711
+ /** Convert a {@link UblSupplier} into the seller party (`cac:AccountingSupplierParty`). */
397
712
  const buildSupplierParty = (supplier) => {
398
713
  const address = normalizeAddress(supplier.address, supplier.countryCode);
399
- return {
714
+ return compact({
400
715
  endpoint: parsePeppolEndpoint(supplier.peppolID),
401
716
  name: supplier.name,
717
+ registrationName: supplier.name,
402
718
  address,
403
- vatNumber: normalizeString(supplier.vatNumber),
404
- legalName: supplier.name,
719
+ vatId: normalizeString(supplier.vatNumber),
405
720
  companyId: buildCompanyId({
406
721
  countryCode: supplier.countryCode,
407
722
  companyNumber: supplier.companyNumber ?? null
408
723
  })
409
- };
724
+ });
410
725
  };
411
726
  /**
412
- * Convert a {@link UblCustomer} into the customer (buyer) party.
727
+ * Convert a {@link UblCustomer} into the buyer party (`cac:AccountingCustomerParty`).
413
728
  *
414
729
  * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in
415
730
  * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered
@@ -420,24 +735,25 @@ const buildSupplierParty = (supplier) => {
420
735
  * document would be unroutable.
421
736
  */
422
737
  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
- }),
738
+ const countryCode = normalizeString(customer.countryCode) ?? customer.address.countryCode ?? null;
739
+ const endpoint = endpointOverride ?? parsePeppolEndpoint(customer.peppolID) ?? (customer.glnNumber ? {
740
+ scheme: "0088",
741
+ value: customer.glnNumber
742
+ } : void 0) ?? resolveVatEndpoint({
743
+ vatNumber: customer.vatNumber,
744
+ countryCode
745
+ });
746
+ return compact({
747
+ endpoint,
432
748
  name: customer.name,
749
+ registrationName: customer.name,
433
750
  address: customer.address,
434
- vatNumber: normalizeString(customer.vatNumber),
435
- legalName: customer.name,
751
+ vatId: normalizeString(customer.vatNumber),
436
752
  companyId: buildCompanyId({
437
753
  countryCode,
438
754
  companyNumber: customer.taxNumber ?? null
439
755
  })
440
- };
756
+ });
441
757
  };
442
758
  //#endregion
443
759
  //#region src/build/attachment.ts
@@ -450,20 +766,20 @@ const buildPdfAttachment = (params) => ({
450
766
  id: params.id ?? params.filename,
451
767
  filename: params.filename,
452
768
  mimeCode: "application/pdf",
453
- base64: Buffer.from(params.bytes).toString("base64")
769
+ base64Content: Buffer.from(params.bytes).toString("base64")
454
770
  });
455
771
  /**
456
772
  * Replace each attachment's base64 payload with `[omitted]` plus a length, so a
457
- * {@link UblDocument} is safe to log or persist for audit.
773
+ * {@link UblInvoice} is safe to log or persist for audit.
458
774
  */
459
775
  const sanitizeUblDocumentForAudit = (doc) => {
460
- if (doc.attachments.length === 0) return doc;
776
+ if (!doc.attachments?.length) return doc;
461
777
  return {
462
778
  ...doc,
463
- attachments: doc.attachments.map((attachment) => ({
779
+ attachments: doc.attachments.map((attachment) => attachment.base64Content === void 0 ? attachment : {
464
780
  ...attachment,
465
- base64: `[omitted ${attachment.base64.length} chars]`
466
- }))
781
+ base64Content: `[omitted ${attachment.base64Content.length} chars]`
782
+ })
467
783
  };
468
784
  };
469
785
  //#endregion
@@ -476,24 +792,26 @@ const centsToDecimal = (cents) => roundCurrency(cents / 100);
476
792
  * Derive the `cac:Price` for a line whose net total is authoritative.
477
793
  *
478
794
  * Peppol rule PEPPOL-EN16931-R120 checks
479
- * `quantity × (priceAmount ÷ baseQuantity)` against the line net amount within
795
+ * `quantity × (PriceAmount ÷ BaseQuantity)` against the line net amount within
480
796
  * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that
481
797
  * whenever the division doesn't land on a cent: 940.00 over 14 units gives
482
798
  * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and
483
799
  * rejected as a fatal validation error.
484
800
  *
485
801
  * 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.
802
+ * exactly. Otherwise the line is priced as a whole via BT-149: `unitPrice` is
803
+ * the exact (unrounded) `net ÷ quantity` and `baseQuantity` = the quantity, so
804
+ * the serializer writes `PriceAmount` = the net and `BaseQuantity` = the
805
+ * quantity, which is exact at any magnitude instead of merely within tolerance
806
+ * — the residual of a rounded unit price grows with quantity and would
807
+ * eventually breach 0.02 at any fixed precision.
490
808
  */
491
809
  const deriveUnitPrice = (netTotal, quantity) => {
492
810
  const units = quantity > 0 ? quantity : 1;
493
811
  const perUnit = roundCurrency(netTotal / units);
494
- if (roundCurrency(perUnit * units) === roundCurrency(netTotal)) return { priceAmount: perUnit };
812
+ if (roundCurrency(perUnit * units) === roundCurrency(netTotal)) return { unitPrice: perUnit };
495
813
  return {
496
- priceAmount: roundCurrency(netTotal),
814
+ unitPrice: roundCurrency(netTotal) / units,
497
815
  baseQuantity: units
498
816
  };
499
817
  };
@@ -523,7 +841,7 @@ const EXEMPTION_REASON_TEXT = {
523
841
  not_collecting: "VAT not collected",
524
842
  not_supported: "VAT not applicable"
525
843
  };
526
- const normalizeTaxCategoryId = (value) => normalizeString(value)?.toUpperCase() ?? null;
844
+ const normalizeTaxCategoryId = (value) => normalizeString(value)?.toUpperCase();
527
845
  /**
528
846
  * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a
529
847
  * numeric rate into a {@link UblTaxCategory}.
@@ -556,7 +874,7 @@ const taxCategoryFromReasonOrRate = (params) => {
556
874
  if (categoryHint === "E" || reason && EXEMPT_TAXABILITY_REASONS.has(reason)) return {
557
875
  id: "E",
558
876
  percent: 0,
559
- exemptionReason: (reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? "Exempt from VAT"
877
+ exemptionReason: (reason ? EXEMPTION_REASON_TEXT[reason] : void 0) ?? "Exempt from VAT"
560
878
  };
561
879
  if (categoryHint === "Z" || reason === "zero_rated" || params.rate <= 0) return {
562
880
  id: "Z",
@@ -614,6 +932,7 @@ const coerceLinesForSupplierVatStatus = (lines, vatStatus, supplierCountryCode)
614
932
  };
615
933
  //#endregion
616
934
  //#region src/build/tax-totals.ts
935
+ const lineNet = (line) => line.lineExtensionAmount ?? 0;
617
936
  /**
618
937
  * Adjust the largest line's net amount so the line nets sum to the
619
938
  * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).
@@ -626,23 +945,23 @@ const coerceLinesForSupplierVatStatus = (lines, vatStatus, supplierCountryCode)
626
945
  */
627
946
  const reconcileLinesToExclTotal = (lines, authoritativeTotalExclVat) => {
628
947
  if (lines.length === 0) return lines;
629
- const computed = roundCurrency(lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0));
948
+ const computed = roundCurrency(lines.reduce((sum, line) => sum + lineNet(line), 0));
630
949
  const diff = roundCurrency(authoritativeTotalExclVat - computed);
631
950
  if (diff === 0) return lines;
632
- const largestIdx = lines.reduce((maxIdx, line, idx, arr) => line.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0) ? idx : maxIdx, 0);
951
+ const largestIdx = lines.reduce((maxIdx, line, idx, arr) => lineNet(line) > lineNet(arr[maxIdx] ?? line) ? idx : maxIdx, 0);
633
952
  return lines.map((line, idx) => {
634
953
  if (idx !== largestIdx) return line;
635
- const adjusted = roundCurrency(line.lineExtensionAmount + diff);
636
- const { priceAmount, baseQuantity } = deriveUnitPrice(adjusted, line.quantity);
637
- return {
954
+ const adjusted = roundCurrency(lineNet(line) + diff);
955
+ const { unitPrice, baseQuantity } = deriveUnitPrice(adjusted, line.quantity ?? 0);
956
+ return compact({
638
957
  ...line,
639
958
  lineExtensionAmount: adjusted,
640
- priceAmount,
959
+ unitPrice,
641
960
  baseQuantity
642
- };
961
+ });
643
962
  });
644
963
  };
645
- const categoryKey = (category) => `${category.id}:${category.percent}`;
964
+ const categoryKey = (category) => `${category.id ?? ""}:${category.percent ?? ""}`;
646
965
  /**
647
966
  * Group lines by `(category, percent)` into a VAT breakdown and compute the
648
967
  * document monetary totals.
@@ -658,26 +977,45 @@ const categoryKey = (category) => `${category.id}:${category.percent}`;
658
977
  * invariant holds by construction. The result is *not* clamped: a prepayment
659
978
  * exceeding the total yields a negative payable amount, surfacing the upstream
660
979
  * overpayment rather than hiding it.
980
+ *
981
+ * @throws {UblBuildError} for a line, allowance or charge without a
982
+ * `taxCategory` — there is no VAT breakdown to put it in.
661
983
  */
662
984
  const buildTaxTotals = (lines, options) => {
663
985
  const groups = /* @__PURE__ */ new Map();
664
986
  for (const line of lines) {
987
+ if (!line.taxCategory) throw new UblBuildError(`Line ${line.id} has no taxCategory (BT-151); cannot build the VAT breakdown`);
665
988
  const key = categoryKey(line.taxCategory);
666
989
  const current = groups.get(key) ?? {
667
990
  category: line.taxCategory,
668
991
  taxableAmount: 0
669
992
  };
670
- current.taxableAmount = roundCurrency(current.taxableAmount + line.lineExtensionAmount);
993
+ current.taxableAmount = roundCurrency(current.taxableAmount + lineNet(line));
994
+ groups.set(key, current);
995
+ }
996
+ const allowanceCharges = options?.allowanceCharges ?? [];
997
+ for (const [index, item] of allowanceCharges.entries()) {
998
+ if (!item.taxCategory) throw new UblBuildError(`allowanceCharges[${index}] has no taxCategory (BT-95/BT-102); cannot build the VAT breakdown`);
999
+ const key = categoryKey(item.taxCategory);
1000
+ const current = groups.get(key) ?? {
1001
+ category: item.taxCategory,
1002
+ taxableAmount: 0
1003
+ };
1004
+ const signed = item.chargeIndicator ? item.amount ?? 0 : -(item.amount ?? 0);
1005
+ current.taxableAmount = roundCurrency(current.taxableAmount + signed);
671
1006
  groups.set(key, current);
672
1007
  }
673
1008
  const subtotals = Array.from(groups.values()).map((group) => ({
674
1009
  taxableAmount: group.taxableAmount,
675
- taxAmount: roundCurrency(group.taxableAmount * group.category.percent / 100),
1010
+ taxAmount: roundCurrency(group.taxableAmount * (group.category.percent ?? 0) / 100),
676
1011
  category: group.category
677
1012
  }));
678
- const lineExtensionAmount = roundCurrency(lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0));
679
- const taxAmount = roundCurrency(subtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0));
680
- const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
1013
+ const lineExtensionAmount = roundCurrency(lines.reduce((sum, line) => sum + lineNet(line), 0));
1014
+ const taxAmount = roundCurrency(subtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0));
1015
+ const allowanceTotalAmount = roundCurrency(allowanceCharges.filter((item) => !item.chargeIndicator).reduce((sum, item) => sum + (item.amount ?? 0), 0));
1016
+ const chargeTotalAmount = roundCurrency(allowanceCharges.filter((item) => item.chargeIndicator).reduce((sum, item) => sum + (item.amount ?? 0), 0));
1017
+ const taxExclusiveAmount = roundCurrency(lineExtensionAmount - allowanceTotalAmount + chargeTotalAmount);
1018
+ const taxInclusiveAmount = roundCurrency(taxExclusiveAmount + taxAmount);
681
1019
  const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
682
1020
  const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
683
1021
  const payableAmount = roundCurrency(taxInclusiveAmount - prepaidAmount + payableRoundingAmount);
@@ -688,15 +1026,66 @@ const buildTaxTotals = (lines, options) => {
688
1026
  },
689
1027
  monetaryTotal: {
690
1028
  lineExtensionAmount,
691
- taxExclusiveAmount: lineExtensionAmount,
1029
+ taxExclusiveAmount,
692
1030
  taxInclusiveAmount,
1031
+ ...allowanceTotalAmount ? { allowanceTotalAmount } : {},
1032
+ ...chargeTotalAmount ? { chargeTotalAmount } : {},
693
1033
  ...prepaidAmount ? { prepaidAmount } : {},
694
1034
  ...payableRoundingAmount ? { payableRoundingAmount } : {},
695
1035
  payableAmount
696
1036
  }
697
1037
  };
698
1038
  };
1039
+ /**
1040
+ * Split one document-level amount into an allowance or charge per VAT
1041
+ * category the lines use, pro rata by each category's line nets, so a
1042
+ * shipping charge or an invoice-wide discount on a mixed-rate invoice lands in
1043
+ * the right VAT subtotals (an ancillary cost follows the supply it belongs to).
1044
+ * Cent remainders go to the largest shares so the parts sum to `amount`
1045
+ * exactly; categories that receive nothing are omitted. With no positive
1046
+ * line net at all the whole amount goes to the first line's category.
1047
+ *
1048
+ * @throws {UblBuildError} for a line without a `taxCategory`.
1049
+ */
1050
+ const allocateAcrossTaxCategories = (amount, lines, template) => {
1051
+ const groups = /* @__PURE__ */ new Map();
1052
+ for (const line of lines) {
1053
+ if (!line.taxCategory) throw new UblBuildError(`Line ${line.id} has no taxCategory (BT-151); cannot allocate across categories`);
1054
+ const key = categoryKey(line.taxCategory);
1055
+ const current = groups.get(key) ?? {
1056
+ category: line.taxCategory,
1057
+ net: 0
1058
+ };
1059
+ current.net = roundCurrency(current.net + Math.max(0, lineNet(line)));
1060
+ groups.set(key, current);
1061
+ }
1062
+ const entries = Array.from(groups.values());
1063
+ const total = roundCurrency(amount);
1064
+ if (entries.length === 0 || total === 0) return [];
1065
+ const netSum = entries.reduce((sum, entry) => sum + entry.net, 0);
1066
+ const shares = netSum > 0 ? entries.map((entry) => total * entry.net / netSum) : entries.map((_entry, index) => index === 0 ? total : 0);
1067
+ const cents = shares.map((share) => Math.floor(share * 100 + 1e-9));
1068
+ let remainder = Math.round(total * 100) - cents.reduce((sum, value) => sum + value, 0);
1069
+ const order = shares.map((share, index) => ({
1070
+ index,
1071
+ fraction: share * 100 - Math.floor(share * 100 + 1e-9)
1072
+ })).sort((a, b) => b.fraction - a.fraction);
1073
+ for (const { index } of order) {
1074
+ if (remainder <= 0) break;
1075
+ cents[index] = (cents[index] ?? 0) + 1;
1076
+ remainder -= 1;
1077
+ }
1078
+ return entries.flatMap((entry, index) => {
1079
+ const value = (cents[index] ?? 0) / 100;
1080
+ if (value === 0) return [];
1081
+ return [compact({
1082
+ ...template,
1083
+ amount: value,
1084
+ taxCategory: entry.category
1085
+ })];
1086
+ });
1087
+ };
699
1088
  //#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 };
1089
+ 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, allocateAcrossTaxCategories, 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
1090
 
702
1091
  //# sourceMappingURL=index.js.map