@financica/ubl 0.17.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.
@@ -66,6 +66,11 @@ function required(value, what, path) {
66
66
  if (value === void 0 || value === null || value === "") throw missing(what, path);
67
67
  return value;
68
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
+ };
69
74
  /** Category `O` (outside scope) is the one category BR-O-05 forbids a percent on. */
70
75
  const requiresPercent = (categoryId) => categoryId !== "O";
71
76
  const validateTaxCategory = (category, path) => {
@@ -77,14 +82,24 @@ const validateTaxCategory = (category, path) => {
77
82
  id
78
83
  };
79
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);
80
93
  const validateLine = (line, index) => {
81
94
  const path = `lines[${index}]`;
82
95
  required(line.id, "line identifier (BT-126)", `${path}.id`);
83
- required(line.quantity, "invoiced quantity (BT-129)", `${path}.quantity`);
96
+ const quantity = required(line.quantity, "invoiced quantity (BT-129)", `${path}.quantity`);
84
97
  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`);
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`);
87
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);
88
103
  };
89
104
  const isExternalOnly = (attachment) => attachment.externalUri !== void 0 && attachment.base64Content === void 0;
90
105
  const validateAttachment = (attachment, index) => {
@@ -94,16 +109,74 @@ const validateAttachment = (attachment, index) => {
94
109
  required(attachment.mimeCode, "attachment MIME code (BT-125-1)", `${path}.mimeCode`);
95
110
  required(attachment.base64Content, "attachment content (BT-125)", `${path}.base64Content`);
96
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
+ };
97
162
  const validateInvoice = (doc) => {
98
163
  required(doc.id, "document identifier (BT-1)", "id");
99
164
  required(doc.issueDate, "issue date (BT-2)", "issueDate");
100
165
  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");
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
+ }
105
176
  if (doc.lines.length === 0) throw new UblBuildError("A document needs at least one line (BG-25, lines)");
106
177
  doc.lines.forEach(validateLine);
178
+ (doc.allowanceCharges ?? []).forEach((item, index) => validateAllowanceCharge(item, `allowanceCharges[${index}]`, "document"));
179
+ paymentMeansList(doc).forEach(validatePaymentMeans);
107
180
  required(doc.taxTotal.taxAmount, "total VAT amount (BT-110)", "taxTotal.taxAmount");
108
181
  const total = doc.monetaryTotal;
109
182
  required(total.lineExtensionAmount, "sum of line net amounts (BT-106)", "monetaryTotal.lineExtensionAmount");
@@ -111,6 +184,7 @@ const validateInvoice = (doc) => {
111
184
  required(total.taxInclusiveAmount, "total with VAT (BT-112)", "monetaryTotal.taxInclusiveAmount");
112
185
  required(total.payableAmount, "amount due (BT-115)", "monetaryTotal.payableAmount");
113
186
  (doc.attachments ?? []).forEach(validateAttachment);
187
+ validateArithmetic(doc);
114
188
  };
115
189
  /** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */
116
190
  const amount = (value) => value.toFixed(2);
@@ -120,36 +194,116 @@ const percent = (value) => {
120
194
  return Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);
121
195
  };
122
196
  const money = (name, value, currency) => el(name, { currencyID: currency }, amount(value));
197
+ const optionalMoney = (name, value, currency) => value !== void 0 ? money(name, value, currency) : null;
123
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;
124
200
  const taxScheme = (schemeId) => el("cac:TaxScheme", null, [el("cbc:ID", null, schemeId ?? "VAT")]);
125
201
  /**
126
202
  * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)
127
- * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption
128
- * 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.
129
206
  */
130
207
  const taxCategory = (name, category, path) => {
131
208
  const valid = validateTaxCategory(category, path);
132
209
  return el(name, null, [
133
210
  el("cbc:ID", null, valid.id),
134
211
  valid.percent !== void 0 ? el("cbc:Percent", null, percent(valid.percent)) : null,
212
+ text("cbc:TaxExemptionReasonCode", valid.exemptionReasonCode),
135
213
  text("cbc:TaxExemptionReason", valid.exemptionReason),
136
214
  taxScheme(valid.schemeId)
137
215
  ]);
138
216
  };
