@tallyui/pos 3.20.1 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/index.d.ts +1008 -111
  2. package/dist/index.js +3158 -907
  3. package/package.json +6 -6
  4. package/src/app-settings/app-settings.ts +77 -0
  5. package/src/app-settings/index.ts +2 -0
  6. package/src/currency/currency-provider.tsx +5 -7
  7. package/src/currency/index.ts +1 -1
  8. package/src/customer/customer-patch.ts +70 -0
  9. package/src/customer-display/display-client.ts +11 -17
  10. package/src/customer-display/display-link.ts +10 -5
  11. package/src/customer-display/index.ts +3 -1
  12. package/src/customer-display/protocol.ts +1 -1
  13. package/src/customer-display/sale-display.ts +6 -8
  14. package/src/customer-display/snapshot-fallback.ts +14 -1
  15. package/src/customer-display/till-device.ts +62 -0
  16. package/src/customer-display/till-display-service.ts +44 -42
  17. package/src/customer-display/till-pairing.ts +20 -23
  18. package/src/customer-display/use-customer-display.ts +2 -1
  19. package/src/customer-display/use-till-pairing.ts +4 -4
  20. package/src/index.ts +37 -18
  21. package/src/order/allocate-order-discount.ts +5 -17
  22. package/src/order/apportion.ts +29 -0
  23. package/src/order/from-store-order.ts +115 -0
  24. package/src/order/index.ts +1 -0
  25. package/src/order/order-builder.ts +239 -52
  26. package/src/order/order-drafts.ts +46 -6
  27. package/src/order/order-manager.ts +2 -1
  28. package/src/order/tax-ids.ts +27 -0
  29. package/src/order/types.ts +61 -5
  30. package/src/order/woocommerce-tax.ts +9 -0
  31. package/src/outbox/index.ts +1 -1
  32. package/src/outbox/order-outbox.ts +138 -43
  33. package/src/outbox/register-outbox.ts +4 -3
  34. package/src/outbox/retry-delay.ts +8 -0
  35. package/src/outbox/use-order-outbox.ts +8 -2
  36. package/src/pos-order/__fixtures__/order-create-v10.json +97 -0
  37. package/src/pos-order/__fixtures__/order-create-v11.json +90 -0
  38. package/src/pos-order/__fixtures__/order-create-v12.json +95 -0
  39. package/src/pos-order/__fixtures__/order-create-v9.json +89 -0
  40. package/src/pos-order/attention-handled.ts +24 -0
  41. package/src/pos-order/command.ts +132 -12
  42. package/src/pos-order/extras-delivery.ts +14 -0
  43. package/src/pos-order/finalize.ts +138 -29
  44. package/src/pos-order/index.ts +7 -3
  45. package/src/pos-order/money-divergence.ts +19 -0
  46. package/src/pos-order/needs-attention.ts +9 -1
  47. package/src/pos-order/refund-due.ts +35 -0
  48. package/src/pos-order/reopen.ts +96 -12
  49. package/src/pos-order/schema.ts +35 -10
  50. package/src/pos-order/till-payments.ts +4 -0
  51. package/src/pos-order/types.ts +45 -6
  52. package/src/print/escpos/__fixtures__/thermal-every-node.xml +33 -0
  53. package/src/print/escpos/commands.ts +79 -0
  54. package/src/print/escpos/drawer.ts +25 -0
  55. package/src/print/escpos/encode.ts +1 -0
  56. package/src/print/escpos/index.ts +6 -1
  57. package/src/print/escpos/network-sinks.ts +130 -0
  58. package/src/print/escpos/render-escpos.ts +155 -0
  59. package/src/print/escpos/transport.ts +2 -1
  60. package/src/print/index.ts +5 -2
  61. package/src/print/resolve-printer.ts +46 -0
  62. package/src/print/types.ts +1 -1
  63. package/src/product/index.ts +2 -0
  64. package/src/product/terms.ts +42 -0
  65. package/src/product/tile-fields.ts +27 -0
  66. package/src/receipt/build-receipt-data.ts +12 -7
  67. package/src/receipt/carried-rows.ts +29 -0
  68. package/src/receipt/index.ts +1 -0
  69. package/src/receipt/reprint.ts +14 -8
  70. package/src/receipt/types.ts +3 -1
  71. package/src/receipt-template/default-templates.ts +3 -0
  72. package/src/receipt-template/template-data.ts +3 -0
  73. package/src/receipt-template/wcpos/build.ts +1 -0
  74. package/src/receipt-template/wcpos/format.ts +2 -2
  75. package/src/receipt-template/wcpos/from-orders.ts +6 -2
  76. package/src/receipt-template/wcpos/types.ts +5 -1
  77. package/src/register/closure-document.ts +42 -4
  78. package/src/register/closure-rows.ts +3 -2
  79. package/src/register/document-labels.ts +25 -0
  80. package/src/register/expected.ts +49 -10
  81. package/src/register/index.ts +5 -5
  82. package/src/register/money.ts +23 -0
  83. package/src/register/register-adoption.ts +6 -5
  84. package/src/register/register-commands.ts +4 -3
  85. package/src/register/schemas.ts +11 -3
  86. package/src/register/session-store.ts +44 -23
  87. package/src/register/settled-figures.ts +5 -19
  88. package/src/register/use-register-session.ts +18 -19
  89. package/src/reopen/index.ts +3 -0
  90. package/src/reopen/reopen-entry.ts +48 -0
  91. package/src/reopen/reopen-store-order.ts +78 -0
  92. package/src/reopen/send-order-reopen.ts +61 -0
  93. package/src/reports/adapters.ts +15 -7
  94. package/src/reports/sales-figures.ts +15 -1
  95. package/src/reports/types.ts +2 -0
  96. package/src/sale/cart.ts +4 -2
  97. package/src/sale/index.ts +1 -1
  98. package/src/sale/open-sales.ts +3 -0
  99. package/src/sale/use-sale.ts +388 -83
  100. package/src/sale/woocommerce/coupon-refetch.ts +1 -0
  101. package/src/sale/woocommerce/coupon-source.ts +4 -4
  102. package/src/sale/woocommerce/coupons.ts +6 -0
  103. package/src/sale/woocommerce/discount-codes.ts +1 -6
  104. package/src/scanner/analyze-trace.ts +86 -0
  105. package/src/scanner/device-scanner.ts +57 -0
  106. package/src/scanner/hid-scanner.ts +14 -41
  107. package/src/scanner/index.ts +2 -0
  108. package/src/scanner/serial-scanner.ts +15 -42
  109. package/src/scanner/use-barcode-scanner.ts +107 -5
  110. package/src/scanner/wedge-detector.ts +33 -15
  111. package/src/tax/exact.ts +1 -13
  112. package/src/tax/taxed-lines.ts +26 -0
  113. package/src/tender/index.ts +6 -1
  114. package/src/tender/split-units.ts +109 -0
  115. package/src/tender/tender-figures.ts +114 -0
  116. package/src/tender/tender-state.ts +105 -17
  117. package/src/currency/format-money-with.ts +0 -45
