@financica/ubl 0.17.0 → 0.18.1

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,25 @@ 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`);
100
+ if (unitPrice < 0) throw new UblBuildError(`BR-27: ${path}.unitPrice is ${unitPrice}, the item net price shall not be negative`);
87
101
  validateTaxCategory(line.taxCategory, `${path}.taxCategory`);
102
+ (line.allowanceCharges ?? []).forEach((item, itemIndex) => validateAllowanceCharge(item, `${path}.allowanceCharges[${itemIndex}]`, "line"));
103
+ assertEqual("PEPPOL-EN16931-R120", net, round2(quantity * unitPrice + lineAllowanceTotal(line, true) - lineAllowanceTotal(line, false)), `${path}.lineExtensionAmount`, .02);
88
104
  };
89
105
  const isExternalOnly = (attachment) => attachment.externalUri !== void 0 && attachment.base64Content === void 0;
90
106
  const validateAttachment = (attachment, index) => {
@@ -94,16 +110,74 @@ const validateAttachment = (attachment, index) => {
94
110
  required(attachment.mimeCode, "attachment MIME code (BT-125-1)", `${path}.mimeCode`);
95
111
  required(attachment.base64Content, "attachment content (BT-125)", `${path}.base64Content`);
96
112
  };
113
+ /** UNCL4461 codes whose payment means need a mandate (direct debit) or an account (credit transfer). */
114
+ const DIRECT_DEBIT_CODES = /* @__PURE__ */ new Set(["49", "59"]);
115
+ const CREDIT_TRANSFER_CODES = /* @__PURE__ */ new Set(["30", "58"]);
116
+ const validatePaymentMeans = (means, index) => {
117
+ const path = `paymentMeansList[${index}]`;
118
+ const code = required(means.code, "payment means code (BT-81)", `${path}.code`);
119
+ if (CREDIT_TRANSFER_CODES.has(code)) required(means.iban, `payment account (BT-84) for code ${code}`, `${path}.iban`);
120
+ if (DIRECT_DEBIT_CODES.has(code)) required(means.mandateId, `mandate reference (BT-89) for code ${code}`, `${path}.mandateId`);
121
+ };
122
+ const validateParty = (party, role, nameBt) => {
123
+ required(party.name, `${role} name (${nameBt})`, `${role}.name`);
124
+ if (party.endpoint && party.endpoint.scheme === void 0) throw missing(`${role} endpoint scheme`, `${role}.endpoint.scheme`);
125
+ };
126
+ const paymentMeansList = (doc) => doc.paymentMeansList ?? (doc.paymentMeans ? [doc.paymentMeans] : []);
127
+ const sumBy = (items, pick) => round2(items.reduce((sum, item) => sum + pick(item), 0));
128
+ const categoryKey$1 = (category) => `${category?.id ?? ""}:${category?.percent ?? ""}`;
129
+ /**
130
+ * The document arithmetic EN 16931 fixes: BR-CO-10 (line sum), BR-CO-11/12
131
+ * (allowance and charge sums), BR-CO-13 (total without VAT), BR-CO-15 (total
132
+ * with VAT), BR-CO-16 (amount due) and the BR-S-08 family (each VAT category's
133
+ * taxable amount is its line nets minus its allowances plus its charges).
134
+ */
135
+ const validateArithmetic = (doc) => {
136
+ const total = doc.monetaryTotal;
137
+ const docItems = doc.allowanceCharges ?? [];
138
+ const allowances = docItems.filter((item) => !item.chargeIndicator);
139
+ const charges = docItems.filter((item) => item.chargeIndicator);
140
+ const lineSum = sumBy(doc.lines, (line) => line.lineExtensionAmount ?? 0);
141
+ const allowanceSum = sumBy(allowances, (item) => item.amount ?? 0);
142
+ const chargeSum = sumBy(charges, (item) => item.amount ?? 0);
143
+ assertEqual("BR-CO-10", total.lineExtensionAmount ?? 0, lineSum, "monetaryTotal.lineExtensionAmount");
144
+ if (allowances.length > 0 || total.allowanceTotalAmount !== void 0) assertEqual("BR-CO-11", total.allowanceTotalAmount ?? 0, allowanceSum, "monetaryTotal.allowanceTotalAmount");
145
+ if (charges.length > 0 || total.chargeTotalAmount !== void 0) assertEqual("BR-CO-12", total.chargeTotalAmount ?? 0, chargeSum, "monetaryTotal.chargeTotalAmount");
146
+ assertEqual("BR-CO-13", total.taxExclusiveAmount ?? 0, round2(lineSum - allowanceSum + chargeSum), "monetaryTotal.taxExclusiveAmount");
147
+ assertEqual("BR-CO-15", total.taxInclusiveAmount ?? 0, round2((total.taxExclusiveAmount ?? 0) + (doc.taxTotal.taxAmount ?? 0)), "monetaryTotal.taxInclusiveAmount");
148
+ assertEqual("BR-CO-16", total.payableAmount ?? 0, round2((total.taxInclusiveAmount ?? 0) - (total.prepaidAmount ?? 0) + (total.payableRoundingAmount ?? 0)), "monetaryTotal.payableAmount");
149
+ const taxableByCategory = /* @__PURE__ */ new Map();
150
+ const add = (category, amount) => {
151
+ const key = categoryKey$1(category);
152
+ taxableByCategory.set(key, round2((taxableByCategory.get(key) ?? 0) + amount));
153
+ };
154
+ for (const line of doc.lines) add(line.taxCategory, line.lineExtensionAmount ?? 0);
155
+ for (const item of docItems) add(item.taxCategory, item.chargeIndicator ? item.amount ?? 0 : -(item.amount ?? 0));
156
+ doc.taxTotal.subtotals.forEach((subtotal, index) => {
157
+ const key = categoryKey$1(subtotal.category);
158
+ const expected = taxableByCategory.get(key);
159
+ if (expected === void 0) throw new UblBuildError(`BR-S-08: taxTotal.subtotals[${index}] (${key}) has no line, allowance or charge in that category`);
160
+ assertEqual("BR-S-08", subtotal.taxableAmount ?? 0, expected, `taxTotal.subtotals[${index}].taxableAmount`);
161
+ });
162
+ };
97
163
  const validateInvoice = (doc) => {
98
164
  required(doc.id, "document identifier (BT-1)", "id");
99
165
  required(doc.issueDate, "issue date (BT-2)", "issueDate");
100
166
  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");
167
+ 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");
168
+ if (doc.taxCurrency !== void 0) required(doc.taxTotal.taxAmountInTaxCurrency, "VAT total in the accounting currency (BT-111, BR-53)", "taxTotal.taxAmountInTaxCurrency");
169
+ validateParty(doc.seller, "seller", "BT-27");
170
+ validateParty(doc.buyer, "buyer", "BT-44");
171
+ if (doc.payee) required(doc.payee.name, "payee name (BT-59)", "payee.name");
172
+ if (doc.taxRepresentative) {
173
+ required(doc.taxRepresentative.name, "tax representative name (BT-62)", "taxRepresentative.name");
174
+ required(doc.taxRepresentative.vatId, "tax representative VAT identifier (BT-63)", "taxRepresentative.vatId");
175
+ required(doc.taxRepresentative.address?.countryCode, "tax representative country (BT-69)", "taxRepresentative.address.countryCode");
176
+ }
105
177
  if (doc.lines.length === 0) throw new UblBuildError("A document needs at least one line (BG-25, lines)");
106
178
  doc.lines.forEach(validateLine);
179
+ (doc.allowanceCharges ?? []).forEach((item, index) => validateAllowanceCharge(item, `allowanceCharges[${index}]`, "document"));
180
+ paymentMeansList(doc).forEach(validatePaymentMeans);
107
181
  required(doc.taxTotal.taxAmount, "total VAT amount (BT-110)", "taxTotal.taxAmount");
108
182
  const total = doc.monetaryTotal;
109
183
  required(total.lineExtensionAmount, "sum of line net amounts (BT-106)", "monetaryTotal.lineExtensionAmount");
@@ -111,6 +185,7 @@ const validateInvoice = (doc) => {
111
185
  required(total.taxInclusiveAmount, "total with VAT (BT-112)", "monetaryTotal.taxInclusiveAmount");
112
186
  required(total.payableAmount, "amount due (BT-115)", "monetaryTotal.payableAmount");
113
187
  (doc.attachments ?? []).forEach(validateAttachment);
188
+ validateArithmetic(doc);
114
189
  };
115
190
  /** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */
116
191
  const amount = (value) => value.toFixed(2);
@@ -120,36 +195,116 @@ const percent = (value) => {
120
195
  return Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);
121
196
  };
122
197
  const money = (name, value, currency) => el(name, { currencyID: currency }, amount(value));
198
+ const optionalMoney = (name, value, currency) => value !== void 0 ? money(name, value, currency) : null;
123
199
  const text = (name, value) => value !== void 0 ? el(name, null, value) : null;
200
+ const schemedId = (name, id) => id !== void 0 ? el(name, id.scheme !== void 0 ? { schemeID: id.scheme } : null, id.value) : null;
124
201
  const taxScheme = (schemeId) => el("cac:TaxScheme", null, [el("cbc:ID", null, schemeId ?? "VAT")]);
125
202
  /**
126
203
  * 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).
204
+ * and `cac:TaxCategory` (in the VAT breakdown and on document allowances and
205
+ * charges). EN 16931 requires an exemption reason for the non-charging
206
+ * categories (E/AE/O/K/G); the code precedes the text in the sequence.
129
207
  */
130
208
  const taxCategory = (name, category, path) => {
131
209
  const valid = validateTaxCategory(category, path);
132
210
  return el(name, null, [
133
211
  el("cbc:ID", null, valid.id),
134
212
  valid.percent !== void 0 ? el("cbc:Percent", null, percent(valid.percent)) : null,
213
+ text("cbc:TaxExemptionReasonCode", valid.exemptionReasonCode),
135
214
  text("cbc:TaxExemptionReason", valid.exemptionReason),
136
215
  taxScheme(valid.schemeId)
137
216
  ]);
138
217
  };
139
- const postalAddress = (address) => el("cac:PostalAddress", null, [
218
+ const addressChildren = (address) => [
140
219
  text("cbc:StreetName", address.street),
141
220
  text("cbc:AdditionalStreetName", address.additionalStreet),
142
221
  text("cbc:CityName", address.city),
143
222
  text("cbc:PostalZone", address.postalZone),
144
223
  text("cbc:CountrySubentity", address.countrySubentity),
145
224
  address.countryCode !== void 0 ? el("cac:Country", null, [el("cbc:IdentificationCode", { listID: COUNTRY_CODE_LIST_ID }, address.countryCode)]) : null
146
- ]);
225
+ ];
226
+ const postalAddress = (address) => el("cac:PostalAddress", null, addressChildren(address));
227
+ const partyIdentifications = (source) => (source.partyIdentifications ?? []).map((identification) => el("cac:PartyIdentification", null, [el("cbc:ID", identification.schemeId !== void 0 ? { schemeID: identification.schemeId } : null, identification.id)]));
228
+ const partyName = (name) => el("cac:PartyName", null, [el("cbc:Name", null, name)]);
229
+ const partyTaxScheme = (source) => source.vatId !== void 0 ? el("cac:PartyTaxScheme", null, [el("cbc:CompanyID", null, source.vatId), taxScheme(source.taxSchemeId)]) : null;
230
+ const companyId = (source) => source.companyId ? el("cbc:CompanyID", source.companyId.scheme !== void 0 ? { schemeID: source.companyId.scheme } : null, source.companyId.value) : null;
231
+ const contact = (source) => source.contact ? el("cac:Contact", null, [
232
+ text("cbc:Name", source.contact.name),
233
+ text("cbc:Telephone", source.contact.phone),
234
+ text("cbc:ElectronicMail", source.contact.email)
235
+ ]) : null;
236
+ /** `cac:Party` for the seller and buyer (BG-4, BG-7). */
147
237
  const party = (source, name) => el("cac:Party", null, [
148
238
  source.endpoint ? el("cbc:EndpointID", { schemeID: source.endpoint.scheme ?? "" }, source.endpoint.value) : null,
149
- el("cac:PartyName", null, [el("cbc:Name", null, name)]),
239
+ ...partyIdentifications(source),
240
+ partyName(name),
150
241
  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])
242
+ partyTaxScheme(source),
243
+ el("cac:PartyLegalEntity", null, [
244
+ el("cbc:RegistrationName", null, source.registrationName ?? name),
245
+ companyId(source),
246
+ text("cbc:CompanyLegalForm", source.companyLegalForm)
247
+ ]),
248
+ contact(source)
249
+ ]);
250
+ /** `cac:PayeeParty` (BG-10): identification, name and legal entity id, unwrapped. */
251
+ const payeeParty = (source) => el("cac:PayeeParty", null, [
252
+ ...partyIdentifications(source),
253
+ partyName(source.name ?? ""),
254
+ source.companyId ? el("cac:PartyLegalEntity", null, [companyId(source)]) : null
255
+ ]);
256
+ /** `cac:TaxRepresentativeParty` (BG-11): name, address and VAT id, unwrapped. */
257
+ const taxRepresentativeParty = (source) => el("cac:TaxRepresentativeParty", null, [
258
+ partyName(source.name ?? ""),
259
+ source.address ? postalAddress(source.address) : null,
260
+ partyTaxScheme(source)
261
+ ]);
262
+ /** `cac:Delivery` (BG-13). */
263
+ const delivery = (source) => {
264
+ 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;
265
+ const deliveryParty = source.partyName !== void 0 ? el("cac:DeliveryParty", null, [partyName(source.partyName)]) : null;
266
+ if (source.actualDeliveryDate === void 0 && !location && !deliveryParty) return null;
267
+ return el("cac:Delivery", null, [
268
+ text("cbc:ActualDeliveryDate", source.actualDeliveryDate),
269
+ location,
270
+ deliveryParty
271
+ ]);
272
+ };
273
+ /**
274
+ * `cac:PaymentMeans` (BG-16). On a credit note BT-9 has no root element and
275
+ * rides in the first payment means as `cbc:PaymentDueDate`. `cbc:NetworkID`
276
+ * is schema-mandatory inside `cac:CardAccount` and carries no business term;
277
+ * the BIS example value is `NA`.
278
+ */
279
+ const paymentMeans = (source, dueDate) => el("cac:PaymentMeans", null, [
280
+ el("cbc:PaymentMeansCode", source.codeName !== void 0 ? { name: source.codeName } : null, source.code ?? ""),
281
+ text("cbc:PaymentDueDate", dueDate),
282
+ text("cbc:PaymentID", source.paymentId),
283
+ source.cardNumber !== void 0 ? el("cac:CardAccount", null, [
284
+ el("cbc:PrimaryAccountNumberID", null, source.cardNumber),
285
+ el("cbc:NetworkID", null, "NA"),
286
+ text("cbc:HolderName", source.cardHolder)
287
+ ]) : null,
288
+ source.iban !== void 0 ? el("cac:PayeeFinancialAccount", null, [
289
+ el("cbc:ID", null, source.iban),
290
+ text("cbc:Name", source.accountName),
291
+ source.bic !== void 0 ? el("cac:FinancialInstitutionBranch", null, [el("cbc:ID", null, source.bic)]) : null
292
+ ]) : null,
293
+ 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
294
+ ]);
295
+ /**
296
+ * `cac:AllowanceCharge` at document level (BG-20/BG-21, with its VAT
297
+ * category) and line level (BG-27/BG-28, without: the line's category
298
+ * applies).
299
+ */
300
+ const allowanceCharge = (item, currency, path, level) => el("cac:AllowanceCharge", null, [
301
+ el("cbc:ChargeIndicator", null, item.chargeIndicator ? "true" : "false"),
302
+ text("cbc:AllowanceChargeReasonCode", item.reasonCode),
303
+ text("cbc:AllowanceChargeReason", item.reason),
304
+ item.multiplierFactorNumeric !== void 0 ? el("cbc:MultiplierFactorNumeric", null, percent(item.multiplierFactorNumeric)) : null,
305
+ money("cbc:Amount", item.amount ?? 0, currency),
306
+ optionalMoney("cbc:BaseAmount", item.baseAmount, currency),
307
+ level === "document" ? taxCategory("cac:TaxCategory", item.taxCategory ?? {}, `${path}.taxCategory`) : null
153
308
  ]);
154
309
  const taxSubtotal = (subtotal, currency, index) => {
155
310
  const path = `taxTotal.subtotals[${index}]`;
@@ -160,17 +315,20 @@ const taxSubtotal = (subtotal, currency, index) => {
160
315
  ]);
161
316
  };
162
317
  /**
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.
318
+ * `cac:LegalMonetaryTotal` children, in UBL sequence order. BT-107/BT-108 are
319
+ * written when the document carries allowances or charges; BT-113 and BT-114
320
+ * are omitted when absent or zero.
167
321
  */
168
322
  const legalMonetaryTotalChildren = (doc) => {
169
323
  const { currency, monetaryTotal: total } = doc;
324
+ const hasAllowances = (doc.allowanceCharges ?? []).some((item) => !item.chargeIndicator);
325
+ const hasCharges = (doc.allowanceCharges ?? []).some((item) => item.chargeIndicator);
170
326
  return [
171
327
  money("cbc:LineExtensionAmount", total.lineExtensionAmount ?? 0, currency),
172
328
  money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount ?? 0, currency),
173
329
  money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount ?? 0, currency),
330
+ hasAllowances || total.allowanceTotalAmount ? money("cbc:AllowanceTotalAmount", total.allowanceTotalAmount ?? 0, currency) : null,
331
+ hasCharges || total.chargeTotalAmount ? money("cbc:ChargeTotalAmount", total.chargeTotalAmount ?? 0, currency) : null,
174
332
  total.prepaidAmount ? money("cbc:PrepaidAmount", total.prepaidAmount, currency) : null,
175
333
  total.payableRoundingAmount ? money("cbc:PayableRoundingAmount", total.payableRoundingAmount, currency) : null,
176
334
  money("cbc:PayableAmount", total.payableAmount ?? 0, currency)
@@ -178,12 +336,31 @@ const legalMonetaryTotalChildren = (doc) => {
178
336
  };
179
337
  /**
180
338
  * `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.
