@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,75 @@
1
+ // Ported from WCPOS v2 packages/scanner/src/scan-events.ts (monorepo 85ecbd43f).
2
+ import { EMPTY, Observable, Subject } from 'rxjs';
3
+
4
+ /** The normalized scan event every input source emits. Structured sources
5
+ * (serial, HID-POS, camera) bypass the wedge timing heuristic and construct
6
+ * these directly; the wedge detector's emissions are wrapped in one. */
7
+ export type ScanSourceKind = 'wedge' | 'wedge-attributed' | 'serial' | 'hid-pos' | 'ble' | 'camera';
8
+
9
+ export interface ScanSource {
10
+ kind: ScanSourceKind;
11
+ /** Scanner profile id for explicitly-configured sources. */
12
+ profileId?: string;
13
+ /** Human-readable device name where the platform provides one. */
14
+ deviceName?: string;
15
+ }
16
+
17
+ export interface ScanEvent {
18
+ code: string;
19
+ /** Symbology where the source knows it (HID-POS reports, camera decoders). */
20
+ symbology?: string;
21
+ source: ScanSource;
22
+ timestamp: number;
23
+ }
24
+
25
+ export interface ScanBus {
26
+ emit: (event: ScanEvent) => void;
27
+ /** The routed stream consumers subscribe to. Every event flows through;
28
+ * prefix-based routing (customer cards, embedded barcodes) plugs in here as
29
+ * upstream filters when those features land. */
30
+ events$: Observable<ScanEvent>;
31
+ }
32
+
33
+ export interface ScanHub {
34
+ /** All scan events from every registered source, hot and multicast. */
35
+ readonly events$: Observable<ScanEvent>;
36
+ /** Register a source and return a function that unregisters it. */
37
+ registerSource(source$: Observable<ScanEvent>): () => void;
38
+ /** Emit from a push-style producer such as the camera decoder. */
39
+ emit(event: ScanEvent): void;
40
+ }
41
+
42
+ export const inertScanHub: ScanHub = {
43
+ events$: EMPTY,
44
+ registerSource: () => () => undefined,
45
+ emit: () => undefined,
46
+ };
47
+
48
+ export function createScanHub(): ScanHub {
49
+ const subject = new Subject<ScanEvent>();
50
+ return {
51
+ events$: subject.asObservable(),
52
+ registerSource: (source$) => {
53
+ // A failing source must not take down the shared channel: scanning from
54
+ // every other registered source keeps working; the errored source is
55
+ // simply dropped (its owner is responsible for reconnect/retry).
56
+ const subscription = source$.subscribe({
57
+ next: (event) => subject.next(event),
58
+ error: () => undefined,
59
+ });
60
+ return () => subscription.unsubscribe();
61
+ },
62
+ emit: (event) => subject.next(event),
63
+ };
64
+ }
65
+
66
+ /** A scan bus is scoped to its consumer surface (e.g. the products screen
67
+ * wires its input sources into one bus), deliberately not a global singleton,
68
+ * so a settings test panel's captures never leak into the cart. */
69
+ export function createScanBus(): ScanBus {
70
+ const subject = new Subject<ScanEvent>();
71
+ return {
72
+ emit: (event) => subject.next(event),
73
+ events$: subject.asObservable(),
74
+ };
75
+ }
@@ -0,0 +1,124 @@
1
+ // Ported from WCPOS v2 packages/core/src/screens/main/hooks/barcodes/scan-hub-context.tsx (monorepo 85ecbd43f).
2
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
3
+ import type { ReactNode } from 'react';
4
+
5
+ import type { DeviceScanner, DeviceScannerErrorHandler, DeviceScannerSettings, DeviceScannerState,
6
+ ScannerProfileStore } from './device-scanner';
7
+ import { createHidScanner, type HidLike } from './hid-scanner';
8
+ import { createScanHub, inertScanHub, type ScanHub } from './scan-events';
9
+ import { createSerialScanner, type SerialLike, type SerialScannerOptions } from './serial-scanner';
10
+
11
+ /** One device source's connect controls and live status (v2's UseSerialScanResult shape). */
12
+ export interface DeviceScanControl {
13
+ available: boolean;
14
+ /** Opens the browser chooser: call it inside a click gesture. */
15
+ connect: () => Promise<void>;
16
+ disconnect: () => Promise<void>;
17
+ connected: boolean;
18
+ /** deviceKey of the scanner this source holds open, or null: tells which saved profile is live. */
19
+ connectedDeviceKey: string | null;
20
+ }
21
+ export interface DeviceScanControls { serial: DeviceScanControl; hid: DeviceScanControl }
22
+
23
+ const inertControl: DeviceScanControl = {
24
+ available: false,
25
+ connect: async () => undefined,
26
+ disconnect: async () => undefined,
27
+ connected: false,
28
+ connectedDeviceKey: null,
29
+ };
30
+ export const inertDeviceScanControls: DeviceScanControls = { serial: inertControl, hid: inertControl };
31
+
32
+ const ScanHubContext = createContext<ScanHub>(inertScanHub);
33
+ const DeviceScanControlsContext = createContext<DeviceScanControls>(inertDeviceScanControls);
34
+
35
+ export interface ScanHubProviderProps {
36
+ children: ReactNode;
37
+ /** Usually scannerProfileStore(db.collections.scanner_profiles). */
38
+ profiles: ScannerProfileStore;
39
+ /** Read at scan time: changing it does not reconnect. */
40
+ settings: DeviceScannerSettings;
41
+ /** Defaults to navigator.serial / navigator.hid where present (undefined elsewhere, e.g. native). */
42
+ serial?: SerialLike;
43
+ hid?: HidLike;
44
+ onError?: DeviceScannerErrorHandler;
45
+ }
46
+
47
+ interface Controllers { serial: DeviceScanner; hid: DeviceScanner }
48
+
49
+ const DISCONNECTED: DeviceScannerState = { connected: false, connectedDeviceKey: null };
50
+ const noSubscription = () => () => undefined;
51
+ const browserNavigator = () =>
52
+ (typeof navigator !== 'undefined' ? navigator : undefined) as { serial?: SerialLike; hid?: HidLike } | undefined;
53
+
54
+ function useDeviceScanControl(scanner: DeviceScanner | null): DeviceScanControl {
55
+ const subscribe = useCallback(
56
+ (listener: () => void) => (scanner ? scanner.subscribe(() => listener()) : noSubscription()),
57
+ [scanner],
58
+ );
59
+ const getState = useCallback(() => (scanner ? scanner.getState() : DISCONNECTED), [scanner]);
60
+ const state = useSyncExternalStore(subscribe, getState, getState);
61
+ return useMemo(
62
+ () => (scanner
63
+ ? { available: scanner.available, connect: scanner.connect, disconnect: scanner.disconnect,
64
+ connected: state.connected, connectedDeviceKey: state.connectedDeviceKey }
65
+ : inertControl),
66
+ [scanner, state],
67
+ );
68
+ }
69
+
70
+ /** Owns the app-scoped scan hub and the direct (Web Serial, WebHID) scanner connections. Mounting it above
71
+ * navigation keeps those connections alive between screens; on mount it silently reopens the saved scanners. */
72
+ export function ScanHubProvider({ children, ...props }: ScanHubProviderProps) {
73
+ const latest = useRef(props);
74
+ latest.current = props;
75
+ const [hub] = useState(() => createScanHub());
76
+ // Created in the mount effect, not at render, so StrictMode's mount, unmount and remount disposes the first pair
77
+ // and replaces it, rather than leaving a disposed controller in use.
78
+ const [controllers, setControllers] = useState<Controllers | null>(null);
79
+
80
+ useEffect(() => {
81
+ const nav = browserNavigator();
82
+ // Every prop is read through the ref at call time, so a new prop never recreates a controller.
83
+ const shared: Omit<SerialScannerOptions, 'serial'> = {
84
+ profiles: {
85
+ read: (types) => latest.current.profiles.read(types),
86
+ save: (profile) => latest.current.profiles.save(profile),
87
+ },
88
+ getSettings: () => latest.current.settings,
89
+ emit: hub.emit,
90
+ onError: (error, info) => latest.current.onError?.(error, info),
91
+ };
92
+ const next: Controllers = {
93
+ serial: createSerialScanner({ ...shared, serial: latest.current.serial ?? nav?.serial }),
94
+ hid: createHidScanner({ ...shared, hid: latest.current.hid ?? nav?.hid }),
95
+ };
96
+ setControllers(next);
97
+ void next.serial.reopenSaved();
98
+ void next.hid.reopenSaved();
99
+ return () => {
100
+ void next.serial.dispose();
101
+ void next.hid.dispose();
102
+ };
103
+ }, [hub]);
104
+
105
+ const serial = useDeviceScanControl(controllers?.serial ?? null);
106
+ const hid = useDeviceScanControl(controllers?.hid ?? null);
107
+ const controls = useMemo<DeviceScanControls>(() => ({ serial, hid }), [serial, hid]);
108
+
109
+ return (
110
+ <ScanHubContext.Provider value={hub}>
111
+ <DeviceScanControlsContext.Provider value={controls}>{children}</DeviceScanControlsContext.Provider>
112
+ </ScanHubContext.Provider>
113
+ );
114
+ }
115
+
116
+ /** The provider's hub, or inertScanHub with no provider. */
117
+ export function useScanHub(): ScanHub {
118
+ return useContext(ScanHubContext);
119
+ }
120
+
121
+ /** The provider's controls, or inertDeviceScanControls with no provider. */
122
+ export function useDeviceScanControls(): DeviceScanControls {
123
+ return useContext(DeviceScanControlsContext);
124
+ }
@@ -7,6 +7,9 @@ export interface ScanSessionOptions {
7
7
  onAccept: (code: string, symbology?: string) => void;
8
8
  cooldownMs?: number;
9
9
  now?: () => number;
10
+ /** A camera sees one item many times while it rests in view: when true, a refused repeat also restarts that
11
+ * code's cooldown, so the item is accepted again only cooldownMs after it was last seen (v2 scan-session.ts:156-162). */
12
+ continuous?: boolean;
10
13
  }
