@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/pos",
3
- "version": "3.18.0",
3
+ "version": "3.20.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.18.0",
37
+ "@tallyui/core": "^3.20.0",
38
38
  "react": ">=18",
39
39
  "rxdb": "~17.5.0",
40
40
  "rxjs": ">=7"
41
41
  },
42
42
  "devDependencies": {
43
- "@tallyui/core": "3.18.0",
43
+ "@tallyui/core": "3.20.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.18.0",
49
- "@tallyui/connector-woocommerce": "3.18.0",
50
- "@tallyui/database": "3.18.0"
48
+ "@tallyui/connector-medusa": "3.20.0",
49
+ "@tallyui/connector-woocommerce": "3.20.0",
50
+ "@tallyui/database": "3.20.0"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsup",
@@ -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
+ }
@@ -0,0 +1,138 @@
1
+ import { DisplaySignallingError } from '@tallyui/core';
2
+ import type { DisplayClock } from './display-link';
3
+ import type { DisplayConfig, DisplayEnvelope } from './protocol';
4
+ import { encode, MAX_MESSAGE_BYTES, messageBytes } from './snapshot';
5
+
6
+ /** A display clock that also tells the time, for the snapshot re-send and the idle clear. */
7
+ export interface ServiceClock extends DisplayClock { now(): number }
8
+
9
+ export interface SnapshotBody { v: 1; seq: number; config: DisplayConfig; event: DisplayEnvelope }
10
+
11
+ export interface SnapshotSenderOptions {
12
+ post: (body: SnapshotBody) => Promise<void>;
13
+ clock: ServiceClock;
14
+ onError?: (error: unknown) => void;
15
+ }
16
+
17
+ export interface SnapshotSender {
18
+ /** The display's latest state. `active` is whether the fallback runs now. */
19
+ update(state: { active: boolean; seq: number; config: DisplayConfig; event: DisplayEnvelope | null }): void;
20
+ stop(): void;
21
+ }
22
+
23
+ // Rate and re-send follow WCPOS v2's display-session.ts (ADR-085 context and d8).
24
+ export const SNAPSHOT_MIN_INTERVAL_MS = 1000;
25
+ export const SNAPSHOT_RESEND_MS = 20_000;
26
+ /** The server keeps a snapshot for at most 60 s (ADR-085 d8). */
27
+ export const SNAPSHOT_LIFETIME_MS = 60_000;
28
+
29
+ type State = Parameters<SnapshotSender['update']>[0];
30
+ interface Body { body: SnapshotBody; key: string; idle: boolean }
31
+
32
+ const retryable = (error: unknown) =>
33
+ !(error instanceof DisplaySignallingError) || error.code === 'network' || error.code === 'server';
34
+ /** Runs a caller's function (a logger, a listener) so that its throw never reaches the fallback or the service. */
35
+ export const quietly = (run: () => void) => {
36
+ try {
37
+ run();
38
+ } catch {
39
+ // The caller's failure is its own.
40
+ }
41
+ };
42
+
43
+ /** One display's snapshot fallback (ADR-085 d8): it posts the display's state while its data channel is not open. */
44
+ export function createSnapshotSender({ post, clock, onError }: SnapshotSenderOptions): SnapshotSender {
45
+ let state: State | null = null;
46
+ let stopped = false;
47
+ let inFlight = false;
48
+ let timer: unknown = null;
49
+ let timerFor: 'change' | 'resend' | null = null;
50
+ // The last POST that settled, the body the server refused for good, and the last body over the cap.
51
+ let last: { key: string; at: number; ok: boolean } | null = null;
52
+ let refused: string | null = null;
53
+ let oversize: string | null = null;
54
+ // When a non-idle body last reached the server, and whether an idle body must clear it (rule 6).
55
+ let cartPostedAt: number | null = null;
56
+ let clearing = false;
57
+
58
+ const report = (error: unknown) => quietly(() => onError?.(error));
59
+ const clear = () => {
60
+ if (timer !== null) clock.clearTimeout(timer);
61
+ timer = timerFor = null;
62
+ };
63
+ const recent = () => cartPostedAt !== null && clock.now() - cartPostedAt < SNAPSHOT_LIFETIME_MS;
64
+
65
+ const current = (): Body | null => {
66
+ if (!state?.event) return null;
67
+ const body: SnapshotBody = { v: 1, seq: state.seq, config: state.config, event: JSON.parse(encode(state.event)) };
68
+ const key = JSON.stringify(body);
69
+ if (messageBytes(key) > MAX_MESSAGE_BYTES) {
70
+ if (key !== oversize) report(new DisplaySignallingError('too_large'));
71
+ oversize = key;
72
+ return null;
73
+ }
74
+ return { body, key, idle: state.event.action === 'display.idle' };
75
+ };
76
+ /** The body to post now or later, or null when nothing should go. */
77
+ const wanted = (): Body | null => {
78
+ const next = current();
79
+ if (!next || next.key === refused) return null;
80
+ return state?.active || (next.idle && clearing) ? next : null;
81
+ };
82
+
83
+ const schedule = () => {
84
+ if (stopped || inFlight) return;
85
+ const next = wanted();
86
+ if (!next) return clear();
87
+ if (last?.key === next.key) {
88
+ // The same body again: a success is re-sent only while active, and a retryable failure is retried, each at the re-send.
89
+ if (last.ok && !state?.active) return clear();
90
+ if (timerFor === 'resend') return;
91
+ clear();
92
+ timerFor = 'resend';
93
+ timer = clock.setTimeout(fire, Math.max(0, last.at + SNAPSHOT_RESEND_MS - clock.now()));
94
+ return;
95
+ }
96
+ // A changed body: trailing edge, so whatever is latest when the timer fires is posted.
97
+ if (timerFor === 'change') return;
98
+ clear();
99
+ timerFor = 'change';
100
+ timer = clock.setTimeout(fire, SNAPSHOT_MIN_INTERVAL_MS);
101
+ };
102
+
103
+ function fire() {
104
+ timer = timerFor = null;
105
+ if (stopped || inFlight) return;
106
+ const next = wanted();
107
+ if (!next) return;
108
+ if (last?.key === next.key && clock.now() < last.at + SNAPSHOT_RESEND_MS) return schedule();
109
+ inFlight = true;
110
+ // The executor runs `post` now, and turns a synchronous throw into a rejection.
111
+ void new Promise<void>((resolve) => resolve(post(next.body))).then(() => {
112
+ last = { key: next.key, at: clock.now(), ok: true };
113
+ cartPostedAt = next.idle ? null : clock.now();
114
+ // An idle body has cleared the server; a cart that landed after the sale went idle must be cleared in turn.
115
+ clearing = !next.idle && state?.event?.action === 'display.idle';
116
+ }, (error: unknown) => {
117
+ report(error);
118
+ if (!retryable(error)) refused = next.key;
119
+ last = { key: next.key, at: clock.now(), ok: false };
120
+ }).finally(() => {
121
+ inFlight = false;
122
+ schedule();
123
+ });
124
+ }
125
+
126
+ return {
127
+ update(next) {
128
+ if (stopped) return;
129
+ state = next;
130
+ clearing = next.event?.action === 'display.idle' && (clearing || recent());
131
+ schedule();
132
+ },
133
+ stop() {
134
+ stopped = true;
135
+ clear();
136
+ },
137
+ };
138
+ }