139
- const postalAddress = (address) => el("cac:PostalAddress", null, [
217
+ const addressChildren = (address) => [
140
218
  text("cbc:StreetName", address.street),
141
219
  text("cbc:AdditionalStreetName", address.additionalStreet),
142
220
  text("cbc:CityName", address.city),
143
221
  text("cbc:PostalZone", address.postalZone),
144
222
  text("cbc:CountrySubentity", address.countrySubentity),
145
223
  address.countryCode !== void 0 ? el("cac:Country", null, [el("cbc:IdentificationCode", { listID: COUNTRY_CODE_LIST_ID }, address.countryCode)]) : null
146
- ]);
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). */
147
236
  const party = (source, name) => el("cac:Party", null, [
148
237
  source.endpoint ? el("cbc:EndpointID", { schemeID: source.endpoint.scheme ?? "" }, source.endpoint.value) : null,
149
- el("cac:PartyName", null, [el("cbc:Name", null, name)]),
238
+ ...partyIdentifications(source),
239
+ partyName(name),
150
240
  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])
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)
248
+ ]);
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
254
+ ]);
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)
260
+ ]);
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
153
307
  ]);
154
308
  const taxSubtotal = (subtotal, currency, index) => {
155
309
  const path = `taxTotal.subtotals[${index}]`;
@@ -160,17 +314,20 @@ const taxSubtotal = (subtotal, currency, index) => {
160
314
  ]);
161
315
  };
162
316
  /**
163
- * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`
164
- * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`
165
- * — emitting them after it produces schema-invalid XML. BT-113/BT-114 are
166
- * omitted when absent or zero.
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.
167
320
  */
168
321
  const legalMonetaryTotalChildren = (doc) => {
169
322
  const { currency, monetaryTotal: total } = doc;
323
+ const hasAllowances = (doc.allowanceCharges ?? []).some((item) => !item.chargeIndicator);
324
+ const hasCharges = (doc.allowanceCharges ?? []).some((item) => item.chargeIndicator);
170
325
  return [
171
326
  money("cbc:LineExtensionAmount", total.lineExtensionAmount ?? 0, currency),
172
327
  money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount ?? 0, currency),
173
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,
174
331
  total.prepaidAmount ? money("cbc:PrepaidAmount", total.prepaidAmount, currency) : null,
175
332
  total.payableRoundingAmount ? money("cbc:PayableRoundingAmount", total.payableRoundingAmount, currency) : null,
176
333
  money("cbc:PayableAmount", total.payableAmount ?? 0, currency)
@@ -178,12 +335,31 @@ const legalMonetaryTotalChildren = (doc) => {
178
335
  };
179
336
  /**
180
337
  * `cac:InvoicePeriod`. Null when neither bound is set — an empty period element
181
- * 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.
182
340
  */
183
341
  const invoicePeriod = (period) => {
184
342
  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)]);
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
+ ]);
186
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
+ ]);
187
363
  const line = (source, currency, documentType) => {
188
364
  const isCreditNote = documentType === "CreditNote";
189
365
  const lineElementName = isCreditNote ? "cac:CreditNoteLine" : "cac:InvoiceLine";
@@ -192,41 +368,67 @@ const line = (source, currency, documentType) => {
192
368
  const priceAmount = (source.unitPrice ?? 0) * (source.baseQuantity ?? 1);
193
369
  return el(lineElementName, null, [
194
370
  el("cbc:ID", null, source.id),
371
+ text("cbc:Note", source.note),
195
372
  el(quantityElementName, { unitCode }, String(source.quantity ?? 0)),
196
373
  money("cbc:LineExtensionAmount", source.lineExtensionAmount ?? 0, currency),
374
+ text("cbc:AccountingCost", source.accountingCost),
197
375
  invoicePeriod(source.invoicePeriod),
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])
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
+ ])
204
389
  ]);
205
390
  };
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 ?? "")])]);
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
+ };
210
410
  const billingReference = (reference) => {
211
411
  if (reference.invoiceId === void 0) return null;
212
- return el("cac:BillingReference", null, [el("cac:InvoiceDocumentReference", null, [el("cbc:ID", null, reference.invoiceId)])]);
412
+ return el("cac:BillingReference", null, [el("cac:InvoiceDocumentReference", null, [el("cbc:ID", null, reference.invoiceId), text("cbc:IssueDate", reference.invoiceIssueDate)])]);
213
413
  };
214
414
  /**
215
415
  * Serialize a {@link UblInvoice} into a Peppol BIS Billing 3.0 XML string.
216
416
  *
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.
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.
223
427
  *
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.
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.
230
432
  */
