@tallyui/pos 3.18.0 → 3.20.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.
Files changed (70) hide show
  1. package/dist/index.d.ts +3202 -1721
  2. package/dist/index.js +3871 -677
  3. package/package.json +6 -6
  4. package/src/customer-display/display-client.ts +341 -0
  5. package/src/customer-display/index.ts +20 -0
  6. package/src/customer-display/sale-display.ts +115 -0
  7. package/src/customer-display/snapshot-fallback.ts +138 -0
  8. package/src/customer-display/till-display-service.ts +304 -0
  9. package/src/customer-display/till-pairing.ts +177 -0
  10. package/src/customer-display/use-display-client.ts +25 -0
  11. package/src/customer-display/use-sale-display.ts +28 -0
  12. package/src/customer-display/use-till-pairing.ts +35 -0
  13. package/src/customer-display/webrtc/index.ts +5 -0
  14. package/src/customer-display/webrtc/peer-link.ts +222 -0
  15. package/src/index.ts +36 -10
  16. package/src/order/index.ts +2 -1
  17. package/src/order/order-builder.ts +104 -16
  18. package/src/order/types.ts +10 -4
  19. package/src/payment-driver/index.ts +1 -1
  20. package/src/payment-driver/registry.ts +23 -0
  21. package/src/pos-order/__fixtures__/order-create-v8.json +117 -0
  22. package/src/pos-order/command.ts +27 -9
  23. package/src/pos-order/finalize.ts +30 -2
  24. package/src/pos-order/schema.ts +16 -5
  25. package/src/pos-order/types.ts +7 -4
  26. package/src/receipt/reprint.ts +3 -10
  27. package/src/receipt/woo-gross.ts +16 -0
  28. package/src/receipt-template/index.ts +8 -0
  29. package/src/receipt-template/render-store-template.ts +51 -0
  30. package/src/receipt-template/wcpos/build.ts +320 -0
  31. package/src/receipt-template/wcpos/context.ts +29 -0
  32. package/src/receipt-template/wcpos/format.ts +153 -0
  33. package/src/receipt-template/wcpos/from-orders.ts +203 -0
  34. package/src/receipt-template/wcpos/index.ts +11 -0
  35. package/src/receipt-template/wcpos/money.ts +42 -0
  36. package/src/receipt-template/wcpos/types.ts +350 -0
  37. package/src/register/expected.ts +60 -0
  38. package/src/register/index.ts +2 -2
  39. package/src/register/use-register-session.ts +8 -4
  40. package/src/sale/discount-codes.ts +7 -2
  41. package/src/sale/index.ts +9 -2
  42. package/src/sale/order-filters-query.ts +59 -0
  43. package/src/sale/store-priced-discount-codes.ts +52 -0
  44. package/src/sale/use-sale.ts +157 -16
  45. package/src/sale/variant-match.ts +44 -0
  46. package/src/scanner/camera-scan.ts +113 -0
  47. package/src/scanner/capabilities.ts +22 -0
  48. package/src/scanner/chooser-cancel.ts +8 -0
  49. package/src/scanner/device-identity.ts +84 -0
  50. package/src/scanner/device-scanner.ts +62 -0
  51. package/src/scanner/hid-pos-decoder.ts +60 -0
  52. package/src/scanner/hid-scanner.ts +171 -0
  53. package/src/scanner/index.ts +27 -0
  54. package/src/scanner/scan-dedup.ts +48 -0
  55. package/src/scanner/scan-events.ts +75 -0
  56. package/src/scanner/scan-hub-context.tsx +124 -0
  57. package/src/scanner/scan-session.ts +4 -0
  58. package/src/scanner/scanner-profiles.ts +96 -0
  59. package/src/scanner/serial-line-decoder.ts +58 -0
  60. package/src/scanner/serial-scanner.ts +227 -0
  61. package/src/scanner/use-barcode-scanner.ts +23 -5
  62. package/src/scanner/use-camera-scan.ts +57 -0
  63. package/src/scanner/wedge-detector.ts +28 -6
  64. package/src/store-settings/use-store-settings.ts +23 -5
  65. package/src/tax/index.ts +6 -0
  66. package/src/tax/location-rates.ts +46 -0
  67. package/src/tax/sale-tax-contexts.ts +40 -0
  68. package/src/tax/tax-context.ts +37 -0
  69. package/src/tax/tax-derivation.ts +99 -0
  70. package/src/tax/tax-provider.tsx +4 -31
