@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.
- package/dist/{commands-BvRgJMgX.d.ts → commands-BPNfbeF9.d.ts} +64 -2
- package/dist/index.d.ts +391 -24
- package/dist/index.js +911 -0
- package/dist/server/index.d.ts +23 -9
- package/dist/server/index.js +146 -2
- package/package.json +5 -3
- package/src/coupons/woocommerce/discount.ts +333 -0
- package/src/coupons/woocommerce/helpers.ts +399 -0
- package/src/coupons/woocommerce/index.ts +15 -0
- package/src/coupons/woocommerce/order-totals.ts +360 -0
- package/src/coupons/woocommerce/pos-data.ts +89 -0
- package/src/coupons/woocommerce/recalculate.ts +405 -0
- package/src/coupons/woocommerce/to-coupon-configs.ts +41 -0
- package/src/coupons/woocommerce/types.ts +155 -0
- package/src/coupons/woocommerce/validate.ts +193 -0
- package/src/index.ts +3 -0
- package/src/server/batch.ts +14 -3
- package/src/server/command-result.ts +27 -1
- package/src/server/index.ts +2 -1
- package/src/server/refund-payload-shape.ts +63 -0
- package/src/server/register-figures.ts +18 -3
- package/src/server/rejection-codes.ts +4 -4
- package/src/server/versions.ts +2 -0
- package/src/types/commands.ts +32 -1
- package/src/types/connector.ts +16 -0
- package/src/types/index.ts +2 -0
- package/src/types/store-settings.ts +2 -0
|
@@ -0,0 +1,405 @@
|
|
|
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 {
|
|
5
|
+
calculateCouponDiscount,
|
|
6
|
+
type CouponDiscountConfig,
|
|
7
|
+
type PerItemDiscount,
|
|
8
|
+
} from './discount';
|
|
9
|
+
import {
|
|
10
|
+
calculateCouponDiscountTaxSplit,
|
|
11
|
+
computeDiscountedLineItems,
|
|
12
|
+
type CouponLineItem,
|
|
13
|
+
} from './helpers';
|
|
14
|
+
import { calculateTaxes } from '../../tax/woocommerce/calculate-taxes';
|
|
15
|
+
import { getRoundingPrecision, roundHalfUp } from '../../tax/woocommerce/precision';
|
|
16
|
+
import { getLineItemTaxStatus, parsePosData } from './pos-data';
|
|
17
|
+
import { normalizeTaxClass } from '../../tax/woocommerce/tax-class';
|
|
18
|
+
|
|
19
|
+
import type { CouponLineInput as CouponLine, LineItemInput as LineItem } from './types';
|
|
20
|
+
|
|
21
|
+
export interface RecalculateInput {
|
|
22
|
+
lineItems: LineItem[];
|
|
23
|
+
couponLines: CouponLine[];
|
|
24
|
+
/** Map of coupon code (lowercase) -> coupon config from RxDB */
|
|
25
|
+
couponConfigs: Map<string, CouponDiscountConfig>;
|
|
26
|
+
pricesIncludeTax: boolean;
|
|
27
|
+
calcDiscountsSequentially: boolean;
|
|
28
|
+
taxRates: {
|
|
29
|
+
id: number;
|
|
30
|
+
rate: string;
|
|
31
|
+
compound: boolean;
|
|
32
|
+
order: number;
|
|
33
|
+
/** WooCommerce `tax_rate_priority` — decides compound sequencing (#1548). */
|
|
34
|
+
priority?: number;
|
|
35
|
+
class?: string;
|
|
36
|
+
}[];
|
|
37
|
+
/** Product categories by product_id for coupon restriction checks */
|
|
38
|
+
productCategories: Map<number, { id: number }[]>;
|
|
39
|
+
/** Whether to round tax at subtotal level (default false = round per-item) */
|
|
40
|
+
taxRoundAtSubtotal?: boolean;
|
|
41
|
+
/** Price decimal places (default 2) */
|
|
42
|
+
dp?: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface RecalculateResult {
|
|
46
|
+
lineItems: LineItem[];
|
|
47
|
+
couponLines: CouponLine[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Round per-rate line taxes to the configured wire precision — ONCE, at the exit.
|
|
52
|
+
*
|
|
53
|
+
* Both halves matter and they pull against each other:
|
|
54
|
+
*
|
|
55
|
+
* - WIDTH. These strings ship as `line_items[].taxes[]`. `String(n)` emits
|
|
56
|
+
* whatever the float prints — "0.0050015" (7dp) or "3.67647" (5dp) — and the
|
|
57
|
+
* divergence comparator forgives a one-microunit cross-engine tie only when
|
|
58
|
+
* BOTH sides were authored at exactly the store's rounding precision. A stray
|
|
59
|
+
* width turns a tie into a cashier-facing "your store changed this order's
|
|
60
|
+
* totals" banner on a correct sale (woocommerce-pos#1548).
|
|
61
|
+
*
|
|
62
|
+
* - PRECISION. Rounding any EARLIER — in the reset below, or per rate as the
|
|
63
|
+
* coupon stage builds them — feeds already-rounded values into the next
|
|
64
|
+
* computation. That double rounding is the exact 1-microunit error this
|
|
65
|
+
* module was fixed to remove: a quantity-two compound line came out
|
|
66
|
+
* 3.676470 against WooCommerce's 3.676471.
|
|
67
|
+
*
|
|
68
|
+
* Hence full precision all the way through, one half-up cut at the boundary.
|
|
69
|
+
* Applied at BOTH exits — the no-coupon reset returns early.
|
|
70
|
+
*/
|
|
71
|
+
function serializeLineItemTaxes<T extends LineItem>(items: T[], roundingPrecision: number): T[] {
|
|
72
|
+
return items.map((item) => {
|
|
73
|
+
if (!Array.isArray(item.taxes)) return item;
|
|
74
|
+
return {
|
|
75
|
+
...item,
|
|
76
|
+
taxes: item.taxes.map((tax) => {
|
|
77
|
+
const widen = (value: unknown) => {
|
|
78
|
+
const parsed =
|
|
79
|
+
typeof value === 'number'
|
|
80
|
+
? value
|
|
81
|
+
: typeof value === 'string' && value.trim() !== ''
|
|
82
|
+
? Number(value)
|
|
83
|
+
: NaN;
|
|
84
|
+
return Number.isFinite(parsed)
|
|
85
|
+
? roundHalfUp(parsed, roundingPrecision).toFixed(roundingPrecision)
|
|
86
|
+
: value;
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
...tax,
|
|
90
|
+
...(tax.subtotal === '' || tax.subtotal == null ? {} : { subtotal: widen(tax.subtotal) }),
|
|
91
|
+
...(tax.total == null ? {} : { total: widen(tax.total) }),
|
|
92
|
+
};
|
|
93
|
+
}),
|
|
94
|
+
};
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Determine whether a line item represents a POS-discounted (on sale) product
|
|
100
|
+
* by comparing the POS price against the regular price in _woocommerce_pos_data.
|
|
101
|
+
*/
|
|
102
|
+
function isLineItemOnSale(item: LineItem | null | undefined): boolean {
|
|
103
|
+
if (!item) return false;
|
|
104
|
+
const posData = parsePosData(item);
|
|
105
|
+
if (posData?.price == null || posData.regular_price == null) return false;
|
|
106
|
+
const price = parseFloat(String(posData.price));
|
|
107
|
+
const regularPrice = parseFloat(String(posData.regular_price));
|
|
108
|
+
if (isNaN(price) || isNaN(regularPrice) || regularPrice <= 0) return false;
|
|
109
|
+
return price < regularPrice;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Recalculate all coupon discounts from scratch, mirroring WooCommerce's
|
|
114
|
+
* recalculate_coupons() in abstract-wc-order.php.
|
|
115
|
+
*
|
|
116
|
+
* Algorithm:
|
|
117
|
+
* 1. Reset line item totals to subtotals (pre-coupon state)
|
|
118
|
+
* 2. Build discount items using POS price as base (mirrors server subtotal filter)
|
|
119
|
+
* 3. Apply each coupon in order, capping by remaining item value
|
|
120
|
+
* 4. Update line item totals and coupon line discount amounts
|
|
121
|
+
*/
|
|
122
|
+
export function recalculateCoupons(input: RecalculateInput): RecalculateResult {
|
|
123
|
+
const {
|
|
124
|
+
lineItems,
|
|
125
|
+
couponLines,
|
|
126
|
+
couponConfigs,
|
|
127
|
+
pricesIncludeTax,
|
|
128
|
+
calcDiscountsSequentially,
|
|
129
|
+
taxRates,
|
|
130
|
+
productCategories,
|
|
131
|
+
taxRoundAtSubtotal = false,
|
|
132
|
+
dp = 2,
|
|
133
|
+
} = input;
|
|
134
|
+
|
|
135
|
+
// Filter to active coupon lines (code is not null/undefined)
|
|
136
|
+
const activeCouponLines = couponLines.filter(
|
|
137
|
+
(cl): cl is CouponLine & { code: string } => cl.code != null
|
|
138
|
+
);
|
|
139
|
+
|
|
140
|
+
// Step 1: Reset — set total to POS price (mirrors server's filtered subtotal).
|
|
141
|
+
// On the server, WC's recalculate_coupons() does $item->set_total($item->get_subtotal()),
|
|
142
|
+
// but WCPOS filters get_subtotal() to return the POS price during recalculation.
|
|
143
|
+
// The raw subtotal holds regular_price * qty; we need pos_data.price * qty instead.
|
|
144
|
+
const resetItems = lineItems.map((item) => {
|
|
145
|
+
const posData = parsePosData(item);
|
|
146
|
+
|
|
147
|
+
const parsedPosPrice = posData?.price != null ? parseFloat(String(posData.price)) : NaN;
|
|
148
|
+
if (Number.isFinite(parsedPosPrice)) {
|
|
149
|
+
const qty = item.quantity ?? 1;
|
|
150
|
+
const posTotal = parsedPosPrice * qty;
|
|
151
|
+
|
|
152
|
+
// Non-taxable items (tax_status !== 'taxable') get no tax, matching WC.
|
|
153
|
+
// For product line items tax_status lives in _woocommerce_pos_data, so
|
|
154
|
+
// filtering by tax_class alone would wrongly tax a 'none' item that
|
|
155
|
+
// happens to sit in the standard class — the very bug this guards against.
|
|
156
|
+
const taxStatus = getLineItemTaxStatus(item);
|
|
157
|
+
|
|
158
|
+
// Determine which tax rates apply to this item's tax class
|
|
159
|
+
const normalizedClass = normalizeTaxClass(item.tax_class);
|
|
160
|
+
const itemRates =
|
|
161
|
+
taxStatus === 'taxable'
|
|
162
|
+
? taxRates.filter((r) => normalizeTaxClass(r.class) === normalizedClass)
|
|
163
|
+
: [];
|
|
164
|
+
|
|
165
|
+
// Use calculateTaxes for exact WC-matching decomposition.
|
|
166
|
+
// This replaces the ratio shortcut which diverged from WC on compound rates.
|
|
167
|
+
const taxResult = calculateTaxes({
|
|
168
|
+
amount: posTotal,
|
|
169
|
+
rates: itemRates.map((r) => ({
|
|
170
|
+
id: r.id,
|
|
171
|
+
rate: r.rate,
|
|
172
|
+
compound: r.compound,
|
|
173
|
+
order: r.order,
|
|
174
|
+
// WC sorts compound rates by tax_rate_priority (#1548) — must survive this map.
|
|
175
|
+
priority: r.priority,
|
|
176
|
+
})),
|
|
177
|
+
amountIncludesTax: pricesIncludeTax,
|
|
178
|
+
dp,
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
const taxTotal = taxResult.total;
|
|
182
|
+
const exTaxTotal = pricesIncludeTax ? posTotal - taxTotal : posTotal;
|
|
183
|
+
|
|
184
|
+
// Per-rate taxes from calculateTaxes (already decomposed correctly)
|
|
185
|
+
const taxes = taxResult.taxes.map((tax) => {
|
|
186
|
+
const origTax = (item.taxes || []).find((t) => t.id === tax.id);
|
|
187
|
+
return {
|
|
188
|
+
...(origTax || { id: tax.id }),
|
|
189
|
+
subtotal: origTax?.subtotal ?? String(tax.total),
|
|
190
|
+
total: String(tax.total),
|
|
191
|
+
};
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
...item,
|
|
196
|
+
total: String(roundHalfUp(exTaxTotal, 6)),
|
|
197
|
+
total_tax: String(roundHalfUp(taxTotal, 6)),
|
|
198
|
+
taxes,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// No POS data — standard reset (total = subtotal)
|
|
203
|
+
return {
|
|
204
|
+
...item,
|
|
205
|
+
total: item.subtotal,
|
|
206
|
+
total_tax: item.subtotal_tax,
|
|
207
|
+
taxes: (item.taxes || []).map((tax) => ({
|
|
208
|
+
...tax,
|
|
209
|
+
total: tax.subtotal ?? tax.total,
|
|
210
|
+
})),
|
|
211
|
+
};
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
// If no active coupons, return reset items
|
|
215
|
+
if (activeCouponLines.length === 0) {
|
|
216
|
+
return {
|
|
217
|
+
lineItems: serializeLineItemTaxes(resetItems, getRoundingPrecision(dp)),
|
|
218
|
+
couponLines,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Step 2: Build CouponLineItems using tax-inclusive POS price as the coupon base.
|
|
223
|
+
//
|
|
224
|
+
// WC_Discounts::set_items_from_order() uses get_subtotal() + get_subtotal_tax()
|
|
225
|
+
// (tax-inclusive) and calculates/caps discounts on the inclusive amount. The tax
|
|
226
|
+
// portion is then extracted by set_coupon_discount_amounts() afterward.
|
|
227
|
+
//
|
|
228
|
+
// We mirror this: use inclusive prices here, and convertDiscountsToExTax handles
|
|
229
|
+
// the tax extraction for ALL discount types.
|
|
230
|
+
const buildCouponLineItems = (items: typeof resetItems): CouponLineItem[] =>
|
|
231
|
+
items
|
|
232
|
+
.map((item, lineIndex) => ({ item, lineIndex }))
|
|
233
|
+
.filter(({ item }) => item.product_id != null)
|
|
234
|
+
.map(({ item, lineIndex }) => {
|
|
235
|
+
const qty = item.quantity ?? 1;
|
|
236
|
+
const posData = parsePosData(item);
|
|
237
|
+
|
|
238
|
+
// Use tax-inclusive POS price as the coupon base (matches WC)
|
|
239
|
+
let basePrice: number;
|
|
240
|
+
const posPriceParsed = posData?.price != null ? parseFloat(String(posData.price)) : NaN;
|
|
241
|
+
if (Number.isFinite(posPriceParsed)) {
|
|
242
|
+
basePrice = posPriceParsed * qty;
|
|
243
|
+
} else {
|
|
244
|
+
const subtotal = parseFloat(item.subtotal || '0');
|
|
245
|
+
const subtotalTax = parseFloat(item.subtotal_tax || '0');
|
|
246
|
+
basePrice = pricesIncludeTax ? subtotal + subtotalTax : subtotal;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
lineIndex,
|
|
251
|
+
product_id: item.product_id!,
|
|
252
|
+
quantity: qty,
|
|
253
|
+
price: qty > 0 ? basePrice / qty : 0,
|
|
254
|
+
subtotal: item.subtotal || '0',
|
|
255
|
+
total: item.total || '0',
|
|
256
|
+
categories: productCategories.get(item.product_id!) || [],
|
|
257
|
+
on_sale: isLineItemOnSale(item),
|
|
258
|
+
};
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
// Step 3: Apply each coupon in order
|
|
262
|
+
const allPerItemDiscounts: PerItemDiscount[][] = [];
|
|
263
|
+
let currentItems = buildCouponLineItems(resetItems);
|
|
264
|
+
|
|
265
|
+
// Sort by price descending (WC behavior)
|
|
266
|
+
currentItems.sort((a, b) => b.price - a.price);
|
|
267
|
+
|
|
268
|
+
// Track cumulative inclusive-price discounts per line item.
|
|
269
|
+
// WC's WC_Discounts::get_discounted_price_in_cents() caps each coupon's
|
|
270
|
+
// actual allocation by the remaining item value after prior coupons,
|
|
271
|
+
// regardless of sequential mode.
|
|
272
|
+
const cumulativeDiscounts = new Map<number, number>();
|
|
273
|
+
|
|
274
|
+
const updatedCouponLines = activeCouponLines.map((cl) => {
|
|
275
|
+
const config = couponConfigs.get(cl.code.toLowerCase());
|
|
276
|
+
if (!config) {
|
|
277
|
+
return {
|
|
278
|
+
...cl,
|
|
279
|
+
discount: '0',
|
|
280
|
+
discount_tax: '0',
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const discountResult = calculateCouponDiscount(config, currentItems, dp);
|
|
285
|
+
|
|
286
|
+
// Cap each per-item discount by the remaining item value after
|
|
287
|
+
// prior coupons. This prevents over-allocation when stacking
|
|
288
|
+
// large-value coupons (e.g., fixed500cart + percent coupon).
|
|
289
|
+
//
|
|
290
|
+
// In sequential mode, currentItems prices are already reduced by prior
|
|
291
|
+
// coupons, so item.price * item.quantity IS the remaining value — using
|
|
292
|
+
// cumulativeDiscounts would double-count. In non-sequential mode, all
|
|
293
|
+
// coupons see the original price, so we track cumulative discounts to cap.
|
|
294
|
+
for (const entry of discountResult.perItem) {
|
|
295
|
+
const idx = entry.lineIndex ?? -1;
|
|
296
|
+
const item = currentItems.find((i) => i.lineIndex === idx);
|
|
297
|
+
if (!item) continue;
|
|
298
|
+
const itemTotal = item.price * item.quantity;
|
|
299
|
+
let remaining: number;
|
|
300
|
+
if (calcDiscountsSequentially) {
|
|
301
|
+
// Prices already reduced — itemTotal is the true remaining value
|
|
302
|
+
remaining = itemTotal;
|
|
303
|
+
} else {
|
|
304
|
+
const cumulative = cumulativeDiscounts.get(idx) || 0;
|
|
305
|
+
remaining = Math.max(0, itemTotal - cumulative);
|
|
306
|
+
}
|
|
307
|
+
entry.discount = Math.min(entry.discount, remaining);
|
|
308
|
+
if (!calcDiscountsSequentially) {
|
|
309
|
+
const cumulative = cumulativeDiscounts.get(idx) || 0;
|
|
310
|
+
cumulativeDiscounts.set(idx, cumulative + entry.discount);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Recalculate totalDiscount after capping
|
|
315
|
+
discountResult.totalDiscount = discountResult.perItem.reduce((sum, e) => sum + e.discount, 0);
|
|
316
|
+
|
|
317
|
+
// Convert inclusive discounts to ex-tax using calculateTaxes for exact
|
|
318
|
+
// WC-matching compound rate decomposition (replaces ratio shortcut).
|
|
319
|
+
const exTaxPerItem = pricesIncludeTax
|
|
320
|
+
? discountResult.perItem.map((entry) => {
|
|
321
|
+
if (entry.discount <= 0) return entry;
|
|
322
|
+
const li =
|
|
323
|
+
entry.lineIndex != null
|
|
324
|
+
? resetItems[entry.lineIndex]
|
|
325
|
+
: resetItems.find((item) => item.product_id === entry.product_id);
|
|
326
|
+
if (!li) return entry;
|
|
327
|
+
|
|
328
|
+
// Non-taxable items carry no embedded tax, so the inclusive
|
|
329
|
+
// discount is already ex-tax — skip extraction.
|
|
330
|
+
if (getLineItemTaxStatus(li) !== 'taxable') return entry;
|
|
331
|
+
|
|
332
|
+
// Get the applicable tax rates for this item's tax class
|
|
333
|
+
const itemTaxClass = normalizeTaxClass(li.tax_class);
|
|
334
|
+
const itemRates = taxRates.filter((r) => normalizeTaxClass(r.class) === itemTaxClass);
|
|
335
|
+
if (itemRates.length === 0) return entry;
|
|
336
|
+
|
|
337
|
+
// Decompose the inclusive discount into tax + ex-tax using WC's algorithm
|
|
338
|
+
const taxResult = calculateTaxes({
|
|
339
|
+
amount: entry.discount,
|
|
340
|
+
rates: itemRates.map((r) => ({
|
|
341
|
+
id: r.id,
|
|
342
|
+
rate: r.rate,
|
|
343
|
+
compound: r.compound,
|
|
344
|
+
order: r.order,
|
|
345
|
+
// WC sorts compound rates by tax_rate_priority (#1548) — must survive this map.
|
|
346
|
+
priority: r.priority,
|
|
347
|
+
})),
|
|
348
|
+
amountIncludesTax: true,
|
|
349
|
+
dp,
|
|
350
|
+
});
|
|
351
|
+
const exTaxDiscount = entry.discount - taxResult.total;
|
|
352
|
+
return { ...entry, discount: roundHalfUp(exTaxDiscount, 6) };
|
|
353
|
+
})
|
|
354
|
+
: discountResult.perItem;
|
|
355
|
+
|
|
356
|
+
allPerItemDiscounts.push(exTaxPerItem);
|
|
357
|
+
|
|
358
|
+
// In sequential mode, also reduce item prices so the next coupon's
|
|
359
|
+
// discount *calculation* (not just allocation) uses the reduced price.
|
|
360
|
+
if (calcDiscountsSequentially) {
|
|
361
|
+
currentItems = currentItems.map((item) => {
|
|
362
|
+
const discount =
|
|
363
|
+
item.lineIndex != null
|
|
364
|
+
? discountResult.perItem.find((d) => d.lineIndex === item.lineIndex)
|
|
365
|
+
: discountResult.perItem.find((d) => d.product_id === item.product_id);
|
|
366
|
+
if (!discount || discount.discount <= 0) return item;
|
|
367
|
+
const qty = item.quantity || 1;
|
|
368
|
+
return {
|
|
369
|
+
...item,
|
|
370
|
+
price: Math.max(0, item.price - discount.discount / qty),
|
|
371
|
+
};
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const { discount, discount_tax } = calculateCouponDiscountTaxSplit(
|
|
376
|
+
exTaxPerItem,
|
|
377
|
+
resetItems,
|
|
378
|
+
taxRates,
|
|
379
|
+
{ pricesIncludeTax, taxRoundAtSubtotal, dp }
|
|
380
|
+
);
|
|
381
|
+
|
|
382
|
+
return { ...cl, discount, discount_tax };
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
// Step 4: Apply all discounts to line items
|
|
386
|
+
const discountedLineItems = computeDiscountedLineItems(
|
|
387
|
+
resetItems,
|
|
388
|
+
allPerItemDiscounts,
|
|
389
|
+
getRoundingPrecision(dp)
|
|
390
|
+
);
|
|
391
|
+
|
|
392
|
+
// Merge updated coupon lines back, preserving non-active ones
|
|
393
|
+
const finalCouponLines = couponLines.map((cl) => {
|
|
394
|
+
if (cl.code == null) return cl;
|
|
395
|
+
const updated = updatedCouponLines.find(
|
|
396
|
+
(u) => u.code?.toLowerCase() === cl.code?.toLowerCase()
|
|
397
|
+
);
|
|
398
|
+
return updated || cl;
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
return {
|
|
402
|
+
lineItems: serializeLineItemTaxes(discountedLineItems, getRoundingPrecision(dp)),
|
|
403
|
+
couponLines: finalCouponLines,
|
|
404
|
+
};
|
|
405
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
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 type { CouponDiscountConfig } from './discount';
|
|
4
|
+
import type { CouponInput } from './types';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Map `CouponInput`s (the adapter-prefetched coupon documents) to the replay's
|
|
8
|
+
* `CouponDiscountConfig` shape, keyed by the given (lowercase) codes.
|
|
9
|
+
*
|
|
10
|
+
* Extracted from `settleCart` so a differential harness can replay the composition
|
|
11
|
+
* with the EXACT mapping settle uses — the defaults here (`amount || '0'`, `?? null`,
|
|
12
|
+
* `?? false`, array copies) must never be duplicated. The original caller,
|
|
13
|
+
* `settle.oracle.test.ts`, is retired; `settle-cart-differential.test.ts` in
|
|
14
|
+
* packages/core is the harness that relies on this now (via its own
|
|
15
|
+
* `toLegacyCouponConfigs`, which must stay in step with this function).
|
|
16
|
+
*
|
|
17
|
+
* Codes absent from the map are skipped; `settleCart`'s missing_coupon gate
|
|
18
|
+
* guarantees presence before this runs, and `recalculateCoupons` zeroes the
|
|
19
|
+
* discount for any coupon line without a config.
|
|
20
|
+
*/
|
|
21
|
+
export function toCouponConfigs(
|
|
22
|
+
codes: readonly string[],
|
|
23
|
+
coupons: ReadonlyMap<string, CouponInput>
|
|
24
|
+
): Map<string, CouponDiscountConfig> {
|
|
25
|
+
const couponConfigs = new Map<string, CouponDiscountConfig>();
|
|
26
|
+
for (const code of codes) {
|
|
27
|
+
const coupon = coupons.get(code);
|
|
28
|
+
if (!coupon) continue;
|
|
29
|
+
couponConfigs.set(code, {
|
|
30
|
+
discount_type: coupon.discount_type,
|
|
31
|
+
amount: coupon.amount || '0',
|
|
32
|
+
limit_usage_to_x_items: coupon.limit_usage_to_x_items ?? null,
|
|
33
|
+
product_ids: [...(coupon.product_ids ?? [])],
|
|
34
|
+
excluded_product_ids: [...(coupon.excluded_product_ids ?? [])],
|
|
35
|
+
product_categories: [...(coupon.product_categories ?? [])],
|
|
36
|
+
excluded_product_categories: [...(coupon.excluded_product_categories ?? [])],
|
|
37
|
+
exclude_sale_items: coupon.exclude_sale_items ?? false,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return couponConfigs;
|
|
41
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
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
|
+
/** String(number) — '95.5', never '95.50'. Per-field precision: §7 of spec. */
|
|
4
|
+
export type MoneyString = string;
|
|
5
|
+
|
|
6
|
+
// ===== structural inputs (assignability-tested against @wcpos/database) =====
|
|
7
|
+
|
|
8
|
+
export interface MetaDataInput {
|
|
9
|
+
id?: number;
|
|
10
|
+
key?: string;
|
|
11
|
+
value?: unknown;
|
|
12
|
+
display_key?: string;
|
|
13
|
+
display_value?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface TaxEntryInput {
|
|
17
|
+
id?: number;
|
|
18
|
+
subtotal?: string;
|
|
19
|
+
total?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface LineItemInput {
|
|
23
|
+
product_id?: number | null; // null ⇒ tombstone
|
|
24
|
+
variation_id?: number | null;
|
|
25
|
+
quantity?: number;
|
|
26
|
+
price?: number;
|
|
27
|
+
tax_class?: string | null;
|
|
28
|
+
tax_status?: string | null;
|
|
29
|
+
subtotal?: string;
|
|
30
|
+
subtotal_tax?: string;
|
|
31
|
+
total?: string;
|
|
32
|
+
total_tax?: string;
|
|
33
|
+
taxes?: TaxEntryInput[];
|
|
34
|
+
meta_data?: MetaDataInput[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface FeeLineInput {
|
|
38
|
+
name?: string | null; // null ⇒ tombstone
|
|
39
|
+
tax_class?: string | null;
|
|
40
|
+
tax_status?: string | null;
|
|
41
|
+
total?: string;
|
|
42
|
+
total_tax?: string;
|
|
43
|
+
taxes?: TaxEntryInput[];
|
|
44
|
+
meta_data?: MetaDataInput[];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ShippingLineInput {
|
|
48
|
+
method_id?: string | null; // null ⇒ tombstone
|
|
49
|
+
method_title?: string | null;
|
|
50
|
+
total?: string;
|
|
51
|
+
total_tax?: string;
|
|
52
|
+
taxes?: TaxEntryInput[];
|
|
53
|
+
meta_data?: MetaDataInput[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface CouponLineInput {
|
|
57
|
+
code?: string | null; // null/undefined ⇒ tombstone (loose != null)
|
|
58
|
+
discount?: string;
|
|
59
|
+
discount_tax?: string;
|
|
60
|
+
meta_data?: MetaDataInput[];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface TaxRateInput {
|
|
64
|
+
id?: number;
|
|
65
|
+
name?: string;
|
|
66
|
+
rate?: string;
|
|
67
|
+
compound?: boolean;
|
|
68
|
+
order?: number;
|
|
69
|
+
/**
|
|
70
|
+
* WooCommerce `tax_rate_priority` — THE key WC_Tax sorts compound rates by, and the
|
|
71
|
+
* one that decides which rate is applied outermost. The app's rate documents carry it
|
|
72
|
+
* (see the taxRates schema), `calculateTaxes` reads it in preference to `order`, and
|
|
73
|
+
* `createCartConfig` has always passed it through by spreading. It simply was not
|
|
74
|
+
* declared here, so a caller assembling rates against this type could not express the
|
|
75
|
+
* field the engine actually sorts on — which is the shape woocommerce-pos#1548 turned
|
|
76
|
+
* on: real stores leave `order` at 0 on every rate and differentiate by priority.
|
|
77
|
+
*/
|
|
78
|
+
priority?: number;
|
|
79
|
+
class?: string;
|
|
80
|
+
shipping?: boolean;
|
|
81
|
+
country?: string;
|
|
82
|
+
state?: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ===== coupon context (adapter prefetches async; module stays sync) =====
|
|
86
|
+
|
|
87
|
+
export interface CouponInput {
|
|
88
|
+
code: string;
|
|
89
|
+
discount_type: 'percent' | 'fixed_cart' | 'fixed_product';
|
|
90
|
+
amount: string;
|
|
91
|
+
limit_usage_to_x_items?: number | null;
|
|
92
|
+
product_ids?: readonly number[];
|
|
93
|
+
excluded_product_ids?: readonly number[];
|
|
94
|
+
product_categories?: readonly number[];
|
|
95
|
+
excluded_product_categories?: readonly number[];
|
|
96
|
+
exclude_sale_items?: boolean;
|
|
97
|
+
individual_use?: boolean; // read for already-applied coupons too (reverse check)
|
|
98
|
+
// validation-only fields (read only when code ∈ validate.codes):
|
|
99
|
+
date_expires_gmt?: string | null;
|
|
100
|
+
usage_limit?: number | null;
|
|
101
|
+
usage_count?: number;
|
|
102
|
+
usage_limit_per_user?: number | null;
|
|
103
|
+
used_by?: readonly (string | number)[];
|
|
104
|
+
minimum_amount?: string;
|
|
105
|
+
maximum_amount?: string;
|
|
106
|
+
email_restrictions?: readonly string[];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface CouponContext {
|
|
110
|
+
/** key = LOWERCASE code. Must contain every active coupon_lines code + every validate.codes entry. */
|
|
111
|
+
readonly coupons: ReadonlyMap<string, CouponInput>;
|
|
112
|
+
/** Directly-assigned categories per product_id (NOT enriched — enrichment is internal). */
|
|
113
|
+
readonly productCategories: ReadonlyMap<number, readonly { id: number }[]>;
|
|
114
|
+
/** category_id -> parent_id; module walks ancestors itself (wc_get_product_cat_ids parity). */
|
|
115
|
+
readonly categoryParents?: ReadonlyMap<number, number>;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// ===== warnings (the logger port, inverted to data-out) =====
|
|
119
|
+
|
|
120
|
+
export interface WarningSite {
|
|
121
|
+
lineType: 'line_item' | 'fee_line' | 'shipping_line' | 'coupon_line';
|
|
122
|
+
index: number;
|
|
123
|
+
uuid?: string;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export type EngineWarning =
|
|
127
|
+
| { code: 'malformed_pos_data'; where: WarningSite }
|
|
128
|
+
| { code: 'unknown_tax_rate_id'; rateId: number };
|
|
129
|
+
|
|
130
|
+
// ===== coupon rejection (moved from internal/coupons/validate.ts) =====
|
|
131
|
+
|
|
132
|
+
export type CouponRejectionCode =
|
|
133
|
+
| 'already_applied'
|
|
134
|
+
| 'expired'
|
|
135
|
+
| 'usage_limit_reached'
|
|
136
|
+
| 'usage_limit_reached_for_customer'
|
|
137
|
+
| 'minimum_spend_not_met'
|
|
138
|
+
| 'maximum_spend_exceeded'
|
|
139
|
+
| 'individual_use'
|
|
140
|
+
| 'individual_use_conflict'
|
|
141
|
+
| 'email_required'
|
|
142
|
+
| 'email_not_allowed'
|
|
143
|
+
| 'not_applicable_to_cart';
|
|
144
|
+
|
|
145
|
+
export interface CouponRejection {
|
|
146
|
+
code: CouponRejectionCode;
|
|
147
|
+
params?: Readonly<Record<string, string | number>>;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ===== refund =====
|
|
151
|
+
|
|
152
|
+
export interface RefundLike {
|
|
153
|
+
total?: string | number | null;
|
|
154
|
+
amount?: string | number | null;
|
|
155
|
+
}
|