339
+ * fails BR-CO-19, which requires at least one of the two dates. BT-8 (the tax
340
+ * point date code) is only meaningful on the document period.
182
341
  */
183
342
  const invoicePeriod = (period) => {
184
343
  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)]);
344
+ return el("cac:InvoicePeriod", null, [
345
+ text("cbc:StartDate", period.startDate),
346
+ text("cbc:EndDate", period.endDate),
347
+ text("cbc:DescriptionCode", period.descriptionCode)
348
+ ]);
186
349
  };
350
+ const item = (source) => el("cac:Item", null, [
351
+ text("cbc:Description", source.description),
352
+ el("cbc:Name", null, source.itemName ?? source.description ?? source.id),
353
+ source.buyersItemId !== void 0 ? el("cac:BuyersItemIdentification", null, [el("cbc:ID", null, source.buyersItemId)]) : null,
354
+ source.sellersItemId !== void 0 ? el("cac:SellersItemIdentification", null, [el("cbc:ID", null, source.sellersItemId)]) : null,
355
+ source.standardItemId !== void 0 ? el("cac:StandardItemIdentification", null, [schemedId("cbc:ID", source.standardItemId)]) : null,
356
+ source.originCountryCode !== void 0 ? el("cac:OriginCountry", null, [el("cbc:IdentificationCode", null, source.originCountryCode)]) : null,
357
+ ...(source.commodityClassifications ?? []).map((classification) => el("cac:CommodityClassification", null, [el("cbc:ItemClassificationCode", {
358
+ listID: classification.listId,
359
+ listVersionID: classification.listVersionId
360
+ }, classification.value)])),
361
+ taxCategory("cac:ClassifiedTaxCategory", source.taxCategory ?? {}, `lines[${source.id}].taxCategory`),
362
+ ...(source.additionalItemProperties ?? []).map((property) => el("cac:AdditionalItemProperty", null, [el("cbc:Name", null, property.name), el("cbc:Value", null, property.value ?? "")]))
363
+ ]);
187
364
  const line = (source, currency, documentType) => {
188
365
  const isCreditNote = documentType === "CreditNote";
189
366
  const lineElementName = isCreditNote ? "cac:CreditNoteLine" : "cac:InvoiceLine";
@@ -192,41 +369,67 @@ const line = (source, currency, documentType) => {
192
369
  const priceAmount = (source.unitPrice ?? 0) * (source.baseQuantity ?? 1);
193
370
  return el(lineElementName, null, [
194
371
  el("cbc:ID", null, source.id),
372
+ text("cbc:Note", source.note),
195
373
  el(quantityElementName, { unitCode }, String(source.quantity ?? 0)),
196
374
  money("cbc:LineExtensionAmount", source.lineExtensionAmount ?? 0, currency),
375
+ text("cbc:AccountingCost", source.accountingCost),
197
376
  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])
377
+ source.orderLineReference !== void 0 ? el("cac:OrderLineReference", null, [el("cbc:LineID", null, source.orderLineReference)]) : null,
378
+ source.objectIdentifier !== void 0 ? el("cac:DocumentReference", null, [schemedId("cbc:ID", source.objectIdentifier), el("cbc:DocumentTypeCode", null, "130")]) : null,
379
+ ...(source.allowanceCharges ?? []).map((entry, index) => allowanceCharge(entry, currency, `lines[${source.id}].allowanceCharges[${index}]`, "line")),
380
+ item(source),
381
+ el("cac:Price", null, [
382
+ money("cbc:PriceAmount", priceAmount, currency),
383
+ source.baseQuantity !== void 0 ? el("cbc:BaseQuantity", { unitCode }, String(source.baseQuantity)) : null,
384
+ source.priceAllowance !== void 0 ? el("cac:AllowanceCharge", null, [
385
+ el("cbc:ChargeIndicator", null, "false"),
386
+ money("cbc:Amount", source.priceAllowance.amount ?? 0, currency),
387
+ optionalMoney("cbc:BaseAmount", source.priceAllowance.baseAmount, currency)
388
+ ]) : null
389
+ ])
204
390
  ]);
