@tallyui/pos 3.18.0 → 3.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/index.d.ts +3202 -1721
  2. package/dist/index.js +3871 -677
  3. package/package.json +6 -6
  4. package/src/customer-display/display-client.ts +341 -0
  5. package/src/customer-display/index.ts +20 -0
  6. package/src/customer-display/sale-display.ts +115 -0
  7. package/src/customer-display/snapshot-fallback.ts +138 -0
  8. package/src/customer-display/till-display-service.ts +304 -0
  9. package/src/customer-display/till-pairing.ts +177 -0
  10. package/src/customer-display/use-display-client.ts +25 -0
  11. package/src/customer-display/use-sale-display.ts +28 -0
  12. package/src/customer-display/use-till-pairing.ts +35 -0
  13. package/src/customer-display/webrtc/index.ts +5 -0
  14. package/src/customer-display/webrtc/peer-link.ts +222 -0
  15. package/src/index.ts +36 -10
  16. package/src/order/index.ts +2 -1
  17. package/src/order/order-builder.ts +104 -16
  18. package/src/order/types.ts +10 -4
  19. package/src/payment-driver/index.ts +1 -1
  20. package/src/payment-driver/registry.ts +23 -0
  21. package/src/pos-order/__fixtures__/order-create-v8.json +117 -0
  22. package/src/pos-order/command.ts +27 -9
  23. package/src/pos-order/finalize.ts +30 -2
  24. package/src/pos-order/schema.ts +16 -5
  25. package/src/pos-order/types.ts +7 -4
  26. package/src/receipt/reprint.ts +3 -10
  27. package/src/receipt/woo-gross.ts +16 -0
  28. package/src/receipt-template/index.ts +8 -0
  29. package/src/receipt-template/render-store-template.ts +51 -0
  30. package/src/receipt-template/wcpos/build.ts +320 -0
  31. package/src/receipt-template/wcpos/context.ts +29 -0
  32. package/src/receipt-template/wcpos/format.ts +153 -0
  33. package/src/receipt-template/wcpos/from-orders.ts +203 -0
  34. package/src/receipt-template/wcpos/index.ts +11 -0
  35. package/src/receipt-template/wcpos/money.ts +42 -0
  36. package/src/receipt-template/wcpos/types.ts +350 -0
  37. package/src/register/expected.ts +60 -0
  38. package/src/register/index.ts +2 -2
  39. package/src/register/use-register-session.ts +8 -4
  40. package/src/sale/discount-codes.ts +7 -2
  41. package/src/sale/index.ts +9 -2
  42. package/src/sale/order-filters-query.ts +59 -0
  43. package/src/sale/store-priced-discount-codes.ts +52 -0
  44. package/src/sale/use-sale.ts +157 -16
  45. package/src/sale/variant-match.ts +44 -0
  46. package/src/scanner/camera-scan.ts +113 -0
  47. package/src/scanner/capabilities.ts +22 -0
  48. package/src/scanner/chooser-cancel.ts +8 -0
  49. package/src/scanner/device-identity.ts +84 -0
  50. package/src/scanner/device-scanner.ts +62 -0
  51. package/src/scanner/hid-pos-decoder.ts +60 -0
  52. package/src/scanner/hid-scanner.ts +171 -0
  53. package/src/scanner/index.ts +27 -0
  54. package/src/scanner/scan-dedup.ts +48 -0
  55. package/src/scanner/scan-events.ts +75 -0
  56. package/src/scanner/scan-hub-context.tsx +124 -0
  57. package/src/scanner/scan-session.ts +4 -0
  58. package/src/scanner/scanner-profiles.ts +96 -0
  59. package/src/scanner/serial-line-decoder.ts +58 -0
  60. package/src/scanner/serial-scanner.ts +227 -0
  61. package/src/scanner/use-barcode-scanner.ts +23 -5
  62. package/src/scanner/use-camera-scan.ts +57 -0
  63. package/src/scanner/wedge-detector.ts +28 -6
  64. package/src/store-settings/use-store-settings.ts +23 -5
  65. package/src/tax/index.ts +6 -0
  66. package/src/tax/location-rates.ts +46 -0
  67. package/src/tax/sale-tax-contexts.ts +40 -0
  68. package/src/tax/tax-context.ts +37 -0
  69. package/src/tax/tax-derivation.ts +99 -0
  70. package/src/tax/tax-provider.tsx +4 -31