@@ -0,0 +1,57 @@
1
+ import { useMemo, useRef, useState } from 'react';
2
+ import { useScanHub } from './scan-hub-context';
3
+ import { createScanSession } from './scan-session';
4
+ import { DEFAULT_MIN_SCAN_CHARS } from './wedge-detector';
5
+
6
+ export interface UseCameraScanOptions {
7
+ /** Drop decodes while false (v2: the POS section is not active). Default true. */
8
+ active?: boolean;
9
+ /** Codes shorter than this are refused and reported to onTooShort. Default DEFAULT_MIN_SCAN_CHARS. */
10
+ minChars?: number;
11
+ onTooShort?: (code: string) => void;
12
+ now?: () => number;
13
+ }
14
+
15
+ export interface CameraScan {
16
+ offer(code: string, symbology?: string): void;
17
+ reset(): void;
18
+ /** Codes accepted and emitted so far; the app passes it to CameraScannerPanel, which flashes on each change. */
19
+ scanCount: number;
20
+ }
21
+
22
+ /** offer: feed one decode; it goes through a continuous scan session and is emitted to the hub as a camera event.
23
+ * reset: clear the cooldowns (call when the scanner opens). Inside a ScanHubProvider the app's useBarcodeScanner
24
+ * receives the events; with no provider the hub is inert and they go nowhere. The app owns this hook and passes
25
+ * { onDetected: offer, onOpen: reset, scanCount } to CameraScannerPanel.
26
+ * Ported from WCPOS v2 packages/core/src/screens/main/pos/products/use-camera-scan.ts. */
27
+ export function useCameraScan(options: UseCameraScanOptions = {}): CameraScan {
28
+ const latest = useRef(options);
29
+ latest.current = options;
30
+ const hub = useScanHub();
31
+ const hubRef = useRef(hub);
32
+ hubRef.current = hub;
33
+ const [scanCount, setScanCount] = useState(0);
34
+ // One session for the hook's lifetime, so a changing option never drops the cooldowns.
35
+ const [session] = useState(() => createScanSession({
36
+ continuous: true,
37
+ now: () => (latest.current.now ?? Date.now)(),
38
+ onAccept: (code, symbology) => {
39
+ hubRef.current.emit({ code, symbology, source: { kind: 'camera' }, timestamp: (latest.current.now ?? Date.now)() });
40
+ setScanCount((count) => count + 1);
41
+ },
42
+ }));
43
+ return useMemo(() => ({
44
+ offer: (code: string, symbology?: string) => {
45
+ const { active = true, minChars = DEFAULT_MIN_SCAN_CHARS, onTooShort } = latest.current;
46
+ if (!active) return;
47
+ // Before the session, so a too-short read never starts a cooldown.
48
+ if (code.length < minChars) {
49
+ onTooShort?.(code);
50
+ return;
51
+ }
52
+ session.offer(code, symbology);
53
+ },
54
+ reset: () => session.reset(),
55
+ scanCount,
56
+ }), [session, scanCount]);
57
+ }
@@ -1,4 +1,4 @@
1
- // Ported from WCPOS v2 packages/scanner/src/wedge-detector.ts (monorepo 5ac185b0).
1
+ // Ported from WCPOS v2 packages/scanner/src/wedge-detector.ts (monorepo 85ecbd43f) (meta only).
2
2
  /** The wedge detector distinguishes scanner bursts from typing using a folded
3
3
  * running average of inter-key gaps. Live and replay paths share the reducer. */
