@tallyui/pos 3.17.0 → 3.19.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 (72) hide show
  1. package/dist/index.d.ts +3214 -1722
  2. package/dist/index.js +3900 -673
  3. package/package.json +6 -6
  4. package/src/currency/currency-provider.tsx +11 -4
  5. package/src/currency/format-money-with.ts +45 -0
  6. package/src/currency/index.ts +1 -0
  7. package/src/customer-display/display-client.ts +341 -0
  8. package/src/customer-display/index.ts +20 -0
  9. package/src/customer-display/sale-display.ts +115 -0
  10. package/src/customer-display/snapshot-fallback.ts +138 -0
  11. package/src/customer-display/till-display-service.ts +304 -0
  12. package/src/customer-display/till-pairing.ts +177 -0
  13. package/src/customer-display/use-display-client.ts +25 -0
  14. package/src/customer-display/use-sale-display.ts +28 -0
  15. package/src/customer-display/use-till-pairing.ts +35 -0
  16. package/src/customer-display/webrtc/index.ts +5 -0
  17. package/src/customer-display/webrtc/peer-link.ts +222 -0
  18. package/src/index.ts +37 -11
  19. package/src/order/index.ts +2 -1
  20. package/src/order/order-builder.ts +104 -16
  21. package/src/order/types.ts +10 -4
  22. package/src/payment-driver/index.ts +1 -1
  23. package/src/payment-driver/registry.ts +23 -0
  24. package/src/pos-order/__fixtures__/order-create-v8.json +117 -0
  25. package/src/pos-order/command.ts +19 -4
  26. package/src/pos-order/finalize.ts +30 -2
  27. package/src/pos-order/schema.ts +16 -5
  28. package/src/pos-order/types.ts +7 -4
  29. package/src/receipt/reprint.ts +3 -10
  30. package/src/receipt/woo-gross.ts +16 -0
  31. package/src/receipt-template/index.ts +8 -0
  32. package/src/receipt-template/render-store-template.ts +51 -0
  33. package/src/receipt-template/wcpos/build.ts +320 -0
  34. package/src/receipt-template/wcpos/context.ts +29 -0
  35. package/src/receipt-template/wcpos/format.ts +153 -0
  36. package/src/receipt-template/wcpos/from-orders.ts +203 -0
  37. package/src/receipt-template/wcpos/index.ts +11 -0
  38. package/src/receipt-template/wcpos/money.ts +42 -0
  39. package/src/receipt-template/wcpos/types.ts +350 -0
  40. package/src/register/expected.ts +60 -0
  41. package/src/register/index.ts +2 -2
  42. package/src/register/use-register-session.ts +8 -4
  43. package/src/sale/discount-codes.ts +7 -2
  44. package/src/sale/index.ts +9 -2
  45. package/src/sale/order-filters-query.ts +59 -0
  46. package/src/sale/store-priced-discount-codes.ts +52 -0
  47. package/src/sale/use-sale.ts +185 -21
  48. package/src/sale/variant-match.ts +44 -0
  49. package/src/scanner/camera-scan.ts +113 -0
  50. package/src/scanner/capabilities.ts +22 -0
  51. package/src/scanner/chooser-cancel.ts +8 -0
  52. package/src/scanner/device-identity.ts +84 -0
  53. package/src/scanner/device-scanner.ts +62 -0
  54. package/src/scanner/hid-pos-decoder.ts +60 -0
  55. package/src/scanner/hid-scanner.ts +171 -0
  56. package/src/scanner/index.ts +27 -0
  57. package/src/scanner/scan-dedup.ts +48 -0
  58. package/src/scanner/scan-events.ts +75 -0
  59. package/src/scanner/scan-hub-context.tsx +124 -0
  60. package/src/scanner/scan-session.ts +4 -0
  61. package/src/scanner/scanner-profiles.ts +96 -0
  62. package/src/scanner/serial-line-decoder.ts +58 -0
  63. package/src/scanner/serial-scanner.ts +227 -0
  64. package/src/scanner/use-barcode-scanner.ts +23 -5
  65. package/src/scanner/use-camera-scan.ts +57 -0
  66. package/src/scanner/wedge-detector.ts +28 -6
  67. package/src/tax/index.ts +6 -0
  68. package/src/tax/location-rates.ts +46 -0
  69. package/src/tax/sale-tax-contexts.ts +40 -0
  70. package/src/tax/tax-context.ts +37 -0
  71. package/src/tax/tax-derivation.ts +99 -0
  72. 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
  /**
@@ -47,6 +53,14 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
47
53
  registerId: string; cashierRef: string; capabilities?: ServerCapabilities;
48
54
  /** The platform's discount codes (ADR-077 amendment 3), e.g. woocommerceDiscountCodes.createDiscountCodes(source); without them, applyCoupon refuses with COUPONS_UNSUPPORTED. */
