@tallyui/pos 3.20.1 → 4.0.1
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 +1008 -111
- package/dist/index.js +3158 -907
- package/package.json +6 -6
- package/src/app-settings/app-settings.ts +77 -0
- package/src/app-settings/index.ts +2 -0
- package/src/currency/currency-provider.tsx +5 -7
- package/src/currency/index.ts +1 -1
- package/src/customer/customer-patch.ts +70 -0
- package/src/customer-display/display-client.ts +11 -17
- package/src/customer-display/display-link.ts +10 -5
- package/src/customer-display/index.ts +3 -1
- package/src/customer-display/protocol.ts +1 -1
- package/src/customer-display/sale-display.ts +6 -8
- package/src/customer-display/snapshot-fallback.ts +14 -1
- package/src/customer-display/till-device.ts +62 -0
- package/src/customer-display/till-display-service.ts +44 -42
- package/src/customer-display/till-pairing.ts +20 -23
- package/src/customer-display/use-customer-display.ts +2 -1
- package/src/customer-display/use-till-pairing.ts +4 -4
- package/src/index.ts +37 -18
- package/src/order/allocate-order-discount.ts +5 -17
- package/src/order/apportion.ts +29 -0
- package/src/order/from-store-order.ts +115 -0
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +239 -52
- package/src/order/order-drafts.ts +46 -6
- package/src/order/order-manager.ts +2 -1
- package/src/order/tax-ids.ts +27 -0
- package/src/order/types.ts +61 -5
- package/src/order/woocommerce-tax.ts +9 -0
- package/src/outbox/index.ts +1 -1
- package/src/outbox/order-outbox.ts +138 -43
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/retry-delay.ts +8 -0
- package/src/outbox/use-order-outbox.ts +8 -2
- package/src/pos-order/__fixtures__/order-create-v10.json +97 -0
- package/src/pos-order/__fixtures__/order-create-v11.json +90 -0
- package/src/pos-order/__fixtures__/order-create-v12.json +95 -0
- package/src/pos-order/__fixtures__/order-create-v9.json +89 -0
- package/src/pos-order/attention-handled.ts +24 -0
- package/src/pos-order/command.ts +132 -12
- package/src/pos-order/extras-delivery.ts +14 -0
- package/src/pos-order/finalize.ts +138 -29
- package/src/pos-order/index.ts +7 -3
- package/src/pos-order/money-divergence.ts +19 -0
- package/src/pos-order/needs-attention.ts +9 -1
- package/src/pos-order/refund-due.ts +35 -0
- package/src/pos-order/reopen.ts +96 -12
- package/src/pos-order/schema.ts +35 -10
- package/src/pos-order/till-payments.ts +4 -0
- package/src/pos-order/types.ts +45 -6
- package/src/print/escpos/__fixtures__/thermal-every-node.xml +33 -0
- package/src/print/escpos/commands.ts +79 -0
- package/src/print/escpos/drawer.ts +25 -0
- package/src/print/escpos/encode.ts +1 -0
- package/src/print/escpos/index.ts +6 -1
- package/src/print/escpos/network-sinks.ts +130 -0
- package/src/print/escpos/render-escpos.ts +155 -0
- package/src/print/escpos/transport.ts +2 -1
- package/src/print/index.ts +5 -2
- package/src/print/resolve-printer.ts +46 -0
- package/src/print/types.ts +1 -1
- package/src/product/index.ts +2 -0
- package/src/product/terms.ts +42 -0
- package/src/product/tile-fields.ts +27 -0
- package/src/receipt/build-receipt-data.ts +12 -7
- package/src/receipt/carried-rows.ts +29 -0
- package/src/receipt/index.ts +1 -0
- package/src/receipt/reprint.ts +14 -8
- package/src/receipt/types.ts +3 -1
- package/src/receipt-template/default-templates.ts +3 -0
- package/src/receipt-template/template-data.ts +3 -0
- package/src/receipt-template/wcpos/build.ts +1 -0
- package/src/receipt-template/wcpos/format.ts +2 -2
- package/src/receipt-template/wcpos/from-orders.ts +6 -2
- package/src/receipt-template/wcpos/types.ts +5 -1
- package/src/register/closure-document.ts +42 -4
- package/src/register/closure-rows.ts +3 -2
- package/src/register/document-labels.ts +25 -0
- package/src/register/expected.ts +49 -10
- package/src/register/index.ts +5 -5
- package/src/register/money.ts +23 -0
- package/src/register/register-adoption.ts +6 -5
- package/src/register/register-commands.ts +4 -3
- package/src/register/schemas.ts +11 -3
- package/src/register/session-store.ts +44 -23
- package/src/register/settled-figures.ts +5 -19
- package/src/register/use-register-session.ts +18 -19
- package/src/reopen/index.ts +3 -0
- package/src/reopen/reopen-entry.ts +48 -0
- package/src/reopen/reopen-store-order.ts +78 -0
- package/src/reopen/send-order-reopen.ts +61 -0
- package/src/reports/adapters.ts +15 -7
- package/src/reports/sales-figures.ts +15 -1
- package/src/reports/types.ts +2 -0
- package/src/sale/cart.ts +4 -2
- package/src/sale/index.ts +1 -1
- package/src/sale/open-sales.ts +3 -0
- package/src/sale/use-sale.ts +388 -83
- package/src/sale/woocommerce/coupon-refetch.ts +1 -0
- package/src/sale/woocommerce/coupon-source.ts +4 -4
- package/src/sale/woocommerce/coupons.ts +6 -0
- package/src/sale/woocommerce/discount-codes.ts +1 -6
- package/src/scanner/analyze-trace.ts +86 -0
- package/src/scanner/device-scanner.ts +57 -0
- package/src/scanner/hid-scanner.ts +14 -41
- package/src/scanner/index.ts +2 -0
- package/src/scanner/serial-scanner.ts +15 -42
- package/src/scanner/use-barcode-scanner.ts +107 -5
- package/src/scanner/wedge-detector.ts +33 -15
- package/src/tax/exact.ts +1 -13
- package/src/tax/taxed-lines.ts +26 -0
- package/src/tender/index.ts +6 -1
- package/src/tender/split-units.ts +109 -0
- package/src/tender/tender-figures.ts +114 -0
- package/src/tender/tender-state.ts +105 -17
- package/src/currency/format-money-with.ts +0 -45
|
@@ -20,6 +20,7 @@ export function startCouponUsageRefetch(deps: {
|
|
|
20
20
|
|| !(now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS)) continue;
|
|
21
21
|
handled.add(order.id);
|
|
22
22
|
for (const coupon of order.coupons) {
|
|
23
|
+
if (coupon.carried) continue;
|
|
23
24
|
const id = Number(coupon.couponId);
|
|
24
25
|
if (Number.isInteger(id)) ids.add(id);
|
|
25
26
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { RxCollection } from 'rxdb';
|
|
2
2
|
import type { PosOrder } from '../../pos-order/types';
|
|
3
|
-
import type
|
|
3
|
+
import { wooCustomerId, type SaleCoupon, type SaleCouponSource } from './coupons';
|
|
4
4
|
|
|
5
5
|
/** How long an applied order still counts when no pull has rewritten its coupon: a refetch that finds the coupon unchanged writes nothing, and the store is authoritative (ADR-077 amendment 2). */
|
|
6
6
|
export const APPLIED_USE_GRACE_MS = 600_000;
|
|
@@ -24,15 +24,15 @@ export function createSaleCouponSource(deps: {
|
|
|
24
24
|
if (!['percent', 'fixed_cart', 'fixed_product'].includes(data.discount_type)
|
|
25
25
|
|| !Number.isInteger(data.id) || typeof data.amount !== 'string') return null;
|
|
26
26
|
const orders = await deps.orders.find({ selector: { syncStatus: { $in: ['pending', 'applied'] } } }).exec();
|
|
27
|
-
const counted = orders.filter((order) => order.coupons?.some((coupon) => coupon.code === code)
|
|
27
|
+
const counted = orders.filter((order) => order.coupons?.some((coupon) => !coupon.carried && coupon.code === code)
|
|
28
28
|
&& (order.syncStatus === 'pending' || (Date.parse(order.updatedAt) > data._meta.lwt
|
|
29
29
|
&& now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS)));
|
|
30
30
|
const usedBy = [...(data.used_by ?? [])];
|
|
31
31
|
for (const order of counted) {
|
|
32
32
|
// Mirrors the identifier validate.ts compares: wooCustomerId, else the email.
|
|
33
|
-
const id =
|
|
33
|
+
const id = wooCustomerId(order.customer);
|
|
34
34
|
const email = order.customer?.email;
|
|
35
|
-
if (
|
|
35
|
+
if (id !== null) usedBy.push(String(id));
|
|
36
36
|
else if (typeof email === 'string' && email.length > 0) usedBy.push(email.toLowerCase());
|
|
37
37
|
}
|
|
38
38
|
const fields = [
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { minorUnitDigits, woocommerceCoupons } from '@tallyui/core';
|
|
2
2
|
import type { LineItem } from '../../order';
|
|
3
3
|
|
|
4
|
+
/** The WooCommerce customer id a coupon check compares: a safe integer above zero, else null (the email is used instead). */
|
|
5
|
+
export function wooCustomerId(customer: { id?: string } | null | undefined): number | null {
|
|
6
|
+
const id = Number(customer?.id);
|
|
7
|
+
return Number.isSafeInteger(id) && id > 0 ? id : null;
|
|
8
|
+
}
|
|
9
|
+
|
|
4
10
|
/** A WooCommerce coupon as the sale needs it: the engine's input and the connector's numeric id. */
|
|
5
11
|
export type SaleCoupon = woocommerceCoupons.CouponInput & { id: number };
|
|
6
12
|
/** Where the sale finds coupons (ADR-077 amendment 2); the app builds it over the till's coupons collection. */
|
|
@@ -1,11 +1,6 @@
|
|
|
1
1
|
import { minorUnitDigits, woocommerceCoupons } from '@tallyui/core';
|
|
2
2
|
import type { SaleDiscountCodes } from '../discount-codes';
|
|
3
|
-
import { couponLineItems, couponRefusal, type SaleCoupon, type SaleCouponSource } from './coupons';
|
|
4
|
-
|
|
5
|
-
function wooCustomerId(customer: { id?: string } | null | undefined): number | null {
|
|
6
|
-
const id = Number(customer?.id);
|
|
7
|
-
return Number.isSafeInteger(id) && id > 0 ? id : null;
|
|
8
|
-
}
|
|
3
|
+
import { couponLineItems, couponRefusal, wooCustomerId, type SaleCoupon, type SaleCouponSource } from './coupons';
|
|
9
4
|
|
|
10
5
|
/** WooCommerce coupons as the sale's discount codes (ADR-077): the source's coupons, checked by woocommerceCoupons.validateCoupon. */
|
|
11
6
|
export function createDiscountCodes(source: SaleCouponSource): SaleDiscountCodes<SaleCoupon> {
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Ported from WCPOS v2 packages/scanner/src/analyze-trace.ts (monorepo origin/main).
|
|
2
|
+
import { replayWedgeDetector, type TraceKey, type WedgeSettings } from './wedge-detector';
|
|
3
|
+
|
|
4
|
+
export type ScanTraceSettings = WedgeSettings & { minChars: number };
|
|
5
|
+
|
|
6
|
+
export interface TraceSuggestion {
|
|
7
|
+
kind: 'raise-threshold' | 'lower-min-chars' | 'set-prefix';
|
|
8
|
+
/** A patch in the same keys as components' `BarcodeScanningValues`. */
|
|
9
|
+
settings: Partial<Pick<ScanTraceSettings, 'threshold' | 'minChars' | 'prefix'>>;
|
|
10
|
+
value: number | string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface TraceAnalysis {
|
|
14
|
+
raw: string;
|
|
15
|
+
code: string;
|
|
16
|
+
avgGapMs: number;
|
|
17
|
+
gaps: number[];
|
|
18
|
+
detectedAsScan: boolean;
|
|
19
|
+
tooShort: boolean;
|
|
20
|
+
nearMiss: boolean;
|
|
21
|
+
leadingSymbol: string | null;
|
|
22
|
+
trailingEnter: boolean;
|
|
23
|
+
shiftMangled: boolean;
|
|
24
|
+
suggestions: TraceSuggestion[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// A trace slower than this is a person typing, not a mis-tuned scanner —
|
|
28
|
+
// no threshold suggestion is worth making beyond it.
|
|
29
|
+
const SCANNER_FAST_CEILING_MS = 60;
|
|
30
|
+
const THRESHOLD_HEADROOM_MS = 8;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Analyze one completed keystroke trace from the settings test panel.
|
|
34
|
+
*
|
|
35
|
+
* The verdict, displayed code, and one-tap fixes all come from replaying the
|
|
36
|
+
* real detector over the trace (`replayWedgeDetector` — the same reducer the
|
|
37
|
+
* live hook streams through), so the panel can never claim a scan the detector
|
|
38
|
+
* would reject, or vice versa.
|
|
39
|
+
*/
|
|
40
|
+
export function analyzeScanTrace(keys: TraceKey[], settings: ScanTraceSettings): TraceAnalysis {
|
|
41
|
+
// Per-key gaps (including non-printable keys) purely for the timing chart.
|
|
42
|
+
const gaps = keys.map((key, index) => (index === 0 ? 0 : key.timeMs - keys[index - 1].timeMs));
|
|
43
|
+
|
|
44
|
+
const printable = keys.filter((entry) => entry.key.length === 1).map((entry) => entry.key);
|
|
45
|
+
const raw = printable.join('');
|
|
46
|
+
|
|
47
|
+
const detector = replayWedgeDetector(keys, settings);
|
|
48
|
+
const { detectedAsScan, code } = detector;
|
|
49
|
+
const avgGapMs = detector.minAvgGapMs;
|
|
50
|
+
|
|
51
|
+
const tooShort = detectedAsScan && code.length < settings.minChars;
|
|
52
|
+
const nearMiss = !detectedAsScan && avgGapMs < SCANNER_FAST_CEILING_MS;
|
|
53
|
+
const leadingSymbol = /^[^0-9A-Za-z]/.test(raw) ? raw[0] : null;
|
|
54
|
+
const lastKey = keys[keys.length - 1]?.key;
|
|
55
|
+
const trailingEnter = lastKey === 'Enter' || lastKey === 'Return';
|
|
56
|
+
const shiftMangled = keys.filter((entry) => entry.key === 'Shift').length >= 2;
|
|
57
|
+
|
|
58
|
+
const suggestions: TraceSuggestion[] = [];
|
|
59
|
+
if (nearMiss) {
|
|
60
|
+
const value = Math.ceil(avgGapMs + THRESHOLD_HEADROOM_MS);
|
|
61
|
+
suggestions.push({ kind: 'raise-threshold', value, settings: { threshold: value } });
|
|
62
|
+
}
|
|
63
|
+
if (tooShort && code.length >= 1) {
|
|
64
|
+
// Lower the minimum to the code's actual length so the detector accepts
|
|
65
|
+
// it — clamping to a higher floor would leave the scan still rejected.
|
|
66
|
+
const value = code.length;
|
|
67
|
+
suggestions.push({ kind: 'lower-min-chars', value, settings: { minChars: value } });
|
|
68
|
+
}
|
|
69
|
+
if (detectedAsScan && leadingSymbol && settings.prefix === '') {
|
|
70
|
+
suggestions.push({ kind: 'set-prefix', value: leadingSymbol, settings: { prefix: leadingSymbol } });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
raw,
|
|
75
|
+
code,
|
|
76
|
+
avgGapMs,
|
|
77
|
+
gaps,
|
|
78
|
+
detectedAsScan,
|
|
79
|
+
tooShort,
|
|
80
|
+
nearMiss,
|
|
81
|
+
leadingSymbol,
|
|
82
|
+
trailingEnter,
|
|
83
|
+
shiftMangled,
|
|
84
|
+
suggestions,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
@@ -60,3 +60,60 @@ export interface DeviceScanner {
|
|
|
60
60
|
getState: () => DeviceScannerState;
|
|
61
61
|
subscribe: (listener: (state: DeviceScannerState) => void) => () => void;
|
|
62
62
|
}
|
|
63
|
+
|
|
64
|
+
export const DEVICE_SCANNER_DISCONNECTED: DeviceScannerState = { connected: false, connectedDeviceKey: null };
|
|
65
|
+
|
|
66
|
+
/** The attach/teardown lifecycle the serial and HID controllers share. One queue runs attaches and teardowns in
|
|
67
|
+
* order. A newer attach, a disconnect or a dispose makes an older attach stale, and a stale attach backs out.
|
|
68
|
+
* After dispose, the controller ignores every later call. */
|
|
69
|
+
export interface DeviceLifecycle {
|
|
70
|
+
readonly disposed: () => boolean;
|
|
71
|
+
/** Queues `teardown`, then `open`, unless the attach went stale before either step. `open` gets an isStale check
|
|
72
|
+
* for its own steps and returns true once the device is attached. Resolves to that value (false when stale). */
|
|
73
|
+
attach: (open: (isStale: () => boolean) => Promise<boolean>) => Promise<boolean>;
|
|
74
|
+
disconnect: () => Promise<void>;
|
|
75
|
+
dispose: () => Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function createDeviceLifecycle(state: DeviceScannerStateCell, teardown: () => Promise<void>): DeviceLifecycle {
|
|
79
|
+
let attachRequest = 0;
|
|
80
|
+
let lifecycleQueue: Promise<void> = Promise.resolve();
|
|
81
|
+
let disposed = false;
|
|
82
|
+
let disposing: Promise<void> | null = null;
|
|
83
|
+
|
|
84
|
+
const attach = async (open: (isStale: () => boolean) => Promise<boolean>) => {
|
|
85
|
+
const request = ++attachRequest;
|
|
86
|
+
const isStale = () => disposed || request !== attachRequest;
|
|
87
|
+
let attached = false;
|
|
88
|
+
const pending = lifecycleQueue.then(async () => {
|
|
89
|
+
if (isStale()) return;
|
|
90
|
+
await teardown();
|
|
91
|
+
if (isStale()) return;
|
|
92
|
+
attached = await open(isStale);
|
|
93
|
+
});
|
|
94
|
+
lifecycleQueue = pending.catch(() => undefined);
|
|
95
|
+
await pending;
|
|
96
|
+
return attached;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const queueTeardown = async () => {
|
|
100
|
+
attachRequest += 1;
|
|
101
|
+
const pending = lifecycleQueue.then(teardown);
|
|
102
|
+
lifecycleQueue = pending.catch(() => undefined);
|
|
103
|
+
await pending;
|
|
104
|
+
state.set(DEVICE_SCANNER_DISCONNECTED);
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
disposed: () => disposed,
|
|
109
|
+
attach,
|
|
110
|
+
disconnect: () => (disposed ? Promise.resolve() : queueTeardown()),
|
|
111
|
+
dispose: () => {
|
|
112
|
+
if (!disposing) {
|
|
113
|
+
disposed = true;
|
|
114
|
+
disposing = queueTeardown();
|
|
115
|
+
}
|
|
116
|
+
return disposing;
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
* decode it, dedup via the scan session, and emit `hid-pos` ScanEvents. */
|
|
4
4
|
import { isChooserCancel } from './chooser-cancel';
|
|
5
5
|
import { scannerDeviceKey } from './device-identity';
|
|
6
|
-
import {
|
|
7
|
-
type ScannerProfileStore } from './device-scanner';
|
|
6
|
+
import { createDeviceLifecycle, createDeviceScannerStateCell, DEVICE_SCANNER_DISCONNECTED, type DeviceScanner,
|
|
7
|
+
type DeviceScannerErrorHandler, type DeviceScannerSettings, type ScannerProfileStore } from './device-scanner';
|
|
8
8
|
import { decodeHidPosReport } from './hid-pos-decoder';
|
|
9
9
|
import type { ScanEvent } from './scan-events';
|
|
10
10
|
import { createScanSession } from './scan-session';
|
|
@@ -40,8 +40,6 @@ export interface HidScannerOptions {
|
|
|
40
40
|
now?: () => number;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
const DISCONNECTED = { connected: false, connectedDeviceKey: null } as const;
|
|
44
|
-
|
|
45
43
|
const hidDeviceKey = (device: HidDeviceLike) =>
|
|
46
44
|
scannerDeviceKey({ connectionType: 'hid-pos', vendorId: device.vendorId, productId: device.productId });
|
|
47
45
|
|
|
@@ -58,10 +56,6 @@ export function createHidScanner(options: HidScannerOptions): DeviceScanner {
|
|
|
58
56
|
|
|
59
57
|
let activeDevice: HidDeviceLike | null = null;
|
|
60
58
|
let activeListener: ((event: HidInputReportEventLike) => void) | null = null;
|
|
61
|
-
let attachRequest = 0;
|
|
62
|
-
let lifecycleQueue: Promise<void> = Promise.resolve();
|
|
63
|
-
let disposed = false;
|
|
64
|
-
let disposing: Promise<void> | null = null;
|
|
65
59
|
|
|
66
60
|
const session = createScanSession({
|
|
67
61
|
onAccept: (code, symbology) => {
|
|
@@ -75,26 +69,21 @@ export function createHidScanner(options: HidScannerOptions): DeviceScanner {
|
|
|
75
69
|
const listener = activeListener;
|
|
76
70
|
activeDevice = null;
|
|
77
71
|
activeListener = null;
|
|
78
|
-
state.set(
|
|
72
|
+
state.set(DEVICE_SCANNER_DISCONNECTED);
|
|
79
73
|
if (!device) return;
|
|
80
74
|
// Remove the listener before closing, so a report racing the close is never delivered.
|
|
81
75
|
if (listener) device.removeEventListener('inputreport', listener);
|
|
82
76
|
await device.close().catch(() => undefined);
|
|
83
77
|
};
|
|
84
78
|
|
|
85
|
-
const
|
|
79
|
+
const lifecycle = createDeviceLifecycle(state, teardown);
|
|
86
80
|
|
|
87
81
|
const attachDevice = async (device: HidDeviceLike, save: boolean) => {
|
|
88
|
-
const
|
|
89
|
-
let attached = false;
|
|
90
|
-
const pending = lifecycleQueue.then(async () => {
|
|
91
|
-
if (isStale(request)) return;
|
|
92
|
-
await teardown();
|
|
93
|
-
if (isStale(request)) return;
|
|
82
|
+
const attached = await lifecycle.attach(async (isStale) => {
|
|
94
83
|
await device.open();
|
|
95
|
-
if (isStale(
|
|
84
|
+
if (isStale()) {
|
|
96
85
|
await device.close().catch(() => undefined);
|
|
97
|
-
return;
|
|
86
|
+
return false;
|
|
98
87
|
}
|
|
99
88
|
const listener = (event: HidInputReportEventLike) => {
|
|
100
89
|
// WebHID delivers event.data as the report body *without* the report id (it is carried separately as
|
|
@@ -107,10 +96,8 @@ export function createHidScanner(options: HidScannerOptions): DeviceScanner {
|
|
|
107
96
|
activeListener = listener;
|
|
108
97
|
session.reset();
|
|
109
98
|
state.set({ connected: true, connectedDeviceKey: hidDeviceKey(device) });
|
|
110
|
-
|
|
99
|
+
return true;
|
|
111
100
|
});
|
|
112
|
-
lifecycleQueue = pending.catch(() => undefined);
|
|
113
|
-
await pending;
|
|
114
101
|
if (!attached || !save) return;
|
|
115
102
|
// Upsert on the canonical key: re-connecting an already-registered scanner refreshes it instead of adding a
|
|
116
103
|
// second row. An absent product name stays empty rather than an invented English label.
|
|
@@ -121,7 +108,7 @@ export function createHidScanner(options: HidScannerOptions): DeviceScanner {
|
|
|
121
108
|
};
|
|
122
109
|
|
|
123
110
|
const connect = async () => {
|
|
124
|
-
if (!hid || disposed) return;
|
|
111
|
+
if (!hid || lifecycle.disposed()) return;
|
|
125
112
|
try {
|
|
126
113
|
const devices = await hid.requestDevice({ filters: [{ usagePage: HID_POS_USAGE_PAGE }] });
|
|
127
114
|
if (devices[0]) await attachDevice(devices[0], true);
|
|
@@ -134,10 +121,10 @@ export function createHidScanner(options: HidScannerOptions): DeviceScanner {
|
|
|
134
121
|
// Silently re-open an already-granted HID device matching a saved hid-pos profile (the browser remembers granted
|
|
135
122
|
// devices across reloads). An HID key always carries vendor and product, so the first match is taken.
|
|
136
123
|
const reopenSaved = async () => {
|
|
137
|
-
if (!hid || disposed) return;
|
|
124
|
+
if (!hid || lifecycle.disposed()) return;
|
|
138
125
|
try {
|
|
139
126
|
const [devices, saved] = await Promise.all([hid.getDevices(), profiles.read(['hid-pos'])]);
|
|
140
|
-
if (disposed) return;
|
|
127
|
+
if (lifecycle.disposed()) return;
|
|
141
128
|
const savedKeys = new Set(saved.map((profile) => profile.deviceKey));
|
|
142
129
|
const match = devices.find((device) => savedKeys.has(hidDeviceKey(device)));
|
|
143
130
|
if (match) await attachDevice(match, false);
|
|
@@ -147,25 +134,11 @@ export function createHidScanner(options: HidScannerOptions): DeviceScanner {
|
|
|
147
134
|
}
|
|
148
135
|
};
|
|
149
136
|
|
|
150
|
-
const queueTeardown = async () => {
|
|
151
|
-
attachRequest += 1;
|
|
152
|
-
const pending = lifecycleQueue.then(teardown);
|
|
153
|
-
lifecycleQueue = pending.catch(() => undefined);
|
|
154
|
-
await pending;
|
|
155
|
-
state.set(DISCONNECTED);
|
|
156
|
-
};
|
|
157
|
-
|
|
158
137
|
return {
|
|
159
138
|
available: !!hid, connect, reopenSaved,
|
|
160
|
-
disconnect:
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
// Release the device and its listener on host teardown (logout, unmount).
|
|
164
|
-
disposed = true;
|
|
165
|
-
disposing = queueTeardown();
|
|
166
|
-
}
|
|
167
|
-
return disposing;
|
|
168
|
-
},
|
|
139
|
+
disconnect: lifecycle.disconnect,
|
|
140
|
+
// Release the device and its listener on host teardown (logout, unmount).
|
|
141
|
+
dispose: lifecycle.dispose,
|
|
169
142
|
getState: state.get, subscribe: state.subscribe,
|
|
170
143
|
};
|
|
171
144
|
}
|
package/src/scanner/index.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export { DEFAULT_WEDGE_SETTINGS, DEFAULT_MIN_SCAN_CHARS, WEDGE_END_OF_SCAN_MS, createWedgeState, foldWedgeKey, stripBoundary, replayWedgeDetector, createWedgeDetector } from './wedge-detector';
|
|
2
2
|
export type { WedgeSettings, WedgeState, TraceKey, WedgeReplayResult, WedgeDetectorOptions, WedgeDetector } from './wedge-detector';
|
|
3
|
+
export { analyzeScanTrace } from './analyze-trace';
|
|
4
|
+
export type { ScanTraceSettings, TraceSuggestion, TraceAnalysis } from './analyze-trace';
|
|
3
5
|
export { DEFAULT_COOLDOWN_MS, normalizeRetailCode, hasValidRetailCheckDigit, retailCodeTwin, createScanSession } from './scan-session';
|
|
4
6
|
export type { ScanRejectReason, ScanOfferResult, ScanSessionOptions, ScanSession } from './scan-session';
|
|
5
7
|
export { useBarcodeScanner } from './use-barcode-scanner';
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
* the shared serial-line decoder, dedups via the scan session, and emits `serial` ScanEvents. */
|
|
4
4
|
import { isChooserCancel } from './chooser-cancel';
|
|
5
5
|
import { normalizeUuid, scannerDeviceKey, type ScannerIdentity } from './device-identity';
|
|
6
|
-
import {
|
|
7
|
-
type ScannerProfileStore } from './device-scanner';
|
|
6
|
+
import { createDeviceLifecycle, createDeviceScannerStateCell, DEVICE_SCANNER_DISCONNECTED, type DeviceScanner,
|
|
7
|
+
type DeviceScannerErrorHandler, type DeviceScannerSettings, type ScannerProfileStore } from './device-scanner';
|
|
8
8
|
import type { ScanEvent } from './scan-events';
|
|
9
9
|
import { createScanSession } from './scan-session';
|
|
10
10
|
import { createSerialLineDecoder } from './serial-line-decoder';
|
|
@@ -57,8 +57,6 @@ export interface SerialScannerOptions {
|
|
|
57
57
|
now?: () => number;
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
const DISCONNECTED = { connected: false, connectedDeviceKey: null } as const;
|
|
61
|
-
|
|
62
60
|
export function createSerialScanner(options: SerialScannerOptions): DeviceScanner {
|
|
63
61
|
const { serial, profiles, getSettings, emit, onError } = options;
|
|
64
62
|
const now = options.now ?? Date.now;
|
|
@@ -67,10 +65,6 @@ export function createSerialScanner(options: SerialScannerOptions): DeviceScanne
|
|
|
67
65
|
let activePort: SerialPortLike | null = null;
|
|
68
66
|
let activeReader: ReadableStreamDefaultReader<Uint8Array> | null = null;
|
|
69
67
|
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
68
|
|
|
75
69
|
const session = createScanSession({
|
|
76
70
|
onAccept: (code) => {
|
|
@@ -104,7 +98,7 @@ export function createSerialScanner(options: SerialScannerOptions): DeviceScanne
|
|
|
104
98
|
}
|
|
105
99
|
} finally {
|
|
106
100
|
// Only the loop that owns the active port clears the state: a replaced port's loop unwinds late.
|
|
107
|
-
if (activePort === port) state.set(
|
|
101
|
+
if (activePort === port) state.set(DEVICE_SCANNER_DISCONNECTED);
|
|
108
102
|
}
|
|
109
103
|
};
|
|
110
104
|
|
|
@@ -113,7 +107,7 @@ export function createSerialScanner(options: SerialScannerOptions): DeviceScanne
|
|
|
113
107
|
const port = activePort;
|
|
114
108
|
activeReader = null;
|
|
115
109
|
activePort = null;
|
|
116
|
-
state.set(
|
|
110
|
+
state.set(DEVICE_SCANNER_DISCONNECTED);
|
|
117
111
|
closing = true;
|
|
118
112
|
try {
|
|
119
113
|
// Cancel the reader before closing the port: an abort signal alone did not release a pending reader.read().
|
|
@@ -124,19 +118,14 @@ export function createSerialScanner(options: SerialScannerOptions): DeviceScanne
|
|
|
124
118
|
}
|
|
125
119
|
};
|
|
126
120
|
|
|
127
|
-
const
|
|
121
|
+
const lifecycle = createDeviceLifecycle(state, teardown);
|
|
128
122
|
|
|
129
123
|
const attachPort = async (port: SerialPortLike, save: boolean) => {
|
|
130
|
-
const
|
|
131
|
-
let attached = false;
|
|
132
|
-
const pending = lifecycleQueue.then(async () => {
|
|
133
|
-
if (isStale(request)) return;
|
|
134
|
-
await teardown();
|
|
135
|
-
if (isStale(request)) return;
|
|
124
|
+
const attached = await lifecycle.attach(async (isStale) => {
|
|
136
125
|
await port.open({ baudRate: DEFAULT_SERIAL_BAUD_RATE });
|
|
137
|
-
if (isStale(
|
|
126
|
+
if (isStale()) {
|
|
138
127
|
await port.close().catch(() => undefined);
|
|
139
|
-
return;
|
|
128
|
+
return false;
|
|
140
129
|
}
|
|
141
130
|
activePort = port;
|
|
142
131
|
const openedIdentity = serialPortIdentity(port.getInfo());
|
|
@@ -145,10 +134,8 @@ export function createSerialScanner(options: SerialScannerOptions): DeviceScanne
|
|
|
145
134
|
session.reset();
|
|
146
135
|
// The read loop runs for the port's lifetime.
|
|
147
136
|
void readLoop(port).catch(() => undefined);
|
|
148
|
-
|
|
137
|
+
return true;
|
|
149
138
|
});
|
|
150
|
-
lifecycleQueue = pending.catch(() => undefined);
|
|
151
|
-
await pending;
|
|
152
139
|
if (!attached || !save) return;
|
|
153
140
|
const info = port.getInfo();
|
|
154
141
|
const identity = serialPortIdentity(info);
|
|
@@ -166,7 +153,7 @@ export function createSerialScanner(options: SerialScannerOptions): DeviceScanne
|
|
|
166
153
|
};
|
|
167
154
|
|
|
168
155
|
const connect = async () => {
|
|
169
|
-
if (!serial || disposed) return;
|
|
156
|
+
if (!serial || lifecycle.disposed()) return;
|
|
170
157
|
try {
|
|
171
158
|
// A saved scanner may use a vendor-specific RFCOMM service class; include saved UUIDs so it stays in the chooser.
|
|
172
159
|
const saved = await profiles.read(['bluetooth-spp']);
|
|
@@ -185,10 +172,10 @@ export function createSerialScanner(options: SerialScannerOptions): DeviceScanne
|
|
|
185
172
|
|
|
186
173
|
// Silently re-open an already-granted port matching a saved profile (the browser remembers grants across reloads).
|
|
187
174
|
const reopenSaved = async () => {
|
|
188
|
-
if (!serial || disposed) return;
|
|
175
|
+
if (!serial || lifecycle.disposed()) return;
|
|
189
176
|
try {
|
|
190
177
|
const [ports, saved] = await Promise.all([serial.getPorts(), profiles.read(['usb-serial', 'bluetooth-spp'])]);
|
|
191
|
-
if (disposed) return;
|
|
178
|
+
if (lifecycle.disposed()) return;
|
|
192
179
|
// Accepted contract: a key identifies a service or model, not a physical unit (the same ceiling as vid:pid
|
|
193
180
|
// for two identical USB scanners). One unambiguous match reconnects silently; ambiguity waits for a chooser pick.
|
|
194
181
|
const savedKeys = new Set(saved.map((profile) => profile.deviceKey));
|
|
@@ -203,25 +190,11 @@ export function createSerialScanner(options: SerialScannerOptions): DeviceScanne
|
|
|
203
190
|
}
|
|
204
191
|
};
|
|
205
192
|
|
|
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
193
|
return {
|
|
215
194
|
available: !!serial, connect, reopenSaved,
|
|
216
|
-
disconnect:
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
// Release the port and read loop on host teardown (logout, unmount).
|
|
220
|
-
disposed = true;
|
|
221
|
-
disposing = queueTeardown();
|
|
222
|
-
}
|
|
223
|
-
return disposing;
|
|
224
|
-
},
|
|
195
|
+
disconnect: lifecycle.disconnect,
|
|
196
|
+
// Release the port and read loop on host teardown (logout, unmount).
|
|
197
|
+
dispose: lifecycle.dispose,
|
|
225
198
|
getState: state.get, subscribe: state.subscribe,
|
|
226
199
|
};
|
|
227
200
|
}
|
|
@@ -10,15 +10,22 @@ export interface UseBarcodeScannerOptions {
|
|
|
10
10
|
/** Listen only while true (default true). */
|
|
11
11
|
enabled?: boolean;
|
|
12
12
|
threshold?: number;
|
|
13
|
+
/** Gap rule for scanner bursts; see WedgeSettings.gapRule. */
|
|
14
|
+
gapRule?: 'folded' | 'every';
|
|
13
15
|
prefix?: string;
|
|
14
16
|
suffix?: string;
|
|
15
17
|
minChars?: number;
|
|
18
|
+
/** Which focused elements own their keys; a key there resets the burst and is never scanned.
|
|
19
|
+
* 'reset' (default): INPUT and TEXTAREA. 'ignore-editable': also SELECT and contentEditable elements.
|
|
20
|
+
* 'hold-money': as 'ignore-editable', but a money field (an input with inputmode="decimal") is held, not reset:
|
|
21
|
+
* a scan into it never reaches the field, and other runs go in at the caret as typing. */
|
|
22
|
+
fieldPolicy?: 'reset' | 'ignore-editable' | 'hold-money';
|
|
16
23
|
/** Called with each accepted scan event (wedge or device) after cross-source de-duplication,
|
|
17
24
|
* before onScan. */
|
|
18
25
|
onScanEvent?: (event: ScanEvent) => void;
|
|
19
26
|
}
|
|
20
27
|
|
|
21
|
-
/** Listen for keyboard-wedge scans
|
|
28
|
+
/** Listen for keyboard-wedge scans according to fieldPolicy, with a minimum length gate. Inside a ScanHubProvider the
|
|
22
29
|
* hub's device scans (serial, HID-POS) join them, and a copy of one physical scan from a second source is dropped.
|
|
23
30
|
* Ported from WCPOS v2 packages/core/src/screens/main/hooks/barcodes/use-barcode-detection.ts (monorepo 5ac185b0).
|
|
24
31
|
* @example
|
|
@@ -44,13 +51,47 @@ export function useBarcodeScanner(options: UseBarcodeScannerOptions): void {
|
|
|
44
51
|
latest.current.onScanEvent?.(event);
|
|
45
52
|
latest.current.onScan(event.code);
|
|
46
53
|
});
|
|
54
|
+
// 'hold-money': the money field the held keys belong to, the keys kept out of it until the run is known, whether
|
|
55
|
+
// some key of the run latched, when the last one was held, and the release and yield timers.
|
|
56
|
+
let field: HTMLInputElement | null = null;
|
|
57
|
+
let held = '';
|
|
58
|
+
let latched = false;
|
|
59
|
+
let lastHeldAt = 0;
|
|
60
|
+
let release: ReturnType<typeof setTimeout> | undefined;
|
|
61
|
+
let yieldTimer: ReturnType<typeof setTimeout> | undefined;
|
|
62
|
+
// A scan: its keys never reached the field, so they are dropped.
|
|
63
|
+
const drop = () => {
|
|
64
|
+
clearTimeout(release);
|
|
65
|
+
clearTimeout(yieldTimer);
|
|
66
|
+
held = '';
|
|
67
|
+
latched = false;
|
|
68
|
+
field = null;
|
|
69
|
+
};
|
|
70
|
+
// Typing: the held keys go in at the caret, replacing a selection, through the native setter and an input event
|
|
71
|
+
// as a key would (vendurepos useWedgeScanner). drop() then clears the timers and the run.
|
|
72
|
+
const flush = () => {
|
|
73
|
+
if (field && held) {
|
|
74
|
+
const start = field.selectionStart ?? field.value.length;
|
|
75
|
+
const end = field.selectionEnd ?? start;
|
|
76
|
+
const value = field.value.slice(0, start) + held + field.value.slice(end);
|
|
77
|
+
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set?.call(field, value);
|
|
78
|
+
field.dispatchEvent(new Event('input', { bubbles: true }));
|
|
79
|
+
field.setSelectionRange(start + held.length, start + held.length);
|
|
80
|
+
}
|
|
81
|
+
drop();
|
|
82
|
+
};
|
|
47
83
|
const detectorOptions = {
|
|
48
84
|
getSettings: () => ({
|
|
49
85
|
threshold: latest.current.threshold ?? DEFAULT_WEDGE_SETTINGS.threshold,
|
|
86
|
+
gapRule: latest.current.gapRule,
|
|
50
87
|
prefix: latest.current.prefix ?? '',
|
|
51
88
|
suffix: latest.current.suffix ?? '',
|
|
52
89
|
}),
|
|
53
90
|
onScan: (code: string, meta: WedgeScanMeta) => {
|
|
91
|
+
if (held && latched) {
|
|
92
|
+
if (code.length >= (latest.current.minChars ?? DEFAULT_MIN_SCAN_CHARS)) drop();
|
|
93
|
+
else flush();
|
|
94
|
+
}
|
|
54
95
|
if (code.length >= (latest.current.minChars ?? DEFAULT_MIN_SCAN_CHARS)) {
|
|
55
96
|
// v2's toWedgeScanEvent: timed from the burst's first key, the physical scan.
|
|
56
97
|
wedge$.next({ code, source: { kind: 'wedge' }, timestamp: meta.startedAtMs });
|
|
@@ -58,11 +99,70 @@ export function useBarcodeScanner(options: UseBarcodeScannerOptions): void {
|
|
|
58
99
|
},
|
|
59
100
|
};
|
|
60
101
|
let detector = createWedgeDetector(detectorOptions);
|
|
102
|
+
const resetDetector = () => {
|
|
103
|
+
detector.dispose();
|
|
104
|
+
detector = createWedgeDetector(detectorOptions);
|
|
105
|
+
};
|
|
106
|
+
// A printable key into a money field is held; the run decides whether it is a scan or typing.
|
|
107
|
+
const holdKey = (e: KeyboardEvent, target: HTMLInputElement) => {
|
|
108
|
+
const accepted = detector.handleKey(e.key);
|
|
109
|
+
// A key the detector did not take starts a new run: the old run was typing (or a dropped 'every' burst).
|
|
110
|
+
if (!accepted && held) flush();
|
|
111
|
+
field = target;
|
|
112
|
+
held += e.key;
|
|
113
|
+
lastHeldAt = Date.now();
|
|
114
|
+
e.preventDefault();
|
|
115
|
+
clearTimeout(release);
|
|
116
|
+
if (accepted) {
|
|
117
|
+
// A latched run waits for the detector's settle.
|
|
118
|
+
latched = true;
|
|
119
|
+
e.stopPropagation();
|
|
120
|
+
} else if (!latched) {
|
|
121
|
+
const threshold = latest.current.threshold ?? DEFAULT_WEDGE_SETTINGS.threshold;
|
|
122
|
+
// Yield once so queued keys from a stalled main thread are handled first, then flush only if none came.
|
|
123
|
+
release = setTimeout(() => {
|
|
124
|
+
yieldTimer = setTimeout(() => {
|
|
125
|
+
if (Date.now() - lastHeldAt >= threshold) flush();
|
|
126
|
+
}, 0);
|
|
127
|
+
}, threshold);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
61
130
|
const handler = (e: KeyboardEvent) => {
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
131
|
+
const target = e.target as HTMLElement | null;
|
|
132
|
+
const policy = latest.current.fieldPolicy ?? 'reset';
|
|
133
|
+
// A key not for the held field, or under another policy now: the held keys go in first.
|
|
134
|
+
const stray = held !== '' && (policy !== 'hold-money' || target !== field);
|
|
135
|
+
if (stray) {
|
|
136
|
+
flush();
|
|
137
|
+
resetDetector();
|
|
138
|
+
}
|
|
139
|
+
if (
|
|
140
|
+
policy === 'hold-money' && !stray
|
|
141
|
+
&& target instanceof HTMLInputElement && target.getAttribute('inputmode') === 'decimal'
|
|
142
|
+
) {
|
|
143
|
+
if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
|
144
|
+
holdKey(e, target);
|
|
145
|
+
} else if (e.key === 'Shift') {
|
|
146
|
+
// A scanner sends Shift for a capital.
|
|
147
|
+
} else if ((e.key === 'Enter' || e.key === 'Tab') && latched) {
|
|
148
|
+
// The scanner's terminator, inside a latched run of this field.
|
|
149
|
+
if (detector.handleKey(e.key)) {
|
|
150
|
+
e.preventDefault();
|
|
151
|
+
e.stopPropagation();
|
|
152
|
+
}
|
|
153
|
+
} else {
|
|
154
|
+
// Named keys and shortcuts act on what the field shows, so the held keys go in before their default action.
|
|
155
|
+
flush();
|
|
156
|
+
resetDetector();
|
|
157
|
+
}
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const tagName = target?.tagName;
|
|
161
|
+
if (
|
|
162
|
+
tagName === 'INPUT' || tagName === 'TEXTAREA'
|
|
163
|
+
|| (policy !== 'reset' && (tagName === 'SELECT' || target?.isContentEditable === true))
|
|
164
|
+
) {
|
|
165
|
+
resetDetector();
|
|
66
166
|
} else if (detector.handleKey(e.key)) {
|
|
67
167
|
e.preventDefault();
|
|
68
168
|
e.stopPropagation();
|
|
@@ -71,6 +171,8 @@ export function useBarcodeScanner(options: UseBarcodeScannerOptions): void {
|
|
|
71
171
|
// v2 uses keydown because keyup gave lowercase.
|
|
72
172
|
window.addEventListener('keydown', handler, { capture: true });
|
|
73
173
|
return () => {
|
|
174
|
+
// Typing is never lost.
|
|
175
|
+
flush();
|
|
74
176
|
window.removeEventListener('keydown', handler, { capture: true });
|
|
75
177
|
detector.dispose();
|
|
76
178
|
subscription.unsubscribe();
|