@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
@@ -1,7 +1,7 @@
1
1
  export { normalizeAmount, isServerDecimal, movementFieldError } from './movement-input';
2
2
  export type { MovementType } from './movement-input';
3
- export { deriveExpected } from './expected';
4
- export type { LedgerRow, Movement } from './expected';
3
+ export { deriveExpected, deriveDrawerTerms } from './expected';
4
+ export type { LedgerRow, Movement, DrawerTerm, DrawerTerms } from './expected';
5
5
  export { parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, closureVariance, denominationTotal, varianceText } from './register-count.helpers';
6
6
  export { denominations } from './register-count.denominations';
7
7
  export { registerSessionSchema, registerSessionCollection, cashMovementSchema, closureSchema } from './schemas';
@@ -24,7 +24,7 @@ import type { PosOrder } from '../pos-order/types';
24
24
  import { replacedOrderIds } from '../pos-order/reopened';
25
25
  import type { PosRefund, PosRefundCollection } from '../refund/pos-refund';
26
26
  import { readFresh, watchFresh } from '../rxdb';
27
- import { deriveExpected, type LedgerRow } from './expected';
27
+ import { deriveDrawerTerms, deriveExpected, type LedgerRow } from './expected';
28
28
  import { recordRegisterFact, registerFactsLogger, type Actor } from './facts';
29
29
  import { closeNeedsApproval, closureVariance } from './register-count.helpers';
