@tallyui/core 3.7.1 → 3.9.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.
@@ -0,0 +1,360 @@
1
+ // Ported from @wcpos/order-math, MIT, Copyright (c) 2021-2026 WCPOS.
2
+ // WooCommerce tax parity (ADR-076): keep the arithmetic as in the original; see docs/DECISIONS.md.
3
+
4
+ import { getRoundingPrecision, roundHalfUp, roundTaxTotal } from '../../tax/woocommerce/precision';
5
+
6
+ import type {
7
+ CouponLineInput as CouponLine,
8
+ FeeLineInput as FeeLine,
9
+ LineItemInput as LineItem,
10
+ ShippingLineInput as ShippingLine,
11
+ TaxRateInput as TaxRateDocument,
12
+ } from './types';
13
+
14
+ // WC NumberUtil::normalize() rounds to the constant WC_ROUNDING_PRECISION (always 6),
15
+ // unlike wc_get_rounding_precision() = max(dp + 2, 6) (NumberUtil.php:23-33, WC 10.8.1).
16
+ const WC_NORMALIZE_PRECISION = 6;
17
+
18
+ interface Props {
19
+ lineItems?: LineItem[];
20
+ shippingLines?: ShippingLine[];
21
+ feeLines?: FeeLine[];
22
+ couponLines?: CouponLine[];
23
+ taxRates?: TaxRateDocument[];
24
+ taxRoundAtSubtotal?: boolean;
25
+ dp?: number;
26
+ pricesIncludeTax?: boolean;
27
+ }
28
+
29
+ interface TaxLine {
30
+ rate_id: number;
31
+ label: string;
32
+ compound: boolean;
33
+ tax_total: number;
34
+ shipping_tax_total: number;
35
+ rate_percent: number;
36
+ meta_data: any[];
37
+ }
38
+
39
+ // Define a type for the accumulator in the reduce function
40
+ type TaxLinesMap = Record<string, TaxLine>;
41
+
42
+ /**
43
+ *
44
+ */
45
+ function parseNumber(value: any): number {
46
+ if (value == null || isNaN(value)) {
47
+ return 0;
48
+ }
49
+ const parsed = parseFloat(value);
50
+ return isNaN(parsed) ? 0 : parsed;
51
+ }
52
+
53
+ /**
54
+ * Calculate order totals from line items, fees, shipping, and coupons.
55
+ *
56
+ * When taxRoundAtSubtotal=true, tax values on individual lines are at rounding precision
57
+ * and the final aggregated tax_total/shipping_tax_total is rounded to dp once.
58
+ *
59
+ * When taxRoundAtSubtotal=false (default), taxes were already rounded per-item to dp.
60
+ *
61
+ * @param dp - Price decimal places (default 2)
62
+ * @param pricesIncludeTax - Whether prices include tax (affects rounding mode)
63
+ * @param onWarning - Optional callback fired when a line references a tax rate id absent
64
+ * from taxRates (a bucket is lazily created instead of throwing)
65
+ */
66
+ export function calculateOrderTotals(
67
+ {
68
+ lineItems = [],
69
+ shippingLines = [],
70
+ feeLines = [],
71
+ couponLines = [],
72
+ taxRates = [],
73
+ taxRoundAtSubtotal = false,
74
+ dp = 2,
75
+ pricesIncludeTax = false,
76
+ }: Props,
77
+ onWarning?: (w: { code: 'unknown_tax_rate_id'; rateId: number }) => void
78
+ ) {
79
+ // Filter out items marked for deletion. WCPOS nulls a key field to signal
80
+ // the server should delete the item: product_id (line_items), name (fee_lines),
81
+ // method_id (shipping_lines), code (coupon_lines). These must never contribute
82
+ // to totals regardless of whether the caller pre-filters.
83
+ const activeLineItems = lineItems.filter((item) => item.product_id !== null);
84
+ const activeFeeLines = feeLines.filter((item) => item.name !== null);
85
+ const activeShippingLines = shippingLines.filter((item) => item.method_id !== null);
86
+ // Loose != null also excludes undefined, matching existing use-cart-lines patterns
87
+ const activeCouponLines = couponLines.filter((item) => item.code != null);
88
+
89
+ let discount_total = 0;
90
+ let discount_tax = 0;
91
+ let shipping_total = 0;
92
+ let shipping_tax = 0;
93
+ let cart_tax = 0;
94
+ let subtotal = 0;
95
+ let subtotal_tax = 0;
96
+ let total = 0;
97
+ let total_tax = 0;
98
+ let fee_total = 0;
99
+ let fee_tax = 0;
100
+ let coupon_total = 0;
101
+ let coupon_tax = 0;
102
+
103
+ // Initialize taxLines as an object
104
+ const taxLines = taxRates.reduce<TaxLinesMap>((acc, taxRate) => {
105
+ const rateId = taxRate.id ?? 0;
106
+ acc[rateId] = {
107
+ rate_id: rateId,
108
+ label: taxRate.name ?? '',
109
+ compound: taxRate.compound ?? false,
110
+ tax_total: 0,
111
+ shipping_tax_total: 0,
112
+ rate_percent: parseFloat(taxRate.rate ?? '0'),
113
+ meta_data: [],
114
+ };
115
+ return acc;
116
+ }, {});
117
+
118
+ // Calculate line item totals
119
+ //
120
+ // WC computes order totals using get_cart_subtotal_for_order() / get_cart_total_for_order(),
121
+ // which call get_rounded_items_total() → round_item_subtotal(). When taxRoundAtSubtotal
122
+ // is false (default), each item is rounded to dp (cents) before summing. When true, items
123
+ // are kept at full precision. This per-item rounding affects discount_total and order.total.
124
+ activeLineItems.forEach((item) => {
125
+ const parsedSubtotal = parseNumber(item.subtotal);
126
+ const parsedTotal = parseNumber(item.total);
127
+ const parsedSubtotalTax = parseNumber(item.subtotal_tax);
128
+ const parsedTotalTax = parseNumber(item.total_tax);
129
+
130
+ // Per-item rounded values matching WC's get_rounded_items_total()
131
+ const roundedItemSubtotal = taxRoundAtSubtotal
132
+ ? parsedSubtotal
133
+ : roundHalfUp(parsedSubtotal, dp);
134
+ const roundedItemTotal = taxRoundAtSubtotal ? parsedTotal : roundHalfUp(parsedTotal, dp);
135
+
136
+ discount_total += roundedItemSubtotal - roundedItemTotal;
137
+
138
+ // WC accumulates discount_tax per tax rate from the taxes[] array,
139
+ // NOT from the collapsed subtotal_tax/total_tax. This matters for
140
+ // multi-rate items where round(a+b, 6) ≠ round(a, 6) + round(b, 6).
141
+ // Pre-round each per-rate difference to rounding precision (6dp) to
142
+ // snap IEEE 754 float artifacts (e.g., 4.5 - 4.275 = 0.22499...).
143
+ const hasPerRateSubtotals =
144
+ Array.isArray(item.taxes) && item.taxes.length > 0 && item.taxes[0].subtotal != null;
145
+ if (hasPerRateSubtotals) {
146
+ item.taxes!.forEach((tax) => {
147
+ const subtotalTaxForRate = parseNumber(tax.subtotal);
148
+ const totalTaxForRate = parseNumber(tax.total);
149
+ discount_tax += roundHalfUp(subtotalTaxForRate - totalTaxForRate, getRoundingPrecision(dp));
150
+ });
151
+ } else {
152
+ // Fallback: use line-level subtotal_tax/total_tax when per-rate subtotals
153
+ // are not available (e.g., taxes array missing or without subtotal field).
154
+ discount_tax += roundHalfUp(parsedSubtotalTax - parsedTotalTax, getRoundingPrecision(dp));
155
+ }
156
+
157
+ // Use per-item-rounded values for subtotal/total (matches WC's calculate_totals)
158
+ subtotal += roundedItemSubtotal;
159
+ subtotal_tax += parsedSubtotalTax;
160
+ total += roundedItemTotal;
161
+ total_tax += parsedTotalTax;
162
+
163
+ if (Array.isArray(item.taxes)) {
164
+ item.taxes.forEach((tax) => {
165
+ const taxAmount = parseNumber(tax.total);
166
+ // When taxRoundAtSubtotal=false, WC rounds each per-item per-rate tax
167
+ // to dp before summing into tax_lines (matching update_taxes() behavior).
168
+ // When true, taxes accumulate at full precision and round only at the end.
169
+ const rateId = tax.id ?? 0;
170
+ if (!taxLines[rateId]) {
171
+ // QUIRK(parity): lazily-created buckets still obey the existing both-zero
172
+ // pre-rounding drop rule — no code change needed, the existing filter handles it.
173
+ taxLines[rateId] = {
174
+ rate_id: rateId,
175
+ label: '',
176
+ compound: false,
177
+ tax_total: 0,
178
+ shipping_tax_total: 0,
179
+ rate_percent: 0,
180
+ meta_data: [],
181
+ };
182
+ onWarning?.({ code: 'unknown_tax_rate_id', rateId });
183
+ }
184
+ taxLines[rateId].tax_total += taxRoundAtSubtotal
185
+ ? taxAmount
186
+ : roundTaxTotal(taxAmount, dp, pricesIncludeTax);
187
+ });
188
+ }
189
+ });
190
+
191
+ // Helper: accumulate per-rate taxes into taxLines with conditional rounding.
192
+ // Shared by fee and shipping lines to avoid the same parity bug as lineItems.
193
+ const accumulateTaxes = (
194
+ taxes: any[] | undefined,
195
+ target: 'tax_total' | 'shipping_tax_total'
196
+ ) => {
197
+ if (!Array.isArray(taxes)) return;
198
+ taxes.forEach((tax) => {
199
+ const taxAmount = parseNumber(tax.total);
200
+ const rateId = tax.id ?? 0;
201
+ if (!taxLines[rateId]) {
202
+ // QUIRK(parity): lazily-created buckets still obey the existing both-zero
203
+ // pre-rounding drop rule — no code change needed, the existing filter handles it.
204
+ taxLines[rateId] = {
205
+ rate_id: rateId,
206
+ label: '',
207
+ compound: false,
208
+ tax_total: 0,
209
+ shipping_tax_total: 0,
210
+ rate_percent: 0,
211
+ meta_data: [],
212
+ };
213
+ onWarning?.({ code: 'unknown_tax_rate_id', rateId });
214
+ }
215
+ taxLines[rateId][target] += taxRoundAtSubtotal
216
+ ? taxAmount
217
+ : roundTaxTotal(taxAmount, dp, pricesIncludeTax);
218
+ });
219
+ };
220
+
221
+ // Calculate fee totals
222
+ //
223
+ // Deliberately NOT rounded per line: WC's calculate_totals() sums fees with
224
+ // `$fees_total += (float) $item->get_total()` and feeds that raw sum straight into
225
+ // set_total(). Only `fee_total` below is rounded, and only because it is a display
226
+ // figure for the cart (matching WC Admin), never a summand of the order total.
227
+ activeFeeLines.forEach((line) => {
228
+ fee_total += parseNumber(line.total);
229
+ fee_tax += parseNumber(line.total_tax);
230
+ total += parseNumber(line.total);
231
+ total_tax += parseNumber(line.total_tax);
232
+ accumulateTaxes(line.taxes, 'tax_total');
233
+ });
234
+
235
+ // Calculate shipping totals
236
+ //
237
+ // WC rounds EACH shipping line to dp before summing (calculate_totals():
238
+ // `$shipping_total += NumberUtil::round( $shipping->get_total(), $price_decimals )`),
239
+ // stores that sum with set_shipping_total(), and adds the SAME rounded figure into
240
+ // set_total(). Unlike line items this rounding is UNCONDITIONAL — it does not depend
241
+ // on woocommerce_tax_round_at_subtotal, which is a tax setting and shipping is summed
242
+ // outside it. Fees are the opposite case and are deliberately left raw below.
243
+ //
244
+ // Summing the raw line values into `total` cost a cent on a $5 tax-inclusive shipping
245
+ // line: the POS sent 65.39 where WooCommerce stored 65.40, because 4.545455 went into
246
+ // the total where WC had already made it 4.55 (dev-free order 110921).
247
+ activeShippingLines.forEach((line) => {
248
+ const roundedLineTotal = roundHalfUp(parseNumber(line.total), dp);
249
+ shipping_total += roundedLineTotal;
250
+ shipping_tax += parseNumber(line.total_tax);
251
+ total += roundedLineTotal;
252
+ total_tax += parseNumber(line.total_tax);
253
+ accumulateTaxes(line.taxes, 'shipping_tax_total');
254
+ });
255
+
256
+ // Accumulate coupon totals for display purposes only.
257
+ // Coupon discounts are already reflected in line_items (subtotal vs total),
258
+ // so we must NOT re-adjust discount_total/total here.
259
+ activeCouponLines.forEach((line) => {
260
+ coupon_total += parseNumber(line.discount);
261
+ coupon_tax += parseNumber(line.discount_tax);
262
+ });
263
+
264
+ // Sum the tax totals for cart_tax before converting to string
265
+ const taxLinesArray = Object.values(taxLines) || [];
266
+
267
+ // When taxRoundAtSubtotal=true, WC keeps per-rate taxes at full precision
268
+ // and only rounds the final aggregated total (cart_tax, total_tax).
269
+ // When taxRoundAtSubtotal=false, taxes were already rounded per-item.
270
+ //
271
+ // For tax_lines, WC stores raw 6dp sums when rounding at subtotal. For cart_tax/total_tax
272
+ // we sum at full precision first, then round — matching WC's update_taxes().
273
+ const fullPrecisionCartTax = taxLinesArray.reduce((sum, tl) => sum + tl.tax_total, 0);
274
+ const fullPrecisionShippingTax = taxLinesArray.reduce(
275
+ (sum, tl) => sum + tl.shipping_tax_total,
276
+ 0
277
+ );
278
+
279
+ const filteredTaxLines = taxLinesArray
280
+ .map((taxLine) => {
281
+ const { tax_total, shipping_tax_total } = taxLine;
282
+
283
+ if (tax_total === 0 && shipping_tax_total === 0) {
284
+ return null;
285
+ }
286
+ return {
287
+ ...taxLine,
288
+ tax_total: taxRoundAtSubtotal
289
+ ? Number(tax_total).toFixed(6)
290
+ : String(roundTaxTotal(tax_total, dp, pricesIncludeTax)),
291
+ shipping_tax_total: taxRoundAtSubtotal
292
+ ? Number(shipping_tax_total).toFixed(6)
293
+ : String(roundTaxTotal(shipping_tax_total, dp, pricesIncludeTax)),
294
+ };
295
+ })
296
+ .filter((line): line is NonNullable<typeof line> => line !== null);
297
+
298
+ // WC set_cart_tax / set_shipping_tax snap summed taxes to rounding precision before
299
+ // set_total_tax / set_total consume them. set_total_tax uses HALF_UP even for inclusive prices.
300
+ const roundedCartTax = roundHalfUp(fullPrecisionCartTax, getRoundingPrecision(dp));
301
+ const roundedShippingTax = roundHalfUp(fullPrecisionShippingTax, getRoundingPrecision(dp));
302
+ // WC 10.1+ NumberUtil::round() normalizes to 6dp (WC_ROUNDING_PRECISION) before rounding to dp
303
+ // (set_total_tax, set_total), so both sums are snapped to 6dp here too.
304
+ const roundedTotalTax = taxRoundAtSubtotal
305
+ ? roundHalfUp(roundHalfUp(roundedCartTax + roundedShippingTax, WC_NORMALIZE_PRECISION), dp)
306
+ : roundTaxTotal(
307
+ roundHalfUp(roundedCartTax + roundedShippingTax, WC_NORMALIZE_PRECISION),
308
+ dp,
309
+ pricesIncludeTax
310
+ );
311
+
312
+ return {
313
+ /**
314
+ * These properties are stored on the order document
315
+ */
316
+ discount_total: String(roundHalfUp(discount_total, dp)),
317
+ discount_tax: String(
318
+ roundTaxTotal(roundHalfUp(discount_tax, WC_NORMALIZE_PRECISION), dp, pricesIncludeTax)
319
+ ),
320
+ shipping_total: String(roundHalfUp(shipping_total, dp)),
321
+ shipping_tax: String(roundedShippingTax),
322
+ cart_tax: String(roundedCartTax),
323
+ // WC: `set_total( round( $cart_total + $fees_total + $shipping_total
324
+ // + $this->get_cart_tax() + $this->get_shipping_tax(), $price_decimals ) )`.
325
+ // The tax summands are the FULL-PRECISION props, not the display-rounded
326
+ // `total_tax` — rounding the tax first and rounding again here is a double
327
+ // rounding that can land a cent away from the store whenever the untaxed part
328
+ // of the sum is not itself at display decimals (a raw fee total is the common
329
+ // way in). `total_tax` stays its own rounded field, which is what WC stores.
330
+ total: String(
331
+ roundHalfUp(
332
+ roundHalfUp(total + roundedCartTax + roundedShippingTax, WC_NORMALIZE_PRECISION),
333
+ dp
334
+ )
335
+ ),
336
+ total_tax: String(roundTaxTotal(roundedTotalTax, dp, pricesIncludeTax)),
337
+ tax_lines: filteredTaxLines,
338
+ /**
339
+ * Subtotals are not stored on the order document, but we need them to display in the cart
340
+ */
341
+ subtotal: String(roundHalfUp(subtotal, dp)),
342
+ subtotal_tax: String(roundHalfUp(subtotal_tax, dp)),
343
+ /**
344
+ * Need to add fee_total to display in the cart, to match the WC Admin display
345
+ */
346
+ fee_total: String(roundHalfUp(fee_total, dp)),
347
+ fee_tax: String(roundHalfUp(fee_tax, dp)),
348
+ coupon_total: String(roundHalfUp(coupon_total, dp)),
349
+ coupon_tax: String(roundHalfUp(coupon_tax, dp)),
350
+ };
351
+ }
352
+
353
+ /**
354
+ * The order-totals read model: the return shape of `calculateOrderTotals`.
355
+ *
356
+ * Named here, beside the one function that produces it, so the shape has a
357
+ * single author. Re-exported as a public type by the package index because
358
+ * `SettleResult.totals` is typed with it and callers must be able to name it.
359
+ */
360
+ export type OrderTotals = ReturnType<typeof calculateOrderTotals>;
@@ -0,0 +1,89 @@
1
+ // Ported from @wcpos/order-math, MIT, Copyright (c) 2021-2026 WCPOS.
2
+ // WooCommerce tax parity (ADR-076): keep the arithmetic as in the original; see docs/DECISIONS.md.
3
+ /** WooCommerce POS line metadata key (`POS_META_KEYS.posData` upstream). */
4
+ const POS_DATA_META_KEY = '_woocommerce_pos_data';
5
+
6
+ export type MetaData = { id?: number; key?: string; value?: unknown }[] | null | undefined;
7
+ type TaxStatus = 'taxable' | 'none';
8
+ type PosData = {
9
+ price?: string | number;
10
+ regular_price?: string | number;
11
+ tax_status?: TaxStatus;
12
+ tax_class?: string;
13
+ amount?: string | number;
14
+ percent?: boolean;
15
+ prices_include_tax?: boolean;
16
+ percent_of_cart_total_with_tax?: boolean;
17
+ virtual?: boolean;
18
+ downloadable?: boolean;
19
+ categories?: { id: number; name: string; [key: string]: unknown }[];
20
+ [key: string]: unknown;
21
+ };
22
+
23
+ const isPosData = (value: unknown): value is PosData =>
24
+ typeof value === 'object' && value !== null && !Array.isArray(value);
25
+
26
+ /**
27
+ * Get tax class from fee line meta data
28
+ */
29
+ export const getMetaDataValueByKey = (metaData: MetaData, key: string) => {
30
+ if (!Array.isArray(metaData)) {
31
+ return;
32
+ }
33
+ const meta = metaData.find((m) => m.key === key);
34
+ return meta ? meta.value : undefined;
35
+ };
36
+
37
+ /**
38
+ * Extract and parse POS metadata from the line item.
39
+ * Structural parameter (meta_data only) so the engine's structural input
40
+ * types (LineItemInput etc.) are accepted alongside DB document fragments.
41
+ */
42
+ export const parsePosData = (item: { meta_data?: MetaData }) => {
43
+ const value = getMetaDataValueByKey(item.meta_data, POS_DATA_META_KEY);
44
+ if (!value) {
45
+ return null;
46
+ }
47
+ if (isPosData(value)) {
48
+ return value;
49
+ }
50
+ if (typeof value !== 'string') {
51
+ return null;
52
+ }
53
+ try {
54
+ const parsed: unknown = JSON.parse(value);
55
+ return isPosData(parsed) ? parsed : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ };
60
+
61
+ /**
62
+ * Resolve a cart line's tax status.
63
+ *
64
+ * Product line items store their tax_status inside `_woocommerce_pos_data` meta
65
+ * — the order schema has no top-level tax_status for line_items. Fee/shipping
66
+ * lines may carry a top-level tax_status. We check top-level first, then
67
+ * pos_data, defaulting to 'taxable' to match WooCommerce's
68
+ * WC_Product::get_tax_status() (empty/invalid values are treated as taxable).
69
+ */
70
+ export const getLineItemTaxStatus = (
71
+ item: { tax_status?: string | null; meta_data?: MetaData } | null | undefined
72
+ ): 'taxable' | 'none' | 'shipping' => {
73
+ const isValid = (value: unknown): value is 'taxable' | 'none' | 'shipping' =>
74
+ value === 'taxable' || value === 'none' || value === 'shipping';
75
+
76
+ const topLevel = item?.tax_status;
77
+ if (isValid(topLevel)) {
78
+ return topLevel;
79
+ }
80
+
81
+ // Guard before calling parsePosData: meta_data must be an array for type safety.
82
+ const posData = Array.isArray(item?.meta_data) ? parsePosData(item) : null;
83
+ const fromPosData = posData?.tax_status;
84
+ if (isValid(fromPosData)) {
85
+ return fromPosData;
86
+ }
87
+
88
+ return 'taxable';
89
+ };