49
55
  discountCodes?: SaleDiscountCodes<any>;
56
+ /**
57
+ * Put on every new sale, as v2's store setting `default_customer` (or the cashier, `default_customer_is_cashier`)
58
+ * is on every new cart: the first sale and each one after complete, discard, park, newSale or a switch to New,
59
+ * never a resumed one. The app resolves which customer. A cashier's change, Guest included, stays on that sale.
60
+ * A change applies at once to an idle cart, else to the next new sale. One `setCustomer` would refuse is skipped
61
+ * (the sale starts on guest, with no error).
62
+ */
63
+ defaultCustomer?: CustomerSummary | null;
50
64
  /** Where `park()` keeps parked carts; create it with `orderDraftSchema` */
51
65
  drafts?: RxCollection;
52
66
  /**
@@ -72,10 +86,36 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
72
86
  isStored?: (posOrder: PosOrder) => Promise<boolean>;
73
87
  /** Tests only: overrides HUNG_SAVE_CHECK_MS, so a test can shrink the hung-save poll's interval. */
74
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;
75
95
  }) {
76
96
  const taxContext = useTax();
77
- const madeWith = useRef({ taxContext, currency: settings.currency });
78
- const [rendered, setBuilder] = useState(() => createOrderBuilder({ currency: settings.currency, taxContext }));
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 });
105
+ // The default customer for a new sale, unless the server would refuse it: then the sale starts on guest.
106
+ function defaulted(): CustomerSummary | null {
107
+ const customer = opts.defaultCustomer ?? null;
108
+ return customer && !customerRefusal(customer) ? customer : null;
109
+ }
110
+ const defaultKey = opts.defaultCustomer ? JSON.stringify([opts.defaultCustomer.id, opts.defaultCustomer.name, opts.defaultCustomer.email]) : '';
111
+ const defaultSeen = useRef(defaultKey);
112
+ const [rendered, setBuilder] = useState(() => {
113
+ const customer = defaulted();
114
+ taxNow.current = contextFor(customer);
115
+ const first = createOrderBuilder({ currency: settings.currency, taxContext: taxNow.current.taxContext });
116
+ if (customer) first.setCustomer(customer);
117
+ return first;
118
+ });
79
119
  // The live builder, which every mutator reads (#301): newSale() sets it before setBuilder(next) renders, so a
80
120
  // call from an older render never reaches a discarded builder. The state only moves the `order` subscription.
81
121
  const builderNow = useRef(rendered);
@@ -132,12 +172,59 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
132
172
  stageNow.current = stage;
133
173
  /** True, with SALE_SAVING shown, from complete()'s entry (inFlight) through a pending retry: the sale can't change. */
134
174
  function locked() {
135
- const active = !!(inFlight.current || pending.current);
175
+ const active = busy();
136
176
  if (active) setError(SALE_SAVING);
137
177
  return active;
138
178
  }
139
- // newSale()'s body (see its doc comment for the guards): `newSale()` is `resetSale(null)`.
140
- function resetSale(customer: CustomerSummary | null, restored?: OrderBuilder) {
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); }
226
+ // newSale()'s body (see its doc comment for the guards): `newSale()` is `resetSale()`, on the default customer.
227
+ function resetSale(customer: CustomerSummary | null = defaulted(), restored?: OrderBuilder, restoredTax?: SaleTax) {
141
228
  if (inFlight.current && !pending.current) return setError(SALE_SAVING);
142
229
  if (pending.current && confirmed.current !== pending.current) {
143
230
  if (inFlight.current) checkStored(pending.current);
@@ -148,12 +235,15 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
148
235
  tenderSession.current = null;
149
236
  droppedReferences.current.clear();
150
237
  setSaving(false);
151
- madeWith.current = { taxContext, currency: settings.currency };
152
- 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 });
153
241
  if (customer !== null) next.setCustomer(customer);
