@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/pos",
3
- "version": "3.17.0",
3
+ "version": "3.19.0",
4
4
  "type": "module",
5
5
  "description": "Shared POS business logic for Tally UI — tax, orders, payments, discounts, receipts",
6
6
  "main": "./dist/index.js",
@@ -34,20 +34,20 @@
34
34
  "mustache": "^4.2.0"
35
35
  },
36
36
  "peerDependencies": {
37
- "@tallyui/core": "^3.17.0",
37
+ "@tallyui/core": "^3.19.0",
38
38
  "react": ">=18",
39
39
  "rxdb": "~17.5.0",
40
40
  "rxjs": ">=7"
41
41
  },
42
42
  "devDependencies": {
43
- "@tallyui/core": "3.17.0",
43
+ "@tallyui/core": "3.19.0",
44
44
  "@types/react": ">=18",
45
45
  "react": "^19.2.4",
46
46
  "rxdb": "17.5.0",
47
47
  "rxjs": "7.8.2",
48
- "@tallyui/connector-medusa": "3.17.0",
49
- "@tallyui/connector-woocommerce": "3.17.0",
50
- "@tallyui/database": "3.17.0"
48
+ "@tallyui/connector-medusa": "3.19.0",
49
+ "@tallyui/connector-woocommerce": "3.19.0",
50
+ "@tallyui/database": "3.19.0"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsup",
@@ -1,10 +1,12 @@
1
1
  import { createContext, useContext, useMemo, useCallback } from 'react';
2
2
  import type { ReactNode } from 'react';
3
3
  import { formatMoney, type Money } from '@tallyui/core';
4
+ import { formatMoneyWith, type CurrencyFormat } from './format-money-with';
4
5
 
5
6
  interface CurrencyContext {
6
7
  currencyCode: string;
7
8
  locale?: string;
9
+ format?: CurrencyFormat;
8
10
  }
9
11
 
10
12
  const CurrencyCtx = createContext<CurrencyContext | null>(null);
@@ -12,11 +14,13 @@ const CurrencyCtx = createContext<CurrencyContext | null>(null);
12
14
  export interface CurrencyProviderProps {
13
15
  currencyCode: string;
14
16
  locale?: string;
17
+ /** The store's own money format; without it, money reads as Intl formats it for `locale`. */
18
+ format?: CurrencyFormat;
15
19
  children: ReactNode;
16
20
  }
17
21
 
18
- export function CurrencyProvider({ currencyCode, locale, children }: CurrencyProviderProps) {
19
- const value = useMemo(() => ({ currencyCode, locale }), [currencyCode, locale]);
22
+ export function CurrencyProvider({ currencyCode, locale, format, children }: CurrencyProviderProps) {
23
+ const value = useMemo(() => ({ currencyCode, locale, format }), [currencyCode, locale, format]);
20
24
  return <CurrencyCtx.Provider value={value}>{children}</CurrencyCtx.Provider>;
21
25
  }
22
26
 
@@ -25,9 +29,12 @@ export function useCurrencyFormatter(): (money: Money) => string {
25
29
  if (!ctx) {
26
30
  throw new Error('useCurrencyFormatter() must be used within a <CurrencyProvider>');
27
31
  }
32
+ const { locale, format } = ctx;
28
33
  return useCallback(
29
- (money: Money) => formatMoney(money, ctx.locale) ?? `${money.amount} ${money.currency}`,
30
- [ctx.locale],
34
+ (money: Money) =>
35
+ (format ? formatMoneyWith(money, format, locale) : formatMoney(money, locale)) ??
36
+ `${money.amount} ${money.currency}`,
37
+ [locale, format],
31
38
  );
32
39
  }
33
40
 
@@ -0,0 +1,45 @@
1
+ import { minorUnitDigits, type Money } from '@tallyui/core';
2
+
3
+ /** A store's own money format (WCPOS v2 General settings); a field left out keeps the locale's. */
4
+ export interface CurrencyFormat {
5
+ position?: 'left' | 'right' | 'left_space' | 'right_space';
6
+ thousandSeparator?: string;
7
+ decimalSeparator?: string;
8
+ decimals?: number;
9
+ }
10
+
11
+ /**
12
+ * Money in a store's format, ported from WCPOS v2 (MIT): the position map of
13
+ * `packages/core/src/screens/main/hooks/use-currency-format.tsx` and the separators and places
14
+ * of `use-number-format.ts`. As there, the places are always shown, the integer is grouped every
15
+ * three digits, and a minus leads the symbol. The symbol is Intl's for the currency and locale.
16
+ * Returns undefined for 'XXX' or a code Intl refuses, so callers can fall back.
17
+ */
18
+ export function formatMoneyWith(money: Money, format: CurrencyFormat, locale?: string): string | undefined {
19
+ if (money.currency === 'XXX') return undefined;
20
+ const minor = minorUnitDigits(money.currency);
21
+ const decimals = format.decimals ?? minor;
22
+ const abs = Math.abs(money.amount);
23
+ // Fewer places round whole minor units half away from zero, so -12.50 and 12.50 read alike.
24
+ const major = decimals >= minor ? abs / 10 ** minor : Math.round(abs / 10 ** (minor - decimals)) / 10 ** decimals;
25
+ let parts: Intl.NumberFormatPart[];
26
+ try {
27
+ parts = new Intl.NumberFormat(locale, {
28
+ style: 'currency', currency: money.currency, minimumFractionDigits: decimals, maximumFractionDigits: decimals,
29
+ }).formatToParts(major);
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ const text = (...types: string[]) => parts.filter((p) => types.includes(p.type)).map((p) => p.value).join('');
34
+ const { position, thousandSeparator, decimalSeparator } = format;
35
+ const integer = thousandSeparator === undefined
36
+ ? text('integer', 'group')
37
+ : text('integer').replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
38
+ const number = integer + (decimals > 0 ? (decimalSeparator ?? text('decimal')) + text('fraction') : '');
39
+ const symbol = text('currency');
40
+ const left = position
41
+ ? position.startsWith('left')
42
+ : parts.findIndex((p) => p.type === 'currency') < parts.findIndex((p) => p.type === 'integer');
43
+ const gap = position ? (position.endsWith('_space') ? ' ' : '') : text('literal');
44
+ return (money.amount < 0 && major > 0 ? '-' : '') + (left ? symbol + gap + number : number + gap + symbol);
45
+ }
@@ -1,2 +1,3 @@
1
1
  export { CurrencyProvider, useCurrencyFormatter, useCurrencyCode } from './currency-provider';
2
2
  export type { CurrencyProviderProps } from './currency-provider';
3
+ export type { CurrencyFormat } from './format-money-with';
@@ -0,0 +1,341 @@
1
+ import {
2
+ DisplaySignallingError, type DisplayAdvertisement, type DisplaySignalling, type DisplaySignallingContext, type SignalMessage,
3
+ } from '@tallyui/core';
4
+ import type { DisplayClock } from './display-link';
5
+ import { displayReducer, initialDisplayState, type DisplayState } from './display-state';
6
+ import { decode, makeEnvelope, type DisplayConfig, type DisplayEnvelope } from './protocol';
7
+ import { DISPLAY_TEMPLATE, HELLO_RETRY_MS } from './use-customer-display';
8
+ import { createDisplayPeerLink, type PeerFactory, type PeerLink, type PeerLinkState } from './webrtc';
9
+
10
+ /** TallyUI's choice: how often a waiting display asks whether the cashier has confirmed. */
11
+ export const COLLECT_POLL_MS = 2000;
12
+ /** TallyUI's choice: how often a paired display drains its inbox while no link is open. */
13
+ export const DISPLAY_SIGNAL_POLL_MS = 1000;
14
+ /** TallyUI's choice: how often it drains its inbox while a link is open, so a re-linking till's offer is still seen. */
15
+ export const OPEN_SIGNAL_POLL_MS = 5000;
16
+ /** TallyUI's choice: how often it reads the snapshot fallback while no link is open. */
17
+ export const SNAPSHOT_POLL_MS = 2000;
18
+
19
+ /** Where the display keeps its token; U8 binds it to a local collection that is never replicated (ADR-085 d5). */
20
+ export interface DisplayTokenStore {
21
+ load(): Promise<string | null>;
22
+ save(token: string): Promise<void>;
23
+ clear(): Promise<void>;
24
+ }
25
+ export type DisplayClientError = 'claim_refused' | 'collect_refused' | 'forgotten' | 'network' | 'server';
26
+ export type DisplayClientPhase =
27
+ | { phase: 'starting' }
28
+ | { phase: 'enter-code'; error?: DisplayClientError }
29
+ | { phase: 'claiming' }
30
+ | { phase: 'waiting'; checkCode: string }
31
+ | { phase: 'paired'; link: PeerLinkState | 'none'; source: 'peer' | 'snapshot' | 'none'; online: boolean };
32
+ type Paired = Extract<DisplayClientPhase, { phase: 'paired' }>;
33
+ export interface DisplayClientOptions {
34
+ signalling: DisplaySignalling;
35
+ context: DisplaySignallingContext;
36
+ tokens: DisplayTokenStore;
37
+ /** The store's advertisement: its ICE servers for the peer, and whether to read snapshots. */
38
+ advertisement: DisplayAdvertisement;
39
+ createPeer?: PeerFactory;
40
+ clock?: DisplayClock;
41
+ onError?: (error: unknown) => void;
42
+ }
43
+ export interface DisplayClient {
44
+ readonly phase: DisplayClientPhase;
45
+ /** What the screen shows: the reducer's state, `initialDisplayState` until a config arrives. */
46
+ readonly state: DisplayState;
47
+ /** Called after any change to `phase` or `state`; returns the unsubscribe. */
48
+ onChange(listener: () => void): () => void;
49
+ /** Claims `code` as `displayName`, passing the current token if there is one (so a confirm moves this display). */
50
+ claim(code: string, displayName: string): Promise<void>;
51
+ /** Stops waiting for the confirm, and goes back to `enter-code` with no error. */
52
+ cancel(): void;
53
+ close(): void;
54
+ }
55
+
56
+ const systemClock: DisplayClock = {
57
+ setTimeout: (run, ms) => setTimeout(run, ms),
58
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
59
+ };
60
+ const SNAPSHOT_EVENTS: readonly string[] = ['cart.updated', 'payment.state', 'display.idle'];
61
+ const codeOf = (error: unknown) => (error instanceof DisplaySignallingError ? error.code : undefined);
62
+
63
+ /** U4's snapshot body as two envelopes, or null when any part of it cannot be trusted (ADR-085 d8). */
64
+ function parseSnapshot(body: unknown): { seq: number; config: DisplayEnvelope; event: DisplayEnvelope } | null {
65
+ if (typeof body !== 'object' || body === null) return null;
66
+ const { v, seq, config, event } = body as Record<string, unknown>;
67
+ if (v !== 1 || typeof seq !== 'number' || !Number.isFinite(seq)) return null;
68
+ try {
69
+ const configResult = decode(JSON.stringify(makeEnvelope('display.config', config as DisplayConfig, 'snapshot')));
70
+ const eventResult = decode(JSON.stringify(event));
71
+ if (!configResult.ok || configResult.envelope.action !== 'display.config') return null;
72
+ if (!eventResult.ok || !SNAPSHOT_EVENTS.includes(eventResult.envelope.action)) return null;
73
+ return { seq, config: configResult.envelope, event: eventResult.envelope };
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * The second-device display's side (ADR-085 d4, d5, d8, d11; #705): pairs through the signalling seam, answers each
81
+ * offer from its till with a peer link, says hello, and shows what the till sends, reading the snapshot fallback while
82
+ * no link is open. A refused token clears the token and the screen, and goes back to the enter-code screen.
83
+ */
84
+ export function createDisplayClient(options: DisplayClientOptions): DisplayClient {
85
+ const { signalling, context, tokens, advertisement, createPeer, clock = systemClock, onError } = options;
86
+ const listeners = new Set<() => void>();
87
+ const timers = new Set<unknown>();
88
+ let phase: DisplayClientPhase = { phase: 'starting' };
89
+ let state: DisplayState = initialDisplayState;
90
+ let token: string | null = null;
91
+ let closed = false;
92
+ // Bumped whenever the client leaves a claim or a pairing, so a call that settles afterwards is dropped.
93
+ let epoch = 0;
94
+ let link: { peer: PeerLink; deliver(message: SignalMessage): void } | null = null;
95
+ let inboxTimer: unknown = null;
96
+ let lastSeq = -Infinity;
97
+ let lastSnapshot = '';
98
+
99
+ const notify = () => listeners.forEach((listener) => listener());
100
+ const setPhase = (next: DisplayClientPhase) => {
101
+ phase = next;
102
+ notify();
103
+ };
104
+ const patchPaired = (patch: Partial<Paired>) => {
105
+ if (phase.phase !== 'paired') return;
106
+ const next: Paired = { ...phase, ...patch };
107
+ if (next.link !== phase.link || next.source !== phase.source || next.online !== phase.online) setPhase(next);
108
+ };
109
+ const report = (error: unknown) => {
110
+ try {
111
+ onError?.(error);
112
+ } catch {
113
+ // A failing error handler must not break the client.
114
+ }
115
+ };
116
+ const live = (session: number) => !closed && session === epoch;
117
+ const after = (ms: number, run: () => void) => {
118
+ const handle = clock.setTimeout(() => {
119
+ timers.delete(handle);
120
+ run();
121
+ }, ms);
122
+ timers.add(handle);
123
+ return handle;
124
+ };
125
+ const linkOpen = () => link?.peer.state === 'open';
126
+
127
+ /** Leaves the current claim or pairing: every timer stops, the link closes, and the screen is emptied (d8). */
128
+ const stop = () => {
129
+ epoch += 1;
130
+ timers.forEach((handle) => clock.clearTimeout(handle));
131
+ timers.clear();
132
+ inboxTimer = null;
133
+ const current = link;
134
+ link = null;
135
+ current?.peer.close();
136
+ lastSeq = -Infinity;
137
+ lastSnapshot = '';
138
+ state = initialDisplayState;
139
+ };
140
+
141
+ const forget = () => {
142
+ stop();
143
+ token = null;
144
+ tokens.clear().catch(report);
145
+ setPhase({ phase: 'enter-code', error: 'forgotten' });
146
+ };
147
+
148
+ /** One token call while paired: a refused token forgets the display; `network` or `server` only marks it offline (d11). */
149
+ async function pairedCall<T>(session: number, work: () => Promise<T>): Promise<{ value: T } | null> {
150
+ try {
151
+ const value = await work();
152
+ if (!live(session)) return null;
153
+ patchPaired({ online: true });
154
+ return { value };
155
+ } catch (error) {
156
+ if (!live(session)) return null;
157
+ const code = codeOf(error);
158
+ if (code === 'token_refused') forget();
159
+ else if (code === 'network' || code === 'server') patchPaired({ online: false });
160
+ else report(error);
161
+ return null;
162
+ }
163
+ }
164
+
165
+ const openLink = (session: number, paired: string, offer: SignalMessage) => {
166
+ const previous = link;
167
+ link = null;
168
+ previous?.peer.close();
169
+ let portListener: ((message: SignalMessage) => void) | null = null;
170
+ const peer = createDisplayPeerLink({
171
+ iceServers: advertisement.iceServers,
172
+ createPeer,
173
+ signal: {
174
+ send: (message) => void pairedCall(session, () => signalling.displaySendSignal(context, paired, message)),
175
+ onSignal: (listener) => {
176
+ portListener = listener;
177
+ return () => {
178
+ portListener = null;
179
+ };
180
+ },
181
+ },
182
+ });
183
+ const current = { peer, deliver: (message: SignalMessage) => portListener?.(message) };
184
+ link = current;
185
+ const hello = makeEnvelope('display.hello', { template: DISPLAY_TEMPLATE });
186
+ let configured = false;
187
+ let retry: unknown = null;
188
+ const sayHello = () => {
189
+ if (link !== current || configured) return;
190
+ peer.send(hello);
191
+ retry = after(HELLO_RETRY_MS, sayHello);
192
+ };
193
+ peer.onMessage((envelope) => {
194
+ if (link !== current) return;
195
+ if (!configured) {
196
+ // As useCustomerDisplay: nothing is applied before the config that answers this hello.
197
+ if (envelope.action !== 'display.config' || envelope.id !== hello.id) return;
198
+ configured = true;
199
+ if (retry !== null) clock.clearTimeout(retry);
200
+ }
201
+ state = displayReducer(state, envelope);
202
+ if (phase.phase === 'paired' && phase.source !== 'peer') patchPaired({ source: 'peer' });
203
+ else notify();
204
+ });
205
+ peer.onStateChange((next) => {
206
+ if (link !== current) return;
207
+ patchPaired({ link: next });
208
+ if (next === 'open') sayHello();
209
+ if (next !== 'closed') return;
210
+ link = null;
211
+ patchPaired({ link: 'none' });
212
+ if (inboxTimer !== null) {
213
+ clock.clearTimeout(inboxTimer);
214
+ timers.delete(inboxTimer);
215
+ inboxTimer = after(DISPLAY_SIGNAL_POLL_MS, () => void pollInbox(session, paired));
216
+ }
217
+ });
218
+ patchPaired({ link: peer.state });
219
+ current.deliver(offer);
220
+ };
221
+
222
+ async function pollInbox(session: number, paired: string) {
223
+ inboxTimer = null;
224
+ const result = await pairedCall(session, () => signalling.displayReceiveSignals(context, paired));
225
+ if (!live(session)) return;
226
+ for (const message of result?.value ?? []) {
227
+ if (!live(session)) return;
228
+ if (message.type === 'offer') openLink(session, paired, message);
229
+ else if (message.type === 'ice') link?.deliver(message);
230
+ }
231
+ inboxTimer = after(linkOpen() ? OPEN_SIGNAL_POLL_MS : DISPLAY_SIGNAL_POLL_MS, () => void pollInbox(session, paired));
232
+ }
233
+
234
+ const applySnapshot = (body: unknown) => {
235
+ if (body === null || linkOpen()) return;
236
+ const parsed = parseSnapshot(body);
237
+ if (!parsed) return report(new Error('display snapshot: malformed body ignored'));
238
+ const key = JSON.stringify(body);
239
+ if (parsed.seq < lastSeq || key === lastSnapshot) return;
240
+ lastSeq = parsed.seq;
241
+ lastSnapshot = key;
242
+ state = displayReducer(displayReducer(state, parsed.config), parsed.event);
243
+ if (phase.phase === 'paired' && phase.source !== 'snapshot') patchPaired({ source: 'snapshot' });
244
+ else notify();
245
+ };
246
+
247
+ async function pollSnapshot(session: number, paired: string) {
248
+ if (!linkOpen()) {
249
+ const result = await pairedCall(session, () => signalling.readSnapshot(context, paired));
250
+ if (!live(session)) return;
251
+ if (result) applySnapshot(result.value);
252
+ }
253
+ after(SNAPSHOT_POLL_MS, () => void pollSnapshot(session, paired));
254
+ }
255
+
256
+ const startPaired = (paired: string) => {
257
+ token = paired;
258
+ setPhase({ phase: 'paired', link: 'none', source: 'none', online: true });
259
+ const session = epoch;
260
+ void pollInbox(session, paired);
261
+ if (advertisement.snapshot) void pollSnapshot(session, paired);
262
+ };
263
+
264
+ async function pollCollect(session: number, claimSecret: string) {
265
+ try {
266
+ const result = await signalling.collect(context, claimSecret);
267
+ if (!live(session)) return;
268
+ if (result.status === 'pending') {
269
+ if (phase.phase === 'waiting' && phase.checkCode !== result.checkCode) setPhase({ phase: 'waiting', checkCode: result.checkCode });
270
+ after(COLLECT_POLL_MS, () => void pollCollect(session, claimSecret));
271
+ return;
272
+ }
273
+ await tokens.save(result.token).catch(report);
274
+ if (live(session)) startPaired(result.token);
275
+ } catch (error) {
276
+ if (!live(session)) return;
277
+ const code = codeOf(error);
278
+ // The claim secret outlives a dropped request, so a transport failure keeps waiting rather than strand the claim.
279
+ if (code === 'network' || code === 'server') after(COLLECT_POLL_MS, () => void pollCollect(session, claimSecret));
280
+ else setPhase({ phase: 'enter-code', error: 'collect_refused' });
281
+ }
282
+ }
283
+
284
+ const loading = tokens.load().then(
285
+ (stored) => {
286
+ token = stored;
287
+ if (closed || phase.phase !== 'starting') return;
288
+ if (stored) startPaired(stored);
289
+ else setPhase({ phase: 'enter-code' });
290
+ },
291
+ (error: unknown) => {
292
+ report(error);
293
+ if (!closed && phase.phase === 'starting') setPhase({ phase: 'enter-code' });
294
+ },
295
+ );
296
+
297
+ return {
298
+ get phase() {
299
+ return phase;
300
+ },
301
+ get state() {
302
+ return state;
303
+ },
304
+ onChange(listener) {
305
+ listeners.add(listener);
306
+ return () => {
307
+ listeners.delete(listener);
308
+ };
309
+ },
310
+ async claim(code, displayName) {
311
+ if (closed || phase.phase === 'claiming' || phase.phase === 'waiting') return;
312
+ stop();
313
+ const session = epoch;
314
+ setPhase({ phase: 'claiming' });
315
+ await loading;
316
+ if (!live(session)) return;
317
+ try {
318
+ const { claimSecret, checkCode } = await signalling.claim(context, { code, displayName, ...(token ? { token } : {}) });
319
+ if (!live(session)) return;
320
+ setPhase({ phase: 'waiting', checkCode });
321
+ after(COLLECT_POLL_MS, () => void pollCollect(session, claimSecret));
322
+ } catch (error) {
323
+ if (!live(session)) return;
324
+ const refusal = codeOf(error);
325
+ if (refusal !== 'claim_refused' && refusal !== 'network' && refusal !== 'server') report(error);
326
+ setPhase({ phase: 'enter-code', error: refusal === 'claim_refused' || refusal === 'network' ? refusal : 'server' });
327
+ }
328
+ },
329
+ cancel() {
330
+ if (closed || (phase.phase !== 'claiming' && phase.phase !== 'waiting')) return;
331
+ stop();
332
+ setPhase({ phase: 'enter-code' });
333
+ },
334
+ close() {
335
+ if (closed) return;
336
+ stop();
337
+ closed = true;
338
+ listeners.clear();
339
+ },
340
+ };
341
+ }
@@ -11,3 +11,23 @@ export type { DisplayTransport, BroadcastChannelLike } from './transport';
11
11
  export { createDisplayLink } from './display-link';
12
12
  export type { DisplayLink, DisplayClock } from './display-link';
13
13
  export { useCustomerDisplay, DISPLAY_TEMPLATE, HELLO_RETRY_MS } from './use-customer-display';
14
+ export { createSaleDisplayPublisher, derivePaymentEvent } from './sale-display';
15
+ export type { SaleDisplayOptions, SaleDisplayInput, SaleDisplayPublisher } from './sale-display';
16
+ export { useSaleDisplay } from './use-sale-display';
17
+ export { createTillPeerLink, createDisplayPeerLink } from './webrtc';
18
+ export type {
19
+ SignalPort, PeerLink, PeerLinkState, PeerLinkOptions, PeerFactory, RTCPeerConnectionLike, RTCDataChannelLike,
20
+ SessionDescriptionLike,
21
+ } from './webrtc';
22
+ export { createDisplayClient, COLLECT_POLL_MS, DISPLAY_SIGNAL_POLL_MS, OPEN_SIGNAL_POLL_MS, SNAPSHOT_POLL_MS } from './display-client';
23
+ export type { DisplayClient, DisplayClientOptions, DisplayClientPhase, DisplayClientError, DisplayTokenStore } from './display-client';
24
+ export { useDisplayClient } from './use-display-client';
25
+ export type { DisplayClientView } from './use-display-client';
26
+ export { createSnapshotSender, SNAPSHOT_MIN_INTERVAL_MS, SNAPSHOT_RESEND_MS, SNAPSHOT_LIFETIME_MS } from './snapshot-fallback';
27
+ export type { SnapshotSender, SnapshotSenderOptions, SnapshotBody } from './snapshot-fallback';
28
+ export { createTillDisplayService, SIGNAL_POLL_MS, LIST_POLL_MS, CONNECT_TIMEOUT_MS } from './till-display-service';
29
+ export type { TillDisplayService, TillDisplayServiceOptions, TillDisplayStatus, TillDisplayEntry, ServiceClock } from './till-display-service';
30
+ export { createTillPairing, PENDING_POLL_MS } from './till-pairing';
31
+ export type { TillPairing, TillPairingOptions, PairingPhase, PairingError } from './till-pairing';
32
+ export { useTillPairing, useTillDisplays } from './use-till-pairing';
33
+ export type { TillPairingView, TillDisplaysView } from './use-till-pairing';
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The live sale as customer-display calls (ADR-085 U1), ported from WCPOS v2 (monorepo 51e7c4351)
3
+ * core/screens/main/pos/customer-display/snapshot-source.tsx and core/services/customer-display/ledger.ts.
4
+ * Not ported: v2's coupon debounce (TallyUI has no COUPON_TOTALS_DEBOUNCE_MS yet) and its mount counter (one publisher per link).
5
+ */
6
+ import type { Order, Payment, SentOrder } from '../order';
7
+ import { buildReceiptData } from '../receipt/build-receipt-data';
8
+ import type { ReceiptConfig, ReceiptData } from '../receipt/types';
9
+ import type { SaleStage } from '../sale/use-sale';
10
+ import { legStatus } from '../tender/payment-legs';
11
+ import type { DisplayLink } from './display-link';
12
+ import type { DisplayPayment } from './protocol';
13
+
14
+ export interface SaleDisplayOptions {
15
+ /** The receipt config used to build what the display shows. Default: `{ storeName: '' }`. */
16
+ receipt?: ReceiptConfig;
17
+ /** A payment method id to the title shown on the display (v2's methodTitles). Default: the id itself. */
18
+ methodTitle?: (method: string) => string;
19
+ /** Shown with a declined leg (v2 passes its translated "payment declined"). Default: no message. */
20
+ declinedMessage?: string;
21
+ }
22
+
23
+ /** The sale as useSale exposes it: its live order and its stage. */
24
+ export interface SaleDisplayInput { order: Order; stage: SaleStage }
25
+
26
+ export interface SaleDisplayPublisher {
27
+ update(sale: SaleDisplayInput): void;
28
+ /** Shows idle (v2 publishes display.idle on unmount); later updates do nothing. */
29
+ close(): void;
30
+ }
31
+
32
+ /** v2 ledger.ts derivePaymentEvent on TallyUI legs. Pure. */
33
+ export function derivePaymentEvent(
34
+ previous: readonly Payment[], next: readonly Payment[],
35
+ wasCompleted: boolean, completed: boolean,
36
+ balanceDueMinor: number, options: Pick<SaleDisplayOptions, 'methodTitle' | 'declinedMessage'> = {},
37
+ ): DisplayPayment | null {
38
+ const leg = (payment: Payment) => ({
39
+ method: options.methodTitle ? options.methodTitle(payment.method) : payment.method, amountMinor: payment.amountMinor,
40
+ });
41
+ if (!wasCompleted && completed) {
42
+ const last = next.filter((payment) => legStatus(payment) === 'captured').at(-1);
43
+ return { state: 'complete', ...(last ? { leg: leg(last) } : {}) };
44
+ }
45
+ const before = new Map(previous.map((payment) => [payment.id, payment]));
46
+ const row = next.filter((payment) => {
47
+ const old = before.get(payment.id);
48
+ return !old || legStatus(old) !== legStatus(payment);
49
+ }).at(-1);
50
+ if (!row) return null;
51
+ const status = legStatus(row);
52
+ if (balanceDueMinor === 0 && status === 'captured') return { state: 'complete', leg: leg(row) };
53
+ if (status === 'failed' || status === 'voided') {
54
+ const { declinedMessage } = options;
55
+ return { state: 'declined', leg: leg(row), ...(declinedMessage === undefined ? {} : { message: declinedMessage }) };
56
+ }
57
+ // The reader approved the card: shown as approved, never as paid (v2, ADR 0040 D6).
58
+ if (status === 'authorized' || status === 'captured') return { state: 'approved', leg: leg(row) };
59
+ if (!before.has(row.id) && status === 'pending') return { state: 'started', leg: leg(row) };
60
+ return null;
61
+ }
62
+
63
+ type DisplayCall = ['cart', ReceiptData | null] | ['payment', ReceiptData, DisplayPayment];
64
+
65
+ /** v2's CustomerDisplaySnapshotSource without React: each `update` shows the sale's cart, payment or idle. */
66
+ export function createSaleDisplayPublisher(link: DisplayLink, options: SaleDisplayOptions = {}): SaleDisplayPublisher {
67
+ let prior: { orderId: string; payments: readonly Payment[]; completed: boolean } | null = null;
68
+ let lastPayment: { orderId: string; payment: DisplayPayment } | null = null;
69
+ let lastKey = '';
70
+ let closed = false;
71
+ // The same call as the last one is not made again (the link dedups too; this skips building its envelope).
72
+ const send = (...call: DisplayCall) => {
73
+ const key = JSON.stringify(call);
74
+ if (key === lastKey) return;
75
+ lastKey = key;
76
+ if (call[0] === 'cart') link.showCart(call[1]);
77
+ else link.showPayment(call[1], call[2]);
78
+ };
79
+ return {
80
+ update({ order, stage }) {
81
+ if (closed) return;
82
+ const completed = stage.kind === 'receipt';
83
+ const shown: SentOrder = stage.kind === 'receipt' ? stage.order : order;
84
+ const sameOrder = prior === null || prior.orderId === shown.id;
85
+ if (!sameOrder) lastPayment = null;
86
+ const remember = () => { prior = { orderId: shown.id, payments: shown.payments, completed }; };
87
+ // An empty order shows idle; the link holds it back until afterCompleteMs after a complete.
88
+ if (!shown.lineItems.length && !shown.fees?.length && !shown.shipping?.length) {
89
+ send('cart', null);
90
+ return remember();
91
+ }
92
+ const receipt = buildReceiptData(shown, options.receipt ?? { storeName: '' });
93
+ // A switch to another sale is never a payment event.
94
+ const event = sameOrder ? derivePaymentEvent(prior?.payments ?? [], shown.payments, prior?.completed ?? false,
95
+ completed, shown.balanceDueMinor, options) : null;
96
+ if (event) {
97
+ lastPayment = { orderId: shown.id, payment: event };
98
+ send('payment', receipt, event);
99
+ } else if (stage.kind === 'tender' || completed) {
100
+ // A cash tender adds no pending leg: the display stays on the payment screen while the cashier tenders.
101
+ // On the receipt the live builder may still emit: the complete stays up, on the link's original idle timer.
102
+ const held = lastPayment?.orderId === shown.id ? lastPayment.payment : null;
103
+ send('payment', receipt, held ?? { state: completed ? 'complete' : 'started' });
104
+ } else {
105
+ send('cart', receipt);
106
+ }
107
+ remember();
108
+ },
109
+ close() {
110
+ if (closed) return;
111
+ closed = true;
112
+ link.showCart(null);
113
+ },
114
+ };
115
+ }