205
391
  };
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 ?? "")])]);
392
+ const attachmentReference = (attachment) => el("cac:AdditionalDocumentReference", null, [
393
+ el("cbc:ID", null, attachment.id ?? attachment.filename ?? attachment.externalUri ?? ""),
394
+ text("cbc:DocumentDescription", attachment.description),
395
+ el("cac:Attachment", null, [isExternalOnly(attachment) ? el("cac:ExternalReference", null, [el("cbc:URI", null, attachment.externalUri ?? "")]) : el("cbc:EmbeddedDocumentBinaryObject", {
396
+ mimeCode: attachment.mimeCode ?? "",
397
+ filename: attachment.filename ?? ""
398
+ }, attachment.base64Content ?? "")])
399
+ ]);
400
+ /** A typed `cac:AdditionalDocumentReference` without attachment (BT-17, BT-18, BT-11 on a credit note). */
401
+ const typedDocumentReference = (id, typeCode) => el("cac:AdditionalDocumentReference", null, [schemedId("cbc:ID", id), el("cbc:DocumentTypeCode", null, typeCode)]);
402
+ const documentReference = (name, id) => id !== void 0 ? el(name, null, [el("cbc:ID", null, id)]) : null;
403
+ /**
404
+ * `cac:OrderReference`. BT-13 (the buyer's order number) is the element's
405
+ * mandatory child, so a sales order id (BT-14) alone is not emitted.
406
+ */
407
+ const orderReference = (doc) => {
408
+ if (doc.orderReference === void 0) return null;
409
+ return el("cac:OrderReference", null, [el("cbc:ID", null, doc.orderReference), text("cbc:SalesOrderID", doc.salesOrderId)]);
410
+ };
210
411
  const billingReference = (reference) => {
211
412
  if (reference.invoiceId === void 0) return null;
212
- return el("cac:BillingReference", null, [el("cac:InvoiceDocumentReference", null, [el("cbc:ID", null, reference.invoiceId)])]);
413
+ return el("cac:BillingReference", null, [el("cac:InvoiceDocumentReference", null, [el("cbc:ID", null, reference.invoiceId), text("cbc:IssueDate", reference.invoiceIssueDate)])]);
213
414
  };