154
242
  builderNow.current = next;
243
+ taxNow.current = tax;
155
244
  applied.current.clear();
156
245
  appliedWith.current = null;
246
+ generation.current++;
157
247
  setBuilder(next);
158
248
  setOrder(next.getSnapshot());
159
249
  // Live at once, so a resume() in the same tick (switchSale) sees the cart before the next render.
@@ -165,16 +255,55 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
165
255
  const subscription = rendered.order$.subscribe(setOrder);
166
256
  return () => subscription.unsubscribe();
167
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
+ });
168
264
  // New tax settings or currency wait until the sale is idle (an empty cart), then start a new sale keeping its customer:
169
265
  // a sale in progress (lines, tender or receipt) finishes on the settings it started with (a money rule).
170
266
  const idle = stage.kind === 'cart' && !order.lineItems.length && !order.fees?.length && !order.shipping?.length;
171
267
  // A layout effect, on live idleness (#301): it runs inside the settings' commit, before any tap can be handled, and
172
268
  // the rendered `idle` would miss a line added since this render (it would then be dropped with the old builder).
269
+ // A new default customer starts a new sale on it at once when idle, as v2 seeds its new cart again; never held pending.
173
270
  useLayoutEffect(() => {
174
271
  const live = builderNow.current.getSnapshot();
175
272
  const liveIdle = stageNow.current.kind === 'cart' && !live.lineItems.length && !live.fees?.length && !live.shipping?.length && !inFlight.current && !pending.current;
176
- if (liveIdle && (madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency)) resetSale(live.customer ?? null);
273
+ const newDefault = defaultSeen.current !== defaultKey;
274
+ defaultSeen.current = defaultKey;
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);
177
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]);
178
307
  // A screen that unmounts (medusapos: Sign out) mid-save must still leave a trace of the loss.
179
308
  useEffect(() => () => {
180
309
  clearHungSaveTimer();
@@ -284,6 +413,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
284
413
 
285
414
  const result = {
286
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,
287
418
  /** The store's capabilities as passed in: a component offers fees, shipping and custom lines
288
419
  * only when `orderCreate >= 5`, and their tax status and class only as `lineTax` allows. */
289
420
  capabilities: opts.capabilities,
@@ -321,6 +452,12 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
321
452
  }
322
453
  },
323
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
+ },
324
461
  /** ADR-075: adds a fee; returns its id or the builder's refusal. */
325
462
  addFee(input: ChargeInput): { id: string } | string {
326
463
  if (locked()) return SALE_SAVING;
@@ -414,6 +551,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
414
551
  catch (error) { if (error instanceof Error) return error.message; throw error; }
415
552
  applied.current.set(normalized, result.found);
416
553
  appliedWith.current = codes;
554
+ generation.current++;
417
555
  setError(null);
418
556
  return null;
419
557
  },
@@ -425,8 +563,17 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
425
563
  const remaining = new Map(applied.current); remaining.delete(normalized);
426
564
  appliedWith.current!.apply(builderNow.current, discountState(builderNow.current.getSnapshot(), remaining));
427
565
  applied.current.delete(normalized);
566
+ generation.current++;
428
567
  return null;
429
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
+ },
430
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). */
431
578
  setNote(note: string) { if (!locked()) builderNow.current.setNote(note); },
432
579
  /** the picked customer reaches the server as order.create v3's customer.customerId */
@@ -435,8 +582,15 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
435
582
  // A searched customer's email or id the server would refuse never reaches the sale; the customer stays as it was.
436
583
  const refused = customer && customerRefusal(customer);
437
584
  if (refused) return setError(refused);
438
- builderNow.current.setCustomer(customer);
439
- 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
440
594
  },