@@ -4,6 +4,9 @@
4
4
  export interface WedgeSettings {
5
5
  /** Folded-average gap (ms) below which input latches as a scan. */
6
6
  threshold: number;
7
+ /** 'folded' (default): v2's folded average, latched for the rest of the burst. 'every': each gap must be under
8
+ * the threshold; a slower key drops the burst and starts a new one. */
9
+ gapRule?: 'folded' | 'every';
7
10
  /** Stripped only when it equals the first key. */
8
11
  prefix: string;
9
12
  /** Stripped only when it equals the last key. */
@@ -24,42 +27,53 @@ export interface WedgeState {
24
27
  lastTimeMs: number | null;
25
28
  /** Time of the first key of the current burst's stack. */
26
29
  startedAtMs: number | null;
30
+ /** Lowest finite folded average seen (v2); `createWedgeState` starts it at +Infinity. */
31
+ minAvgGapMs?: number;
27
32
  /** An Enter/Tab arrived during the burst — the signature of a scanner terminator. */
28
33
  sawTerminator: boolean;
29
34
  }
30
35
 
36
+ /** @deprecated Internal helper, not supported API; leaves the public entry at the next major. */
31
37
  export function createWedgeState(): WedgeState {
32
- return { avg: 0, detecting: false, stack: [], lastTimeMs: null, startedAtMs: null, sawTerminator: false };
38
+ return { avg: 0, detecting: false, stack: [], lastTimeMs: null, startedAtMs: null, minAvgGapMs: Number.POSITIVE_INFINITY, sawTerminator: false };
33
39
  }
34
40
 
35
41
  /** Fold one key, mutating and returning state. Kept bug-for-bug with v2:
36
42
  * only length-1 keys advance timing; the first gap is +Infinity; the average
37
43
  * folds as (avg + gap) / 2. Scanning latches below threshold for the burst;
38
- * a slow key outside a burst resets the average and restarts the stack. */
39
- export function foldWedgeKey(state: WedgeState, key: string, timeMs: number, threshold: number): WedgeState {
44
+ * a slow key outside a burst resets the average and restarts the stack;
45
+ * 'every' ends the burst on a slow gap.
46
+ * @deprecated Internal helper, not supported API; leaves the public entry at the next major. */
47
+ export function foldWedgeKey(state: WedgeState, key: string, timeMs: number, threshold: number, gapRule: 'folded' | 'every' = 'folded'): WedgeState {
40
48
  if (key.length !== 1) return state;
41
49
  let gap = Number.POSITIVE_INFINITY;
42
50
  if (state.lastTimeMs !== null) gap = timeMs - state.lastTimeMs;
43
51
  state.avg = state.avg === 0 ? gap : (state.avg + gap) / 2;
44
- if (state.detecting || state.avg < threshold) {
52
+ if (Number.isFinite(state.avg)) state.minAvgGapMs = Math.min(state.minAvgGapMs ?? Number.POSITIVE_INFINITY, state.avg);
53
+ if (gapRule === 'every' ? gap < threshold : state.detecting || state.avg < threshold) {
45
54
  state.detecting = true;
46
55
  state.stack.push(key);
47
56
  } else {
48
57
  state.avg = 0;
49
58
  state.stack = [key];
59
+ if (gapRule === 'every') {
60
+ state.detecting = false;
61
+ state.sawTerminator = false;
62
+ }
50
63
  }
51
64
  if (state.stack.length === 1) state.startedAtMs = timeMs;
52
65
  state.lastTimeMs = timeMs;
53
66
  return state;
54
67
  }
55
68
 
56
- /** Strip a configured prefix/suffix only when it equals the single key at
57
- * that edge of the stack — never as a substring. */
69
+ /** Match whole strings at the edges: prefix first, then suffix on the remainder.
70
+ * A one-character setting behaves as before.
71
+ * @deprecated Internal helper, not supported API; leaves the public entry at the next major. */
58
72
  export function stripBoundary(stack: string[], settings: WedgeSettings): string {
59
- const inputStack = [...stack];
60
- if (settings.prefix && inputStack[0] === settings.prefix) inputStack.shift();
61
- if (settings.suffix && inputStack[inputStack.length - 1] === settings.suffix) inputStack.pop();
62
- return inputStack.join('');
73
+ let code = stack.join('');
74
+ if (settings.prefix && code.startsWith(settings.prefix)) code = code.slice(settings.prefix.length);
75
+ if (settings.suffix && code.endsWith(settings.suffix)) code = code.slice(0, -settings.suffix.length);
76
+ return code;
63
77
  }
64
78
 
65
79
  export interface TraceKey { key: string; timeMs: number; }
@@ -68,14 +82,18 @@ export interface WedgeReplayResult {
68
82
  detectedAsScan: boolean;
69
83
  /** The barcode the detector would emit, with prefix/suffix stripped. */
70
84
  code: string;
85
+ /** Lowest folded average gap in ms (+Infinity when no gap was measured). */
86
+ minAvgGapMs: number;
71
87
  }
72
88
 
73
- /** Replay the detector over a completed keystroke trace. */
89
+ /** Replay the detector over a completed keystroke trace.
90
+ * @deprecated Internal helper, not supported API; leaves the public entry at the next major. */
74
91
  export function replayWedgeDetector(keys: TraceKey[], settings: WedgeSettings): WedgeReplayResult {
75
92
  const state = createWedgeState();
76
- for (const entry of keys) foldWedgeKey(state, entry.key, entry.timeMs, settings.threshold);
77
- if (!state.detecting) return { detectedAsScan: false, code: '' };
78
- return { detectedAsScan: true, code: stripBoundary(state.stack, settings) };
93
+ for (const entry of keys) foldWedgeKey(state, entry.key, entry.timeMs, settings.threshold, settings.gapRule);
94
+ const minAvgGapMs = state.minAvgGapMs ?? Number.POSITIVE_INFINITY;
95
+ if (!state.detecting) return { detectedAsScan: false, code: '', minAvgGapMs };
96
+ return { detectedAsScan: true, code: stripBoundary(state.stack, settings), minAvgGapMs };
79
97
  }
80
98
 
81
99
  export interface WedgeScanMeta {
@@ -132,7 +150,7 @@ export function createWedgeDetector(options: WedgeDetectorOptions): WedgeDetecto
132
150
  return false;
133
151
  }
134
152
  const settings = options.getSettings();
135
- foldWedgeKey(state, key, time, settings.threshold);
153
+ foldWedgeKey(state, key, time, settings.threshold, settings.gapRule);
136
154
  if (!state.detecting) return false;
137
155
  clearTimer();
138
156
  function settle() {
package/src/tax/exact.ts CHANGED
@@ -7,19 +7,7 @@ export const MICROS_PER_MINOR = 1_000_000n;
7
7
  /** What an absent `TaxRounding` means (#287): the till's only rounding before #287a. */
8
8
  export const DEFAULT_TAX_ROUNDING = { granularity: 'per_order', mode: 'half_away_from_zero' } as const satisfies TaxRounding;
9
9
 
10
- /** Converts a plain decimal percentage with at most four fractional digits to safe integer ppm. */
11
- export function ratePpmFromPercent(percent: number | string): number {
12
- const value = String(percent);
13
- const match = /^(\d+)(?:\.(\d{1,4}))?$/.exec(value);
14
- if (!match || match[0] !== value) {
15
- throw new RangeError('Percent must be a plain decimal with at most four fractional digits');
16
- }
17
- const ratePpm = BigInt(match[1]) * 10000n + BigInt((match[2] ?? '').padEnd(4, '0'));
18
- if (ratePpm > BigInt(Number.MAX_SAFE_INTEGER)) {
19
- throw new RangeError('Rate must be a safe integer');
20
- }
21
- return Number(ratePpm);
22
- }
10
+ export { ratePpmFromPercent } from '@tallyui/core';
23
11
 
24
12
  /**
25
13
  * Exact exclusive tax, or inclusive tax rounded half away from zero to a micro-minor-unit.
@@ -0,0 +1,26 @@
1
+ import type { TaxRounding } from '@tallyui/core';
2
+
3
+ /** The lines and charges `taxLinesByRate` splits, each in the tax mode its tax was rounded in (ADR-065: the
4
+ * receipt's figures, which every per-rate split must equal). Under `woocommerce` rounding a line with `netMicros`
5
+ * is in the store's mode, since WooCommerce rounds every line that way. Otherwise a line keeps its own mode, and
6
+ * a line without one is in the store's; a charge outside `woocommerce` keeps its `amountIncludesTax`, else the store's. */
7
+ export function taxedLinesFor<L extends { netMicros?: string; taxInclusive?: boolean }, C>(
8
+ lines: readonly L[], charges: readonly (C & { amountIncludesTax?: boolean })[], pricesIncludeTax: boolean, rounding?: TaxRounding,
9
+ ): Array<(L | C) & { taxInclusive: boolean }> {
10
+ return [...lines.map((line) => ({ ...line, taxInclusive: rounding?.granularity === 'woocommerce' && line.netMicros !== undefined
11
+ ? pricesIncludeTax : line.taxInclusive ?? pricesIncludeTax })),
12
+ ...charges.map((charge) => ({ ...charge, taxInclusive: rounding?.granularity === 'woocommerce'
13
+ ? pricesIncludeTax : charge.amountIncludesTax ?? pricesIncludeTax }))];
14
+ }
15
+
16
+ /** The stored per-rate split a reader may use, or undefined to recompute it with `taxedLinesFor`. A
17
+ * WooCommerce-rounded sale with a converted line (`netMicros` and a stored `taxInclusive`) is always
18
+ * recomputed: before #834 its stored split used the line's own mode (ADR-065, amended 2026-11-17). */
19
+ export function recordedTaxByRate<T>(order: {
20
+ taxByRate?: T; taxRounding?: TaxRounding;
21
+ lines: readonly { netMicros?: string; taxInclusive?: boolean }[];
22
+ }): T | undefined {
23
+ if (order.taxRounding?.granularity === 'woocommerce'
24
+ && order.lines.some((line) => line.netMicros !== undefined && line.taxInclusive !== undefined)) return undefined;
25
+ return order.taxByRate;
26
+ }
@@ -1,5 +1,10 @@
1
- export { tenderReducer, initTenderState, initialTenderState, appliedMinor, changeMinor, quickTenderedAmounts, evenSplitShareMinor, activePlan, planLegs, MAX_TENDER_MINOR } from './tender-state';
1
+ export { tenderReducer, initTenderState, initialTenderState, appliedMinor, changeMinor, quickTenderedAmounts, evenSplitShareMinor, percentOfMinor, activePlan, planLegs, MAX_TENDER_MINOR } from './tender-state';
2
2
  export type { PaymentTransport, TenderView, TenderLineId, TenderPlan, SplitTab, TenderState, TenderKey, TenderAction, PlanLeg } from './tender-state';
3
+ export { splitUnitLines, unitsMinor, unitAllocationsFromLegs, paidUnitsByLine, unpaidUnitsByLine, pickedUnitsMinor } from './split-units';
4
+ export { heldUnitsByLine } from './split-units';
5
+ export type { SplitUnitLine, UnitAllocations } from './split-units';
6
+ export { tenderFigures, runsWholeOrder } from './tender-figures';
7
+ export type { TenderFacts, TenderFigures } from './tender-figures';
3
8
  export { tenderVoidSchema, tenderVoidCollection } from './tender-void';
4
9
  export type { TenderVoid } from './tender-void';
5
10
  export { roundedDue, tenderRounding } from './cash-rounding';
@@ -0,0 +1,109 @@
1
+ import type { Order, Payment } from '../order/types';
2
+ import { roundMicrosToMinor, roundedTaxByRate } from '../tax/exact';
3
+ import { countsTowardPaid, isInMotion } from './payment-legs';
4
+ import type { TenderLineId } from './tender-state';
5
+
6
+ /** A cart line as a unit split prices it: `totalMinor` is the line's money with tax inside, as the cashier is charged. */
7
+ export interface SplitUnitLine {
8
+ id: TenderLineId;
9
+ quantity: number;
10
+ totalMinor: number;
11
+ }
12
+ /** Payment id → line id (as `String(id)`) → units that payment paid for. */
13
+ export type UnitAllocations = Record<string, Record<string, number>>;
14
+
15
+ /** Each line as a unit split prices it: its charged money with tax inside, in lineItems order. A line whose figure is
16
+ * negative is left out (unitsMinor refuses it). Fees, shipping and cash rounding are never in a figure. */
17
+ export function splitUnitLines(order: Pick<Order, 'lineItems' | 'pricesIncludeTax' | 'taxRounding'>): SplitUnitLine[] {
18
+ let taxSoFar = 0n;
19
+ const mode = order.taxRounding?.granularity === 'per_order' ? order.taxRounding.mode : undefined;
20
+ return order.lineItems.map((li) => {
21
+ let totalMinor: number;
22
+ if (order.taxRounding?.granularity === 'woocommerce' && li.netMicros !== undefined && li.totalMinor !== undefined) {
23
+ totalMinor = li.totalMinor;
24
+ } else if (li.taxInclusive) {
25
+ totalMinor = li.netMinor;
26
+ } else if (order.taxRounding?.granularity === 'per_line_items') {
27
+ const r = roundedTaxByRate([li], order.taxRounding)!;
28
+ totalMinor = r.baseMinor + r.taxMinor;
29
+ } else {
30
+ const t = BigInt(li.taxMicros);
31
+ totalMinor = li.netMinor + (roundMicrosToMinor(taxSoFar + t, mode) - roundMicrosToMinor(taxSoFar, mode));
32
+ taxSoFar += t;
33
+ }
34
+ return { id: li.id, quantity: li.quantity, totalMinor };
35
+ }).filter((line) => line.totalMinor >= 0);
36
+ }
37
+
38
+ export function unitAllocationsFromLegs(payments: readonly Payment[]): UnitAllocations {
39
+ return Object.fromEntries(payments.filter((leg) => leg.units !== undefined).map((leg) => [leg.id, { ...leg.units }]));
40
+ }
41
+
42
+ /** Units of each line a leg holds while captured or in motion (pending, authorized); a failed or voided leg frees them (#1133). */
43
+ export function heldUnitsByLine(payments: readonly Payment[]): Record<string, number> { return paidUnitsByLine(unitAllocationsFromLegs(payments), payments.filter((leg) => countsTowardPaid(leg) || isInMotion(leg)).map((leg) => leg.id)); }
44
+
45
+ /**
46
+ * The money `units` units of a line carry, cumulatively: floor(total·units/quantity).
47
+ * Unit k of n costs floor(total·k/n) − floor(total·(k−1)/n), so any run of picks sums exactly to the line
48
+ * total, and no stray cent is left over. (v2's unitsMinor puts the rounding on the last unit instead.)
49
+ * Throws RangeError when quantity is not a positive integer, or units is not an integer in 0..quantity.
50
+ */
51
+ export function unitsMinor(totalMinor: number, quantity: number, units: number): number {
52
+ if (!Number.isInteger(quantity) || quantity <= 0)
53
+ throw new RangeError(`quantity ${quantity} is not a positive integer`);
54
+ if (!Number.isInteger(units) || units < 0 || units > quantity)
55
+ throw new RangeError(`units ${units} is not an integer in 0..${quantity}`);
56
+ // The split is for sales: a refund line (negative total) cannot be split by units.
57
+ if (!Number.isInteger(totalMinor) || totalMinor < 0)
58
+ throw new RangeError(`totalMinor ${totalMinor} is not a non-negative integer`);
59
+ // Exact in integers: totalMinor is at most MAX_TENDER_MINOR and quantities are small, so the product stays under 2^53.
60
+ const product = totalMinor * units;
61
+ if (!Number.isSafeInteger(product)) throw new RangeError(`totalMinor × units ${product} is not a safe integer`);
62
+ return Math.floor(product / quantity);
63
+ }
64
+
65
+ /** Units of each line the live payments paid for. A payment not in `livePaymentIds` (voided, cancelled, refused) frees its units. */
66
+ export function paidUnitsByLine(
67
+ allocations: UnitAllocations,
68
+ livePaymentIds: readonly string[],
69
+ ): Record<string, number> {
70
+ const live = new Set(livePaymentIds);
71
+ const paid: Record<string, number> = {};
72
+ for (const [paymentId, lines] of Object.entries(allocations)) {
73
+ if (!live.has(paymentId)) continue;
74
+ for (const [lineId, units] of Object.entries(lines)) paid[lineId] = (paid[lineId] ?? 0) + units;
75
+ }
76
+ return paid;
77
+ }
78
+
79
+ /** Units of each line still unpaid, by `String(id)`. A line whose quantity is not a positive integer is left out: it cannot be split by units (vet §11.3, until the decimal-quantity ADR). */
80
+ export function unpaidUnitsByLine(
81
+ lines: readonly SplitUnitLine[],
82
+ paid: Record<string, number>,
83
+ ): Record<string, number> {
84
+ const unpaid: Record<string, number> = {};
85
+ for (const line of lines) {
86
+ if (!(Number.isInteger(line.quantity) && line.quantity > 0)) continue;
87
+ const key = String(line.id);
88
+ unpaid[key] = Math.max(0, line.quantity - (paid[key] ?? 0));
89
+ }
90
+ return unpaid;
91
+ }
92
+
93
+ /** The money the picks add to this payment: Σ unitsMinor(total, n, paid+picked) − unitsMinor(total, n, paid). Picks on a line not in `lines` throw RangeError, and so does a pick beyond the line's unpaid units. */
94
+ export function pickedUnitsMinor(
95
+ lines: readonly SplitUnitLine[],
96
+ picked: Record<string, number>,
97
+ paid: Record<string, number>,
98
+ ): number {
99
+ const unpaid = unpaidUnitsByLine(lines, paid);
100
+ let sum = 0;
101
+ for (const [key, units] of Object.entries(picked)) {
102
+ const line = lines.find((candidate) => String(candidate.id) === key);
103
+ if (!line) throw new RangeError(`picked units on unknown line ${key}`);
104
+ if (!(units <= (unpaid[key] ?? 0))) throw new RangeError(`${units} units picked on line ${key}, more than unpaid`);
105
+ const before = paid[key] ?? 0;
106
+ sum += unitsMinor(line.totalMinor, line.quantity, before + units) - unitsMinor(line.totalMinor, line.quantity, before);
107
+ }
108
+ return sum;
109
+ }
@@ -0,0 +1,114 @@
1
+ import type { PaymentMethodDescriptor } from '@tallyui/core';
2
+ import { roundedDue, settlesAtRoundedDue } from './cash-rounding';
3
+ import { countsTowardPaid, type PaymentLegStatus } from './payment-legs';
4
+ import {
5
+ activePlan,
6
+ appliedMinor,
7
+ changeMinor,
8
+ percentOfMinor,
9
+ planLegs,
10
+ quickTenderedAmounts,
11
+ type TenderState,
12
+ } from './tender-state';
13
+
14
+ /** The notes a cashier is handed: the balance itself, then the next whole 5, 10 and 50. */
15
+ const QUICK_TENDER_STEPS = [5, 10, 50] as const;
16
+
17
+ /** A gateway that takes no part payment runs the whole order. */
18
+ export const runsWholeOrder = (method: PaymentMethodDescriptor | null) =>
19
+ method?.capture.mode === 'gateway' && !method.capabilities.amount.partial;
20
+
21
+ export interface TenderFacts {
22
+ /** Currency decimal places; every `*Minor` number is in these units. */
23
+ dp: number;
24
+ balanceMinor: number;
25
+ /** The order's payment legs in ledger order; only those that count toward paid are numbered. */
26
+ payments: readonly { status?: PaymentLegStatus }[];
27
+ /** The plan's counted legs (by `plan.before`, else since `plan.from`), as `tender-recorded` and `planLegs` read them. */
28
+ rowsSinceFrom: { minor: number; title: string }[];
29
+ /** The selected method, or null in the select view. */
30
+ method: PaymentMethodDescriptor | null;
31
+ state: Pick<TenderState, 'view' | 'entryMinor' | 'entryDirty' | 'entryMode' | 'plan'>;
32
+ }
33
+ export type TenderFigures = ReturnType<typeof tenderFigures>;
34
+
35
+ /** Every number the keypad shows and commits, computed once and formatted by the pane. */
36
+ export function tenderFigures(facts: TenderFacts) {
37
+ const { dp, balanceMinor, payments, rowsSinceFrom, method, state } = facts;
38
+ const fixedAmount = runsWholeOrder(method);
39
+ const plan = fixedAmount ? null : activePlan(state.plan, rowsSinceFrom.length, balanceMinor);
40
+ const split = plan ? planLegs(plan, rowsSinceFrom, balanceMinor) : null;
41
+ const legs = split?.legs ?? [];
42
+ const done = legs.filter((leg) => leg.state === 'done');
43
+ const counted = payments.filter(countsTowardPaid).length;
44
+ const n = counted + 1;
45
+ const ways = plan && split ? counted - rowsSinceFrom.length + split.label.ways : 0;
46
+ const groupDone =
47
+ plan?.kind === 'items' && done.reduce((sum, leg) => sum + leg.minor, 0) >= plan.firstMinor;
48
+ const thisPaymentMinor = split?.thisPaymentMinor ?? balanceMinor;
49
+ const legCapMinor = method?.capabilities.change ? thisPaymentMinor : balanceMinor;
50
+ const roundedDueMinor = roundedDue(balanceMinor, method).dueMinor;
51
+ const percent = state.entryMode === 'percent';
52
+ const percentMinor = percent ? percentOfMinor(balanceMinor, state.entryMinor) : null;
53
+ const entryMinor =
54
+ percentMinor ??
55
+ (!state.entryDirty && state.entryMinor === balanceMinor ? roundedDueMinor : state.entryMinor);
56
+ const enteredLegMinor = fixedAmount ? balanceMinor : appliedMinor(entryMinor, legCapMinor);
57
+ const roundingMinor = settlesAtRoundedDue({
58
+ amountMinor: enteredLegMinor,
59
+ tenderedMinor: entryMinor,
60
+ balanceMinor,
61
+ dueMinor: roundedDueMinor,
62
+ }) ? roundedDueMinor - balanceMinor : 0;
63
+ const entryAppliedMinor = roundingMinor !== 0 ? roundedDueMinor : enteredLegMinor;
64
+ const givesChange = method?.capabilities.change ?? false;
65
+ const nowMinor = state.view === 'amount' ? entryAppliedMinor : thisPaymentMinor;
66
+ const dueMinor = roundingMinor !== 0 ? roundedDueMinor : thisPaymentMinor;
67
+ const typed = state.entryDirty && entryAppliedMinor > 0 && entryAppliedMinor < balanceMinor;
68
+ return {
69
+ fixedAmount,
70
+ /** The plan as the keypad sees it: null once its legs are taken, or for a fixed gateway. */
71
+ plan,
72
+ legs,
73
+ /** The plan's untranslated label pieces; the flow localizes them. */
74
+ label: split?.label ?? null,
75
+ /** "Payment n of ways", numbered across the bill; `ways` is 0 without a plan. */
76
+ n,
77
+ ways,
78
+ /** Planned payments still to come after this one. */
79
+ toCome: legs.filter((leg) => leg.state === 'todo').length,
80
+ groupDone,
81
+ /** An items plan shared more than one way, its group not yet paid. */
82
+ shared: plan?.kind === 'items' && plan.ways > 1 && !groupDone,
83
+ /** The planned leg, or the balance with no plan. */
84
+ thisPaymentMinor,
85
+ roundedDueMinor,
86
+ /** `roundedDueMinor - balanceMinor` when the entry settles at the rounded due, else 0. */
87
+ roundingMinor,
88
+ percentMinor,
89
+ /** The entry as the cashier sees it: percent share or the (rounded) prefill. */
90
+ entryMinor,
91
+ /** The leg the entry makes before rounding (the commit's `amountMinor`). */
92
+ enteredLegMinor,
93
+ /** That leg after cash rounding: what the entry applies to the order. */
94
+ entryAppliedMinor,
95
+ entryChangeMinor: changeMinor(entryMinor, entryAppliedMinor, givesChange),
96
+ /** THIS payment: the applied entry on the keypad, the planned share in the select view. */
97
+ nowMinor,
98
+ afterThisPaymentMinor: balanceMinor + roundingMinor - nowMinor,
99
+ quickAmountsMinor: givesChange
100
+ ? quickTenderedAmounts(nowMinor, QUICK_TENDER_STEPS.map((step) => step * 10 ** dp))
101
+ : [],
102
+ dueMinor,
103
+ /** The Exact chip: the rounded due whenever this leg is the whole balance, since tapping it settles. */
104
+ exactMinor: thisPaymentMinor === balanceMinor ? roundedDueMinor : dueMinor,
105
+ /** The big figure. */
106
+ shownMinor:
107
+ state.view === 'select' ? dueMinor : fixedAmount || percent ? entryAppliedMinor : entryMinor,
108
+ /** A no-change method typed past the balance; a fixed-amount gateway applies the balance whatever is typed. */
109
+ noChange: method !== null && !givesChange && !fixedAmount && !percent && entryMinor > balanceMinor,
110
+ /** An amount typed below the balance is THIS payment; the split helpers divide the rest. */
111
+ typed,
112
+ restMinor: balanceMinor - (typed ? entryAppliedMinor : 0),
113
+ };
114
+ }