@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.
@@ -1,5 +1,6 @@
1
1
  import { UblBuildError } from "../errors";
2
2
  import type {
3
+ UblAllowanceCharge,
3
4
  UblLine,
4
5
  UblMonetaryTotal,
5
6
  UblTaxCategory,
@@ -43,12 +44,14 @@ export const reconcileLinesToExclTotal = (
43
44
  // nudging the net without re-deriving BT-146/BT-149 to match is exactly
44
45
  // what PEPPOL-EN16931-R120 rejects. Assign `baseQuantity` unconditionally
45
46
  // so a line that no longer needs one doesn't keep a stale value.
46
- const { unitPrice, baseQuantity } = deriveUnitPrice(
47
- adjusted,
48
- line.quantity ?? 0,
49
- );
47
+ // The price may never be negative (BR-27): a net that ends up below zero
48
+ // carries its sign on the quantity instead.
49
+ const units = Math.abs(line.quantity ?? 0);
50
+ const { unitPrice, baseQuantity } = deriveUnitPrice(Math.abs(adjusted), units);
50
51
  return compact({
51
52
  ...line,
53
+ quantity:
54
+ line.quantity === undefined ? undefined : adjusted < 0 ? -units : units,
52
55
  lineExtensionAmount: adjusted,
53
56
  unitPrice,
54
57
  baseQuantity,
@@ -73,6 +76,13 @@ export interface BuildTaxTotalsOptions {
73
76
  prepaidAmount?: number;
74
77
  /** BT-114 — rounding applied to the payable amount. */
75
78
  payableRoundingAmount?: number;
79
+ /**
80
+ * Document-level allowances and charges (BG-20/BG-21). Each one joins the
81
+ * VAT breakdown of its own category (BR-S-08: taxable = line nets −
82
+ * allowances + charges) and feeds BT-107/BT-108, so BT-109 is
83
+ * BT-106 − BT-107 + BT-108 (BR-CO-13). Put the same array on the document.
84
+ */
85
+ allowanceCharges?: UblAllowanceCharge[];
76
86
  }
77
87
 
78
88
  /**
@@ -91,8 +101,8 @@ export interface BuildTaxTotalsOptions {
91
101
  * exceeding the total yields a negative payable amount, surfacing the upstream
92
102
  * overpayment rather than hiding it.
93
103
  *
94
- * @throws {UblBuildError} for a line without a `taxCategory` — there is no
95
- * VAT breakdown to put it in.
104
+ * @throws {UblBuildError} for a line, allowance or charge without a
105
+ * `taxCategory` — there is no VAT breakdown to put it in.
96
106
  */
97
107
  export const buildTaxTotals = (
98
108
  lines: UblLine[],
@@ -117,6 +127,22 @@ export const buildTaxTotals = (
117
127
  current.taxableAmount = roundCurrency(current.taxableAmount + lineNet(line));
118
128
  groups.set(key, current);
119
129
  }
130
+ const allowanceCharges = options?.allowanceCharges ?? [];
131
+ for (const [index, item] of allowanceCharges.entries()) {
132
+ if (!item.taxCategory) {
133
+ throw new UblBuildError(
134
+ `allowanceCharges[${index}] has no taxCategory (BT-95/BT-102); cannot build the VAT breakdown`,
135
+ );
136
+ }
137
+ const key = categoryKey(item.taxCategory);
138
+ const current = groups.get(key) ?? {
139
+ category: item.taxCategory,
140
+ taxableAmount: 0,
141
+ };
142
+ const signed = item.chargeIndicator ? (item.amount ?? 0) : -(item.amount ?? 0);
143
+ current.taxableAmount = roundCurrency(current.taxableAmount + signed);
144
+ groups.set(key, current);
145
+ }
120
146
 
121
147
  const subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({
122
148
  taxableAmount: group.taxableAmount,
@@ -132,7 +158,20 @@ export const buildTaxTotals = (
132
158
  const taxAmount = roundCurrency(
133
159
  subtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0),
134
160
  );
135
- const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
161
+ const allowanceTotalAmount = roundCurrency(
162
+ allowanceCharges
163
+ .filter((item) => !item.chargeIndicator)
164
+ .reduce((sum, item) => sum + (item.amount ?? 0), 0),
165
+ );
166
+ const chargeTotalAmount = roundCurrency(
167
+ allowanceCharges
168
+ .filter((item) => item.chargeIndicator)
169
+ .reduce((sum, item) => sum + (item.amount ?? 0), 0),
170
+ );
171
+ const taxExclusiveAmount = roundCurrency(
172
+ lineExtensionAmount - allowanceTotalAmount + chargeTotalAmount,
173
+ );
174
+ const taxInclusiveAmount = roundCurrency(taxExclusiveAmount + taxAmount);
136
175
 
137
176
  const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
138
177
  const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
@@ -144,11 +183,70 @@ export const buildTaxTotals = (
144
183
  taxTotal: { taxAmount, subtotals },
145
184
  monetaryTotal: {
146
185
  lineExtensionAmount,
147
- taxExclusiveAmount: lineExtensionAmount,
186
+ taxExclusiveAmount,
148
187
  taxInclusiveAmount,
188
+ ...(allowanceTotalAmount ? { allowanceTotalAmount } : {}),
189
+ ...(chargeTotalAmount ? { chargeTotalAmount } : {}),
149
190
  ...(prepaidAmount ? { prepaidAmount } : {}),
150
191
  ...(payableRoundingAmount ? { payableRoundingAmount } : {}),
151
192
  payableAmount,
152
193
  },
153
194
  };
154
195
  };
196
+
197
+ /**
198
+ * Split one document-level amount into an allowance or charge per VAT
199
+ * category the lines use, pro rata by each category's line nets, so a
200
+ * shipping charge or an invoice-wide discount on a mixed-rate invoice lands in
201
+ * the right VAT subtotals (an ancillary cost follows the supply it belongs to).
202
+ * Cent remainders go to the largest shares so the parts sum to `amount`
203
+ * exactly; categories that receive nothing are omitted. With no positive
204
+ * line net at all the whole amount goes to the first line's category.
205
+ *
206
+ * @throws {UblBuildError} for a line without a `taxCategory`.
207
+ */
208
+ export const allocateAcrossTaxCategories = (
209
+ amount: number,
210
+ lines: UblLine[],
211
+ template: Pick<UblAllowanceCharge, "chargeIndicator" | "reason" | "reasonCode">,
212
+ ): UblAllowanceCharge[] => {
213
+ const groups = new Map<string, { category: UblTaxCategory; net: number }>();
214
+ for (const line of lines) {
215
+ if (!line.taxCategory) {
216
+ throw new UblBuildError(
217
+ `Line ${line.id} has no taxCategory (BT-151); cannot allocate across categories`,
218
+ );
219
+ }
220
+ const key = categoryKey(line.taxCategory);
221
+ const current = groups.get(key) ?? { category: line.taxCategory, net: 0 };
222
+ current.net = roundCurrency(current.net + Math.max(0, lineNet(line)));
223
+ groups.set(key, current);
224
+ }
225
+ const entries = Array.from(groups.values());
226
+ const total = roundCurrency(amount);
227
+ if (entries.length === 0 || total === 0) return [];
228
+ const netSum = entries.reduce((sum, entry) => sum + entry.net, 0);
229
+ const shares =
230
+ netSum > 0
231
+ ? entries.map((entry) => (total * entry.net) / netSum)
232
+ : entries.map((_entry, index) => (index === 0 ? total : 0));
233
+ const cents = shares.map((share) => Math.floor(share * 100 + 1e-9));
234
+ let remainder =
235
+ Math.round(total * 100) - cents.reduce((sum, value) => sum + value, 0);
236
+ const order = shares
237
+ .map((share, index) => ({
238
+ index,
239
+ fraction: share * 100 - Math.floor(share * 100 + 1e-9),
240
+ }))
241
+ .sort((a, b) => b.fraction - a.fraction);
242
+ for (const { index } of order) {
243
+ if (remainder <= 0) break;
244
+ cents[index] = (cents[index] ?? 0) + 1;
245
+ remainder -= 1;
246
+ }
247
+ return entries.flatMap((entry, index) => {
248
+ const value = (cents[index] ?? 0) / 100;
249
+ if (value === 0) return [];
250
+ return [compact({ ...template, amount: value, taxCategory: entry.category })];
251
+ });
252
+ };