214
415
  /**
215
416
  * Serialize a {@link UblInvoice} into a Peppol BIS Billing 3.0 XML string.
216
417
  *
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.
418
+ * Writes every EN 16931 business term the model holds, at its position in the
419
+ * UBL 2.1 sequence: the header terms (`customizationId`, `profileId` and
420
+ * `invoiceTypeCode` default to the BIS values), the references (BT-10 to
421
+ * BT-19), the parties with identifications, legal form and contacts, the
422
+ * payee and tax representative, delivery, payment means, payment terms,
423
+ * document and line allowances and charges, the VAT breakdown (plus BT-111 in
424
+ * the accounting currency), the monetary totals, attachments and document
425
+ * references, and lines with their item identifiers, classifications,
426
+ * properties, price discount and classified VAT category. Line-level tax
427
+ * totals are not emitted: BIS Billing 3.0 forbids them.
223
428
  *
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.
429
+ * @throws {UblBuildError} when a field EN 16931 / Peppol BIS makes mandatory
430
+ * is missing (naming the BT and the model path), or when the document's
431
+ * arithmetic breaks a business rule: BR-CO-3, BR-CO-10 to BR-CO-13, BR-CO-15,
432
+ * BR-CO-16, BR-53, the BR-S-08 family, PEPPOL-EN16931-R040 and R120.
230
433
  */