@@ -0,0 +1,304 @@
1
+ import {
2
+ DisplaySignallingError, type DisplayAdvertisement, type DisplayRecord, type DisplaySignalling, type SignalMessage,
3
+ type SyncContext,
4
+ } from '@tallyui/core';
5
+ import type { ReceiptData } from '../receipt/types';
6
+ import { createDisplayLink, type DisplayLink } from './display-link';
7
+ import type { DisplayConfig, DisplayEnvelope, DisplayPayment } from './protocol';
8
+ import { createSnapshotSender, quietly, type ServiceClock, type SnapshotSender } from './snapshot-fallback';
9
+ import type { DisplayTransport } from './transport';
10
+ import { createTillPeerLink, type PeerFactory, type PeerLink, type PeerLinkState, type SignalPort } from './webrtc';
11
+
12
+ export type { ServiceClock } from './snapshot-fallback';
13
+
14
+ /** How often the till drains its signal inbox while a link is connecting; TallyUI's choice. */
15
+ export const SIGNAL_POLL_MS = 1000;
16
+ /** How often the till lists its displays; TallyUI's choice. */
17
+ export const LIST_POLL_MS = 10_000;
18
+ /** How long a link may stay connecting before it counts as a drop; TallyUI's choice. */
19
+ export const CONNECT_TIMEOUT_MS = 30_000;
20
+
21
+ export interface TillDisplayServiceOptions {
22
+ signalling: DisplaySignalling;
23
+ /** The cashier session; null while nobody is logged in, which stops every server call (d5). */
24
+ context: () => SyncContext | null;
25
+ /** The till's own device id (d5); U8 stores it. */
26
+ deviceId: string;
27
+ advertisement: DisplayAdvertisement;
28
+ /** One display's config: the store, i18n and idle settings, with `display` from its record. */
29
+ configFor: (display: DisplayRecord) => DisplayConfig;
30
+ createPeer?: PeerFactory;
31
+ clock?: ServiceClock;
32
+ /** Every refused or failed server call, for logs. Never throws into the service. */
33
+ onError?: (error: unknown) => void;
34
+ }
35
+ export type TillDisplayStatus = 'online' | 'offline' | 'paused' | 'closed';
36
+ export interface TillDisplayEntry { display: DisplayRecord; link: PeerLinkState }
37
+ export interface TillDisplayService extends DisplayLink {
38
+ readonly status: TillDisplayStatus;
39
+ /** The owned displays from the last successful list, each with its current link's state. */
40
+ readonly displays: readonly TillDisplayEntry[];
41
+ /** Called after any change to `status` or `displays`; returns the unsubscribe. */
42
+ onChange(listener: () => void): () => void;
43
+ /** Lists now (U5 calls it after a confirm or a forget); resolves when that list settles. A `paused` service tries again. */
44
+ refresh(): Promise<void>;
45
+ }
46
+
47
+ const systemClock: ServiceClock = {
48
+ now: () => Date.now(),
49
+ setTimeout: (run, ms) => setTimeout(run, ms),
50
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
51
+ };
52
+
53
+ /** The sale states a display shows: its current event, which the snapshot carries. */
54
+ const SALE_ACTIONS: ReadonlySet<string> = new Set(['cart.updated', 'payment.state', 'display.idle']);
55
+ /** Handed to a snapshot sender in place of a POST while the server is lost or paused; retried, never logged. */
56
+ const NOT_SENT = new DisplaySignallingError('network', 'not sent: the display service is offline or paused');
57
+
58
+ type Call = ['cart', ReceiptData | null] | ['payment', ReceiptData, DisplayPayment];
59
+
60
+ interface Slot {
61
+ id: string;
62
+ record: DisplayRecord;
63
+ config: DisplayConfig;
64
+ /**
65
+ * The snapshot `seq`: the first link's is the time the display was listed, and each later link's one more. A display
66
+ * ignores a `seq` below the highest it applied (U5a), so it must not start again from 1 when the till reloads.
67
+ */
68
+ seq: number;
69
+ link: PeerLink | null;
70
+ view: DisplayLink | null;
71
+ deliver: ((message: SignalMessage) => void) | null;
72
+ connectTimer: unknown;
73
+ event: DisplayEnvelope | null;
74
+ sender: SnapshotSender;
75
+ }
76
+
77
+ /**
78
+ * The till's second-device displays (ADR-085 U4): one WebRTC link and one display link per owned display, each sale
79
+ * state fanned out to all of them (d9), the snapshot fallback while a channel is not open (d8), and d11 when the
80
+ * server is lost. It is a `DisplayLink`, so `createSaleDisplayPublisher` drives it.
81
+ */
82
+ export function createTillDisplayService(options: TillDisplayServiceOptions): TillDisplayService {
83
+ const { signalling, deviceId, advertisement, configFor, createPeer, clock = systemClock } = options;
84
+ const slots = new Map<string, Slot>();
85
+ const listeners = new Set<() => void>();
86
+ let status: TillDisplayStatus = 'online';
87
+ // A `forbidden` pause stops every call until refresh(); a null context pauses without one, and the list timer
88
+ // keeps reading context() so the till picks its displays up again when a cashier logs in (d5).
89
+ let forbidden = false;
90
+ let latest: Call | null = null;
91
+ let entries: readonly TillDisplayEntry[] = [];
92
+ const timers: { list: unknown; signal: unknown } = { list: null, signal: null };
93
+ let signalBusy = false;
94
+ let listGeneration = 0;
95
+
96
+ const report = (error: unknown) => quietly(() => options.onError?.(error));
97
+ const stopTimer = (which: keyof typeof timers) => {
98
+ if (timers[which] !== null) clock.clearTimeout(timers[which]);
99
+ timers[which] = null;
100
+ };
101
+ const emit = () => {
102
+ entries = [...slots.values()].map((slot) => ({ display: slot.record, link: slot.link?.state ?? 'closed' }));
103
+ listeners.forEach(quietly);
104
+ };
105
+ const push = (slot: Slot) => slot.sender.update({
106
+ active: advertisement.snapshot && status === 'online' && slot.record.connected && slot.link?.state !== 'open',
107
+ seq: slot.seq, config: slot.config, event: slot.event,
108
+ });
109
+ const setStatus = (next: TillDisplayStatus) => {
110
+ if (status === next || status === 'closed') return;
111
+ status = next;
112
+ slots.forEach(push);
113
+ if (next === 'online') ensureSignalPoll();
114
+ emit();
115
+ };
116
+
117
+ /** The context for a server call, or null when none may be made now. */
118
+ const contextNow = (): SyncContext | null => {
119
+ if (status === 'closed' || forbidden) return null;
120
+ const ctx = options.context();
121
+ if (!ctx) setStatus('paused');
122
+ return ctx;
123
+ };
124
+ /** The service's reading of a failed call: d11 for a lost server, a pause, or a display that is gone. */
125
+ const handle = (error: unknown, displayId?: string) => {
126
+ if (status === 'closed' || !(error instanceof DisplaySignallingError)) return;
127
+ if (error.code === 'network' || error.code === 'server') {
128
+ if (!forbidden) setStatus('offline');
129
+ } else if (error.code === 'forbidden') {
130
+ forbidden = true;
131
+ stopTimer('list');
132
+ setStatus('paused');
133
+ } else if (error.code === 'not_found' && displayId !== undefined) {
134
+ remove(displayId);
135
+ emit();
136
+ }
137
+ };
138
+ /** A server call whose failure is logged and handled, never thrown; `null` when it failed or was not made. */
139
+ const call = async <T>(work: (ctx: SyncContext) => Promise<T>, displayId?: string): Promise<{ value: T } | null> => {
140
+ try {
141
+ const ctx = contextNow();
142
+ return ctx ? { value: await work(ctx) } : null;
143
+ } catch (error) {
144
+ report(error);
145
+ handle(error, displayId);
146
+ return null;
147
+ }
148
+ };
149
+
150
+ function ensureSignalPoll() {
151
+ if (timers.signal !== null || signalBusy || status === 'closed' || status === 'paused') return;
152
+ if (![...slots.values()].some((slot) => slot.link?.state === 'connecting')) return;
153
+ timers.signal = clock.setTimeout(async () => {
154
+ timers.signal = null;
155
+ signalBusy = true;
156
+ const result = await call((ctx) => signalling.receiveSignals(ctx, deviceId));
157
+ signalBusy = false;
158
+ for (const { displayId, type, payload } of result?.value ?? []) slots.get(displayId)?.deliver?.({ type, payload });
159
+ ensureSignalPoll();
160
+ }, SIGNAL_POLL_MS);
161
+ }
162
+
163
+ /** Closes a display's link and its display link; its snapshot sender carries on with the current event. */
164
+ const dropLink = (slot: Slot) => {
165
+ const { link, view, connectTimer } = slot;
166
+ if (!link) return;
167
+ slot.link = slot.view = slot.deliver = null;
168
+ clock.clearTimeout(connectTimer);
169
+ view?.close();
170
+ link.close();
171
+ };
172
+ function remove(displayId: string) {
173
+ const slot = slots.get(displayId);
174
+ if (!slot) return;
175
+ slots.delete(displayId);
176
+ slot.sender.stop();
177
+ dropLink(slot);
178
+ }
179
+
180
+ const connect = (slot: Slot) => {
181
+ if (status !== 'online' || slot.link) return;
182
+ slot.seq += 1;
183
+ const port: SignalPort = {
184
+ send: (message) => void call((ctx) => signalling.sendSignal(ctx, deviceId, slot.id, message), slot.id),
185
+ onSignal: (listener) => {
186
+ slot.deliver = listener;
187
+ return () => void (slot.deliver === listener && (slot.deliver = null));
188
+ },
189
+ };
190
+ const link = createTillPeerLink({ signal: port, iceServers: advertisement.iceServers, createPeer });
191
+ // The tee: each sale state the display link sends is that display's current event, for its snapshot.
192
+ const tee: DisplayTransport = {
193
+ send(envelope) {
194
+ if (SALE_ACTIONS.has(envelope.action) && slot.link === link) {
195
+ slot.event = envelope;
196
+ push(slot);
197
+ }
198
+ return link.send(envelope);
199
+ },
200
+ onMessage: (listener) => link.onMessage(listener),
201
+ close: () => link.close(),
202
+ };
203
+ slot.link = link;
204
+ slot.view = createDisplayLink(tee, { config: slot.config, clock });
205
+ slot.connectTimer = clock.setTimeout(() => {
206
+ if (slot.link === link && link.state === 'connecting') link.close();
207
+ }, CONNECT_TIMEOUT_MS);
208
+ link.onStateChange((state) => {
209
+ if (slot.link !== link) return;
210
+ if (state === 'closed') dropLink(slot);
211
+ push(slot);
212
+ emit();
213
+ });
214
+ if (latest?.[0] === 'cart') slot.view.showCart(latest[1]);
215
+ else if (latest) slot.view.showPayment(latest[1], latest[2]);
216
+ ensureSignalPoll();
217
+ };
218
+
219
+ const addSlot = (record: DisplayRecord): Slot => {
220
+ const id = record.displayId;
221
+ const sender = createSnapshotSender({
222
+ clock,
223
+ onError: (error) => void (error !== NOT_SENT && report(error)),
224
+ post: async (body) => {
225
+ const ctx = status === 'online' ? contextNow() : null;
226
+ if (!ctx) throw NOT_SENT;
227
+ await signalling.postSnapshot(ctx, deviceId, id, body).catch((error: unknown) => {
228
+ handle(error, id);
229
+ throw error;
230
+ });
231
+ },
232
+ });
233
+ const slot: Slot = {
234
+ id, record, config: configFor(record), seq: clock.now() - 1, link: null, view: null, deliver: null, connectTimer: null, event: null, sender,
235
+ };
236
+ slots.set(id, slot);
237
+ return slot;
238
+ };
239
+
240
+ const reconcile = (records: readonly DisplayRecord[]) => {
241
+ const listed = new Set(records.map((record) => record.displayId));
242
+ for (const id of [...slots.keys()]) if (!listed.has(id)) remove(id);
243
+ for (const record of records) {
244
+ let slot = slots.get(record.displayId);
245
+ if (slot) Object.assign(slot, { record, config: configFor(record) });
246
+ else slot = addSlot(record);
247
+ connect(slot);
248
+ push(slot);
249
+ }
250
+ emit();
251
+ };
252
+
253
+ async function listNow(): Promise<void> {
254
+ stopTimer('list');
255
+ const generation = ++listGeneration;
256
+ const result = await call((ctx) => signalling.list(ctx, deviceId));
257
+ if (status === 'closed' || generation !== listGeneration) return;
258
+ if (result) {
259
+ setStatus('online');
260
+ // A configFor that throws is logged, and the next list tries again.
261
+ try {
262
+ reconcile(result.value);
263
+ } catch (error) {
264
+ report(error);
265
+ }
266
+ }
267
+ if (!forbidden) timers.list = clock.setTimeout(() => void listNow(), LIST_POLL_MS);
268
+ }
269
+ void listNow();
270
+
271
+ const fanOut = (next: Call) => {
272
+ if (status === 'closed') return;
273
+ latest = next;
274
+ for (const { view } of slots.values()) {
275
+ if (next[0] === 'cart') view?.showCart(next[1]);
276
+ else view?.showPayment(next[1], next[2]);
277
+ }
278
+ };
279
+
280
+ return {
281
+ get status() { return status; },
282
+ get displays() { return entries; },
283
+ onChange(listener) {
284
+ listeners.add(listener);
285
+ return () => void listeners.delete(listener);
286
+ },
287
+ refresh() {
288
+ if (status === 'closed') return Promise.resolve();
289
+ forbidden = false;
290
+ return listNow();
291
+ },
292
+ showCart: (receipt) => fanOut(['cart', receipt]),
293
+ showPayment: (receipt, payment) => fanOut(['payment', receipt, payment]),
294
+ close() {
295
+ if (status === 'closed') return;
296
+ stopTimer('list');
297
+ stopTimer('signal');
298
+ for (const id of [...slots.keys()]) remove(id);
299
+ status = 'closed';
300
+ emit();
301
+ listeners.clear();
302
+ },
303
+ };
304
+ }
@@ -0,0 +1,177 @@
1
+ import { DisplaySignallingError, type DisplaySignalling, type PendingPairing, type SyncContext } from '@tallyui/core';
2
+ import { quietly, type ServiceClock } from './snapshot-fallback';
3
+ import type { TillDisplayService } from './till-display-service';
4
+
5
+ /** How often the till lists the claims on its code while it shows one; TallyUI's choice. */
6
+ export const PENDING_POLL_MS = 2000;
7
+
8
+ export type PairingError = 'forbidden' | 'limit' | 'expired' | 'not_found' | 'network' | 'server';
9
+ export type PairingPhase =
10
+ | { phase: 'idle'; error?: PairingError }
11
+ | { phase: 'minting' }
12
+ | { phase: 'code'; code: string; expiresAt: string; claims: PendingPairing[] }
13
+ | { phase: 'confirming'; claimId: string };
14
+ export interface TillPairingOptions {
15
+ signalling: DisplaySignalling;
16
+ /** The cashier session; null while nobody is logged in, which refuses every call as `forbidden` (d5). */
17
+ context: () => SyncContext | null;
18
+ /** The till's own device id (d5). */
19
+ deviceId: string;
20
+ /** U4's service, refreshed after a confirm or a forget. */
21
+ service?: Pick<TillDisplayService, 'refresh'>;
22
+ clock?: ServiceClock;
23
+ /** Every refused or failed call, for logs. Never throws into the pairing. */
24
+ onError?: (error: unknown) => void;
25
+ }
26
+ export interface TillPairing {
27
+ readonly phase: PairingPhase;
28
+ /** The last forget's refusal, cleared by the next forget. */
29
+ readonly forgetError: PairingError | null;
30
+ /** Called after any change to `phase` or `forgetError`; returns the unsubscribe. */
31
+ onChange(listener: () => void): () => void;
32
+ start(): Promise<void>;
33
+ confirm(claimId: string): Promise<void>;
34
+ decline(claimId: string): Promise<void>;
35
+ /** Back to idle; the minted code is left to expire on the server. */
36
+ cancel(): void;
37
+ forget(displayId: string): Promise<void>;
38
+ close(): void;
39
+ }
40
+
41
+ const systemClock: ServiceClock = {
42
+ now: () => Date.now(),
43
+ setTimeout: (run, ms) => setTimeout(run, ms),
44
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
45
+ };
46
+
47
+ const NAMED: ReadonlySet<string> = new Set<PairingError>(['forbidden', 'limit', 'expired', 'not_found', 'network', 'server']);
48
+ /** A signalling refusal keeps its code; anything else is `server`. */
49
+ const nameOf = (error: unknown): PairingError =>
50
+ error instanceof DisplaySignallingError && NAMED.has(error.code) ? (error.code as PairingError) : 'server';
51
+
52
+ /**
53
+ * The till's pairing flow (ADR-085 U5, d4, d5): mint a code, list its claims with each display's check code (#705),
54
+ * confirm or decline one, and forget a paired display. Framework-free; `useTillPairing` renders it.
55
+ */
56
+ export function createTillPairing(options: TillPairingOptions): TillPairing {
57
+ const { signalling, deviceId, service, clock = systemClock } = options;
58
+ const listeners = new Set<() => void>();
59
+ let phase: PairingPhase = { phase: 'idle' };
60
+ let forgetError: PairingError | null = null;
61
+ let closed = false;
62
+ // Bumped on each change of flow, so a call that settles after it is ignored.
63
+ let epoch = 0;
64
+ // The one timer while a code shows: the next poll, or the expiry when that comes first.
65
+ let timer: unknown = null;
66
+
67
+ const report = (error: unknown) => quietly(() => options.onError?.(error));
68
+ const emit = () => listeners.forEach(quietly);
69
+ const setPhase = (next: PairingPhase) => {
70
+ if (next.phase !== 'code' && timer !== null) {
71
+ clock.clearTimeout(timer);
72
+ timer = null;
73
+ }
74
+ phase = next;
75
+ emit();
76
+ };
77
+ const idle = (error?: PairingError) => setPhase(error ? { phase: 'idle', error } : { phase: 'idle' });
78
+ /** Runs one signalling call with the cashier session; a missing session is a `forbidden` refusal, with no call. */
79
+ const run = <T>(work: (ctx: SyncContext) => Promise<T>): Promise<T> => {
80
+ const ctx = options.context();
81
+ return ctx ? work(ctx) : Promise.reject(new DisplaySignallingError('forbidden', 'no cashier session'));
82
+ };
83
+ const refresh = async () => {
84
+ if (!closed) await (async () => service?.refresh())().catch(report);
85
+ };
86
+
87
+ /** While `mine`'s code shows: expire it at `expiresAt`, else poll its claims in `PENDING_POLL_MS`. */
88
+ const tick = (mine: number) => {
89
+ if (mine !== epoch || phase.phase !== 'code') return;
90
+ const left = Date.parse(phase.expiresAt) - clock.now();
91
+ if (!(left > 0)) return idle('expired');
92
+ timer = clock.setTimeout(left > PENDING_POLL_MS ? () => void poll(mine) : () => tick(mine), Math.min(left, PENDING_POLL_MS));
93
+ };
94
+ const poll = async (mine: number) => {
95
+ timer = null;
96
+ try {
97
+ const claims = await run((ctx) => signalling.pending(ctx, deviceId));
98
+ if (mine === epoch && phase.phase === 'code') setPhase({ ...phase, claims });
99
+ } catch (error) {
100
+ report(error);
101
+ if (mine === epoch && phase.phase === 'code' && nameOf(error) === 'forbidden') idle('forbidden');
102
+ }
103
+ tick(mine);
104
+ };
105
+
106
+ return {
107
+ get phase() { return phase; },
108
+ get forgetError() { return forgetError; },
109
+ onChange(listener) {
110
+ listeners.add(listener);
111
+ return () => void listeners.delete(listener);
112
+ },
113
+ async start() {
114
+ if (closed) return;
115
+ const mine = ++epoch;
116
+ setPhase({ phase: 'minting' });
117
+ try {
118
+ const { code, expiresAt } = await run((ctx) => signalling.mint(ctx, deviceId));
119
+ if (mine !== epoch) return;
120
+ setPhase({ phase: 'code', code, expiresAt, claims: [] });
121
+ tick(mine);
122
+ } catch (error) {
123
+ report(error);
124
+ if (mine === epoch) idle(nameOf(error));
125
+ }
126
+ },
127
+ async confirm(claimId) {
128
+ if (closed || phase.phase !== 'code') return;
129
+ const mine = ++epoch;
130
+ setPhase({ phase: 'confirming', claimId });
131
+ try {
132
+ await run((ctx) => signalling.confirm(ctx, deviceId, claimId));
133
+ } catch (error) {
134
+ report(error);
135
+ if (mine === epoch) idle(nameOf(error));
136
+ return;
137
+ }
138
+ await refresh();
139
+ if (mine === epoch) idle();
140
+ },
141
+ async decline(claimId) {
142
+ if (closed || phase.phase !== 'code') return;
143
+ const mine = epoch;
144
+ try {
145
+ await run((ctx) => signalling.decline(ctx, deviceId, claimId));
146
+ } catch (error) {
147
+ return report(error);
148
+ }
149
+ if (mine === epoch && phase.phase === 'code') setPhase({ ...phase, claims: phase.claims.filter((claim) => claim.claimId !== claimId) });
150
+ },
151
+ cancel() {
152
+ if (closed) return;
153
+ epoch += 1;
154
+ idle();
155
+ },
156
+ async forget(displayId) {
157
+ if (closed) return;
158
+ if (forgetError !== null) { forgetError = null; emit(); }
159
+ try {
160
+ await run((ctx) => signalling.forget(ctx, deviceId, displayId));
161
+ } catch (error) {
162
+ report(error);
163
+ if (closed) return;
164
+ forgetError = nameOf(error);
165
+ return emit();
166
+ }
167
+ await refresh();
168
+ },
169
+ close() {
170
+ if (closed) return;
171
+ closed = true;
172
+ epoch += 1;
173
+ if (timer !== null) clock.clearTimeout(timer);
174
+ listeners.clear();
175
+ },
176
+ };
177
+ }
@@ -0,0 +1,25 @@
1
+ import { useCallback, useSyncExternalStore } from 'react';
2
+ import type { DisplayClient, DisplayClientPhase } from './display-client';
3
+ import { initialDisplayState, type DisplayState } from './display-state';
4
+
5
+ export interface DisplayClientView { phase: DisplayClientPhase; state: DisplayState }
6
+
7
+ const STARTING: DisplayClientView = { phase: { phase: 'starting' }, state: initialDisplayState };
8
+ // The last view handed out per client, so the hook returns the same object until the client changes.
9
+ const views = new WeakMap<DisplayClient, DisplayClientView>();
10
+ const noSubscription = () => () => {};
11
+
12
+ function viewOf(client: DisplayClient): DisplayClientView {
13
+ const last = views.get(client);
14
+ if (last && last.phase === client.phase && last.state === client.state) return last;
15
+ const view = { phase: client.phase, state: client.state };
16
+ views.set(client, view);
17
+ return view;
18
+ }
19
+
20
+ /** The display client's phase and screen state for React; a null client is `starting`. */
21
+ export function useDisplayClient(client: DisplayClient | null): DisplayClientView {
22
+ const subscribe = useCallback((listener: () => void) => (client ? client.onChange(listener) : noSubscription()), [client]);
23
+ const getSnapshot = useCallback(() => (client ? viewOf(client) : STARTING), [client]);
24
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
25
+ }
@@ -0,0 +1,28 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import type { DisplayLink } from './display-link';
3
+ import { createSaleDisplayPublisher, type SaleDisplayInput, type SaleDisplayOptions, type SaleDisplayPublisher } from './sale-display';
4
+
5
+ /** Publishes the sale to `link` on every change; a null link publishes nothing. Closes the publisher when the link changes or on unmount. */
6
+ export function useSaleDisplay(link: DisplayLink | null, sale: SaleDisplayInput, options?: SaleDisplayOptions): void {
7
+ // Read through a ref, so a new options object each render neither re-creates the publisher nor goes stale.
8
+ const latest = useRef(options);
9
+ useEffect(() => { latest.current = options; });
10
+ const held = useRef<{ link: DisplayLink; publisher: SaleDisplayPublisher } | null>(null);
11
+ useEffect(() => {
12
+ if (!link) return;
13
+ if (held.current?.link !== link) {
14
+ const live: SaleDisplayOptions = {
15
+ get receipt() { return latest.current?.receipt; },
16
+ get methodTitle() { return latest.current?.methodTitle; },
17
+ get declinedMessage() { return latest.current?.declinedMessage; },
18
+ };
19
+ held.current = { link, publisher: createSaleDisplayPublisher(link, live) };
20
+ }
21
+ held.current.publisher.update({ order: sale.order, stage: sale.stage });
22
+ }, [link, sale.order, sale.stage]);
23
+ // Closes the old link's publisher; the hook test pins that the old link gets idle and the new one the sale.
24
+ useEffect(() => () => {
25
+ held.current?.publisher.close();
26
+ held.current = null;
27
+ }, [link]);
28
+ }
@@ -0,0 +1,35 @@
1
+ import { useCallback, useRef, useSyncExternalStore } from 'react';
2
+ import type { TillDisplayService, TillDisplayEntry, TillDisplayStatus } from './till-display-service';
3
+ import type { PairingError, PairingPhase, TillPairing } from './till-pairing';
4
+
5
+ export interface TillPairingView { phase: PairingPhase; forgetError: PairingError | null }
6
+ export interface TillDisplaysView { status: TillDisplayStatus; displays: readonly TillDisplayEntry[] }
7
+
8
+ const NO_PAIRING: TillPairingView = { phase: { phase: 'idle' }, forgetError: null };
9
+ const NO_DISPLAYS: TillDisplaysView = { status: 'closed', displays: [] };
10
+
11
+ /** A store over `source.onChange` whose snapshot is a new object only when one of its parts changed. */
12
+ function useView<S extends { onChange(listener: () => void): () => void }, V extends object>(
13
+ source: S | null, empty: V, read: (source: S) => V,
14
+ ): V {
15
+ const held = useRef<V | null>(null);
16
+ const subscribe = useCallback((listener: () => void) => source?.onChange(listener) ?? (() => {}), [source]);
17
+ const snapshot = () => {
18
+ if (!source) return empty;
19
+ const next = read(source);
20
+ const last = held.current;
21
+ if (!last || (Object.keys(next) as Array<keyof V>).some((key) => last[key] !== next[key])) held.current = next;
22
+ return held.current as V;
23
+ };
24
+ return useSyncExternalStore(subscribe, snapshot, snapshot);
25
+ }
26
+
27
+ /** The till pairing's phase and last forget refusal, re-rendered on each change; null gives idle. */
28
+ export function useTillPairing(pairing: TillPairing | null): TillPairingView {
29
+ return useView(pairing, NO_PAIRING, (p) => ({ phase: p.phase, forgetError: p.forgetError }));
30
+ }
31
+
32
+ /** The till display service's status and displays, re-rendered on each change; null gives `closed` with none. */
33
+ export function useTillDisplays(service: TillDisplayService | null): TillDisplaysView {
34
+ return useView(service, NO_DISPLAYS, (s) => ({ status: s.status, displays: s.displays }));
35
+ }
@@ -0,0 +1,5 @@
1
+ export { createTillPeerLink, createDisplayPeerLink } from './peer-link';
2
+ export type {
3
+ SignalPort, PeerLink, PeerLinkState, PeerLinkOptions, PeerFactory, RTCPeerConnectionLike, RTCDataChannelLike,
4
+ SessionDescriptionLike,
5
+ } from './peer-link';