@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.
- package/dist/index.d.ts +3214 -1722
- package/dist/index.js +3900 -673
- package/package.json +6 -6
- package/src/currency/currency-provider.tsx +11 -4
- package/src/currency/format-money-with.ts +45 -0
- package/src/currency/index.ts +1 -0
- package/src/customer-display/display-client.ts +341 -0
- package/src/customer-display/index.ts +20 -0
- package/src/customer-display/sale-display.ts +115 -0
- package/src/customer-display/snapshot-fallback.ts +138 -0
- package/src/customer-display/till-display-service.ts +304 -0
- package/src/customer-display/till-pairing.ts +177 -0
- package/src/customer-display/use-display-client.ts +25 -0
- package/src/customer-display/use-sale-display.ts +28 -0
- package/src/customer-display/use-till-pairing.ts +35 -0
- package/src/customer-display/webrtc/index.ts +5 -0
- package/src/customer-display/webrtc/peer-link.ts +222 -0
- package/src/index.ts +37 -11
- package/src/order/index.ts +2 -1
- package/src/order/order-builder.ts +104 -16
- package/src/order/types.ts +10 -4
- package/src/payment-driver/index.ts +1 -1
- package/src/payment-driver/registry.ts +23 -0
- package/src/pos-order/__fixtures__/order-create-v8.json +117 -0
- package/src/pos-order/command.ts +19 -4
- package/src/pos-order/finalize.ts +30 -2
- package/src/pos-order/schema.ts +16 -5
- package/src/pos-order/types.ts +7 -4
- package/src/receipt/reprint.ts +3 -10
- package/src/receipt/woo-gross.ts +16 -0
- package/src/receipt-template/index.ts +8 -0
- package/src/receipt-template/render-store-template.ts +51 -0
- package/src/receipt-template/wcpos/build.ts +320 -0
- package/src/receipt-template/wcpos/context.ts +29 -0
- package/src/receipt-template/wcpos/format.ts +153 -0
- package/src/receipt-template/wcpos/from-orders.ts +203 -0
- package/src/receipt-template/wcpos/index.ts +11 -0
- package/src/receipt-template/wcpos/money.ts +42 -0
- package/src/receipt-template/wcpos/types.ts +350 -0
- package/src/register/expected.ts +60 -0
- package/src/register/index.ts +2 -2
- package/src/register/use-register-session.ts +8 -4
- package/src/sale/discount-codes.ts +7 -2
- package/src/sale/index.ts +9 -2
- package/src/sale/order-filters-query.ts +59 -0
- package/src/sale/store-priced-discount-codes.ts +52 -0
- package/src/sale/use-sale.ts +185 -21
- package/src/sale/variant-match.ts +44 -0
- package/src/scanner/camera-scan.ts +113 -0
- package/src/scanner/capabilities.ts +22 -0
- package/src/scanner/chooser-cancel.ts +8 -0
- package/src/scanner/device-identity.ts +84 -0
- package/src/scanner/device-scanner.ts +62 -0
- package/src/scanner/hid-pos-decoder.ts +60 -0
- package/src/scanner/hid-scanner.ts +171 -0
- package/src/scanner/index.ts +27 -0
- package/src/scanner/scan-dedup.ts +48 -0
- package/src/scanner/scan-events.ts +75 -0
- package/src/scanner/scan-hub-context.tsx +124 -0
- package/src/scanner/scan-session.ts +4 -0
- package/src/scanner/scanner-profiles.ts +96 -0
- package/src/scanner/serial-line-decoder.ts +58 -0
- package/src/scanner/serial-scanner.ts +227 -0
- package/src/scanner/use-barcode-scanner.ts +23 -5
- package/src/scanner/use-camera-scan.ts +57 -0
- package/src/scanner/wedge-detector.ts +28 -6
- package/src/tax/index.ts +6 -0
- package/src/tax/location-rates.ts +46 -0
- package/src/tax/sale-tax-contexts.ts +40 -0
- package/src/tax/tax-context.ts +37 -0
- package/src/tax/tax-derivation.ts +99 -0
- package/src/tax/tax-provider.tsx +4 -31
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|