11
14
  export interface ScanSession {
12
15
  offer: (code: string, symbology?: string) => ScanOfferResult;
@@ -74,6 +77,7 @@ export function createScanSession(options: ScanSessionOptions): ScanSession {
74
77
  }
75
78
  const lastAt = cooldownFrom.get(code);
76
79
  if (lastAt !== undefined && at - lastAt < cooldownMs) {
80
+ if (options.continuous) cooldownFrom.set(code, at);
77
81
  return { accepted: false, reason: 'cooldown' };
78
82
  }
79
83
  cooldownFrom.set(code, at);
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Scanners set up on this device. Local only, never replicated; the app adds the collection as
3
+ * `scanner_profiles`. Ported from WCPOS v2 `packages/database/src/collections/schemas/scanner-profiles.ts`
4
+ * (monorepo 85ecbd43f, version 0, device-local) and its helpers in `packages/query/src/store-local/scanner-profiles.ts`.
5
+ * `deviceKey` (from `scannerDeviceKey()`) is the primary key and the only field anything matches on; every other
6
+ * identity field is display data. v2's `connectionType` `default: 'keyboard'` is left out because the field is required.
7
+ */
8
+ import type { RxCollection, RxDatabase, RxJsonSchema } from 'rxdb';
9
+ import { map, type Observable } from 'rxjs';
10
+ import { SCANNER_DEVICE_KEY_MAX_LENGTH, type ScannerConnectionType } from './device-identity';
11
+
12
+ export const SCANNER_PROFILES_COLLECTION = 'scanner_profiles';
13
+
14
+ export interface ScannerProfile {
15
+ /** scannerDeviceKey(): "<connectionType>:<normalized identity>". The primary key: one profile per device. */
16
+ deviceKey: string;
17
+ /** User-assigned, e.g. "Front counter scanner"; the UI falls back to deviceName when blank. */
18
+ name?: string;
19
+ connectionType: ScannerConnectionType;
20
+ /** As the platform reports it. Display only. */
21
+ deviceName: string;
22
+ /** USB vendor id where the platform reports one. Display only. */
23
+ vendorId?: number;
24
+ productId?: number;
25
+ /** Bluetooth service UUID, lowercase. Display only. */
26
+ serviceUuid?: string;
27
+ /** bluetooth-le platform peripheral id. Display only. */
28
+ peripheralId?: string;
29
+ /** ISO 8601 instant the profile was registered. */
30
+ createdAt?: string;
31
+ }
32
+
33
+ export const scannerProfileSchema: RxJsonSchema<ScannerProfile> = {
34
+ title: 'Scanner profiles', version: 0, primaryKey: 'deviceKey', type: 'object', additionalProperties: false,
35
+ properties: {
36
+ deviceKey: { type: 'string', maxLength: SCANNER_DEVICE_KEY_MAX_LENGTH },
37
+ name: { type: 'string' },
38
+ connectionType: { type: 'string', enum: ['keyboard', 'usb-serial', 'bluetooth-spp', 'bluetooth-le', 'hid-pos'] },
39
+ deviceName: { type: 'string' },
40
+ vendorId: { type: 'integer' },
41
+ productId: { type: 'integer' },
42
+ serviceUuid: { type: 'string' },
43
+ peripheralId: { type: 'string' },
44
+ createdAt: { type: 'string' },
45
+ },
46
+ required: ['deviceKey', 'connectionType', 'deviceName'],
47
+ };
48
+
49
+ export function scannerProfileCollection(): { readonly schema: RxJsonSchema<ScannerProfile> } {
50
+ return { schema: scannerProfileSchema } as const;
51
+ }
52
+
53
+ export type ScannerProfileCollection = RxCollection<ScannerProfile>;
54
+
55
+ export async function addScannerProfileCollection(db: RxDatabase): Promise<ScannerProfileCollection> {
56
+ const added = await db.addCollections({ [SCANNER_PROFILES_COLLECTION]: scannerProfileCollection() });
57
+ return added[SCANNER_PROFILES_COLLECTION] as ScannerProfileCollection;
58
+ }
59
+
60
+ function profilesQuery(collection: ScannerProfileCollection, types?: readonly ScannerConnectionType[]) {
61
+ if (!types?.length) return collection.find();
62
+ return collection.find({ selector: { connectionType: types.length === 1 ? types[0] : { $in: [...types] } } });
63
+ }
64
+
65
+ /** The profiles as JSON rows, filtered to `types` when non-empty, re-emitting on every change. */
66
+ export function scannerProfiles$(
67
+ collection: ScannerProfileCollection, types?: readonly ScannerConnectionType[],
68
+ ): Observable<ScannerProfile[]> {
69
+ return profilesQuery(collection, types).$.pipe(map((docs) => docs.map((doc) => doc.toJSON())));
70
+ }
71
+
72
+ /** One-shot read with the same filter. */
73
+ export async function readScannerProfiles(
74
+ collection: ScannerProfileCollection, types?: readonly ScannerConnectionType[],
75
+ ): Promise<ScannerProfile[]> {
76
+ const docs = await profilesQuery(collection, types).exec();
77
+ return docs.map((doc) => doc.toJSON());
78
+ }
79
+
80
+ /** Upsert on deviceKey: saving an existing device's profile again replaces it (a rename), never adds a twin. */
81
+ export async function saveScannerProfile(collection: ScannerProfileCollection, profile: ScannerProfile): Promise<void> {
82
+ await collection.upsert(profile);
83
+ }
84
+
85
+ /** true when this call removed the profile; false when it was absent or another removal won the race. */
86
+ export async function removeScannerProfile(collection: ScannerProfileCollection, deviceKey: string): Promise<boolean> {
87
+ const doc = await collection.findOne(deviceKey).exec();
88
+ if (!doc) return false;
89
+ try {
90
+ await doc.remove();
91
+ } catch (error) {
92
+ if (!(await collection.findOne(deviceKey).exec())) return false;
93
+ throw error;
94
+ }
95
+ return true;
96
+ }
@@ -0,0 +1,58 @@
1
+ // Ported from WCPOS v2 packages/scanner/src/serial-line-decoder.ts (monorepo 85ecbd43f).
2
+ import { stripBoundary, type WedgeSettings } from './wedge-detector';
3
+
4
+ /** Frames a text stream from a serial (USB-CDC / Bluetooth-SPP) scanner into
5
+ * complete barcodes. Unlike the wedge detector there is no timing heuristic:
6
+ * a serial scanner ends each scan with a terminator (CR, LF or CRLF), so a
7
+ * line ends the moment a terminator arrives. */
8
+
9
+ const DEFAULT_TERMINATORS = ['\r', '\n'];
10
+
11
+ export interface SerialLineDecoderOptions {
12
+ /** A completed line, configured prefix/suffix stripped, non-empty. */
13
+ onScan: (code: string) => void;
14
+ /** Chars that terminate a line. Defaults to CR and LF (handles CRLF too). */
15
+ terminators?: string[];
16
+ /** Read current prefix/suffix at emit time (same stripping as the wedge). */
17
+ getSettings?: () => Pick<WedgeSettings, 'prefix' | 'suffix'>;
18
+ }
19
+
20
+ export interface SerialLineDecoder {
21
+ /** Feed a chunk of decoded text (already TextDecoder'd from bytes). */
22
+ push: (chunk: string) => void;
23
+ /** Drop any buffered partial line (device disconnect). */
24
+ reset: () => void;
25
+ }
26
+
27
+ const NO_BOUNDARY = { prefix: '', suffix: '' };
28
+
29
+ export function createSerialLineDecoder(options: SerialLineDecoderOptions): SerialLineDecoder {
30
+ const terminators = new Set(options.terminators ?? DEFAULT_TERMINATORS);
31
+ const getSettings = options.getSettings ?? (() => NO_BOUNDARY);
32
+ let buffer = '';
33
+
34
+ const emit = () => {
35
+ if (buffer.length === 0) return;
36
+ const line = buffer;
37
+ buffer = '';
38
+ const settings = getSettings();
39
+ const code = stripBoundary(line.split(''), { threshold: 0, ...settings });
40
+ if (code.length > 0) options.onScan(code);
41
+ };
42
+
43
+ const push = (chunk: string) => {
44
+ for (const char of chunk) {
45
+ // A terminator ends the current line; consecutive terminators (CRLF, or
46
+ // blank lines) collapse because the buffer is empty.
47
+ if (terminators.has(char)) emit();
48
+ else buffer += char;
49
+ }
50
+ };
51
+
52
+ return {
53
+ push,
54
+ reset: () => {
55
+ buffer = '';
56
+ },
57
+ };
58
+ }
@@ -0,0 +1,227 @@
1
+ // Ported from WCPOS v2 packages/core/src/screens/main/pos/products/use-serial-scan.web.ts (monorepo 85ecbd43f), as a framework-agnostic controller.
2
+ /** Web Serial (USB-CDC / Bluetooth-SPP) barcode source. Reads the port's byte stream, frames it into barcodes with
3
+ * the shared serial-line decoder, dedups via the scan session, and emits `serial` ScanEvents. */
4
+ import { isChooserCancel } from './chooser-cancel';
5
+ import { normalizeUuid, scannerDeviceKey, type ScannerIdentity } from './device-identity';
6
+ import { createDeviceScannerStateCell, type DeviceScanner, type DeviceScannerErrorHandler, type DeviceScannerSettings,
7
+ type ScannerProfileStore } from './device-scanner';
8
+ import type { ScanEvent } from './scan-events';
9
+ import { createScanSession } from './scan-session';
10
+ import { createSerialLineDecoder } from './serial-line-decoder';
11
+
12
+ export const DEFAULT_SERIAL_BAUD_RATE = 9600;
13
+
14
+ // Chromium's chooser only lists unmapped Bluetooth RFCOMM ports whose service class is the standard Serial Port
15
+ // Profile (0x1101); any other UUID must be named in `allowedBluetoothServiceClassIds` or the device is silently absent
16
+ // (https://developer.chrome.com/blog/serial-over-bluetooth). Scanners with a vendor-specific RFCOMM service go here as
17
+ // we learn their UUIDs; saved profiles' UUIDs are added at request time. Known limitation: a FIRST-TIME scanner with a
18
+ // vendor UUID not yet in this list cannot appear in the chooser at all; manual UUID entry is planned for setup.
19
+ export const STANDARD_SPP_SERVICE_CLASS_ID = '00001101-0000-1000-8000-00805f9b34fb';
20
+ const KNOWN_SCANNER_BLUETOOTH_SERVICE_CLASS_IDS: string[] = [STANDARD_SPP_SERVICE_CLASS_ID];
21
+
22
+ // Minimal Web Serial typings (not in the TS DOM lib).
23
+ /** bluetoothServiceClassId: the service class UUID of a Bluetooth RFCOMM port (no USB ids on those). */
24
+ export interface SerialPortInfoLike { usbVendorId?: number; usbProductId?: number; bluetoothServiceClassId?: string }
25
+ export interface SerialPortLike {
26
+ open: (options: { baudRate: number }) => Promise<void>;
27
+ close: () => Promise<void>;
28
+ readable: ReadableStream<Uint8Array> | null;
29
+ getInfo: () => SerialPortInfoLike;
30
+ }
31
+ export interface SerialLike {
32
+ requestPort: (options?: { allowedBluetoothServiceClassIds?: string[] }) => Promise<SerialPortLike>;
33
+ getPorts: () => Promise<SerialPortLike[]>;
34
+ }
35
+
36
+ /** A Web Serial port is either a USB-CDC device (USB ids, no service class) or a Bluetooth RFCOMM port (service
37
+ * class, no USB ids). One place decides which, so the connect path and the silent-reconnect path can never disagree
38
+ * about a port's identity: they used to, and the Bluetooth branch compared UUIDs case-sensitively on read while
39
+ * writing them lowercased. */
40
+ export function serialPortIdentity(info: SerialPortInfoLike): ScannerIdentity | null {
41
+ if (info.usbVendorId !== undefined && info.usbProductId !== undefined) {
42
+ return { connectionType: 'usb-serial', vendorId: info.usbVendorId, productId: info.usbProductId };
43
+ }
44
+ if (info.bluetoothServiceClassId !== undefined) {
45
+ return { connectionType: 'bluetooth-spp', serviceUuid: info.bluetoothServiceClassId };
46
+ }
47
+ return null;
48
+ }
49
+
50
+ export interface SerialScannerOptions {
51
+ /** navigator.serial, or undefined where Web Serial is absent (then available is false and every call is a no-op). */
52
+ serial: SerialLike | undefined;
53
+ profiles: ScannerProfileStore;
54
+ getSettings: () => DeviceScannerSettings;
55
+ emit: (event: ScanEvent) => void;
56
+ onError?: DeviceScannerErrorHandler;
57
+ now?: () => number;
58
+ }
59
+
60
+ const DISCONNECTED = { connected: false, connectedDeviceKey: null } as const;
61
+
62
+ export function createSerialScanner(options: SerialScannerOptions): DeviceScanner {
63
+ const { serial, profiles, getSettings, emit, onError } = options;
64
+ const now = options.now ?? Date.now;
65
+ const state = createDeviceScannerStateCell();
66
+
67
+ let activePort: SerialPortLike | null = null;
68
+ let activeReader: ReadableStreamDefaultReader<Uint8Array> | null = null;
69
+ let closing = false;
70
+ let attachRequest = 0;
71
+ let lifecycleQueue: Promise<void> = Promise.resolve();
72
+ let disposed = false;
73
+ let disposing: Promise<void> | null = null;
74
+
75
+ const session = createScanSession({
76
+ onAccept: (code) => {
77
+ if (code.length < getSettings().minChars) return;
78
+ emit({ code, source: { kind: 'serial' }, timestamp: now() });
79
+ },
80
+ });
81
+ const decoder = createSerialLineDecoder({
82
+ getSettings: () => ({ prefix: getSettings().prefix, suffix: getSettings().suffix }),
83
+ onScan: (code) => session.offer(code),
84
+ });
85
+
86
+ const readLoop = async (port: SerialPortLike) => {
87
+ const textDecoder = new TextDecoder();
88
+ try {
89
+ while (port.readable && !closing) {
90
+ const reader = port.readable.getReader();
91
+ activeReader = reader;
92
+ try {
93
+ for (let result = await reader.read(); !result.done; result = await reader.read()) {
94
+ decoder.push(textDecoder.decode(result.value, { stream: true }));
95
+ }
96
+ } catch {
97
+ // A read error usually means the port was cancelled/closed.
98
+ break;
99
+ } finally {
100
+ reader.releaseLock();
101
+ if (activeReader === reader) activeReader = null;
102
+ }
103
+ break;
104
+ }
105
+ } finally {
106
+ // Only the loop that owns the active port clears the state: a replaced port's loop unwinds late.
107
+ if (activePort === port) state.set(DISCONNECTED);
108
+ }
109
+ };
110
+
111
+ const teardown = async () => {
112
+ const reader = activeReader;
113
+ const port = activePort;
114
+ activeReader = null;
115
+ activePort = null;
116
+ state.set(DISCONNECTED);
117
+ closing = true;
118
+ try {
119
+ // Cancel the reader before closing the port: an abort signal alone did not release a pending reader.read().
120
+ await reader?.cancel().catch(() => undefined);
121
+ if (port) await port.close().catch(() => undefined);
122
+ } finally {
123
+ closing = false;
124
+ }
125
+ };
126
+
127
+ const isStale = (request: number) => disposed || request !== attachRequest;
128
+
129
+ const attachPort = async (port: SerialPortLike, save: boolean) => {
130
+ const request = ++attachRequest;
131
+ let attached = false;
132
+ const pending = lifecycleQueue.then(async () => {
133
+ if (isStale(request)) return;
134
+ await teardown();
135
+ if (isStale(request)) return;
136
+ await port.open({ baudRate: DEFAULT_SERIAL_BAUD_RATE });
137
+ if (isStale(request)) {
138
+ await port.close().catch(() => undefined);
139
+ return;
140
+ }
141
+ activePort = port;
142
+ const openedIdentity = serialPortIdentity(port.getInfo());
143
+ state.set({ connected: true, connectedDeviceKey: openedIdentity ? scannerDeviceKey(openedIdentity) : null });
144
+ decoder.reset();
145
+ session.reset();
146
+ // The read loop runs for the port's lifetime.
147
+ void readLoop(port).catch(() => undefined);
148
+ attached = true;
149
+ });
150
+ lifecycleQueue = pending.catch(() => undefined);
151
+ await pending;
152
+ if (!attached || !save) return;
153
+ const info = port.getInfo();
154
+ const identity = serialPortIdentity(info);
155
+ if (!identity) return;
156
+ // deviceKey is the primary key, so a re-registration of the same scanner is an upsert rather than a duplicate
157
+ // row: no read-then-insert dup check, and no race between two rapid Connect presses. Web Serial reports no product
158
+ // name for either transport, so deviceName stays empty: an invented English label would freeze one language into
159
+ // the document and shadow the type label the row derives from connectionType. Undefined keys are left out.
160
+ const { usbVendorId: vendorId, usbProductId: productId, bluetoothServiceClassId: serviceUuid } = info;
161
+ await profiles.save({
162
+ deviceKey: scannerDeviceKey(identity), name: '', connectionType: identity.connectionType, deviceName: '',
163
+ ...(vendorId !== undefined ? { vendorId } : {}), ...(productId !== undefined ? { productId } : {}),
164
+ ...(serviceUuid ? { serviceUuid: normalizeUuid(serviceUuid) } : {}), createdAt: new Date(now()).toISOString(),
165
+ });
166
+ };
167
+
168
+ const connect = async () => {
169
+ if (!serial || disposed) return;
170
+ try {
171
+ // A saved scanner may use a vendor-specific RFCOMM service class; include saved UUIDs so it stays in the chooser.
172
+ const saved = await profiles.read(['bluetooth-spp']);
173
+ const allowedBluetoothServiceClassIds = Array.from(new Set([
174
+ ...KNOWN_SCANNER_BLUETOOTH_SERVICE_CLASS_IDS,
175
+ ...saved.map((profile) => profile.serviceUuid)
176
+ .filter((id): id is string => typeof id === 'string' && id.length > 0),
177
+ ]));
178
+ const port = await serial.requestPort({ allowedBluetoothServiceClassIds });
179
+ await attachPort(port, true);
180
+ } catch (error) {
181
+ // Closing the browser's port chooser throws NotFoundError: a cancel, not a fault.
182
+ onError?.(error, { phase: 'connect', cancelled: isChooserCancel(error) });
183
+ }
184
+ };
185
+
186
+ // Silently re-open an already-granted port matching a saved profile (the browser remembers grants across reloads).
187
+ const reopenSaved = async () => {
188
+ if (!serial || disposed) return;
189
+ try {
190
+ const [ports, saved] = await Promise.all([serial.getPorts(), profiles.read(['usb-serial', 'bluetooth-spp'])]);
191
+ if (disposed) return;
192
+ // Accepted contract: a key identifies a service or model, not a physical unit (the same ceiling as vid:pid
193
+ // for two identical USB scanners). One unambiguous match reconnects silently; ambiguity waits for a chooser pick.
194
+ const savedKeys = new Set(saved.map((profile) => profile.deviceKey));
195
+ const matches = ports.filter((port) => {
196
+ const identity = serialPortIdentity(port.getInfo());
197
+ return identity !== null && savedKeys.has(scannerDeviceKey(identity));
198
+ });
199
+ if (matches.length === 1) await attachPort(matches[0], false);
200
+ } catch (error) {
201
+ // A silent best-effort reopen (another tab may hold the port).
202
+ onError?.(error, { phase: 'reopen', cancelled: false });
203
+ }
204
+ };
205
+
206
+ const queueTeardown = async () => {
207
+ attachRequest += 1;
208
+ const pending = lifecycleQueue.then(teardown);
209
+ lifecycleQueue = pending.catch(() => undefined);
210
+ await pending;
211
+ state.set(DISCONNECTED);
212
+ };
213
+
214
+ return {
215
+ available: !!serial, connect, reopenSaved,
216
+ disconnect: () => (disposed ? Promise.resolve() : queueTeardown()),
217
+ dispose: () => {
218
+ if (!disposing) {
219
+ // Release the port and read loop on host teardown (logout, unmount).
220
+ disposed = true;
221
+ disposing = queueTeardown();
222
+ }
223
+ return disposing;
224
+ },
225
+ getState: state.get, subscribe: state.subscribe,
226
+ };
227
+ }
@@ -1,5 +1,9 @@
1
1
  import { useEffect, useRef } from 'react';
2
- import { createWedgeDetector, DEFAULT_MIN_SCAN_CHARS, DEFAULT_WEDGE_SETTINGS } from './wedge-detector';
2
+ import { merge, Subject } from 'rxjs';
3
+ import { dedupeScans, SCAN_DEDUP_WINDOW_MS, scanTimeOf } from './scan-dedup';
4
+ import type { ScanEvent } from './scan-events';
5
+ import { useScanHub } from './scan-hub-context';
6
+ import { createWedgeDetector, DEFAULT_MIN_SCAN_CHARS, DEFAULT_WEDGE_SETTINGS, type WedgeScanMeta } from './wedge-detector';
3
7
 
4
8
  export interface UseBarcodeScannerOptions {
5
9
  onScan: (code: string) => void;
@@ -9,9 +13,13 @@ export interface UseBarcodeScannerOptions {
9
13
  prefix?: string;
10
14
  suffix?: string;
11
15
  minChars?: number;
16
+ /** Called with each accepted scan event (wedge or device) after cross-source de-duplication,
17
+ * before onScan. */
18
+ onScanEvent?: (event: ScanEvent) => void;
12
19
  }
13
20
 
14
- /** Listen for keyboard-wedge scans outside INPUT/TEXTAREA, with a minimum length gate.
21
+ /** Listen for keyboard-wedge scans outside INPUT/TEXTAREA, with a minimum length gate. Inside a ScanHubProvider the
22
+ * hub's device scans (serial, HID-POS) join them, and a copy of one physical scan from a second source is dropped.
15
23
  * Ported from WCPOS v2 packages/core/src/screens/main/hooks/barcodes/use-barcode-detection.ts (monorepo 5ac185b0).
16
24
  * @example
17
25
  * useBarcodeScanner({ onScan: (code) => {
@@ -26,17 +34,26 @@ export function useBarcodeScanner(options: UseBarcodeScannerOptions): void {
26
34
  const latest = useRef(options);
27
35
  latest.current = options;
28
36
  const enabled = options.enabled ?? true;
37
+ const hub = useScanHub();
29
38
  useEffect(() => {
30
39
  if (!enabled) return;
40
+ const wedge$ = new Subject<ScanEvent>();
41
+ const subscription = merge(wedge$, hub.events$)
42
+ .pipe(dedupeScans(SCAN_DEDUP_WINDOW_MS, scanTimeOf))
43
+ .subscribe((event) => {
44
+ latest.current.onScanEvent?.(event);
45
+ latest.current.onScan(event.code);
46
+ });
31
47
  const detectorOptions = {
32
48
  getSettings: () => ({
33
49
  threshold: latest.current.threshold ?? DEFAULT_WEDGE_SETTINGS.threshold,
34
50
  prefix: latest.current.prefix ?? '',
35
51
  suffix: latest.current.suffix ?? '',
36
52
  }),
37
- onScan: (code: string) => {
53
+ onScan: (code: string, meta: WedgeScanMeta) => {
38
54
  if (code.length >= (latest.current.minChars ?? DEFAULT_MIN_SCAN_CHARS)) {
39
- latest.current.onScan(code);
55
+ // v2's toWedgeScanEvent: timed from the burst's first key, the physical scan.
56
+ wedge$.next({ code, source: { kind: 'wedge' }, timestamp: meta.startedAtMs });
40
57
  }
41
58
  },
42
59
  };
@@ -56,6 +73,7 @@ export function useBarcodeScanner(options: UseBarcodeScannerOptions): void {
56
73
  return () => {
57
74
  window.removeEventListener('keydown', handler, { capture: true });
58
75
  detector.dispose();
76
+ subscription.unsubscribe();
59
77
  };
60
- }, [enabled]);
78
+ }, [enabled, hub]);
61
79
  }