231
434
  const serializeUblInvoice = (doc) => {
232
435
  validateInvoice(doc);
@@ -234,23 +437,45 @@ const serializeUblInvoice = (doc) => {
234
437
  const rootName = isCreditNote ? "CreditNote" : "Invoice";
235
438
  const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
236
439
  const typeCodeElement = isCreditNote ? el("cbc:CreditNoteTypeCode", null, doc.invoiceTypeCode ?? "381") : el("cbc:InvoiceTypeCode", null, doc.invoiceTypeCode ?? "380");
440
+ const taxPointDate = text("cbc:TaxPointDate", doc.taxPointDate);
441
+ const means = paymentMeansList(doc);
442
+ const creditNoteDueDate = isCreditNote && means.length > 0 ? doc.dueDate : void 0;
237
443
  const children = [
238
444
  el("cbc:CustomizationID", null, doc.customizationId ?? "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0"),
239
445
  el("cbc:ProfileID", null, doc.profileId ?? "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0"),
240
446
  el("cbc:ID", null, doc.id),
241
447
  el("cbc:IssueDate", null, doc.issueDate),
242
448
  !isCreditNote ? text("cbc:DueDate", doc.dueDate) : null,
449
+ isCreditNote ? taxPointDate : null,
243
450
  typeCodeElement,
244
451
  text("cbc:Note", doc.note),
452
+ !isCreditNote ? taxPointDate : null,
245
453
  el("cbc:DocumentCurrencyCode", null, doc.currency),
454
+ text("cbc:TaxCurrencyCode", doc.taxCurrency),
455
+ text("cbc:AccountingCost", doc.accountingCost),
246
456
  text("cbc:BuyerReference", doc.buyerReference),
247
457
  invoicePeriod(doc.invoicePeriod),
458
+ orderReference(doc),
248
459
  doc.billingReference ? billingReference(doc.billingReference) : null,
460
+ documentReference("cac:DespatchDocumentReference", doc.despatchReference),
461
+ documentReference("cac:ReceiptDocumentReference", doc.receivingAdviceReference),
462
+ documentReference("cac:ContractDocumentReference", doc.contractReference),
249
463
  ...(doc.attachments ?? []).map(attachmentReference),
464
+ ...(doc.documentReferences ?? []).map((reference) => el("cac:AdditionalDocumentReference", null, [el("cbc:ID", null, reference.id ?? ""), text("cbc:DocumentDescription", reference.description)])),
465
+ doc.invoicedObjectId !== void 0 ? typedDocumentReference(doc.invoicedObjectId, "130") : null,
466
+ !isCreditNote && doc.tenderReference !== void 0 ? typedDocumentReference({ value: doc.tenderReference }, "50") : null,
467
+ isCreditNote && doc.projectReference !== void 0 ? typedDocumentReference({ value: doc.projectReference }, "50") : null,
468
+ !isCreditNote ? documentReference("cac:ProjectReference", doc.projectReference) : null,
250
469
  el("cac:AccountingSupplierParty", null, [party(doc.seller, doc.seller.name ?? "")]),
251
470
  el("cac:AccountingCustomerParty", null, [party(doc.buyer, doc.buyer.name ?? "")]),
471
+ doc.payee ? payeeParty(doc.payee) : null,
472
+ doc.taxRepresentative ? taxRepresentativeParty(doc.taxRepresentative) : null,
473
+ doc.delivery ? delivery(doc.delivery) : null,
474
+ ...means.map((entry, index) => paymentMeans(entry, index === 0 ? creditNoteDueDate : void 0)),
252
475
  doc.paymentTermsNote !== void 0 ? el("cac:PaymentTerms", null, [el("cbc:Note", null, doc.paymentTermsNote)]) : null,
476
+ ...(doc.allowanceCharges ?? []).map((entry, index) => allowanceCharge(entry, doc.currency, `allowanceCharges[${index}]`, "document")),
253
477
  el("cac:TaxTotal", null, [money("cbc:TaxAmount", doc.taxTotal.taxAmount ?? 0, doc.currency), ...doc.taxTotal.subtotals.map((subtotal, index) => taxSubtotal(subtotal, doc.currency, index))]),
478
+ doc.taxCurrency !== void 0 ? el("cac:TaxTotal", null, [money("cbc:TaxAmount", doc.taxTotal.taxAmountInTaxCurrency ?? 0, doc.taxCurrency)]) : null,
254
479
  el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
255
480
  ...doc.lines.map((source) => line(source, doc.currency, doc.documentType))
256
481
  ];
@@ -728,9 +953,11 @@ const reconcileLinesToExclTotal = (lines, authoritativeTotalExclVat) => {
728
953
  return lines.map((line, idx) => {
729
954
  if (idx !== largestIdx) return line;
730
955
  const adjusted = roundCurrency(lineNet(line) + diff);
731
- const { unitPrice, baseQuantity } = deriveUnitPrice(adjusted, line.quantity ?? 0);
956
+ const units = Math.abs(line.quantity ?? 0);
957
+ const { unitPrice, baseQuantity } = deriveUnitPrice(Math.abs(adjusted), units);
732
958
  return compact({
733
959
  ...line,
960
+ quantity: line.quantity === void 0 ? void 0 : adjusted < 0 ? -units : units,
734
961
  lineExtensionAmount: adjusted,
735
962
  unitPrice,
736
963
  baseQuantity
@@ -754,8 +981,8 @@ const categoryKey = (category) => `${category.id ?? ""}:${category.percent ?? ""
754
981
  * exceeding the total yields a negative payable amount, surfacing the upstream
755
982
  * overpayment rather than hiding it.
756
983
  *
757
- * @throws {UblBuildError} for a line without a `taxCategory` — there is no
758
- * VAT breakdown to put it in.
984
+ * @throws {UblBuildError} for a line, allowance or charge without a
985
+ * `taxCategory` — there is no VAT breakdown to put it in.
759
986
  */
760
987
  const buildTaxTotals = (lines, options) => {
761
988
  const groups = /* @__PURE__ */ new Map();
@@ -769,6 +996,18 @@ const buildTaxTotals = (lines, options) => {
769
996
  current.taxableAmount = roundCurrency(current.taxableAmount + lineNet(line));
770
997
  groups.set(key, current);
771
998
  }
999
+ const allowanceCharges = options?.allowanceCharges ?? [];
1000
+ for (const [index, item] of allowanceCharges.entries()) {
1001
+ if (!item.taxCategory) throw new UblBuildError(`allowanceCharges[${index}] has no taxCategory (BT-95/BT-102); cannot build the VAT breakdown`);
1002
+ const key = categoryKey(item.taxCategory);
1003
+ const current = groups.get(key) ?? {
1004
+ category: item.taxCategory,
1005
+ taxableAmount: 0
1006
+ };
1007
+ const signed = item.chargeIndicator ? item.amount ?? 0 : -(item.amount ?? 0);
1008
+ current.taxableAmount = roundCurrency(current.taxableAmount + signed);
1009
+ groups.set(key, current);
1010
+ }
772
1011
  const subtotals = Array.from(groups.values()).map((group) => ({
773
1012
  taxableAmount: group.taxableAmount,
774
1013
  taxAmount: roundCurrency(group.taxableAmount * (group.category.percent ?? 0) / 100),
@@ -776,7 +1015,10 @@ const buildTaxTotals = (lines, options) => {
776
1015
  }));
777
1016
  const lineExtensionAmount = roundCurrency(lines.reduce((sum, line) => sum + lineNet(line), 0));
778
1017
  const taxAmount = roundCurrency(subtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0));
779
- const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
1018
+ const allowanceTotalAmount = roundCurrency(allowanceCharges.filter((item) => !item.chargeIndicator).reduce((sum, item) => sum + (item.amount ?? 0), 0));
1019
+ const chargeTotalAmount = roundCurrency(allowanceCharges.filter((item) => item.chargeIndicator).reduce((sum, item) => sum + (item.amount ?? 0), 0));
1020
+ const taxExclusiveAmount = roundCurrency(lineExtensionAmount - allowanceTotalAmount + chargeTotalAmount);
1021
+ const taxInclusiveAmount = roundCurrency(taxExclusiveAmount + taxAmount);
780
1022
  const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
781
1023
  const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
782
1024
  const payableAmount = roundCurrency(taxInclusiveAmount - prepaidAmount + payableRoundingAmount);
@@ -787,15 +1029,66 @@ const buildTaxTotals = (lines, options) => {
787
1029
  },
788
1030
  monetaryTotal: {
789
1031
  lineExtensionAmount,
790
- taxExclusiveAmount: lineExtensionAmount,
1032
+ taxExclusiveAmount,
791
1033
  taxInclusiveAmount,
1034
+ ...allowanceTotalAmount ? { allowanceTotalAmount } : {},
1035
+ ...chargeTotalAmount ? { chargeTotalAmount } : {},
792
1036
  ...prepaidAmount ? { prepaidAmount } : {},
793
1037
  ...payableRoundingAmount ? { payableRoundingAmount } : {},
794
1038
  payableAmount
795
1039
  }
796
1040
  };
797
1041
  };
1042
+ /**
1043
+ * Split one document-level amount into an allowance or charge per VAT
1044
+ * category the lines use, pro rata by each category's line nets, so a
1045
+ * shipping charge or an invoice-wide discount on a mixed-rate invoice lands in
1046
+ * the right VAT subtotals (an ancillary cost follows the supply it belongs to).
1047
+ * Cent remainders go to the largest shares so the parts sum to `amount`
1048
+ * exactly; categories that receive nothing are omitted. With no positive
1049
+ * line net at all the whole amount goes to the first line's category.
1050
+ *
1051
+ * @throws {UblBuildError} for a line without a `taxCategory`.
1052
+ */
1053
+ const allocateAcrossTaxCategories = (amount, lines, template) => {
1054
+ const groups = /* @__PURE__ */ new Map();
1055
+ for (const line of lines) {
1056
+ if (!line.taxCategory) throw new UblBuildError(`Line ${line.id} has no taxCategory (BT-151); cannot allocate across categories`);
1057
+ const key = categoryKey(line.taxCategory);
1058
+ const current = groups.get(key) ?? {
1059
+ category: line.taxCategory,
1060
+ net: 0
1061
+ };
1062
+ current.net = roundCurrency(current.net + Math.max(0, lineNet(line)));
1063
+ groups.set(key, current);
1064
+ }
1065
+ const entries = Array.from(groups.values());
1066
+ const total = roundCurrency(amount);
1067
+ if (entries.length === 0 || total === 0) return [];
1068
+ const netSum = entries.reduce((sum, entry) => sum + entry.net, 0);
1069
+ const shares = netSum > 0 ? entries.map((entry) => total * entry.net / netSum) : entries.map((_entry, index) => index === 0 ? total : 0);
1070
+ const cents = shares.map((share) => Math.floor(share * 100 + 1e-9));
1071
+ let remainder = Math.round(total * 100) - cents.reduce((sum, value) => sum + value, 0);
1072
+ const order = shares.map((share, index) => ({
1073
+ index,
1074
+ fraction: share * 100 - Math.floor(share * 100 + 1e-9)
1075
+ })).sort((a, b) => b.fraction - a.fraction);
1076
+ for (const { index } of order) {
1077
+ if (remainder <= 0) break;
1078
+ cents[index] = (cents[index] ?? 0) + 1;
1079
+ remainder -= 1;
1080
+ }
1081
+ return entries.flatMap((entry, index) => {
1082
+ const value = (cents[index] ?? 0) / 100;
1083
+ if (value === 0) return [];
1084
+ return [compact({
1085
+ ...template,
1086
+ amount: value,
1087
+ taxCategory: entry.category
1088
+ })];
1089
+ });
1090
+ };
798
1091
  //#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 };
1092
+ 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
1093
 
801
1094
  //# sourceMappingURL=index.js.map