441
595
  /**
442
596
  * Pins `options.session` for this tender when given, else the rendered `session` option. Pass the
@@ -447,6 +601,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
447
601
  if (locked()) return;
448
602
  const current = builderNow.current.getSnapshot();
449
603
  if (!current.lineItems.length) return;
604
+ if (couponsUnpriced()) return setError(COUPONS_REPRICING);
450
605
  tenderSession.current ??= { session: options?.session ?? opts.session }; // a repeat call mid-tender keeps the pin
451
606
  setTender(method === 'external' ? { method, amountMinor: current.totalMinor } : null);
452
607
  setStage({ kind: 'tender', method });
@@ -492,7 +647,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
492
647
  if (locked()) return;
493
648
  setTender(null);
494
649
  tenderSession.current = null;
495
- 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);
496
654
  },
497
655
  /**
498
656
  * Finalizes the tender, stamps the session (see `session`), hands the order to `onSaleCompleted`,
@@ -516,6 +674,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
516
674
  setSaving(true);
517
675
  const snapshot = builderNow.current.getSnapshot();
518
676
  if (snapshot.payments.some(isInMotion)) { setSaving(false); setError(PAYMENT_IN_MOTION); return; }
677
+ if (couponsUnpriced()) { setSaving(false); setError(COUPONS_REPRICING); return; }
519
678
  // Failed and voided legs stay on the screen's ledger but are never sent: only captured money is the sale's.
520
679
  const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid) };
521
680
  const localWarnings = current.payments.filter((payment) => droppedReferences.current.has(payment.id))
@@ -523,7 +682,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
523
682
  let posOrder: PosOrder;
524
683
  try {
525
684
  posOrder = finalizeOrder(current, { registerId: opts.registerId, cashierRef: opts.cashierRef, capabilities: opts.capabilities,
526
- ...(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 } : {}) });
527
688
  } catch (error) {
528
689
  setSaving(false);
529
690
  setError((error as Error).message);
@@ -572,7 +733,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
572
733
  * clears the screen, never the record (the Front desk, 2026-09-25). `newSale()` never deletes,
573
734
  * updates or requeues `pos_orders` itself.
574
735
  */
575
- newSale() { resetSale(null); },
736
+ newSale() { resetSale(); },
576
737
  /** Parks the cart in `drafts`; resolves to a refusal message, or null once parked. */
577
738
  async park(): Promise<string | null> {
578
739
  if (locked()) return SALE_SAVING;
@@ -583,7 +744,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
583
744
  if (!snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length) return 'There is nothing to park';
584
745
  await writeOrderDraft(opts.drafts, snapshot);
585
746
  if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
586
- resetSale(null);
747
+ resetSale();
587
748
  return null;
588
749
  },
589
750
  /** Resumes a draft into an empty cart; resolves to a refusal message, or null once resumed. */
@@ -597,7 +758,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
597
758
  if (!doc) return 'That parked sale is no longer there';
598
759
  const saved: Order = JSON.parse(doc.toJSON().data);
599
760
  if (saved.currency.toUpperCase() !== settings.currency.toUpperCase()) return 'That parked sale is in another currency';
600
- 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 });
601
764
  let n = 0;
602
765
  // A draft whose legs took money keeps the prices it was paid against (u19).
603
766
  if (opts.currentPrice && !options?.keepParkedPrices && capturedMinor(saved.payments ?? []) === 0) {
@@ -635,10 +798,11 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
635
798
  await writeOrderDraft(opts.drafts, saved);
636
799
  return 'The sale changed while it was being resumed; resume it again';
637
800
  }
638
- resetSale(null, builder);
801
+ resetSale(null, builder, restoredTax);
639
802
  if (builderNow.current === builder) {
640
803
  applied.current = kept;
641
804
  appliedWith.current = kept.size ? codes : null;
805
+ generation.current++;
642
806
  }
643
807
  if (messages.length) setError(messages.join(' '));
644
808
  return null;
@@ -662,7 +826,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
662
826
  await writeOrderDraft(opts.drafts, snapshot);
663
827
  if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
664
828
  }
665
- resetSale(null);
829
+ resetSale();
666
830
  return draftId === null ? null : result.resume(draftId);
667
831
  },
668
832
  /** Discards the current sale (nothing is parked) and starts an empty one; refused while saving, once a leg of an unfinished sale took or holds money, or in the tender stage. */
@@ -671,7 +835,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
671
835
  const { payments } = builderNow.current.getSnapshot();
672
836
  if (stageNow.current.kind !== 'receipt' && (capturedMinor(payments) > 0 || payments.some(isInMotion))) return SALE_PARTLY_PAID;
673
837
  if (stageNow.current.kind === 'tender') return SALE_IN_TENDER;
674
- resetSale(null);
838
+ resetSale();
675
839
  return null;
676
840
  },
677
841
  /**
@@ -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
+ }