30
30
  import {
@@ -326,9 +326,11 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
326
326
  const entries = data?.entries ?? [];
327
327
  const sales = data?.sales ?? [];
328
328
  const replaced = replacedOrderIds(sales);
329
- const expected = session
330
- ? deriveExpected({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries, ledgerRowsBySession: ledgerRows(sales, replaced), refunds: data?.refundRows ?? [] })
331
- : {};
329
+ // The drawer ledger's terms; their `expected` is `deriveExpected`'s own result for the same rows.
330
+ const terms = session
331
+ ? deriveDrawerTerms({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries, ledgerRowsBySession: ledgerRows(sales, replaced), refunds: data?.refundRows ?? [] })
332
+ : null;
333
+ const expected = terms ? terms.expected : {};
332
334
  const now = new Date();
333
335
  const [hour, minute] = String(expectedCloseTime ?? '').split(':').map(Number);
334
336
  const overdue = session?.status === 'open' && !!expectedCloseTime
@@ -371,6 +373,8 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
371
373
  needsUpgrade: data?.rows.some((row) => !store.isKnownSessionStatus(row.status)) ?? false,
372
374
  movements: entries,
373
375
  expected,
376
+ /** `expected`'s drawer ledger, term by term with row counts (`deriveDrawerTerms`); `null` without a session. */
377
+ terms,
374
378
  salesCount: sales.filter((order) => !replaced.has(order.id)).length,
375
379
  overdue,
376
380
  /** A `closeSession` for this register is in flight, in any hook instance: the session can already be stored `closed` while its closure isn't written yet. */
@@ -3,6 +3,8 @@ import type { Order, OrderBuilder } from '../order';
3
3
 
4
4
  /** applyCoupon's refusal when the store cannot take coupons (ADR-077 R2, R3). */
5
5
  export const COUPONS_UNSUPPORTED = "This store's plugin does not support coupons yet";
6
+ /** A store-priced code's transient refusal (TallyUI#710): the store could not be asked, so the code was neither priced nor refused. */
7
+ export const COUPONS_NEED_CONNECTION = 'Coupons need a connection to the store';
6
8
 
7
9
  /** What a platform's discount codes see of the sale (ADR-077 amendment 3). */
8
10
  export interface SaleDiscountState<Accepted> {
@@ -23,8 +25,11 @@ export interface SaleDiscountState<Accepted> {
23
25
  export interface SaleDiscountCodes<Accepted = unknown> {
24
26
  /** Whether this store can take codes in this tax context; `useSale` also requires `capabilities.coupons` and `orderCreate >= 6`. */
25
27
  supports(store: { capabilities?: ServerCapabilities; rounding?: TaxRounding }): boolean;
26
- /** Looks up a trimmed, lower-case code: what was found, or the refusal to show. */
27
- find(code: string, sale: SaleDiscountState<Accepted>): Promise<{ found: Accepted } | { refusal: string }>;
28
+ /**
29
+ * Looks up a trimmed, lower-case code: what was found, or the refusal to show. `transient: true` means the store
30
+ * could not be asked (no connection, say), not that it refused the code; the WooCommerce codes never set it.
31
+ */
32
+ find(code: string, sale: SaleDiscountState<Accepted>): Promise<{ found: Accepted } | { refusal: string; transient?: true }>;
28
33
  /** Checks a found code against the sale; the refusal to show, or null when it may be applied. */
29
34
  check(code: string, found: Accepted, sale: SaleDiscountState<Accepted>): string | null;
30
35
  /** Puts `sale.accepted`'s codes, in order, on the builder; throws an Error whose message is the refusal. */
package/src/sale/index.ts CHANGED
@@ -1,12 +1,19 @@
1
- export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, saleLogger } from './use-sale';
1
+ export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, COUPONS_REPRICING, saleLogger } from './use-sale';
2
2
  export { openSales, isPartlyPaid } from './open-sales';
3
3
  export type { OpenSale } from './open-sales';
4
4
  export type { SaleStage } from './use-sale';
5
- export { COUPONS_UNSUPPORTED } from './discount-codes';
5
+ export { COUPONS_UNSUPPORTED, COUPONS_NEED_CONNECTION } from './discount-codes';
6
6
  export type { SaleDiscountCodes, SaleDiscountState } from './discount-codes';
7
+ export { createStorePricedDiscountCodes } from './store-priced-discount-codes';
8
+ export type { StorePricedAccepted, StorePricedCodePricing, StorePricedDiscountCodesOptions } from './store-priced-discount-codes';
7
9
  export * as woocommerceDiscountCodes from './woocommerce';
8
10
  export { addEntryToCart, CartError } from './cart';
9
11
  export { catalogueEntries, findEntryByCode, variantPriceLabel } from './catalogue';
10
12
  export type { CatalogueEntry } from './catalogue';
13
+ export { variantFits, matchVariant, disabledOptions } from './variant-match';
14
+ export type { OptionPicks } from './variant-match';
11
15
  export { cartQuantities } from './in-cart';
16
+ export { SPLIT_FIXED_DISCOUNT } from '../order/order-builder';
12
17
  export type { CartQuantityLine } from './in-cart';
18
+ export { orderFiltersQuery } from './order-filters-query';
19
+ export type { OrderFilterValue } from './order-filters-query';
@@ -0,0 +1,59 @@
1
+ import type { ListOrdersQuery, OrderFilterField } from '@tallyui/core';
2
+ import type { DayRange, StoreDay } from '../reports/types';
3
+
4
+ /** What the orders filter bar holds (#721): store ids as strings, and the date range as store days. */
5
+ export interface OrderFilterValue {
6
+ status?: string;
7
+ customerId?: string;
8
+ cashierId?: string;
9
+ registerId?: string;
10
+ paymentMethod?: string;
11
+ storeId?: string;
12
+ createdVia?: string;
13
+ /** Store days, inclusive. */
14
+ dateRange?: DayRange;
15
+ }
16
+
17
+ const COPIED = ['status', 'customerId', 'cashierId', 'registerId', 'paymentMethod', 'storeId', 'createdVia'] as const;
18
+ const DAY_MS = 86_400_000;
19
+
20
+ /** How far `timezone`'s wall clock is ahead of UTC at instant `at`, in ms. `Intl`, so no date library. */
21
+ function offsetMs(at: number, timezone: string): number {
22
+ const format = new Intl.DateTimeFormat('en-US', {
23
+ timeZone: timezone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric',
24
+ hour: 'numeric', minute: 'numeric', second: 'numeric',
25
+ });
26
+ const part = Object.fromEntries(format.formatToParts(new Date(at)).map(({ type, value }) => [type, Number(value)]));
27
+ const wall = Date.UTC(part.year, part.month - 1, part.day, part.hour, part.minute, part.second);
28
+ return wall - Math.floor(at / 1000) * 1000;
29
+ }
30
+
31
+ /** The instant store day `day` starts in `timezone` (IANA or 'device'), as an ISO string ending in Z. */
32
+ function dayStart(day: StoreDay, timezone: string): string {
33
+ const [year, month, date] = day.split('-').map(Number);
34
+ if (timezone === 'device') return new Date(year, month - 1, date).toISOString();
35
+ const wall = Date.UTC(year, month - 1, date);
36
+ // Two passes: the offset at the first guess can differ from the offset at the day's start across a DST change.
37
+ const guess = wall - offsetMs(wall, timezone);
38
+ return new Date(wall - offsetMs(guess, timezone)).toISOString();
39
+ }
40
+
41
+ const nextDay = (day: StoreDay): StoreDay => {
42
+ const [year, month, date] = day.split('-').map(Number);
43
+ return new Date(Date.UTC(year, month - 1, date) + DAY_MS).toISOString().slice(0, 10);
44
+ };
45
+
46
+ /**
47
+ * The bar's value as ListOrdersQuery filter fields. Set fields are copied; `dateRange` becomes UTC instants: `after`
48
+ * the start of `from` in `timezone`, `before` the start of the day after `to` (exclusive), as `presetRange` reads days.
49
+ */
50
+ export function orderFiltersQuery(value: OrderFilterValue, timezone: string): Pick<ListOrdersQuery, OrderFilterField> {
51
+ const query: Pick<ListOrdersQuery, OrderFilterField> = {};
52
+ for (const field of COPIED) {
53
+ if (value[field] !== undefined) query[field] = value[field];
54
+ }
55
+ if (value.dateRange) {
56
+ query.dateRange = { after: dayStart(value.dateRange.from, timezone), before: dayStart(nextDay(value.dateRange.to), timezone) };
57
+ }
58
+ return query;
59
+ }
@@ -0,0 +1,52 @@
1
+ import { couponPricingBasis, type StorePricedCoupon } from '../order';
2
+ import { COUPONS_NEED_CONNECTION, type SaleDiscountCodes, type SaleDiscountState } from './discount-codes';
3
+
4
+ /** What one `price` call gave (TallyUI#710): the codes priced, in order, their amounts, and the order's couponPricingBasis before the call. */
5
+ export interface StorePricedCodePricing { codes: readonly string[]; priced: ReadonlyMap<string, StorePricedCoupon>; basis: string }
6
+ /** An accepted store-priced code: its own amounts, and the pricing of every code up to it. */
7
+ export interface StorePricedAccepted { coupon: StorePricedCoupon; pricing: StorePricedCodePricing }
8
+ export interface StorePricedDiscountCodesOptions {
9
+ /** Defaults to every store; `useSale` still requires `capabilities.coupons` and `orderCreate >= 6`. */
10
+ supports?: SaleDiscountCodes['supports'];
11
+ /**
12
+ * Prices `codes` (the accepted codes in order, then the new one) against `sale.order`'s lines and discounts:
13
+ * the store's amount per line for every code, or the refusal to show. Rejects when the store cannot be reached.
14
+ * The order's own coupon figures may be stale; price from the inputs couponPricingBasis lists, never from them.
15
+ */
16
+ price(codes: readonly string[], sale: SaleDiscountState<StorePricedAccepted>):
17
+ Promise<{ priced: ReadonlyMap<string, StorePricedCoupon> } | { refusal: string }>;
18
+ }
19
+
20
+ // A basis couponPricingBasis' JSON never equals: the order shows stale until its codes are priced again.
21
+ const STALE_PRICING = '';
22
+
23
+ /**
24
+ * Discount codes for a store that prices its own codes (TallyUI#710; Medusa promotions first): `price` asks the store,
25
+ * and the till applies the store's amounts through setCoupons' store-priced context, never computing a coupon's value.
26
+ */
27
+ export function createStorePricedDiscountCodes(options: StorePricedDiscountCodesOptions): SaleDiscountCodes<StorePricedAccepted> {
28
+ return {
29
+ supports: options.supports ?? (() => true),
30
+ async find(code, sale) {
31
+ if (sale.accepted.has(code)) return { refusal: `Coupon ${code} is already applied` };
32
+ const basis = couponPricingBasis(sale.order), codes = [...sale.accepted.keys(), code];
33
+ let result: Awaited<ReturnType<StorePricedDiscountCodesOptions['price']>>;
34
+ try { result = await options.price(codes, sale); }
35
+ catch { return { refusal: COUPONS_NEED_CONNECTION, transient: true }; }
36
+ if ('refusal' in result) return result;
37
+ const missing = codes.find((each) => !result.priced.has(each));
38
+ if (missing !== undefined) return { refusal: `Coupon ${missing} was not priced by the store` };
39
+ return { found: { coupon: result.priced.get(code)!, pricing: { codes, priced: new Map(result.priced), basis } } };
40
+ },
41
+ check: () => null, // the store accepted the code when it priced it
42
+ apply(builder, sale) {
43
+ const codes = [...sale.accepted.keys()];
44
+ const pricing = [...sale.accepted.values()].at(-1)?.pricing;
45
+ if (!pricing) return builder.setCoupons([], { kind: 'store-priced', priced: new Map(), basis: couponPricingBasis(sale.order) });
46
+ const same = pricing.codes.length === codes.length && pricing.codes.every((each, k) => each === codes[k]);
47
+ // After a removal the remaining codes were priced together with the removed one: kept, but stale until priced again.
48
+ builder.setCoupons(codes, same ? { kind: 'store-priced', priced: pricing.priced, basis: pricing.basis }
49
+ : { kind: 'store-priced', priced: new Map([...pricing.priced].filter(([each]) => codes.includes(each))), basis: STALE_PRICING });
50
+ },
51
+ };
52
+ }
@@ -1,13 +1,13 @@
1
- import { useEffect, useLayoutEffect, useRef, useState } from 'react';
1
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
2
2
  import type { RxCollection } from 'rxdb';
3
- import type { ProductTraits, ServerCapabilities, StoreSettings } from '@tallyui/core';
3
+ import type { ProductTraits, ServerCapabilities, StoreSettings, woocommerceTax } from '@tallyui/core';
4
4
  import { paymentMethodOf } from '@tallyui/core';
5
5
  import { canVoidLeg, capturedMinor, countsTowardPaid, inMotionMinor, isInMotion } from '../tender/payment-legs';
6
6
  import { createOrderBuilder, writeOrderDraft, restoreOrderDraft, type ChargeInput, type OrderBuilder, type CustomerSummary, type Discount, type Order, type SentOrder } from '../order';
7
7
  import { finalizeOrder, uuidv7, type PosOrder } from '../pos-order';
8
8
  import { MESSAGE_NAME_MAX, referenceError, referenceReason, withSentForm } from '../pos-order/finalize';
9
9
  import { CUSTOMER_REFUSALS, customerRefusal, cutText, PAYLOAD_STRING_MAX } from '../pos-order/command';
10
- import { useTax } from '../tax';
10
+ import { useTax, type SaleTaxContext, type SaleTaxLocation, type TaxContext } from '../tax';
11
11
  import { recordRegisterFact, stampSession, type RegisterSessionCollection } from '../register';
12
12
  import { createLogger } from '../logging';
13
13
  import type { CatalogueEntry } from './catalogue';
@@ -32,6 +32,12 @@ export const PAYMENT_IN_MOTION = 'Finish or void the payment in progress before
32
32
  */
33
33
  export const SALE_PARTLY_PAID = 'This sale is partly paid. Take the rest of the payment or void the paid legs first.';
34
34
  export const SALE_IN_TENDER = 'Finish or cancel the payment before switching sales';
35
+ /** startTender and complete() refuse with this while the order's store-priced coupons are stale or being priced again (TallyUI#710). */
36
+ export const COUPONS_REPRICING = 'Coupon prices are being checked; try again in a moment';
37
+ /** #722: setCustomer's refusal of a customer whose address moves the sale's rates once they can no longer change (tender, receipt, money live); interim until #759 re-taxes like v2. */
38
+ export const CUSTOMER_RETAX_REFUSED = 'This customer would change the tax on this sale. To use them, cancel the payment and change the customer in the cart, or start a new order.';
39
+ /** The sale's tax context and, with `taxContextFor`, the address it matched (#722). */
40
+ type SaleTax = { taxContext: TaxContext; location?: woocommerceTax.ResolvedTaxLocation };
35
41
  // The start of the message addOne sets when a terminal reference is dropped; a later tender change keeps it.
36
42
  const REFERENCE_DROPPED = "The terminal's payment reference couldn't be kept";
37
43
  /**
@@ -80,9 +86,22 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
80
86
  isStored?: (posOrder: PosOrder) => Promise<boolean>;
81
87
  /** Tests only: overrides HUNG_SAVE_CHECK_MS, so a test can shrink the hung-save poll's interval. */
82
88
  hungSaveCheckMs?: number;
89
+ /**
90
+ * #722: the tax context for a customer's address (`saleTaxContexts(settings)`, memoized). Each new sale is taxed for its
91
+ * customer, and `setCustomer` re-taxes a cart whose new customer moves the matched rates; tender and receipt keep theirs.
92
+ * Without it, every sale is taxed by `useTax()`.
93
+ */
94
+ taxContextFor?: (customer: CustomerSummary | null) => SaleTaxContext;
83
95
  }) {
84
96
  const taxContext = useTax();
85
- const madeWith = useRef({ taxContext, currency: settings.currency });
97
+ // The store's context and the settings the sale started with, for the idle reset; the sale's own context is `taxNow`.
98
+ const madeWith = useRef({ taxContext, currency: settings.currency, taxContextFor: opts.taxContextFor });
99
+ function contextFor(customer: CustomerSummary | null): SaleTax {
100
+ return opts.taxContextFor ? opts.taxContextFor(customer) : { taxContext };
101
+ }
102
+ // The live builder's tax context, the store's or its customer's, and the address it matched (#722), from one
103
+ // `taxContextFor` call: a newer function mid-sale never changes the address the sale's lines were taxed on.
104
+ const taxNow = useRef<SaleTax>({ taxContext });
86
105
  // The default customer for a new sale, unless the server would refuse it: then the sale starts on guest.
87
106
  function defaulted(): CustomerSummary | null {
88
107
  const customer = opts.defaultCustomer ?? null;
@@ -91,8 +110,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
91
110
  const defaultKey = opts.defaultCustomer ? JSON.stringify([opts.defaultCustomer.id, opts.defaultCustomer.name, opts.defaultCustomer.email]) : '';
92
111
  const defaultSeen = useRef(defaultKey);
93
112
  const [rendered, setBuilder] = useState(() => {
94
- const first = createOrderBuilder({ currency: settings.currency, taxContext });
95
113
  const customer = defaulted();
114
+ taxNow.current = contextFor(customer);
115
+ const first = createOrderBuilder({ currency: settings.currency, taxContext: taxNow.current.taxContext });
96
116
  if (customer) first.setCustomer(customer);
97
117
  return first;
98
118
  });
@@ -152,12 +172,59 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
152
172
  stageNow.current = stage;
153
173
  /** True, with SALE_SAVING shown, from complete()'s entry (inFlight) through a pending retry: the sale can't change. */
154
174
  function locked() {
155
- const active = !!(inFlight.current || pending.current);
175
+ const active = busy();
156
176
  if (active) setError(SALE_SAVING);
157
177
  return active;
158
178
  }
179
+ /** locked() without its error. */
180
+ function busy() { return !!(inFlight.current || pending.current); }
181
+ // TallyUI#710: the coupon re-price in flight (at most one), the count of coupon changes that discards its result,
182
+ // and the order snapshot a transient refusal or a throw stopped it on, with that reason.
183
+ const repricing = useRef<Promise<string | null> | null>(null);
184
+ const [couponsRepricing, setCouponsRepricing] = useState(false);
185
+ const generation = useRef(0);
186
+ const stopped = useRef<{ order: Order; reason: string } | null>(null);
187
+ /** Prices the accepted codes again, as resume() checks them, on the live builder; resolves to the error it set, or null. */
188
+ function reprice(): Promise<string | null> {
189
+ if (repricing.current) return repricing.current;
190
+ const b = builderNow.current, codes = appliedWith.current!, at = generation.current;
191
+ let asked = b.getSnapshot();
192
+ // A transient refusal or a throw stops the re-price, changing nothing; the effect skips the snapshot it stopped on.
193
+ const stop = (reason: string) => {
194
+ stopped.current = { order: asked, reason };
195
+ if (builderNow.current === b && generation.current === at) setError(reason);
196
+ return reason;
197
+ };
198
+ const run = (async () => {
199
+ try {
200
+ const kept = new Map<string, unknown>(), messages: string[] = [];
201
+ for (const code of [...applied.current.keys()]) {
202
+ asked = b.getSnapshot();
203
+ const result = await codes.find(code, discountState(asked, kept));
204
+ if ('refusal' in result && result.transient) return stop(result.refusal);
205
+ const reason = 'refusal' in result ? result.refusal : codes.check(code, result.found, discountState(b.getSnapshot(), kept));
206
+ if (reason === null) kept.set(code, (result as { found: unknown }).found);
207
+ else messages.push(`Coupon ${code} was removed: ${reason}.`);
208
+ }
209
+ if (builderNow.current !== b || generation.current !== at) return null;
210
+ asked = b.getSnapshot();
211
+ codes.apply(b, discountState(asked, kept));
212
+ applied.current = kept;
213
+ if (!kept.size) appliedWith.current = null;
214
+ const message = messages.length ? messages.join(' ') : null;
215
+ // A refusal only a re-price could have set goes once the codes are priced.
216
+ setError((current) => message ?? (current === COUPONS_REPRICING || current === stopped.current?.reason ? null : current));
217
+ return message;
218
+ } catch (error) { return stop(error instanceof Error ? error.message : String(error)); }
219
+ })().finally(() => { repricing.current = null; setCouponsRepricing(false); });
220
+ repricing.current = run;
221
+ setCouponsRepricing(true);
222
+ return run;
223
+ }
224
+ /** startTender's and complete()'s check: the live order's coupon prices are stale or being priced again. */
225
+ function couponsUnpriced() { return !!(builderNow.current.getSnapshot().couponPricesStale || repricing.current); }
159
226
  // newSale()'s body (see its doc comment for the guards): `newSale()` is `resetSale()`, on the default customer.
160
- function resetSale(customer: CustomerSummary | null = defaulted(), restored?: OrderBuilder) {
227
+ function resetSale(customer: CustomerSummary | null = defaulted(), restored?: OrderBuilder, restoredTax?: SaleTax) {
161
228
  if (inFlight.current && !pending.current) return setError(SALE_SAVING);
162
229
  if (pending.current && confirmed.current !== pending.current) {
163
230
  if (inFlight.current) checkStored(pending.current);
@@ -168,12 +235,15 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
168
235
  tenderSession.current = null;
169
236
  droppedReferences.current.clear();
170
237
  setSaving(false);
171
- madeWith.current = { taxContext, currency: settings.currency };
172
- const next = restored ?? createOrderBuilder({ currency: settings.currency, taxContext });
238
+ madeWith.current = { taxContext, currency: settings.currency, taxContextFor: opts.taxContextFor };
239
+ const tax = restoredTax ?? contextFor(customer);
240
+ const next = restored ?? createOrderBuilder({ currency: settings.currency, taxContext: tax.taxContext });
173
241
  if (customer !== null) next.setCustomer(customer);
174
242
  builderNow.current = next;
243
+ taxNow.current = tax;
175
244
  applied.current.clear();
176
245
  appliedWith.current = null;
246
+ generation.current++;
177
247
  setBuilder(next);
178
248
  setOrder(next.getSnapshot());
179
249
  // Live at once, so a resume() in the same tick (switchSale) sees the cart before the next render.
@@ -185,6 +255,12 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
185
255
  const subscription = rendered.order$.subscribe(setOrder);
186
256
  return () => subscription.unsubscribe();
187
257
  }, [rendered]);
258
+ // TallyUI#710: a rendered order whose store-priced coupons went stale prices them again, one re-price at a time. Checked
259
+ // on every render, so it runs again when one ends (the sale may have changed meanwhile), never on a snapshot one stopped on.
260
+ useEffect(() => {
261
+ if (order.couponPricesStale && appliedWith.current && applied.current.size > 0 && !repricing.current
262
+ && stageNow.current.kind !== 'receipt' && !busy() && stopped.current?.order !== order) void reprice();
263
+ });
188
264
  // New tax settings or currency wait until the sale is idle (an empty cart), then start a new sale keeping its customer:
189
265
  // a sale in progress (lines, tender or receipt) finishes on the settings it started with (a money rule).
190
266
  const idle = stage.kind === 'cart' && !order.lineItems.length && !order.fees?.length && !order.shipping?.length;
@@ -196,8 +272,38 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
196
272
  const liveIdle = stageNow.current.kind === 'cart' && !live.lineItems.length && !live.fees?.length && !live.shipping?.length && !inFlight.current && !pending.current;
197
273
  const newDefault = defaultSeen.current !== defaultKey;
198
274
  defaultSeen.current = defaultKey;
199
- if (liveIdle && (newDefault || madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency)) resetSale(newDefault ? undefined : live.customer ?? null);
275
+ if (liveIdle && (newDefault || madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency
276
+ || madeWith.current.taxContextFor !== opts.taxContextFor)) resetSale(newDefault ? undefined : live.customer ?? null);
200
277
  });
278
+ /**
279
+ * #722: the cart rebuilt on `next`, its customer's context, as resume() restores a draft: the order id, lines, discounts,
280
+ * fees, shipping and note are kept, line taxes re-derived from the new rates, and the applied codes put back (store-priced
281
+ * ones go stale and price again, as the basis has the customer). `applied`, the error and the stage are kept.
282
+ */
283
+ function retax(customer: CustomerSummary | null, next: SaleTax) {
284
+ const snapshot = { ...builderNow.current.getSnapshot(), customer };
285
+ const rebuilt = restoreOrderDraft(snapshot, { currency: snapshot.currency, taxContext: next.taxContext });
286
+ if (appliedWith.current && applied.current.size) appliedWith.current.apply(rebuilt, discountState(rebuilt.getSnapshot(), applied.current));
287
+ builderNow.current = rebuilt;
288
+ taxNow.current = next;
289
+ setBuilder(rebuilt);
290
+ setOrder(rebuilt.getSnapshot());
291
+ }
292
+ /**
293
+ * #722, v2's rule: a cart is re-taxed for `customer` when that customer moves its rates and no money is live (tender,
294
+ * receipt, a paid or moving leg finish on their rates). setCustomer's and cancelTender's check; true when it re-taxed.
295
+ */
296
+ function retaxFor(customer: CustomerSummary | null): boolean {
297
+ const next = opts.taxContextFor?.(customer);
298
+ const { payments } = builderNow.current.getSnapshot();
299
+ if (!next || next.taxContext === taxNow.current.taxContext || stageNow.current.kind !== 'cart' || busy()
300
+ || capturedMinor(payments) !== 0 || payments.some(isInMotion)) return false;
301
+ retax(customer, next);
302
+ return true;
303
+ }
304
+ const liveCustomer = order.customer, taxContextFor = opts.taxContextFor;
305
+ const taxLocation = useMemo<SaleTaxLocation | undefined>(() => taxContextFor
306
+ ? { ...taxContextFor(liveCustomer).location, hasCustomer: liveCustomer !== null } : undefined, [liveCustomer, taxContextFor]);
201
307
  // A screen that unmounts (medusapos: Sign out) mid-save must still leave a trace of the loss.
202
308
  useEffect(() => () => {
203
309
  clearHungSaveTimer();
@@ -307,6 +413,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
307
413
 
308
414
  const result = {
309
415
  order, stage, error, idle,
416
+ /** #722: the address the sale's customer is taxed by (WooCommerce's `tax_based_on`), for a "Tax based on" panel; undefined without `taxContextFor`. */
417
+ taxLocation,
310
418
  /** The store's capabilities as passed in: a component offers fees, shipping and custom lines
311
419
  * only when `orderCreate >= 5`, and their tax status and class only as `lineTax` allows. */
312
420
  capabilities: opts.capabilities,
@@ -344,6 +452,12 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
344
452
  }
345
453
  },
346
454
  setQuantity(lineId: string, quantity: number) { if (!locked()) builderNow.current.updateQuantity(lineId, quantity); },
455
+ /** v2's cart Split: a line of quantity N becomes N lines of 1. Returns the refusal to show (SPLIT_FIXED_DISCOUNT), or null. */
456
+ splitLine(lineId: string): string | null {
457
+ if (locked()) return SALE_SAVING;
458
+ try { builderNow.current.splitLine(lineId); return null; }
459
+ catch (error) { if (error instanceof RangeError) return error.message; throw error; }
460
+ },
347
461
  /** ADR-075: adds a fee; returns its id or the builder's refusal. */
348
462
  addFee(input: ChargeInput): { id: string } | string {
349
463
  if (locked()) return SALE_SAVING;
@@ -437,6 +551,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
437
551
  catch (error) { if (error instanceof Error) return error.message; throw error; }
438
552
  applied.current.set(normalized, result.found);
439
553
  appliedWith.current = codes;
554
+ generation.current++;
440
555
  setError(null);
441
556
  return null;
442
557
  },
@@ -448,8 +563,17 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
448
563
  const remaining = new Map(applied.current); remaining.delete(normalized);
449
564
  appliedWith.current!.apply(builderNow.current, discountState(builderNow.current.getSnapshot(), remaining));
450
565
  applied.current.delete(normalized);
566
+ generation.current++;
451
567
  return null;
452
568
  },
569
+ /** TallyUI#710: true while the sale prices its store-priced coupons again; tender is refused with COUPONS_REPRICING meanwhile. */
570
+ couponsRepricing,
571
+ /** Prices the sale's coupons again now, as Retry after a transient refusal; resolves to the refusal or error it set, or null. */
572
+ async repriceCoupons(): Promise<string | null> {
573
+ if (locked()) return SALE_SAVING;
574
+ if (!appliedWith.current || !applied.current.size || stageNow.current.kind === 'receipt') return null;
575
+ return reprice();
576
+ },
453
577
  /** The sale's note, kept on the open sale (parked and resumed with it, cleared by newSale) and sent as order.create v7's note (ADR-083). */
454
578
  setNote(note: string) { if (!locked()) builderNow.current.setNote(note); },
455
579
  /** the picked customer reaches the server as order.create v3's customer.customerId */
@@ -458,8 +582,15 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
458
582
  // A searched customer's email or id the server would refuse never reaches the sale; the customer stays as it was.
459
583
  const refused = customer && customerRefusal(customer);
460
584
  if (refused) return setError(refused);
461
- builderNow.current.setCustomer(customer);
462
- setError((current) => current !== null && CUSTOMER_REFUSALS.includes(current) ? null : current); // any other error stays
585
+ // #722: the sale's rates and its customer always agree, so a customer with other rates is refused once they are fixed.
586
+ if (!retaxFor(customer)) {
587
+ const same = opts.taxContextFor?.(customer);
588
+ if (same && same.taxContext !== taxNow.current.taxContext) return setError(CUSTOMER_RETAX_REFUSED);
589
+ // Same rates: the address now matched is this customer's (a guest's is the base), so finalize never names one they lack.
590
+ if (same) taxNow.current = same;
591
+ builderNow.current.setCustomer(customer);
592
+ }
593
+ setError((current) => current !== null && (CUSTOMER_REFUSALS.includes(current) || current === CUSTOMER_RETAX_REFUSED) ? null : current); // any other error stays
463
594
  },
