@tallyui/core 3.8.0 → 3.9.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.
@@ -0,0 +1,399 @@
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
+ import { calculateTaxes } from '../../tax/woocommerce/calculate-taxes';
4
+ import { roundHalfUp, roundTaxTotal } from '../../tax/woocommerce/precision';
5
+ import { getLineItemTaxStatus } from './pos-data';
6
+ import { normalizeTaxClass } from '../../tax/woocommerce/tax-class';
7
+
8
+ import type { PerItemDiscount } from './discount';
9
+
10
+ export interface CouponLineItem {
11
+ product_id: number;
12
+ quantity: number;
13
+ price: number;
14
+ subtotal: string;
15
+ total: string;
16
+ categories: { id: number }[];
17
+ on_sale: boolean;
18
+ /** Stable index into the source line-items array for per-line matching */
19
+ lineIndex?: number;
20
+ }
21
+
22
+ export interface CouponRestrictions {
23
+ product_ids: number[];
24
+ excluded_product_ids: number[];
25
+ product_categories: number[];
26
+ excluded_product_categories: number[];
27
+ exclude_sale_items: boolean;
28
+ }
29
+
30
+ /**
31
+ * Determines whether a product is on sale by comparing price to regular_price.
32
+ * Handles null/undefined/NaN values safely (returns false when data is missing).
33
+ */
34
+ export function isProductOnSale(
35
+ product: { price?: string | null; regular_price?: string | null } | null | undefined
36
+ ): boolean {
37
+ if (!product || !product.price || !product.regular_price) return false;
38
+ const price = parseFloat(product.price);
39
+ const regularPrice = parseFloat(product.regular_price);
40
+ if (isNaN(price) || isNaN(regularPrice) || regularPrice <= 0) return false;
41
+ return price < regularPrice;
42
+ }
43
+
44
+ /**
45
+ * Filters line items to those eligible for a given coupon based on its restrictions.
46
+ * Mirrors the WooCommerce coupon product/category restriction logic.
47
+ */
48
+ export function getEligibleItems(
49
+ items: CouponLineItem[],
50
+ restrictions: CouponRestrictions
51
+ ): CouponLineItem[] {
52
+ return items.filter((item) => {
53
+ // Product ID inclusion filter
54
+ if (
55
+ restrictions.product_ids.length > 0 &&
56
+ !restrictions.product_ids.includes(item.product_id)
57
+ ) {
58
+ return false;
59
+ }
60
+
61
+ // Product ID exclusion filter
62
+ if (restrictions.excluded_product_ids.includes(item.product_id)) {
63
+ return false;
64
+ }
65
+
66
+ // Category inclusion filter
67
+ if (restrictions.product_categories.length > 0) {
68
+ const itemCategoryIds = item.categories.map((c) => c.id);
69
+ if (!restrictions.product_categories.some((catId) => itemCategoryIds.includes(catId))) {
70
+ return false;
71
+ }
72
+ }
73
+
74
+ // Category exclusion filter
75
+ if (restrictions.excluded_product_categories.length > 0) {
76
+ const itemCategoryIds = item.categories.map((c) => c.id);
77
+ if (
78
+ restrictions.excluded_product_categories.some((catId) => itemCategoryIds.includes(catId))
79
+ ) {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ // Exclude sale items
85
+ if (restrictions.exclude_sale_items && item.on_sale) {
86
+ return false;
87
+ }
88
+
89
+ return true;
90
+ });
91
+ }
92
+
93
+ /**
94
+ * Build a product categories map enriched with ancestor category IDs.
95
+ *
96
+ * WooCommerce's wc_get_product_cat_ids() includes ALL ancestor categories
97
+ * (via get_ancestors()) when checking coupon category restrictions. The POS
98
+ * REST API only returns directly-assigned categories on product documents.
99
+ * This function bridges the gap by walking up the category tree.
100
+ *
101
+ * @param productCategories - Map of product_id → directly-assigned categories
102
+ * @param categoryParentMap - Map of category_id → parent_id (from products/categories collection)
103
+ * @returns Enriched map with ancestor categories included
104
+ */
105
+ export function enrichCategoriesWithAncestors(
106
+ productCategories: Map<number, { id: number }[]>,
107
+ categoryParentMap: Map<number, number>
108
+ ): Map<number, { id: number }[]> {
109
+ if (categoryParentMap.size === 0) return productCategories;
110
+
111
+ const enriched = new Map<number, { id: number }[]>();
112
+
113
+ for (const [productId, categories] of productCategories) {
114
+ const allCategoryIds = new Set<number>();
115
+
116
+ for (const cat of categories) {
117
+ allCategoryIds.add(cat.id);
118
+ // Walk up the parent chain
119
+ let parentId = categoryParentMap.get(cat.id);
120
+ while (parentId && parentId > 0 && !allCategoryIds.has(parentId)) {
121
+ allCategoryIds.add(parentId);
122
+ parentId = categoryParentMap.get(parentId);
123
+ }
124
+ }
125
+
126
+ enriched.set(
127
+ productId,
128
+ Array.from(allCategoryIds).map((id) => ({ id }))
129
+ );
130
+ }
131
+
132
+ return enriched;
133
+ }
134
+
135
+ /**
136
+ * Convert tax-inclusive per-item discounts to ex-tax amounts.
137
+ *
138
+ * Percent coupon discounts are already ex-tax (calculated from ex-tax prices),
139
+ * so only fixed_cart and fixed_product discounts need conversion.
140
+ *
141
+ * Each item's discount is divided by (1 + effective_tax_rate), where the rate
142
+ * is derived from the order line item's subtotal_tax / subtotal.
143
+ */
144
+ export function convertDiscountsToExTax(
145
+ perItem: PerItemDiscount[],
146
+ lineItems: { product_id?: number | null; subtotal?: string; subtotal_tax?: string }[],
147
+ discountType: string,
148
+ pricesIncludeTax: boolean
149
+ ): PerItemDiscount[] {
150
+ if (!pricesIncludeTax || discountType === 'percent') return perItem;
151
+
152
+ return perItem.map((entry) => {
153
+ if (entry.discount <= 0) return entry;
154
+ const li =
155
+ entry.lineIndex != null
156
+ ? lineItems[entry.lineIndex]
157
+ : lineItems.find((item) => item.product_id === entry.product_id);
158
+ const subtotal = parseFloat(li?.subtotal || '0');
159
+ const subtotalTax = parseFloat(li?.subtotal_tax || '0');
160
+ const rate = subtotal > 0 ? subtotalTax / subtotal : 0;
161
+ if (rate <= 0) return entry;
162
+ return { ...entry, discount: roundHalfUp(entry.discount / (1 + rate), 6) };
163
+ });
164
+ }
165
+
166
+ /**
167
+ * Adjusts line item prices by subtracting per-item discounts from a prior coupon.
168
+ * Used in sequential discount mode so the next coupon sees reduced prices.
169
+ *
170
+ * Discounts must be ex-tax (use convertDiscountsToExTax first when pricesIncludeTax).
171
+ */
172
+ export function applyPerItemDiscountsToLineItems(
173
+ items: CouponLineItem[],
174
+ perItem: { product_id: number; discount: number }[]
175
+ ): CouponLineItem[] {
176
+ const nextItems = items.map((item) => ({ ...item }));
177
+
178
+ for (const entry of perItem) {
179
+ const remaining = entry.discount;
180
+ if (remaining <= 0) continue;
181
+
182
+ let left = remaining;
183
+ for (const item of nextItems) {
184
+ if (item.product_id !== entry.product_id || item.quantity <= 0) continue;
185
+
186
+ const lineTotal = item.price * item.quantity;
187
+ if (lineTotal <= 0) continue;
188
+
189
+ const lineDiscount = Math.min(lineTotal, left);
190
+ item.price = Math.max(0, item.price - lineDiscount / item.quantity);
191
+ left -= lineDiscount;
192
+
193
+ if (left <= 0) break;
194
+ }
195
+ }
196
+
197
+ return nextItems;
198
+ }
199
+
200
+ /**
201
+ * Apply coupon per-item discounts to order line items.
202
+ * Reduces each line item's total, total_tax, and per-rate taxes
203
+ * while keeping subtotal/subtotal_tax unchanged.
204
+ *
205
+ * Discounts must be ex-tax (use convertDiscountsToExTax first when pricesIncludeTax).
206
+ * Line items should have pre-coupon totals before calling this.
207
+ */
208
+ export function computeDiscountedLineItems<
209
+ T extends {
210
+ product_id?: number | null;
211
+ total?: string;
212
+ total_tax?: string;
213
+ taxes?: { id?: number; subtotal?: string; total?: string; [key: string]: any }[];
214
+ [key: string]: any;
215
+ },
216
+ >(lineItems: T[], allPerItemDiscounts: PerItemDiscount[][], roundingPrecision = 6): T[] {
217
+ if (allPerItemDiscounts.length === 0) return lineItems;
218
+
219
+ // Check whether any discount entry uses lineIndex — if so, prefer per-line
220
+ // matching over product_id aggregation to preserve per-line precision when
221
+ // the same product_id appears on multiple lines at different prices.
222
+ const hasLineIndex = allPerItemDiscounts.some((list) => list.some((e) => e.lineIndex != null));
223
+
224
+ if (hasLineIndex) {
225
+ // Per-line matching: aggregate discounts by lineIndex
226
+ const discountByLine = new Map<number, number>();
227
+ for (const perItemDiscounts of allPerItemDiscounts) {
228
+ for (const entry of perItemDiscounts) {
229
+ if (entry.lineIndex != null) {
230
+ discountByLine.set(
231
+ entry.lineIndex,
232
+ (discountByLine.get(entry.lineIndex) || 0) + entry.discount
233
+ );
234
+ }
235
+ }
236
+ }
237
+
238
+ if (discountByLine.size === 0) return lineItems;
239
+
240
+ return lineItems.map((item, idx) => {
241
+ const lineDiscount = discountByLine.get(idx);
242
+ if (!lineDiscount || lineDiscount <= 0) return item;
243
+
244
+ const currentTotal = parseFloat(item.total || '0');
245
+ if (currentTotal <= 0) return item;
246
+
247
+ const newTotal = Math.max(0, currentTotal - lineDiscount);
248
+ const ratio = currentTotal > 0 ? newTotal / currentTotal : 0;
249
+
250
+ const taxes = (item.taxes || []).map((tax) => ({
251
+ ...tax,
252
+ total: roundHalfUp(parseFloat(tax.total || '0') * ratio, roundingPrecision).toFixed(
253
+ roundingPrecision
254
+ ),
255
+ }));
256
+ const newTotalTax = taxes.reduce((sum, tax) => sum + parseFloat(tax.total), 0);
257
+
258
+ return {
259
+ ...item,
260
+ total: String(roundHalfUp(newTotal, roundingPrecision)),
261
+ total_tax: String(roundHalfUp(newTotalTax, roundingPrecision)),
262
+ taxes,
263
+ } as T;
264
+ });
265
+ }
266
+
267
+ // Fallback: aggregate by product_id (original behavior for callers without lineIndex)
268
+ const discountMap = new Map<number, number>();
269
+ for (const perItemDiscounts of allPerItemDiscounts) {
270
+ for (const { product_id, discount } of perItemDiscounts) {
271
+ discountMap.set(product_id, (discountMap.get(product_id) || 0) + discount);
272
+ }
273
+ }
274
+
275
+ if (discountMap.size === 0) return lineItems;
276
+
277
+ // Sum totals per product_id for proportional distribution when multiple
278
+ // line items share the same product_id
279
+ const totalByProductId = new Map<number, number>();
280
+ for (const item of lineItems) {
281
+ const pid = item.product_id;
282
+ if (pid == null || !discountMap.has(pid)) continue;
283
+ totalByProductId.set(pid, (totalByProductId.get(pid) || 0) + parseFloat(item.total || '0'));
284
+ }
285
+
286
+ return lineItems.map((item) => {
287
+ const pid = item.product_id;
288
+ if (pid == null || !discountMap.has(pid)) return item;
289
+
290
+ const totalDiscountForProduct = discountMap.get(pid)!;
291
+ if (totalDiscountForProduct <= 0) return item;
292
+
293
+ const currentTotal = parseFloat(item.total || '0');
294
+ if (currentTotal <= 0) return item;
295
+
296
+ const productTotal = totalByProductId.get(pid) || currentTotal;
297
+ const itemDiscount = totalDiscountForProduct * (currentTotal / productTotal);
298
+ const newTotal = Math.max(0, currentTotal - itemDiscount);
299
+ const ratio = currentTotal > 0 ? newTotal / currentTotal : 0;
300
+
301
+ const taxes = (item.taxes || []).map((tax) => ({
302
+ ...tax,
303
+ total: roundHalfUp(parseFloat(tax.total || '0') * ratio, roundingPrecision).toFixed(
304
+ roundingPrecision
305
+ ),
306
+ }));
307
+ const newTotalTax = taxes.reduce((sum, tax) => sum + parseFloat(tax.total), 0);
308
+
309
+ return {
310
+ ...item,
311
+ total: String(roundHalfUp(newTotal, roundingPrecision)),
312
+ total_tax: String(roundHalfUp(newTotalTax, roundingPrecision)),
313
+ taxes,
314
+ } as T;
315
+ });
316
+ }
317
+
318
+ /**
319
+ * Calculate the coupon_line discount and discount_tax split.
320
+ *
321
+ * Expects ex-tax discount amounts (use convertDiscountsToExTax first).
322
+ * Tax is calculated per-item using each line item's tax class, then summed.
323
+ *
324
+ * When taxRoundAtSubtotal is false (default), each item's tax is rounded to dp
325
+ * before accumulation — matching WC's set_coupon_discount_amounts() which calls
326
+ * wc_round_tax_total() per-item.
327
+ */
328
+ export function calculateCouponDiscountTaxSplit(
329
+ perItemDiscounts: PerItemDiscount[],
330
+ lineItems: {
331
+ product_id?: number | null;
332
+ tax_class?: string | null;
333
+ tax_status?: string | null;
334
+ }[],
335
+ taxRates: { id: number; rate: string; compound: boolean; order: number; class?: string }[],
336
+ options?: {
337
+ pricesIncludeTax?: boolean;
338
+ taxRoundAtSubtotal?: boolean;
339
+ dp?: number;
340
+ }
341
+ ): { discount: string; discount_tax: string } {
342
+ const pricesIncludeTax = options?.pricesIncludeTax ?? false;
343
+ const taxRoundAtSubtotal = options?.taxRoundAtSubtotal ?? false;
344
+ const dp = options?.dp ?? 2;
345
+
346
+ let totalDiscount = 0;
347
+ let totalDiscountTax = 0;
348
+
349
+ for (const entry of perItemDiscounts) {
350
+ if (entry.discount <= 0) continue;
351
+
352
+ const lineItem =
353
+ entry.lineIndex != null
354
+ ? lineItems[entry.lineIndex]
355
+ : lineItems.find((item) => item.product_id === entry.product_id);
356
+
357
+ // WC: skip non-taxable items (tax_status !== 'taxable'). For product line
358
+ // items tax_status lives in _woocommerce_pos_data, so read it from there
359
+ // rather than a (non-existent) top-level field.
360
+ const taxStatus = getLineItemTaxStatus(lineItem);
361
+ if (taxStatus !== 'taxable') {
362
+ totalDiscount += entry.discount;
363
+ continue;
364
+ }
365
+
366
+ const taxClass = normalizeTaxClass(lineItem?.tax_class);
367
+ const applicableRates = taxRates.filter((r) => r.class === taxClass);
368
+
369
+ if (applicableRates.length > 0) {
370
+ const taxResult = calculateTaxes({
371
+ amount: entry.discount,
372
+ rates: applicableRates as {
373
+ id: number;
374
+ rate: string;
375
+ compound: boolean;
376
+ order: number;
377
+ }[],
378
+ amountIncludesTax: false,
379
+ dp,
380
+ });
381
+
382
+ // WC rounds per-item tax to dp when not rounding at subtotal level.
383
+ // Uses HALF_DOWN when prices include tax, HALF_UP otherwise.
384
+ const perItemTax = taxRoundAtSubtotal
385
+ ? taxResult.total
386
+ : roundTaxTotal(taxResult.total, dp, pricesIncludeTax);
387
+
388
+ totalDiscount += entry.discount;
389
+ totalDiscountTax += perItemTax;
390
+ } else {
391
+ totalDiscount += entry.discount;
392
+ }
393
+ }
394
+
395
+ return {
396
+ discount: String(roundHalfUp(totalDiscount, 6)),
397
+ discount_tax: String(roundHalfUp(totalDiscountTax, 6)),
398
+ };
399
+ }
@@ -0,0 +1,15 @@
1
+ // Ported from @wcpos/order-math, MIT, Copyright (c) 2021-2026 WCPOS.
2
+ // WooCommerce coupon parity (ADR-077): keep the arithmetic as in the original; see docs/DECISIONS.md.
3
+ export { recalculateCoupons } from './recalculate';
4
+ export { calculateOrderTotals } from './order-totals';
5
+ export type { OrderTotals } from './order-totals';
6
+ export { validateCoupon } from './validate';
7
+ export { toCouponConfigs } from './to-coupon-configs';
8
+ export { enrichCategoriesWithAncestors } from './helpers';
9
+ export type { RecalculateInput, RecalculateResult } from './recalculate';
10
+ export type { CouponValidationContext, ValidationResult } from './validate';
11
+ export type { CouponDiscountConfig } from './discount';
12
+ export type {
13
+ CouponInput, CouponContext, CouponLineInput, LineItemInput, TaxRateInput,
14
+ CouponRejection, CouponRejectionCode, EngineWarning,
15
+ } from './types';