4
4
  export interface WedgeSettings {
@@ -22,10 +22,14 @@ export interface WedgeState {
22
22
  detecting: boolean;
23
23
  stack: string[];
24
24
  lastTimeMs: number | null;
25
+ /** Time of the first key of the current burst's stack. */
26
+ startedAtMs: number | null;
27
+ /** An Enter/Tab arrived during the burst — the signature of a scanner terminator. */
28
+ sawTerminator: boolean;
25
29
  }
26
30
 
27
31
  export function createWedgeState(): WedgeState {
28
- return { avg: 0, detecting: false, stack: [], lastTimeMs: null };
32
+ return { avg: 0, detecting: false, stack: [], lastTimeMs: null, startedAtMs: null, sawTerminator: false };
29
33
  }
30
34
 
31
35
  /** Fold one key, mutating and returning state. Kept bug-for-bug with v2:
@@ -44,6 +48,7 @@ export function foldWedgeKey(state: WedgeState, key: string, timeMs: number, thr
44
48
  state.avg = 0;
45
49
  state.stack = [key];
46
50
  }
51
+ if (state.stack.length === 1) state.startedAtMs = timeMs;
47
52
  state.lastTimeMs = timeMs;
48
53
  return state;
49
54
  }
@@ -73,11 +78,19 @@ export function replayWedgeDetector(keys: TraceKey[], settings: WedgeSettings):
73
78
  return { detectedAsScan: true, code: stripBoundary(state.stack, settings) };
74
79
  }
75
80
 
81
+ export interface WedgeScanMeta {
82
+ /** The burst ended with an Enter/Tab terminator — scanners send one, typists rarely do. */
83
+ terminated: boolean;
84
+ /** When the burst's first key arrived (the detector's clock): the physical scan time.
85
+ * The emit itself is WEDGE_END_OF_SCAN_MS after the LAST key. */
86
+ startedAtMs: number;
87
+ }
88
+
76
89
  export interface WedgeDetectorOptions {
77
90
  /** Read current settings per keystroke so live changes apply. */
78
91
  getSettings: () => WedgeSettings;
79
92
  /** A completed burst, prefix/suffix already stripped. */
80
- onScan: (code: string) => void;
93
+ onScan: (code: string, meta: WedgeScanMeta) => void;
81
94
  /** Injectable clock/timers so hosts and tests control time. */
82
95
  now?: () => number;
83
96
  setTimeout?: (fn: () => void, ms: number) => unknown;
@@ -108,8 +121,15 @@ export function createWedgeDetector(options: WedgeDetectorOptions): WedgeDetecto
108
121
  const time = timeMs ?? now();
109
122
  const sinceLastMs = state.lastTimeMs === null ? Number.POSITIVE_INFINITY : time - state.lastTimeMs;
110
123
  if (key.length !== 1) {
111
- // Non-printable keys never advance the burst; only its terminator is consumed.
112
- return (key === 'Enter' || key === 'Tab') && state.detecting && sinceLastMs <= WEDGE_END_OF_SCAN_MS;
124
+ const inBurst = state.detecting && sinceLastMs <= WEDGE_END_OF_SCAN_MS;
125
+ // Non-printable keys never advance the burst, but an Enter/Tab landing
126
+ // inside one is the scanner-terminator signature — remember it so the
127
+ // emit can tell a real (mis-configured) scan from fast typing.
128
+ if ((key === 'Enter' || key === 'Tab') && inBurst) {
129
+ state.sawTerminator = true;
130
+ return true;
131
+ }
132
+ return false;
113
133
  }
114
134
  const settings = options.getSettings();
115
135
  foldWedgeKey(state, key, time, settings.threshold);
@@ -120,11 +140,13 @@ export function createWedgeDetector(options: WedgeDetectorOptions): WedgeDetecto
120
140
  const current = options.getSettings();
121
141
  if (state.detecting && now() - (state.lastTimeMs || 0) > current.threshold) {
122
142
  const code = stripBoundary(state.stack, current);
143
+ const terminated = state.sawTerminator;
144
+ const startedAtMs = state.startedAtMs;
123
145
  // Reset for the next burst, deliberately keeping lastTimeMs.
124
146
  const lastTimeMs = state.lastTimeMs;
125
147
  state = createWedgeState();
126
148
  state.lastTimeMs = lastTimeMs;
127
- options.onScan(code);
149
+ options.onScan(code, { terminated, startedAtMs: startedAtMs ?? now() });
128
150
  } else if (state.detecting) {
129
151
  // A threshold at or above the settle window must not latch forever.
130
152
  timer = schedule(settle, WEDGE_END_OF_SCAN_MS);
@@ -6,7 +6,13 @@ import type { ResolveStoreSettingsOptions } from './resolve-store-settings';
6
6
 
7
7
  export type StoreSettingsState =
8
8
  | { state: 'loading' }
9
- | { state: 'ready'; settings: StoreSettings; choice?: StoreSettingsChoice }
9
+ | { state: 'ready'; settings: StoreSettings; choice?: StoreSettingsChoice;
10
+ /** Re-reads the store's settings and tax rounding in place, for a "sync" button; the till stays `ready` meanwhile. A call while one runs is ignored. */
11
+ refresh: () => void;
12
+ /** True while a refresh runs; `settings` are still the ones in hand. */
13
+ refreshing?: boolean;
14
+ /** Why the last refresh failed; `settings` are the ones from before it. Cleared when the next refresh starts. */
15
+ refreshError?: unknown }
10
16
  | { state: 'choose'; choices: StoreSettingsChoices; initial?: StoreSettingsChoice; choose: (choice: StoreSettingsChoice) => void }
11
17
  | { state: 'error'; error: unknown; retry: () => void; nextRetryAt?: number }
12
18
  | { state: 'unsupported' };
@@ -60,6 +66,7 @@ function readTaxRounding({ connector, context }: ResolveStoreSettingsOptions): P
60
66
  * if (store.state === 'choose')
61
67
  * return <StoreSettingsChoiceScreen choices={store.choices} initial={store.initial} onSubmit={store.choose} />;
62
68
  * if (store.state !== 'ready') return <Loading />; // or an error with store.retry, or the app's own config when unsupported
69
+ * // Use store.refresh for a sync button.
63
70
  * const syncContext = withPricingContext(context, store.settings); // for the replication
64
71
  * return <TaxProvider {...taxProviderProps(store.settings)}>{children}</TaxProvider>;
65
72
  * ```
@@ -77,19 +84,26 @@ export function useStoreSettings(options: ResolveStoreSettingsOptions): StoreSet
77
84
  // arriving after a store switch made that request stale is ignored, so it can't apply an old
78
85
  // pick to the new store. `known`, when given, is the rounding that request already read, so
79
86
  // a pick doesn't read it again.
80
- const resolve = useCallback((choice?: StoreSettingsChoice, from?: number, known?: Promise<TaxRounding | undefined>) => {
87
+ const resolve = useCallback((choice?: StoreSettingsChoice, from?: number, known?: Promise<TaxRounding | undefined>, previous?: Extract<StoreSettingsState, { state: 'ready' }>) => {
81
88
  if (from !== undefined && from !== requestRef.current) return;
82
89
  clearTimeout(retryTimerRef.current);
83
90
  const request = ++requestRef.current;
84
91
  const current = () => request === requestRef.current;
85
- setState(LOADING);
92
+ const ready = (value: Omit<Extract<StoreSettingsState, { state: 'ready' }>, 'state' | 'refresh'>) => {
93
+ const next: Extract<StoreSettingsState, { state: 'ready' }> = { state: 'ready', ...value, refresh: () => resolve(value.choice, request, undefined, next) };
94
+ return next;
95
+ };
96
+ if (previous) {
97
+ const { refreshError: _error, ...refreshing } = previous;
98
+ setState({ ...refreshing, refreshing: true });
99
+ } else setState(LOADING);
86
100
  const rounding = known ?? readTaxRounding(optionsRef.current);
87
101
  Promise.all([resolveStoreSettings(optionsRef.current, choice), rounding]).then(
88
102
  ([result, taxRounding]) => {
89
103
  if (!current()) return;
90
- retryDelayRef.current = INITIAL_RETRY_MS;
104
+ if (!previous) retryDelayRef.current = INITIAL_RETRY_MS;
91
105
  if (result.status === 'ready')
92
- setState({ state: 'ready', settings: taxRounding ? { ...result.settings, taxRounding } : result.settings, choice: result.choice });
106
+ setState(ready({ settings: taxRounding ? { ...result.settings, taxRounding } : result.settings, choice: result.choice }));
93
107
  else if (result.status === 'choose')
94
108
  setState({ state: 'choose', choices: result.choices, initial: result.initial, choose: (pick) => resolve(pick, request, rounding) });
95
109
  else setState({ state: 'unsupported' });
@@ -97,6 +111,10 @@ export function useStoreSettings(options: ResolveStoreSettingsOptions): StoreSet
97
111
  // A retry keeps the choice that failed: a new pick is saved only once it resolves.
98
112
  (error: unknown) => {
99
113
  if (!current()) return;
114
+ if (previous) {
115
+ setState(ready({ settings: previous.settings, choice: previous.choice, refreshError: error }));
116
+ return;
117
+ }
100
118
  const retry = () => resolve(choice, request);
101
119
  if (error instanceof StoreCapabilitiesUnavailableError) {
102
120
  const delay = retryDelayRef.current;
package/src/tax/index.ts CHANGED
@@ -3,3 +3,9 @@ export type { TaxLineInput, OrderTaxTotals, RateTaxLine } from './exact';
3
3
  export { TaxProvider, useTax, taxLogger } from './tax-provider';
4
4
  export type { TaxProviderProps } from './tax-provider';
5
5
  export type { TaxRateMap, TaxContext } from './types';
6
+ export { taxSettingsForLocation } from './location-rates';
7
+ export { createTaxContext } from './tax-context';
8
+ export { saleTaxContexts } from './sale-tax-contexts';
9
+ export type { SaleTaxContext } from './sale-tax-contexts';
10
+ export { taxDerivation } from './tax-derivation';
11
+ export type { TaxDerivation, TaxDerivationClass, TaxDerivationRate, TaxRateWhy, SaleTaxLocation } from './tax-derivation';
@@ -0,0 +1,46 @@
1
+ import { woocommerceTax, type StoreSettings } from '@tallyui/core';
2
+
3
+ type TaxRates = NonNullable<StoreSettings['taxRates']>;
4
+
5
+ /** WooCommerce's order tax line `rate_code` (`WC_Tax::get_rate_code`), as the WooCommerce connector builds it. */
6
+ function rateCode(rate: woocommerceTax.WooTaxRate): string {
7
+ return [rate.country, rate.state, rate.name || 'TAX', String(rate.priority)].filter(Boolean).join('-').toUpperCase();
8
+ }
9
+
10
+ /** A class's effective rate on 100 units taxed exclusive, compound rates included (v2's class ledger, tax-derivation.ts:49-74), in percent. */
11
+ export function classRatePercent(rates: woocommerceTax.CalculateTaxesInput['rates']): number {
12
+ if (rates.length === 0) return 0;
13
+ return woocommerceTax.calculateTaxes({ amount: 100, rates, amountIncludesTax: false }).total;
14
+ }
15
+
16
+ function classRatePpm(rates: woocommerceTax.WooTaxRate[]): number {
17
+ return Math.round(classRatePercent(rates) * 10000);
18
+ }
19
+
20
+ /**
21
+ * `settings` with `taxRates` and `taxRatesPpm` re-derived for `location` from `settings.taxRateTable` (WooCommerce rules);
22
+ * `settings` unchanged (the same object) when `taxRateTable` is absent. `taxRatesPpm` keys the standard class as `default`,
23
+ * and every class in the table is present, at 0 when no rate matches, so it does not fall back to `default`.
24
+ */
25
+ export function taxSettingsForLocation(settings: StoreSettings, location: woocommerceTax.TaxAddress): StoreSettings {
26
+ const table = settings.taxRateTable;
27
+ if (!table) return settings;
28
+ const matched = woocommerceTax.filterTaxRates(table, location.country, location.state, location.postcode, location.city);
29
+ const byClass = new Map<string, woocommerceTax.WooTaxRate[]>();
30
+ for (const rate of table) {
31
+ const slug = woocommerceTax.normalizeTaxClass(rate.class);
32
+ if (!byClass.has(slug)) byClass.set(slug, []);
33
+ }
34
+ const taxRates: TaxRates = {};
35
+ for (const rate of matched) {
36
+ const slug = woocommerceTax.normalizeTaxClass(rate.class);
37
+ byClass.get(slug)!.push(rate);
38
+ (taxRates[slug] ??= []).push({ id: rate.id, code: rateCode(rate), label: rate.name, rate: rate.rate,
39
+ priority: rate.priority, compound: rate.compound, shipping: rate.shipping });
40
+ }
41
+ const taxRatesPpm: StoreSettings['taxRatesPpm'] = { default: classRatePpm(byClass.get(woocommerceTax.STANDARD_TAX_CLASS) ?? []) };
42
+ for (const [slug, rates] of byClass) {
43
+ if (slug !== woocommerceTax.STANDARD_TAX_CLASS) taxRatesPpm[slug] = classRatePpm(rates);
44
+ }
45
+ return { ...settings, taxRates, taxRatesPpm };
46
+ }
@@ -0,0 +1,40 @@
1
+ import { woocommerceTax, type StoreSettings } from '@tallyui/core';
2
+ import type { CustomerSummary } from '../order/types';
3
+ import { TAX_ADDRESS_ORDER_CREATE_VERSION } from '../pos-order/command';
4
+ import { taxProviderProps } from '../store-settings/map-store-settings';
5
+ import { taxSettingsForLocation } from './location-rates';
6
+ import { createTaxContext } from './tax-context';
7
+ import type { TaxContext } from './types';
8
+
9
+ /** A sale's tax context for one customer (#722), and the address WooCommerce matched its rates against. */
10
+ export interface SaleTaxContext { taxContext: TaxContext; location: woocommerceTax.ResolvedTaxLocation }
11
+
12
+ const NO_ADDRESS: woocommerceTax.TaxAddress = { country: '', state: '', city: '', postcode: '' };
13
+
14
+ /**
15
+ * `useSale`'s `taxContextFor` (#722): the tax context for a customer's address, as WooCommerce's `tax_based_on` picks it.
16
+ * Customers whose addresses match the same rates get the same `TaxContext` object, so a customer change that moves no
17
+ * rate never re-taxes. It re-matches only with `taxRateTable`, `baseTaxAddress` and an `orderCreateVersion` (the
18
+ * connector's `orderCreate` capability) of at least TAX_ADDRESS_ORDER_CREATE_VERSION: only order.create 8 tells the
19
+ * server which address the sale was taxed on, so below it the server taxes on the base. Otherwise, the option absent
20
+ * included, every customer gets the store's own context.
21
+ * Build it once per settings (an app memoizes it): a new function restarts an idle sale, as new settings do.
22
+ */
23
+ export function saleTaxContexts(settings: StoreSettings, options?: { orderCreateVersion?: number }): (customer: CustomerSummary | null) => SaleTaxContext {
24
+ const store = createTaxContext(taxProviderProps(settings));
25
+ const base = settings.baseTaxAddress, table = settings.taxRateTable;
26
+ if (!table || !base || (options?.orderCreateVersion ?? 0) < TAX_ADDRESS_ORDER_CREATE_VERSION) {
27
+ const location = woocommerceTax.orderTaxLocation(base ?? NO_ADDRESS, settings.taxBasedOn);
28
+ return () => ({ taxContext: store, location });
29
+ }
30
+ const cache = new Map<string, TaxContext>();
31
+ return (customer) => {
32
+ const location = woocommerceTax.orderTaxLocation(base, settings.taxBasedOn,
33
+ customer ? { billing: customer.billing, shipping: customer.shipping } : undefined);
34
+ const local = taxSettingsForLocation(settings, location.location);
35
+ const key = JSON.stringify([local.taxRates, local.taxRatesPpm]);
36
+ let taxContext = cache.get(key);
37
+ if (!taxContext) cache.set(key, taxContext = createTaxContext(taxProviderProps(local)));
38
+ return { taxContext, location };
39
+ };
40
+ }
@@ -0,0 +1,37 @@
1
+ import { woocommerceTax } from '@tallyui/core';
2
+ import type { TaxContext } from './types';
3
+ import type { TaxProviderProps } from './tax-provider';
4
+ import { createLogger } from '../logging';
5
+
6
+ export const taxLogger = createLogger('tax');
7
+
8
+ /** `TaxProvider`'s context, built outside React (#722): a sale taxing by the customer's address builds one per matched rates. */
9
+ export function createTaxContext(props: Omit<TaxProviderProps, 'children'>): TaxContext {
10
+ const { ratesPpm, pricesIncludeTax, rounding, rateCodes, taxRates, shippingTaxClass, taxClassSlugs } = props;
11
+ if (Object.values(ratesPpm).some((rate) => !Number.isSafeInteger(rate) || rate < 0)) {
12
+ throw new RangeError('TaxProvider: rates must be integer ppm');
13
+ }
14
+ const unknown = new Set<string>();
15
+ return {
16
+ ...(taxRates ? { getTaxRates: (taxClass?: string, options?: { shipping?: boolean }) =>
17
+ (taxRates[woocommerceTax.normalizeTaxClass(taxClass)] ?? []).filter((rate) => !options?.shipping || rate.shipping) } : {}),
18
+ getTaxRatePpm: (taxClass) => {
19
+ if (taxClass !== undefined && Object.hasOwn(ratesPpm, taxClass)) return ratesPpm[taxClass];
20
+ // A class the store's rates don't key is taxed at the default rate; warn once per class and rate map.
21
+ if (taxClass !== undefined && !unknown.has(taxClass)) {
22
+ unknown.add(taxClass);
23
+ taxLogger.warn('No tax rate for this tax class; using the default rate', { taxClass });
24
+ }
25
+ return ratesPpm.default ?? 0;
26
+ },
27
+ // The name of the rate getTaxRatePpm picks: the class's own, else the default's.
28
+ getTaxRateCode: (taxClass) => {
29
+ const key = taxClass !== undefined && Object.hasOwn(ratesPpm, taxClass) ? taxClass : 'default';
30
+ return rateCodes && Object.hasOwn(rateCodes, key) ? rateCodes[key] : undefined;
31
+ },
32
+ pricesIncludeTax,
33
+ ...(rounding ? { rounding } : {}),
34
+ ...(shippingTaxClass !== undefined ? { shippingTaxClass } : {}),
35
+ ...(taxClassSlugs !== undefined ? { taxClassSlugs } : {}),
36
+ };
37
+ }
@@ -0,0 +1,99 @@
1
+ // The "Tax based on" panel's derivation (#722), after WCPOS v2 components/product/tax-based-on/tax-derivation.ts, MIT, WCPOS.
2
+ import { woocommerceTax, type StoreSettings } from '@tallyui/core';
3
+ import { classRatePercent } from './location-rates';
4
+
5
+ /** `useSale().taxLocation`: the address WooCommerce matched the sale's rates against, and whether the sale has a customer. */
6
+ export type SaleTaxLocation = woocommerceTax.ResolvedTaxLocation & { hasCustomer: boolean };
7
+
8
+ /** Why a rate matched, narrowest field first (v2's `rateWhy`). */
9
+ export type TaxRateWhy =
10
+ | { field: 'postcode'; pattern: string } | { field: 'city' } | { field: 'state' }
11
+ | { field: 'country'; country: string } | { field: 'anywhere' };
12
+
13
+ export interface TaxDerivationRate { id: number; name: string; percent: string; why: TaxRateWhy }
14
+ export interface TaxDerivationClass { slug: string; name: string; percent: string; rates: TaxDerivationRate[] }
15
+
16
+ export interface TaxDerivation {
17
+ taxBasedOn: woocommerceTax.TaxBasedOn;
18
+ addressUsed: woocommerceTax.TaxBasedOn;
19
+ /** True when the address is the customer's (hasCustomer && addressUsed !== 'base'). */
20
+ fromOrder: boolean;
21
+ location: woocommerceTax.TaxAddress;
22
+ fallback: 'shipping-to-billing' | 'shipping-to-shop' | 'billing-to-shop' | null;
23
+ failure: 'address' | 'rates' | null;
24
+ noRateCause: 'no-country' | 'not-covered' | 'no-rate-for-country' | null;
25
+ /** Only the classes with at least one matched rate, in table order. Empty on failure. */
26
+ classes: TaxDerivationClass[];
27
+ }
28
+
29
+ /** At most 4 decimals, trailing zeros and dot trimmed: "10.0000" → "10%", 8.875 → "8.875%". */
30
+ function formatTaxPercent(value: number | string): string {
31
+ return `${Number(value).toFixed(4).replace(/0+$/, '').replace(/\.$/, '')}%`;
32
+ }
33
+
34
+ /** `standard` → "Standard", `reduced-rate` → "Reduced rate". TallyUI's own rule: StoreSettings has no class names. */
35
+ function taxClassName(slug: string): string {
36
+ if (slug === woocommerceTax.STANDARD_TAX_CLASS) return 'Standard';
37
+ const words = slug.replace(/-/g, ' ');
38
+ return words.charAt(0).toUpperCase() + words.slice(1);
39
+ }
40
+
41
+ function rateWhy(rate: woocommerceTax.WooTaxRate): TaxRateWhy {
42
+ if (rate.postcodes.length) return { field: 'postcode', pattern: rate.postcodes.join(', ') };
43
+ if (rate.cities.length) return { field: 'city' };
44
+ if (rate.state) return { field: 'state' };
45
+ if (rate.country) return { field: 'country', country: rate.country };
46
+ return { field: 'anywhere' };
47
+ }
48
+
49
+ type Matched = { slug: string; id: number; name: string; rate: string; why: TaxRateWhy;
50
+ calc: woocommerceTax.CalculateTaxesInput['rates'][number] };
51
+
52
+ function matchedRates(settings: StoreSettings, location: woocommerceTax.TaxAddress): Matched[] {
53
+ const table = settings.taxRateTable;
54
+ if (!table) {
55
+ return Object.entries(settings.taxRates ?? {}).flatMap(([slug, rates]) => rates.map((rate, index) => {
56
+ const id = Number.isFinite(Number(rate.id)) ? Number(rate.id) : index;
57
+ return { slug: woocommerceTax.normalizeTaxClass(slug), id, name: rate.label, rate: rate.rate, why: { field: 'anywhere' as const },
58
+ calc: { id, rate: rate.rate, compound: rate.compound, priority: rate.priority, order: rate.priority } };
59
+ }));
60
+ }
61
+ const order = new Map<string, number>();
62
+ for (const rate of table) {
63
+ const slug = woocommerceTax.normalizeTaxClass(rate.class);
64
+ if (!order.has(slug)) order.set(slug, order.size);
65
+ }
66
+ const matched = woocommerceTax.filterTaxRates(table, location.country, location.state, location.postcode, location.city)
67
+ .map((rate) => ({ slug: woocommerceTax.normalizeTaxClass(rate.class), id: rate.id, name: rate.name, rate: rate.rate,
68
+ why: rateWhy(rate), calc: rate }));
69
+ return matched.sort((a, b) => order.get(a.slug)! - order.get(b.slug)!);
70
+ }
71
+
72
+ function fallbackOf({ taxBasedOn, addressUsed, hasCustomer }: SaleTaxLocation): TaxDerivation['fallback'] {
73
+ if (!hasCustomer || addressUsed === taxBasedOn) return null;
74
+ if (taxBasedOn === 'shipping') return addressUsed === 'billing' ? 'shipping-to-billing' : 'shipping-to-shop';
75
+ if (taxBasedOn === 'billing' && addressUsed === 'base') return 'billing-to-shop';
76
+ return null;
77
+ }
78
+
79
+ /** Everything the "Tax based on" panel shows: the setting, the address used, and the rates that match it (#722). Pure. */
80
+ export function taxDerivation(settings: StoreSettings, taxLocation: SaleTaxLocation): TaxDerivation {
81
+ const { taxBasedOn, addressUsed, location, hasCustomer } = taxLocation;
82
+ const matched = matchedRates(settings, location);
83
+ const empty = !location.country && !location.state && !location.city && !location.postcode;
84
+ const failure = matched.length ? null : taxBasedOn !== 'base' && hasCustomer && empty ? 'address' : 'rates';
85
+ let noRateCause: TaxDerivation['noRateCause'] = null;
86
+ if (failure === 'rates') {
87
+ const country = location.country.toUpperCase();
88
+ noRateCause = !country ? 'no-country'
89
+ : (settings.taxRateTable ?? []).some((rate) => rate.country.toUpperCase() === country) ? 'not-covered' : 'no-rate-for-country';
90
+ }
91
+ const groups = new Map<string, Matched[]>();
92
+ for (const rate of matched) groups.set(rate.slug, [...(groups.get(rate.slug) ?? []), rate]);
93
+ const classes = [...groups].map(([slug, rates]): TaxDerivationClass => ({
94
+ slug, name: taxClassName(slug), percent: formatTaxPercent(classRatePercent(rates.map((rate) => rate.calc))),
95
+ rates: rates.map(({ id, name, rate, why }) => ({ id, name, percent: formatTaxPercent(rate), why })),
96
+ }));
97
+ return { taxBasedOn, addressUsed, fromOrder: hasCustomer && addressUsed !== 'base', location,
98
+ fallback: fallbackOf(taxLocation), failure, noRateCause, classes };
99
+ }
@@ -1,10 +1,10 @@
1
1
  import { createContext, useContext, useMemo } from 'react';
2
2
  import type { ReactNode } from 'react';
3
- import { woocommerceTax, type StoreSettings, type TaxRounding } from '@tallyui/core';
3
+ import type { StoreSettings, TaxRounding } from '@tallyui/core';
4
4
  import type { TaxContext } from './types';
5
- import { createLogger } from '../logging';
5
+ import { createTaxContext } from './tax-context';
6
6
 
7
- export const taxLogger = createLogger('tax');
7
+ export { taxLogger } from './tax-context';
8
8
 
9
9
  const TaxCtx = createContext<TaxContext | null>(null);
10
10
 
@@ -21,34 +21,7 @@ export interface TaxProviderProps extends Pick<StoreSettings, 'taxRoundAtSubtota
21
21
 
22
22
  export function TaxProvider({ ratesPpm, pricesIncludeTax, rounding, rateCodes, taxRates, shippingTaxClass, taxClassSlugs, children }: TaxProviderProps) {
23
23
  const value = useMemo<TaxContext>(
24
- () => {
25
- if (Object.values(ratesPpm).some((rate) => !Number.isSafeInteger(rate) || rate < 0)) {
26
- throw new RangeError('TaxProvider: rates must be integer ppm');
27
- }
28
- const unknown = new Set<string>();
29
- return {
30
- ...(taxRates ? { getTaxRates: (taxClass?: string, options?: { shipping?: boolean }) =>
31
- (taxRates[woocommerceTax.normalizeTaxClass(taxClass)] ?? []).filter((rate) => !options?.shipping || rate.shipping) } : {}),
32
- getTaxRatePpm: (taxClass) => {
33
- if (taxClass !== undefined && Object.hasOwn(ratesPpm, taxClass)) return ratesPpm[taxClass];
34
- // A class the store's rates don't key is taxed at the default rate; warn once per class and rate map.
35
- if (taxClass !== undefined && !unknown.has(taxClass)) {
36
- unknown.add(taxClass);
37
- taxLogger.warn('No tax rate for this tax class; using the default rate', { taxClass });
38
- }
39
- return ratesPpm.default ?? 0;
40
- },
41
- // The name of the rate getTaxRatePpm picks: the class's own, else the default's.
42
- getTaxRateCode: (taxClass) => {
43
- const key = taxClass !== undefined && Object.hasOwn(ratesPpm, taxClass) ? taxClass : 'default';
44
- return rateCodes && Object.hasOwn(rateCodes, key) ? rateCodes[key] : undefined;
45
- },
46
- pricesIncludeTax,
47
- ...(rounding ? { rounding } : {}),
48
- ...(shippingTaxClass !== undefined ? { shippingTaxClass } : {}),
49
- ...(taxClassSlugs !== undefined ? { taxClassSlugs } : {}),
50
- };
51
- },
24
+ () => createTaxContext({ ratesPpm, pricesIncludeTax, rounding, rateCodes, taxRates, shippingTaxClass, taxClassSlugs }),
52
25
  [ratesPpm, pricesIncludeTax, rounding, rateCodes, taxRates, shippingTaxClass, taxClassSlugs],
53
26
  );
54
27