464
595
  /**
465
596
  * Pins `options.session` for this tender when given, else the rendered `session` option. Pass the
@@ -470,6 +601,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
470
601
  if (locked()) return;
471
602
  const current = builderNow.current.getSnapshot();
472
603
  if (!current.lineItems.length) return;
604
+ if (couponsUnpriced()) return setError(COUPONS_REPRICING);
473
605
  tenderSession.current ??= { session: options?.session ?? opts.session }; // a repeat call mid-tender keeps the pin
474
606
  setTender(method === 'external' ? { method, amountMinor: current.totalMinor } : null);
475
607
  setStage({ kind: 'tender', method });
@@ -515,7 +647,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
515
647
  if (locked()) return;
516
648
  setTender(null);
517
649
  tenderSession.current = null;
518
- setStage({ kind: 'cart' });
650
+ stageNow.current = { kind: 'cart' };
651
+ setStage(stageNow.current);
652
+ // #722: a customer set during tender is taxed for once the cart is back, unless money was taken.
653
+ retaxFor(builderNow.current.getSnapshot().customer ?? null);
519
654
  },
520
655
  /**
521
656
  * Finalizes the tender, stamps the session (see `session`), hands the order to `onSaleCompleted`,
@@ -539,6 +674,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
539
674
  setSaving(true);
540
675
  const snapshot = builderNow.current.getSnapshot();
541
676
  if (snapshot.payments.some(isInMotion)) { setSaving(false); setError(PAYMENT_IN_MOTION); return; }
677
+ if (couponsUnpriced()) { setSaving(false); setError(COUPONS_REPRICING); return; }
542
678
  // Failed and voided legs stay on the screen's ledger but are never sent: only captured money is the sale's.
543
679
  const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid) };
544
680
  const localWarnings = current.payments.filter((payment) => droppedReferences.current.has(payment.id))
@@ -546,7 +682,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
546
682
  let posOrder: PosOrder;
547
683
  try {
548
684
  posOrder = finalizeOrder(current, { registerId: opts.registerId, cashierRef: opts.cashierRef, capabilities: opts.capabilities,
549
- ...(localWarnings.length ? { localWarnings } : {}) });
685
+ ...(localWarnings.length ? { localWarnings } : {}),
686
+ // #722: the address the sale's lines were taxed on, kept with their context (taxNow), never a newer function's.
687
+ ...(taxNow.current.location ? { taxLocation: taxNow.current.location } : {}) });
550
688
  } catch (error) {
551
689
  setSaving(false);
552
690
  setError((error as Error).message);
@@ -620,7 +758,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
620
758
  if (!doc) return 'That parked sale is no longer there';
621
759
  const saved: Order = JSON.parse(doc.toJSON().data);
622
760
  if (saved.currency.toUpperCase() !== settings.currency.toUpperCase()) return 'That parked sale is in another currency';
623
- const builder = restoreOrderDraft(saved, { currency: settings.currency, taxContext });
761
+ // Taxed for the customer the draft restores (a refused one isn't).
762
+ const restoredTax = contextFor(saved.customer && !customerRefusal(saved.customer) ? saved.customer : null);
763
+ const builder = restoreOrderDraft(saved, { currency: settings.currency, taxContext: restoredTax.taxContext });
624
764
  let n = 0;
625
765
  // A draft whose legs took money keeps the prices it was paid against (u19).
626
766
  if (opts.currentPrice && !options?.keepParkedPrices && capturedMinor(saved.payments ?? []) === 0) {
@@ -658,10 +798,11 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
658
798
  await writeOrderDraft(opts.drafts, saved);
659
799
  return 'The sale changed while it was being resumed; resume it again';
660
800
  }
661
- resetSale(null, builder);
801
+ resetSale(null, builder, restoredTax);
662
802
  if (builderNow.current === builder) {
663
803
  applied.current = kept;
664
804
  appliedWith.current = kept.size ? codes : null;
805
+ generation.current++;
665
806
  }
666
807
  if (messages.length) setError(messages.join(' '));
667
808
  return null;
@@ -0,0 +1,44 @@
1
+ import type { VariantOptionGroup, VariantSummary } from '@tallyui/core';
2
+
3
+ /** Picks so far, group name → value. */
4
+ export type OptionPicks = Readonly<Record<string, string>>;
5
+
6
+ const has = (options: Record<string, string>, name: string) => Object.prototype.hasOwnProperty.call(options, name);
7
+
8
+ /** A variant fits the picks when, for every picked group, it has no value (an "Any" group) or the same value.
9
+ * A variant with `options` undefined fits only empty picks. */
10
+ export function variantFits(variant: VariantSummary, picks: OptionPicks): boolean {
11
+ const { options } = variant;
12
+ if (options === undefined) return Object.keys(picks).length === 0;
13
+ return Object.entries(picks).every(([name, value]) => !has(options, name) || options[name] === value);
14
+ }
15
+
16
+ /**
17
+ * The variant for complete picks (every group in `groups` picked): the first fitting variant in the given
18
+ * order, preferring one whose own value matches over an "Any" one; undefined when none fits or picks are incomplete.
19
+ * The variant with the most groups set to exactly the picked value wins; a tie goes to the first in order.
20
+ */
21
+ export function matchVariant(variants: readonly VariantSummary[], groups: readonly VariantOptionGroup[],
22
+ picks: OptionPicks): VariantSummary | undefined {
23
+ if (!groups.every(({ name }) => has(picks, name))) return undefined;
24
+ let best: VariantSummary | undefined;
25
+ let bestScore = -1;
26
+ for (const variant of variants) {
27
+ if (!variantFits(variant, picks)) continue;
28
+ const score = groups.filter(({ name }) => variant.options?.[name] === picks[name]).length;
29
+ if (score > bestScore) { best = variant; bestScore = score; }
30
+ }
31
+ return best;
32
+ }
33
+
34
+ /** Per group, the values no fitting variant allows given the OTHER groups' picks (v2 getDisabledVariationOptions). */
35
+ export function disabledOptions(variants: readonly VariantSummary[], groups: readonly VariantOptionGroup[],
36
+ picks: OptionPicks): Record<string, Set<string>> {
37
+ const disabled: Record<string, Set<string>> = {};
38
+ for (const { name, values } of groups) {
39
+ const others = Object.fromEntries(Object.entries(picks).filter(([group]) => group !== name));
40
+ const fitting = variants.filter((variant) => variantFits(variant, others));
41
+ disabled[name] = new Set(values.filter((value) => !fitting.some((variant) => variantFits(variant, { [name]: value }))));
42
+ }
43
+ return disabled;
44
+ }