@tallyui/core 3.2.0 → 3.3.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.
- package/dist/chunk-MLKGABMK.js +9 -0
- package/dist/{commands-BW4YYgRG.d.ts → commands-xE2xMmC_.d.ts} +64 -11
- package/dist/index.d.ts +250 -4
- package/dist/index.js +369 -4
- package/dist/rxdb/index.js +2 -0
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +84 -3
- package/package.json +1 -1
- package/src/index.ts +2 -1
- package/src/server/batch.ts +19 -4
- package/src/server/fiscal-figures.ts +22 -1
- package/src/server/order-payload-shape.ts +47 -1
- package/src/tax/woocommerce/calculate-taxes.ts +183 -0
- package/src/tax/woocommerce/filter-tax-rates.ts +179 -0
- package/src/tax/woocommerce/index.ts +14 -0
- package/src/tax/woocommerce/precision.ts +169 -0
- package/src/tax/woocommerce/sum-taxes.ts +31 -0
- package/src/tax/woocommerce/tax-class.ts +105 -0
- package/src/tax/woocommerce/types.ts +40 -0
- package/src/types/commands.ts +66 -11
- package/src/types/connector.ts +27 -4
- package/src/types/store-settings.ts +5 -0
- package/src/types/traits/product.ts +6 -0
|
@@ -22,7 +22,7 @@ export function fiscalFiguresErrors(payload: OrderCreatePayloadV3): string[] {
|
|
|
22
22
|
for (const key of keys) check(Number.isSafeInteger(value[key]), `${path}.${key}`, 'a safe integer')
|
|
23
23
|
}
|
|
24
24
|
const { display, taxByRate } = payload
|
|
25
|
-
if (object(display, 'display', ['currency', 'exponent', 'taxInclusive', 'subtotalMinor', 'discountMinor', 'taxMinor', 'totalMinor', 'orderDiscountMinor', 'lines'])) {
|
|
25
|
+
if (object(display, 'display', ['currency', 'exponent', 'taxInclusive', 'subtotalMinor', 'discountMinor', 'taxMinor', 'totalMinor', 'orderDiscountMinor', 'lines', 'fees', 'shipping'])) {
|
|
26
26
|
check(typeof display.currency === 'string', 'display.currency', 'a string')
|
|
27
27
|
check(Number.isInteger(display.exponent) && display.exponent >= 0, 'display.exponent', 'an integer >= 0')
|
|
28
28
|
check(typeof display.taxInclusive === 'boolean', 'display.taxInclusive', 'a boolean')
|
|
@@ -42,6 +42,27 @@ export function fiscalFiguresErrors(payload: OrderCreatePayloadV3): string[] {
|
|
|
42
42
|
money(discount, discountPath, ['amountMinor'])
|
|
43
43
|
})
|
|
44
44
|
})
|
|
45
|
+
if (payload.fees?.length || payload.shipping?.length) check(display.taxInclusive === payload.pricesIncludeTax, 'display.taxInclusive', 'payload.pricesIncludeTax')
|
|
46
|
+
for (const field of ['fees', 'shipping'] as const) {
|
|
47
|
+
const id = field === 'fees' ? 'clientFeeId' : 'clientShippingId'
|
|
48
|
+
const amounts = new Map((payload[field] ?? []).map(entry => [
|
|
49
|
+
'clientFeeId' in entry ? entry.clientFeeId : entry.clientShippingId, entry.amountMinor,
|
|
50
|
+
]))
|
|
51
|
+
const rows = display[field]
|
|
52
|
+
if (rows !== undefined) check(Array.isArray(rows), `display.${field}`, 'an array')
|
|
53
|
+
const seen = new Set<unknown>()
|
|
54
|
+
if (Array.isArray(rows)) rows.forEach((row: unknown, index) => {
|
|
55
|
+
const path = `display.${field}[${index}]`
|
|
56
|
+
if (!object(row, path, [id, 'amountMinor'])) return
|
|
57
|
+
check(typeof row[id] === 'string' && row[id].length > 0, `${path}.${id}`, 'a non-empty string')
|
|
58
|
+
money(row, path, ['amountMinor'])
|
|
59
|
+
check(amounts.has(row[id] as string), `${path}.${id}`, `a payload.${field}[].${id}`)
|
|
60
|
+
check(!seen.has(row[id]), `${path}.${id}`, `no duplicate ${id}`)
|
|
61
|
+
seen.add(row[id])
|
|
62
|
+
if (amounts.has(row[id] as string)) check(row.amountMinor === amounts.get(row[id] as string), `${path}.amountMinor`, `the payload.${field} amountMinor`)
|
|
63
|
+
})
|
|
64
|
+
for (const key of amounts.keys()) check(seen.has(key), `display.${field}`, `a row for ${id} ${key}`)
|
|
65
|
+
}
|
|
45
66
|
}
|
|
46
67
|
check(Array.isArray(taxByRate), 'taxByRate', 'an array')
|
|
47
68
|
if (Array.isArray(taxByRate)) taxByRate.forEach((rate, index) => {
|
|
@@ -34,6 +34,7 @@ export function payloadShapeErrors(payload: unknown): string[] {
|
|
|
34
34
|
check(object(item), path, 'an object')
|
|
35
35
|
if (!object(item)) continue
|
|
36
36
|
for (const key of isLines ? ['clientLineId', 'variantId'] : ['clientPaymentId', 'method']) {
|
|
37
|
+
if (key === 'variantId' && item.custom !== undefined && item.variantId === undefined) continue
|
|
37
38
|
check(typeof item[key] === 'string', `${path}.${key}`, 'a string')
|
|
38
39
|
}
|
|
39
40
|
const optionalString = isLines ? 'title' : 'reference'
|
|
@@ -73,6 +74,36 @@ export function payloadShapeErrors(payload: unknown): string[] {
|
|
|
73
74
|
for (const field of ['registerId', 'cashierRef', 'locationId']) {
|
|
74
75
|
if (payload[field] !== undefined) check(typeof payload[field] === 'string', field, 'a string')
|
|
75
76
|
}
|
|
77
|
+
for (const field of ['fees', 'shipping', 'lines']) {
|
|
78
|
+
const items = payload[field]
|
|
79
|
+
if (items === undefined || field === 'lines' && !Array.isArray(items)) continue
|
|
80
|
+
check(Array.isArray(items), field, 'an array')
|
|
81
|
+
if (!Array.isArray(items)) continue
|
|
82
|
+
const id = field === 'fees' ? 'clientFeeId' : 'clientShippingId'
|
|
83
|
+
const seen = new Set<unknown>()
|
|
84
|
+
items.forEach((entry, index) => {
|
|
85
|
+
const custom = field === 'lines'
|
|
86
|
+
const item = custom && object(entry) ? entry.custom : entry
|
|
87
|
+
const path = `${field}[${index}]${custom ? '.custom' : ''}`
|
|
88
|
+
if (custom && (!object(entry) || item === undefined)) return
|
|
89
|
+
check(object(item), path, 'an object')
|
|
90
|
+
if (!object(item)) return
|
|
91
|
+
const keys = custom ? ['name', 'sku', 'taxClass', 'taxStatus']
|
|
92
|
+
: [id, 'name', 'amountMinor', 'taxMinor', 'taxStatus', 'taxClass', ...(field === 'shipping' ? ['methodId'] : [])]
|
|
93
|
+
for (const key of Object.keys(item)) check(keys.includes(key), `${path}.${key}`, 'no unknown key')
|
|
94
|
+
check(typeof item.name === 'string' && item.name.length > 0, `${path}.name`, 'a non-empty string')
|
|
95
|
+
check(item.taxStatus === 'taxable' || item.taxStatus === 'none', `${path}.taxStatus`, 'taxable or none')
|
|
96
|
+
for (const key of keys.filter(key => ['sku', 'taxClass', 'methodId'].includes(key))) {
|
|
97
|
+
if (item[key] !== undefined) check(typeof item[key] === 'string', `${path}.${key}`, 'a string')
|
|
98
|
+
}
|
|
99
|
+
if (!custom) {
|
|
100
|
+
check(typeof item[id] === 'string' && item[id].length > 0, `${path}.${id}`, 'a non-empty string')
|
|
101
|
+
check(!seen.has(item[id]), `${path}.${id}`, `no duplicate ${id}`)
|
|
102
|
+
seen.add(item[id])
|
|
103
|
+
for (const key of ['amountMinor', 'taxMinor']) check(Number.isSafeInteger(item[key]) && (item[key] as number) >= 0, `${path}.${key}`, 'a safe integer >= 0')
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
}
|
|
76
107
|
// NUL, only on strings (the checks above name any other type): Postgres text can't hold it, and the lookup keys must be clean.
|
|
77
108
|
for (const [value, path] of payloadStrings(payload)) check(!value.includes('\u0000'), path, 'no NUL character')
|
|
78
109
|
return errors
|
|
@@ -80,7 +111,7 @@ export function payloadShapeErrors(payload: unknown): string[] {
|
|
|
80
111
|
|
|
81
112
|
/** Length-bound errors of an order.create payload, e.g. ['lines[0].title: expected at most 255
|
|
82
113
|
* characters']; [] when every string is within its bound, at most ten. Bounds in UTF-16 code units:
|
|
83
|
-
* `customer.email` 254,
|
|
114
|
+
* `customer.email` 254, v5 ids 36 and class/sku/method 64, other strings 255 (`customerId` and `sessionId` keep theirs in
|
|
84
115
|
* payloadShapeErrors); only strings are checked. A plugin calls it through precheckCommand, after
|
|
85
116
|
* its replay lookup, so a bound tightened later never turns an applied command's resend into
|
|
86
117
|
* `invalid_payload`. */
|
|
@@ -106,6 +137,21 @@ function payloadStrings(payload: Record<string, unknown>): Array<[string, string
|
|
|
106
137
|
}
|
|
107
138
|
})
|
|
108
139
|
}
|
|
140
|
+
if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
|
|
141
|
+
if (object(line) && object(line.custom)) for (const key of ['name', 'sku', 'taxClass', 'taxStatus']) {
|
|
142
|
+
found.push([line.custom[key], `lines[${index}].custom.${key}`, key === 'name' ? 255 : 64])
|
|
143
|
+
}
|
|
144
|
+
})
|
|
145
|
+
for (const field of ['fees', 'shipping']) for (const prefix of ['', 'display.']) {
|
|
146
|
+
const parent = prefix ? payload.display : payload
|
|
147
|
+
const items = object(parent) ? parent[field] : undefined
|
|
148
|
+
if (Array.isArray(items)) items.forEach((item, index) => {
|
|
149
|
+
if (object(item)) for (const key of prefix ? [field === 'fees' ? 'clientFeeId' : 'clientShippingId']
|
|
150
|
+
: [field === 'fees' ? 'clientFeeId' : 'clientShippingId', 'name', 'taxClass', 'taxStatus', ...(field === 'shipping' ? ['methodId'] : [])]) {
|
|
151
|
+
found.push([item[key], `${prefix}${field}[${index}].${key}`, key.startsWith('client') ? 36 : key === 'name' ? 255 : 64])
|
|
152
|
+
}
|
|
153
|
+
})
|
|
154
|
+
}
|
|
109
155
|
if (object(payload.customer)) found.push([payload.customer.email, 'customer.email', 254], [payload.customer.customerId, 'customer.customerId', undefined])
|
|
110
156
|
found.push([payload.sessionId, 'sessionId', undefined])
|
|
111
157
|
return found.filter((entry): entry is [string, string, number | undefined] => typeof entry[0] === 'string')
|
|
@@ -0,0 +1,183 @@
|
|
|
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 { CalculateTaxesInput, CalculateTaxesResult } from './types';
|
|
4
|
+
import {
|
|
5
|
+
addNumberPrecision,
|
|
6
|
+
getRoundingPrecision,
|
|
7
|
+
removeNumberPrecision,
|
|
8
|
+
roundHalfUp,
|
|
9
|
+
} from './precision';
|
|
10
|
+
import { sumTaxes } from './sum-taxes';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Calculate taxes when price includes tax
|
|
14
|
+
*/
|
|
15
|
+
function calcInclusiveTax({
|
|
16
|
+
amount,
|
|
17
|
+
rates,
|
|
18
|
+
}: {
|
|
19
|
+
amount: number;
|
|
20
|
+
rates: { id: number; rate: string; compound: boolean }[];
|
|
21
|
+
}) {
|
|
22
|
+
const taxes: { id: number; total: number }[] = [];
|
|
23
|
+
const compoundRates: { id: number; rate: number }[] = [];
|
|
24
|
+
const regularRates: { id: number; rate: number }[] = [];
|
|
25
|
+
let nonCompoundAmount = amount;
|
|
26
|
+
|
|
27
|
+
// Index array so taxes are output in correct order and see what compound/regular rates we have to calculate.
|
|
28
|
+
rates.forEach((_rate) => {
|
|
29
|
+
const { id, rate, compound } = _rate;
|
|
30
|
+
|
|
31
|
+
if (compound) {
|
|
32
|
+
compoundRates.push({ id, rate: Number(rate) });
|
|
33
|
+
} else {
|
|
34
|
+
regularRates.push({ id, rate: Number(rate) });
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
compoundRates.reverse(); // Working backwards.
|
|
39
|
+
|
|
40
|
+
compoundRates.forEach((compoundRate) => {
|
|
41
|
+
const { id, rate } = compoundRate;
|
|
42
|
+
const total = nonCompoundAmount - nonCompoundAmount / (1 + rate / 100);
|
|
43
|
+
taxes.push({ id, total });
|
|
44
|
+
nonCompoundAmount -= total;
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
// Regular taxes.
|
|
48
|
+
const regularTaxRate = 1 + regularRates.reduce((sum, regularRate, index) =>
|
|
49
|
+
index === 0 ? regularRate.rate / 100 : sum + regularRate.rate / 100, 0);
|
|
50
|
+
|
|
51
|
+
regularRates.forEach((regularRate) => {
|
|
52
|
+
const { id, rate } = regularRate;
|
|
53
|
+
const theRate = rate / 100 / regularTaxRate;
|
|
54
|
+
const netPrice = amount - theRate * nonCompoundAmount;
|
|
55
|
+
const total = amount - netPrice;
|
|
56
|
+
taxes.push({ id, total });
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
return taxes;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Calculate taxes when price excludes tax
|
|
64
|
+
*/
|
|
65
|
+
function calcExclusiveTax({
|
|
66
|
+
amount,
|
|
67
|
+
rates,
|
|
68
|
+
}: {
|
|
69
|
+
amount: number;
|
|
70
|
+
rates: { id: number; rate: string; compound: boolean }[];
|
|
71
|
+
}) {
|
|
72
|
+
const taxes: { id: number; total: number }[] = [];
|
|
73
|
+
|
|
74
|
+
rates.forEach((_rate) => {
|
|
75
|
+
const { id, rate, compound } = _rate;
|
|
76
|
+
|
|
77
|
+
if (!compound) {
|
|
78
|
+
const total = amount * (Number(rate) / 100);
|
|
79
|
+
taxes.push({ id, total });
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
let preCompoundTotal = sumTaxes({ taxes });
|
|
84
|
+
|
|
85
|
+
// Compound taxes.
|
|
86
|
+
rates.forEach((_rate) => {
|
|
87
|
+
const { id, rate, compound } = _rate;
|
|
88
|
+
|
|
89
|
+
if (compound) {
|
|
90
|
+
const thePriceIncTax = amount + preCompoundTotal;
|
|
91
|
+
const total = thePriceIncTax * (Number(rate) / 100);
|
|
92
|
+
taxes.push({ id, total });
|
|
93
|
+
preCompoundTotal = sumTaxes({ taxes });
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
return taxes;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Takes a price and an array of tax rates, eg: [{ id: 1, rate: '4.0000', order: 1 }]
|
|
102
|
+
* Returns the calculated array of taxes tax, eg: [{ id: 1, total: 1.2345 }]
|
|
103
|
+
*
|
|
104
|
+
* @param dp - Price decimal places (wc_get_price_decimals), default 2
|
|
105
|
+
* @param perRatePrecision - Decimals each rate is rounded to. Defaults to the cart-space
|
|
106
|
+
* precision below; order-item callers pass `getRoundingPrecision(dp)` (#2344).
|
|
107
|
+
*/
|
|
108
|
+
export function calculateTaxes({
|
|
109
|
+
amount,
|
|
110
|
+
rates,
|
|
111
|
+
amountIncludesTax,
|
|
112
|
+
dp = 2,
|
|
113
|
+
perRatePrecision,
|
|
114
|
+
}: CalculateTaxesInput): CalculateTaxesResult {
|
|
115
|
+
// Sort rates matching WC_Tax::sort_rates_callback():
|
|
116
|
+
// 1. tax_rate_priority (ascending) — mapped to `order`
|
|
117
|
+
// 2. tax_rate_country: non-empty first
|
|
118
|
+
// 3. tax_rate_state: non-empty first
|
|
119
|
+
// 4. tax_rate_id (ascending) — mapped to `id`
|
|
120
|
+
// `priority` is WooCommerce's `tax_rate_priority` — THE key WC_Tax sorts by, and
|
|
121
|
+
// the one that decides which compound rate is applied outermost. It is read first
|
|
122
|
+
// because the app passes RxDB tax-rate documents straight through, and those carry
|
|
123
|
+
// BOTH `priority` and `order` (WC's `tax_rate_order`, a display-only field that is
|
|
124
|
+
// commonly 0 for every rate). Sorting by `order` therefore tied on real stores and
|
|
125
|
+
// fell through to id-ascending, inverting the compound sequence: on dev-next's GB
|
|
126
|
+
// store (VAT prio 1 + Surcharge prio 2, both compound) a discounted line came out
|
|
127
|
+
// VAT 3.750000 / Surcharge 0.367647 against WooCommerce's 3.676471 / 0.441176 —
|
|
128
|
+
// same total, wrong split, and the cashier saw a totals-changed banner on a correct
|
|
129
|
+
// sale (woocommerce-pos#1548). `order` remains the fallback for callers that map
|
|
130
|
+
// priority onto it (this module's original contract, and its existing tests).
|
|
131
|
+
const sortKey = (rate: { order: number; priority?: number }): number =>
|
|
132
|
+
typeof rate.priority === 'number' ? rate.priority : rate.order;
|
|
133
|
+
const sortedRates = [...rates].sort((a, b) => {
|
|
134
|
+
if (sortKey(a) !== sortKey(b)) return sortKey(a) - sortKey(b);
|
|
135
|
+
const aCountry = (a as any).country || '';
|
|
136
|
+
const bCountry = (b as any).country || '';
|
|
137
|
+
if ((aCountry !== '') !== (bCountry !== '')) return aCountry !== '' ? -1 : 1;
|
|
138
|
+
const aState = (a as any).state || '';
|
|
139
|
+
const bState = (b as any).state || '';
|
|
140
|
+
if ((aState !== '') !== (bState !== '')) return aState !== '' ? -1 : 1;
|
|
141
|
+
return a.id - b.id;
|
|
142
|
+
});
|
|
143
|
+
const roundingPrecision = perRatePrecision ?? dp + getRoundingPrecision(dp);
|
|
144
|
+
const normalizedAmount = removeNumberPrecision(addNumberPrecision(amount, dp), dp);
|
|
145
|
+
|
|
146
|
+
const taxes = amountIncludesTax
|
|
147
|
+
? calcInclusiveTax({ amount: normalizedAmount, rates: sortedRates })
|
|
148
|
+
: calcExclusiveTax({ amount: normalizedAmount, rates: sortedRates });
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* WC_Cart_Totals calculates in cents space, so WC_Tax::round()'s rounding precision
|
|
152
|
+
* is effectively dp + wc_get_rounding_precision() decimals in currency space.
|
|
153
|
+
*
|
|
154
|
+
* An ORDER ITEM is different: `WC_Order_Item::calculate_taxes` calls `calc_tax` on the
|
|
155
|
+
* currency-unit total, so WC_Tax::round() rounds once at wc_get_rounding_precision().
|
|
156
|
+
* Rounding at dp + 6 first and then at 6 made a `…49x` (x ≥ 5) tail a midpoint and put
|
|
157
|
+
* ~0.45% of lines at non-integer rates 1 µ above WooCommerce (#2344). Order-item callers
|
|
158
|
+
* therefore pass `perRatePrecision`.
|
|
159
|
+
*
|
|
160
|
+
* That single round first pre-rounds to 15 significant digits, as PHP's round() does
|
|
161
|
+
* (`_php_math_round` through PHP 8.3). Without it a true midpoint whose float product
|
|
162
|
+
* lands an ulp low — 11.8885 × 5.5% = 0.6538675 → 0.65386749999… — would round down
|
|
163
|
+
* where WooCommerce, and the old 8dp step, round up.
|
|
164
|
+
*/
|
|
165
|
+
const roundRate = (value: number) =>
|
|
166
|
+
perRatePrecision === undefined
|
|
167
|
+
? roundHalfUp(value, roundingPrecision)
|
|
168
|
+
: roundHalfUp(Number(value.toPrecision(15)), roundingPrecision);
|
|
169
|
+
const roundedItemizedTaxes = taxes.map((tax) => ({
|
|
170
|
+
id: tax.id,
|
|
171
|
+
total: roundRate(tax.total),
|
|
172
|
+
}));
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Sum before downstream code reduces emitted money strings to 6 currency decimals.
|
|
176
|
+
*/
|
|
177
|
+
const total = sumTaxes({ taxes: roundedItemizedTaxes });
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
total: roundHalfUp(total, roundingPrecision),
|
|
181
|
+
taxes: roundedItemizedTaxes,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// Ported from @wcpos/core, 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 { WooTaxRate } from './types';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Normalize a given postcode by removing spaces and converting it to uppercase.
|
|
7
|
+
*/
|
|
8
|
+
function normalizePostcode(postcode: string): string {
|
|
9
|
+
return String(postcode ?? '').replace(/\s+/g, '').toUpperCase();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Generate an array of possible postcodes based on a given wildcard or range pattern.
|
|
14
|
+
*/
|
|
15
|
+
function getMatchingPostcodes(pattern: string): string[] {
|
|
16
|
+
if (pattern.includes('...')) {
|
|
17
|
+
const [start, end] = pattern.split('...').map(normalizePostcode);
|
|
18
|
+
let current = parseInt(start, 10);
|
|
19
|
+
const last = parseInt(end, 10);
|
|
20
|
+
const matches = [];
|
|
21
|
+
|
|
22
|
+
while (current <= last) {
|
|
23
|
+
matches.push(current.toString());
|
|
24
|
+
current++;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return matches;
|
|
28
|
+
} else if (pattern.endsWith('*')) {
|
|
29
|
+
// For wildcard patterns, return the pattern for comparison in `includes` check.
|
|
30
|
+
return [pattern.slice(0, -1)];
|
|
31
|
+
} else {
|
|
32
|
+
// Handle exact match
|
|
33
|
+
return [normalizePostcode(pattern)];
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function postcodePatternMatches(normalizedPostcode: string, pattern: string): boolean {
|
|
38
|
+
const matchingPostcodes = getMatchingPostcodes(pattern);
|
|
39
|
+
return matchingPostcodes.some((pc) =>
|
|
40
|
+
pattern.endsWith('*') ? normalizedPostcode.startsWith(pc) : pc === normalizedPostcode
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Check if a given postcode matches any of the patterns in the provided list.
|
|
46
|
+
*/
|
|
47
|
+
function postcodeMatcher(postcode: string, patterns: string[]): boolean {
|
|
48
|
+
const normalizedPostcode = normalizePostcode(postcode);
|
|
49
|
+
|
|
50
|
+
return patterns.some((pattern) => postcodePatternMatches(normalizedPostcode, pattern));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* WooCommerce compares specificity by the number of location rows that MATCHED the
|
|
55
|
+
* customer's address (`COUNT(locations.location_id)` under the query criteria in
|
|
56
|
+
* `WC_Tax::get_matched_tax_rates`), not by how many postcodes/cities a rate lists.
|
|
57
|
+
*/
|
|
58
|
+
type MatchedLocationCounts = { postcodes: number; cities: number };
|
|
59
|
+
|
|
60
|
+
/** Mirrors `WC_Tax::sort_rates_callback`: priority, then location specificity, then id. */
|
|
61
|
+
function compareTaxRates(
|
|
62
|
+
rate1: WooTaxRate,
|
|
63
|
+
rate2: WooTaxRate,
|
|
64
|
+
matchedCounts: Map<WooTaxRate, MatchedLocationCounts>
|
|
65
|
+
): number {
|
|
66
|
+
const priority1 = rate1.priority ?? 0;
|
|
67
|
+
const priority2 = rate2.priority ?? 0;
|
|
68
|
+
if (priority1 !== priority2) {
|
|
69
|
+
return priority1 < priority2 ? -1 : 1;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const country1 = rate1.country ?? '';
|
|
73
|
+
const country2 = rate2.country ?? '';
|
|
74
|
+
if (country1 !== country2) {
|
|
75
|
+
if (country1 === '') {
|
|
76
|
+
return 1;
|
|
77
|
+
}
|
|
78
|
+
if (country2 === '') {
|
|
79
|
+
return -1;
|
|
80
|
+
}
|
|
81
|
+
return country1 > country2 ? 1 : -1;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const state1 = rate1.state ?? '';
|
|
85
|
+
const state2 = rate2.state ?? '';
|
|
86
|
+
if (state1 !== state2) {
|
|
87
|
+
if (state1 === '') {
|
|
88
|
+
return 1;
|
|
89
|
+
}
|
|
90
|
+
if (state2 === '') {
|
|
91
|
+
return -1;
|
|
92
|
+
}
|
|
93
|
+
return state1 > state2 ? 1 : -1;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const postcodeCount1 = matchedCounts.get(rate1)?.postcodes ?? 0;
|
|
97
|
+
const postcodeCount2 = matchedCounts.get(rate2)?.postcodes ?? 0;
|
|
98
|
+
if (postcodeCount1 !== postcodeCount2) {
|
|
99
|
+
return postcodeCount1 < postcodeCount2 ? 1 : -1;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const cityCount1 = matchedCounts.get(rate1)?.cities ?? 0;
|
|
103
|
+
const cityCount2 = matchedCounts.get(rate2)?.cities ?? 0;
|
|
104
|
+
if (cityCount1 !== cityCount2) {
|
|
105
|
+
return cityCount1 < cityCount2 ? 1 : -1;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const id1 = rate1.id ?? 0;
|
|
109
|
+
const id2 = rate2.id ?? 0;
|
|
110
|
+
|
|
111
|
+
if (id1 === id2) {
|
|
112
|
+
return 0;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return id1 < id2 ? -1 : 1;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Filter tax rates based on the provided country, state, postcode, and city.
|
|
120
|
+
*/
|
|
121
|
+
export function filterTaxRates(
|
|
122
|
+
taxRates: WooTaxRate[],
|
|
123
|
+
country: string = '',
|
|
124
|
+
state: string = '',
|
|
125
|
+
postcode: string = '',
|
|
126
|
+
city: string = ''
|
|
127
|
+
): WooTaxRate[] {
|
|
128
|
+
const taxRatesByClass: Record<string, WooTaxRate[]> = Object.create(null);
|
|
129
|
+
for (const rate of taxRates) {
|
|
130
|
+
(taxRatesByClass[rate.class] ??= []).push(rate);
|
|
131
|
+
}
|
|
132
|
+
const normalizedPostcode = normalizePostcode(postcode);
|
|
133
|
+
const filteredTaxRatesByClass = Object.values(taxRatesByClass).map((taxRatesInClass) => {
|
|
134
|
+
const cityUpperCase = city.toUpperCase();
|
|
135
|
+
const matchedCounts = new Map<WooTaxRate, MatchedLocationCounts>(
|
|
136
|
+
taxRatesInClass.map((rate) => [
|
|
137
|
+
rate,
|
|
138
|
+
{
|
|
139
|
+
postcodes: (rate.postcodes ?? []).filter((pattern) =>
|
|
140
|
+
postcodePatternMatches(normalizedPostcode, pattern)
|
|
141
|
+
).length,
|
|
142
|
+
cities: (rate.cities ?? []).filter((c) => c.toUpperCase() === cityUpperCase).length,
|
|
143
|
+
},
|
|
144
|
+
])
|
|
145
|
+
);
|
|
146
|
+
const sortedTaxRates = [...taxRatesInClass].sort((rate1, rate2) =>
|
|
147
|
+
compareTaxRates(rate1, rate2, matchedCounts)
|
|
148
|
+
);
|
|
149
|
+
let foundMatchAtCurrentPriority = false;
|
|
150
|
+
|
|
151
|
+
return sortedTaxRates.filter((rate, index) => {
|
|
152
|
+
const countryMatch =
|
|
153
|
+
!rate.country?.length || (rate.country ?? '').toUpperCase() === country.toUpperCase();
|
|
154
|
+
const stateMatch =
|
|
155
|
+
!rate.state?.length || (rate.state ?? '').toUpperCase() === state.toUpperCase();
|
|
156
|
+
const postcodeMatch =
|
|
157
|
+
!rate.postcodes?.length || postcodeMatcher(postcode, rate.postcodes ?? []);
|
|
158
|
+
const cityMatch =
|
|
159
|
+
!rate.cities?.length ||
|
|
160
|
+
(rate.cities ?? []).map((city) => city.toUpperCase()).includes(cityUpperCase);
|
|
161
|
+
|
|
162
|
+
const isMatch = countryMatch && stateMatch && postcodeMatch && cityMatch;
|
|
163
|
+
const isNewPriority = index === 0 || sortedTaxRates[index - 1].priority !== rate.priority;
|
|
164
|
+
|
|
165
|
+
if (isNewPriority) {
|
|
166
|
+
foundMatchAtCurrentPriority = false;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (isMatch && !foundMatchAtCurrentPriority) {
|
|
170
|
+
foundMatchAtCurrentPriority = true;
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return false;
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
return filteredTaxRatesByClass.flat();
|
|
179
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
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
|
+
export { calculateTaxes } from './calculate-taxes';
|
|
4
|
+
export { filterTaxRates } from './filter-tax-rates';
|
|
5
|
+
export {
|
|
6
|
+
roundHalfUp, roundHalfDown, getRoundingPrecision, roundTaxTotal,
|
|
7
|
+
addNumberPrecision, removeNumberPrecision,
|
|
8
|
+
} from './precision';
|
|
9
|
+
export { sumTaxes, sumItemizedTaxes } from './sum-taxes';
|
|
10
|
+
export {
|
|
11
|
+
normalizeTaxClass, taxClassFromWire, taxClassToWire,
|
|
12
|
+
resolveInheritedShippingTaxClass, NO_SHIPPING_TAX, STANDARD_TAX_CLASS,
|
|
13
|
+
} from './tax-class';
|
|
14
|
+
export type { WooTaxRate, CalculateTaxesInput, CalculateTaxesResult, ItemizedTax } from './types';
|
|
@@ -0,0 +1,169 @@
|
|
|
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
|
+
* WooCommerce-compatible precision and rounding utilities.
|
|
5
|
+
*
|
|
6
|
+
* These functions mirror the PHP implementations in:
|
|
7
|
+
* - wc-core-functions.php (wc_get_rounding_precision, wc_add_number_precision, wc_remove_number_precision)
|
|
8
|
+
* - wc-formatting-functions.php (wc_round_tax_total, wc_round_discount)
|
|
9
|
+
* - class-woocommerce.php (WC_ROUNDING_PRECISION, WC_DISCOUNT_ROUNDING_MODE, WC_TAX_ROUNDING_MODE)
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Return a fixed-point decimal string for a non-negative finite number.
|
|
14
|
+
* Handles values that `String()` renders in scientific notation (e.g. 1.5e-7).
|
|
15
|
+
* For normal decimals, `String()` already returns fixed-point notation.
|
|
16
|
+
*/
|
|
17
|
+
function toDecimalString(n: number): string {
|
|
18
|
+
const s = String(n);
|
|
19
|
+
if (!s.includes('e') && !s.includes('E')) return s;
|
|
20
|
+
// toFixed(20) is the max JS allows; trailing zeros are harmless here
|
|
21
|
+
// because the caller only inspects digits up to `precision`.
|
|
22
|
+
return n.toFixed(20);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Equivalent to PHP's round() with PHP_ROUND_HALF_UP (mode 1).
|
|
27
|
+
* This is the default rounding in most languages, including JS Math.round for positive numbers,
|
|
28
|
+
* but we need an explicit implementation that handles arbitrary precision.
|
|
29
|
+
*/
|
|
30
|
+
export function roundHalfUp(value: number, precision: number): number {
|
|
31
|
+
if (!Number.isFinite(value) || value === 0) return value;
|
|
32
|
+
|
|
33
|
+
const sign = value < 0 ? -1 : 1;
|
|
34
|
+
const abs = Math.abs(value);
|
|
35
|
+
const factor = Math.pow(10, precision);
|
|
36
|
+
|
|
37
|
+
// Baseline: PHP's core algorithm — floor(shifted + 0.5).
|
|
38
|
+
// This handles non-midpoint cases correctly even when float subtraction
|
|
39
|
+
// produces values like 2 - 1.33 = 0.6699999999999999 (shifted * 100 = 67 exact).
|
|
40
|
+
const shifted = abs * factor;
|
|
41
|
+
let result = Math.floor(shifted + 0.5);
|
|
42
|
+
|
|
43
|
+
// Fix for true midpoints where float multiplication lands just below .5.
|
|
44
|
+
// Example: 19.275 * 100 = 1927.4999999998 → floor(+0.5) = 1927 (wrong).
|
|
45
|
+
// But String(19.275) = "19.275" — the '5' at the 3rd decimal proves it IS
|
|
46
|
+
// a true midpoint. PHP's round() correctly returns 19.28 for these cases.
|
|
47
|
+
//
|
|
48
|
+
// We detect true midpoints via the shortest decimal representation:
|
|
49
|
+
// if the digit at `precision` is exactly 5 with no trailing non-zero digits,
|
|
50
|
+
// force round up (away from zero).
|
|
51
|
+
const str = toDecimalString(abs);
|
|
52
|
+
const dot = str.indexOf('.');
|
|
53
|
+
if (dot !== -1) {
|
|
54
|
+
const decimals = str.slice(dot + 1);
|
|
55
|
+
if (precision < decimals.length && decimals[precision] === '5') {
|
|
56
|
+
const rest = decimals.slice(precision + 1);
|
|
57
|
+
if (rest === '' || /^0*$/.test(rest)) {
|
|
58
|
+
// True midpoint — ensure we round UP (HALF_UP)
|
|
59
|
+
result = Math.floor(shifted) + 1;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return (sign * result) / factor;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Equivalent to PHP's round() with PHP_ROUND_HALF_DOWN (mode 2).
|
|
69
|
+
* When the value is exactly at the midpoint (e.g., 2.725 with precision 2),
|
|
70
|
+
* it rounds DOWN (toward zero) instead of up.
|
|
71
|
+
*
|
|
72
|
+
* WooCommerce uses this for:
|
|
73
|
+
* - Tax rounding when prices_include_tax = 'yes' (WC_TAX_ROUNDING_MODE = PHP_ROUND_HALF_DOWN)
|
|
74
|
+
* - Discount rounding (WC_DISCOUNT_ROUNDING_MODE = PHP_ROUND_HALF_DOWN)
|
|
75
|
+
*/
|
|
76
|
+
export function roundHalfDown(value: number, precision: number): number {
|
|
77
|
+
if (!Number.isFinite(value) || value === 0) return value;
|
|
78
|
+
|
|
79
|
+
const sign = value < 0 ? -1 : 1;
|
|
80
|
+
const abs = Math.abs(value);
|
|
81
|
+
const factor = Math.pow(10, precision);
|
|
82
|
+
|
|
83
|
+
// Baseline: floor(shifted + 0.5) — standard rounding (half up).
|
|
84
|
+
const shifted = abs * factor;
|
|
85
|
+
let result = Math.floor(shifted + 0.5);
|
|
86
|
+
|
|
87
|
+
// For true midpoints (detected via shortest decimal), round DOWN toward zero.
|
|
88
|
+
// Same detection as roundHalfUp but opposite action at the midpoint.
|
|
89
|
+
const str = toDecimalString(abs);
|
|
90
|
+
const dot = str.indexOf('.');
|
|
91
|
+
if (dot !== -1) {
|
|
92
|
+
const decimals = str.slice(dot + 1);
|
|
93
|
+
if (precision < decimals.length && decimals[precision] === '5') {
|
|
94
|
+
const rest = decimals.slice(precision + 1);
|
|
95
|
+
if (rest === '' || /^0*$/.test(rest)) {
|
|
96
|
+
// True midpoint — round DOWN (toward zero, HALF_DOWN)
|
|
97
|
+
result = Math.floor(shifted);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return (sign * result) / factor;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* WC: wc_get_rounding_precision()
|
|
107
|
+
* Returns max(dp + 2, WC_ROUNDING_PRECISION) where WC_ROUNDING_PRECISION = 6.
|
|
108
|
+
*/
|
|
109
|
+
export function getRoundingPrecision(dp: number): number {
|
|
110
|
+
return Math.max(dp + 2, 6);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* WC: wc_add_number_precision($value, $round)
|
|
115
|
+
* Shifts a decimal value into "cents" (integer precision).
|
|
116
|
+
*
|
|
117
|
+
* e.g., with dp=2: 9.99 -> 999
|
|
118
|
+
*
|
|
119
|
+
* The $round parameter controls the rounding precision after multiplication:
|
|
120
|
+
* - true (default): round to (roundingPrecision - dp) places, e.g. 6-2=4
|
|
121
|
+
* - false: round to roundingPrecision places, e.g. 6
|
|
122
|
+
*/
|
|
123
|
+
export function addNumberPrecision(value: number, dp: number, round = true): number {
|
|
124
|
+
const factor = Math.pow(10, dp);
|
|
125
|
+
const result = value * factor;
|
|
126
|
+
const roundingPrecision = getRoundingPrecision(dp);
|
|
127
|
+
const roundPrecision = round ? roundingPrecision - dp : roundingPrecision;
|
|
128
|
+
return roundHalfUp(result, roundPrecision);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* WC: wc_remove_number_precision($value)
|
|
133
|
+
* Shifts a "cents" value back to decimal.
|
|
134
|
+
*
|
|
135
|
+
* e.g., with dp=2: 999 -> 9.99
|
|
136
|
+
*/
|
|
137
|
+
export function removeNumberPrecision(value: number, dp: number): number {
|
|
138
|
+
return value / Math.pow(10, dp);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* WC: wc_round_tax_total($value, $precision)
|
|
143
|
+
* Rounds a tax total using the appropriate rounding mode:
|
|
144
|
+
* - HALF_DOWN when prices include tax (WC_TAX_ROUNDING_MODE = PHP_ROUND_HALF_DOWN)
|
|
145
|
+
* - HALF_UP when prices exclude tax (WC_TAX_ROUNDING_MODE = PHP_ROUND_HALF_UP)
|
|
146
|
+
*
|
|
147
|
+
* @param value - The tax value to round
|
|
148
|
+
* @param dp - The number of decimal places (wc_get_price_decimals)
|
|
149
|
+
* @param pricesIncludeTax - Whether prices include tax
|
|
150
|
+
* @param precision - Override precision (defaults to dp). Pass 0 for cent-precision rounding.
|
|
151
|
+
*/
|
|
152
|
+
export function roundTaxTotal(
|
|
153
|
+
value: number,
|
|
154
|
+
dp: number,
|
|
155
|
+
pricesIncludeTax: boolean,
|
|
156
|
+
precision?: number
|
|
157
|
+
): number {
|
|
158
|
+
const p = precision ?? dp;
|
|
159
|
+
return pricesIncludeTax ? roundHalfDown(value, p) : roundHalfUp(value, p);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* WC: wc_round_discount($value, $precision)
|
|
164
|
+
* Rounds a discount amount using PHP_ROUND_HALF_DOWN.
|
|
165
|
+
* WC_DISCOUNT_ROUNDING_MODE = PHP_ROUND_HALF_DOWN (always, regardless of tax setting).
|
|
166
|
+
*/
|
|
167
|
+
export function roundDiscount(value: number, precision: number): number {
|
|
168
|
+
return roundHalfDown(value, precision);
|
|
169
|
+
}
|