231
433
  const serializeUblInvoice = (doc) => {
232
434
  validateInvoice(doc);
@@ -234,23 +436,45 @@ const serializeUblInvoice = (doc) => {
234
436
  const rootName = isCreditNote ? "CreditNote" : "Invoice";
235
437
  const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
236
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;
237
442
  const children = [
238
443
  el("cbc:CustomizationID", null, doc.customizationId ?? "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0"),
239
444
  el("cbc:ProfileID", null, doc.profileId ?? "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0"),
240
445
  el("cbc:ID", null, doc.id),
241
446
  el("cbc:IssueDate", null, doc.issueDate),
242
447
  !isCreditNote ? text("cbc:DueDate", doc.dueDate) : null,
448
+ isCreditNote ? taxPointDate : null,
243
449
  typeCodeElement,
244
450
  text("cbc:Note", doc.note),
451
+ !isCreditNote ? taxPointDate : null,
245
452
  el("cbc:DocumentCurrencyCode", null, doc.currency),
453
+ text("cbc:TaxCurrencyCode", doc.taxCurrency),
454
+ text("cbc:AccountingCost", doc.accountingCost),
246
455
  text("cbc:BuyerReference", doc.buyerReference),
247
456
  invoicePeriod(doc.invoicePeriod),
457
+ orderReference(doc),
248
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),
249
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,
250
468
  el("cac:AccountingSupplierParty", null, [party(doc.seller, doc.seller.name ?? "")]),
251
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)),
252
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")),
253
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,
254
478
  el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
255
479
  ...doc.lines.map((source) => line(source, doc.currency, doc.documentType))
256
480
  ];
@@ -754,8 +978,8 @@ const categoryKey = (category) => `${category.id ?? ""}:${category.percent ?? ""
754
978
  * exceeding the total yields a negative payable amount, surfacing the upstream
755
979
  * overpayment rather than hiding it.
756
980
  *
757
- * @throws {UblBuildError} for a line without a `taxCategory` — there is no
758
- * VAT breakdown to put it in.
981
+ * @throws {UblBuildError} for a line, allowance or charge without a
982
+ * `taxCategory` — there is no VAT breakdown to put it in.
759
983
  */
760
984
  const buildTaxTotals = (lines, options) => {
761
985
  const groups = /* @__PURE__ */ new Map();
@@ -769,6 +993,18 @@ const buildTaxTotals = (lines, options) => {
769
993
  current.taxableAmount = roundCurrency(current.taxableAmount + lineNet(line));
770
994
  groups.set(key, current);
771
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);
1006
+ groups.set(key, current);
1007
+ }
772
1008
  const subtotals = Array.from(groups.values()).map((group) => ({
773
1009
  taxableAmount: group.taxableAmount,
774
1010
  taxAmount: roundCurrency(group.taxableAmount * (group.category.percent ?? 0) / 100),
@@ -776,7 +1012,10 @@ const buildTaxTotals = (lines, options) => {
776
1012
  }));
777
1013
  const lineExtensionAmount = roundCurrency(lines.reduce((sum, line) => sum + lineNet(line), 0));
778
1014
  const taxAmount = roundCurrency(subtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0));
779
- const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
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);
780
1019
  const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
781
1020
  const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
782
1021
  const payableAmount = roundCurrency(taxInclusiveAmount - prepaidAmount + payableRoundingAmount);
@@ -787,15 +1026,66 @@ const buildTaxTotals = (lines, options) => {
787
1026
  },
788
1027
  monetaryTotal: {
789
1028
  lineExtensionAmount,
790
- taxExclusiveAmount: lineExtensionAmount,
1029
+ taxExclusiveAmount,
791
1030
  taxInclusiveAmount,
1031
+ ...allowanceTotalAmount ? { allowanceTotalAmount } : {},
1032
+ ...chargeTotalAmount ? { chargeTotalAmount } : {},
792
1033
  ...prepaidAmount ? { prepaidAmount } : {},
793
1034
  ...payableRoundingAmount ? { payableRoundingAmount } : {},
794
1035
  payableAmount
795
1036
  }
796
1037
  };
797
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
+ };
798
1088
  //#endregion
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 };
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 };
800
1090
 
801
1091
  //# sourceMappingURL=index.js.map