@tallyui/pos 3.11.0 → 3.13.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 +1621 -358
- package/dist/index.js +6515 -4314
- package/package.json +12 -6
- package/src/app-settings/app-settings.ts +93 -0
- package/src/app-settings/index.ts +8 -0
- package/src/app-settings/use-app-settings.ts +23 -0
- package/src/cashier/can.ts +12 -0
- package/src/cashier/index.ts +2 -0
- package/src/cashier/use-cashier.ts +81 -0
- package/src/csv/csv.ts +33 -0
- package/src/csv/index.ts +2 -0
- package/src/customer-display/display-state.ts +30 -0
- package/src/customer-display/index.ts +8 -0
- package/src/customer-display/protocol.ts +87 -0
- package/src/customer-display/snapshot.ts +65 -0
- package/src/index.ts +68 -11
- package/src/order/order-builder.ts +19 -2
- package/src/order/order-drafts.ts +17 -0
- package/src/order/types.ts +10 -3
- package/src/outbox/index.ts +5 -1
- package/src/outbox/outbox-health.ts +40 -0
- package/src/outbox/register-outbox.ts +59 -6
- package/src/outbox/safe-error.ts +11 -0
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-outbox-health.ts +22 -0
- package/src/outbox/use-register-outbox.ts +6 -0
- package/src/payment-driver/index.ts +8 -0
- package/src/payment-driver/registry.ts +39 -0
- package/src/payment-driver/simulated-driver.ts +104 -0
- package/src/payment-driver/types.ts +73 -0
- package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
- package/src/pos-order/command.ts +39 -17
- package/src/pos-order/finalize.ts +11 -3
- package/src/pos-order/index.ts +1 -0
- package/src/pos-order/note-delivery.ts +13 -0
- package/src/pos-order/reopen.ts +4 -2
- package/src/pos-order/schema.ts +7 -4
- package/src/pos-order/types.ts +5 -2
- package/src/print/index.ts +10 -0
- package/src/print/print-queue.ts +67 -0
- package/src/print/printer-profiles.ts +71 -0
- package/src/print/system-transport.ts +101 -0
- package/src/print/types.ts +40 -0
- package/src/receipt/index.ts +1 -0
- package/src/receipt/reprint.ts +149 -0
- package/src/receipt/types.ts +2 -0
- package/src/receipt-template/default-templates.ts +78 -0
- package/src/receipt-template/index.ts +15 -0
- package/src/receipt-template/parse-xml.ts +175 -0
- package/src/receipt-template/render-html.ts +152 -0
- package/src/receipt-template/render-receipt.ts +19 -0
- package/src/receipt-template/render-template.ts +35 -0
- package/src/receipt-template/sanitize-html.ts +146 -0
- package/src/receipt-template/template-data.ts +97 -0
- package/src/receipt-template/types.ts +49 -0
- package/src/refund/index.ts +2 -0
- package/src/refund/refundable-lines.ts +91 -0
- package/src/register/export-csv.ts +24 -35
- package/src/register/float-suggestion.ts +22 -0
- package/src/register/index.ts +8 -3
- package/src/register/register-adoption.ts +71 -2
- package/src/register/register-commands.ts +7 -4
- package/src/register/register-count.helpers.ts +4 -0
- package/src/register/session-store.ts +4 -1
- package/src/register/use-register-session.ts +112 -28
- package/src/reports/adapters.ts +67 -0
- package/src/reports/index.ts +5 -0
- package/src/reports/presets.ts +27 -0
- package/src/reports/sales-figures.ts +173 -0
- package/src/reports/types.ts +63 -0
- package/src/sale/cart.ts +15 -3
- package/src/sale/catalogue.ts +5 -1
- package/src/sale/index.ts +3 -1
- package/src/sale/open-sales.ts +40 -0
- package/src/sale/use-sale.ts +72 -8
- package/src/scanner/index.ts +6 -0
- package/src/scanner/scan-session.ts +84 -0
- package/src/scanner/use-barcode-scanner.ts +61 -0
- package/src/scanner/wedge-detector.ts +137 -0
- package/src/tender/cash-rounding.ts +74 -0
- package/src/tender/index.ts +4 -0
- package/src/tender/payment-legs.ts +48 -0
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// Ported from WCPOS v2 packages/scanner/src/scan-session.ts (monorepo 5ac185b0).
|
|
2
|
+
/** Suppress repeated reads within a cooldown and reject retail check-digit misreads. */
|
|
3
|
+
export const DEFAULT_COOLDOWN_MS = 1200;
|
|
4
|
+
export type ScanRejectReason = 'cooldown' | 'bad-check-digit';
|
|
5
|
+
export interface ScanOfferResult { accepted: boolean; reason?: ScanRejectReason; }
|
|
6
|
+
export interface ScanSessionOptions {
|
|
7
|
+
onAccept: (code: string, symbology?: string) => void;
|
|
8
|
+
cooldownMs?: number;
|
|
9
|
+
now?: () => number;
|
|
10
|
+
}
|
|
11
|
+
export interface ScanSession {
|
|
12
|
+
offer: (code: string, symbology?: string) => ScanOfferResult;
|
|
13
|
+
reset: () => void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// UPC-E is excluded: its check digit is computed over the expanded UPC-A,
|
|
17
|
+
// so validating its printed 8 digits as EAN-8 would reject valid reads.
|
|
18
|
+
const RETAIL_SYMBOLOGIES = new Set(['ean13', 'ean8', 'upc_a', 'ean-13', 'ean-8', 'upc-a']);
|
|
19
|
+
// Decoders can expand UPC-E to UPC-A and then pad it to 13 digits too.
|
|
20
|
+
const ZERO_PADDED_SYMBOLOGIES = new Set(['ean13', 'upc_a', 'upc_e', 'ean-13', 'upc-a', 'upc-e']);
|
|
21
|
+
|
|
22
|
+
/** Report the printed UPC-A digits by dropping an implied zero from labelled
|
|
23
|
+
* EAN-13/UPC reads. Unlabelled reads and printed 8-digit UPC-E stay unchanged. */
|
|
24
|
+
export function normalizeRetailCode(code: string, symbology?: string): string {
|
|
25
|
+
if (symbology === undefined || !ZERO_PADDED_SYMBOLOGIES.has(symbology.toLowerCase())) {
|
|
26
|
+
return code;
|
|
27
|
+
}
|
|
28
|
+
return /^0\d{12}$/.test(code) ? code.slice(1) : code;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Validate EAN-13/EAN-8/UPC-A check digits; non-retail-length inputs pass. */
|
|
32
|
+
export function hasValidRetailCheckDigit(code: string): boolean {
|
|
33
|
+
if (!/^\d+$/.test(code)) return true;
|
|
34
|
+
if (code.length !== 8 && code.length !== 12 && code.length !== 13) return true;
|
|
35
|
+
const digits = code.split('').map(Number);
|
|
36
|
+
const check = digits.pop() as number;
|
|
37
|
+
// From the rightmost data digit, weights alternate 3,1,3,1…
|
|
38
|
+
let sum = 0;
|
|
39
|
+
for (let i = digits.length - 1, weight = 3; i >= 0; i -= 1, weight = weight === 3 ? 1 : 3) {
|
|
40
|
+
sum += digits[i] * weight;
|
|
41
|
+
}
|
|
42
|
+
const expected = (10 - (sum % 10)) % 10;
|
|
43
|
+
return expected === check;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The other printing of the same UPC-A: `0`+12 digits -> the 12; 12 digits -> `0`+12; anything else undefined.
|
|
47
|
+
* Ported from the UPC-A <-> EAN-13 branch of v2 barcodeMatchCandidates (sync-core/src/barcodeResolve.ts).
|
|
48
|
+
* Match the twin against barcodes only, never SKUs (v2 BARCODE_SYMBOLOGY_FIELDS excludes sku). */
|
|
49
|
+
export function retailCodeTwin(code: string): string | undefined {
|
|
50
|
+
const trimmed = code.trim();
|
|
51
|
+
if (/^0\d{12}$/.test(trimmed)) return trimmed.slice(1);
|
|
52
|
+
if (/^\d{12}$/.test(trimmed)) return `0${trimmed}`;
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function looksRetail(code: string, symbology?: string): boolean {
|
|
57
|
+
// Explicit symbology is authoritative: numeric code128/qr/upc_e must pass.
|
|
58
|
+
if (symbology) return RETAIL_SYMBOLOGIES.has(symbology.toLowerCase());
|
|
59
|
+
// Unlabelled length 8 is ambiguous between EAN-8 and UPC-E; gate only 12/13.
|
|
60
|
+
return /^\d+$/.test(code) && (code.length === 12 || code.length === 13);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function createScanSession(options: ScanSessionOptions): ScanSession {
|
|
64
|
+
const cooldownMs = options.cooldownMs ?? DEFAULT_COOLDOWN_MS;
|
|
65
|
+
const now = options.now ?? Date.now;
|
|
66
|
+
// Per-code cooldown starts at the last accepted read for trigger sources.
|
|
67
|
+
const cooldownFrom = new Map<string, number>();
|
|
68
|
+
const offer = (rawCode: string, symbology?: string): ScanOfferResult => {
|
|
69
|
+
const at = now();
|
|
70
|
+
// Normalize first so cooldown keys and downstream consumers see the same code.
|
|
71
|
+
const code = normalizeRetailCode(rawCode, symbology);
|
|
72
|
+
if (looksRetail(code, symbology) && !hasValidRetailCheckDigit(code)) {
|
|
73
|
+
return { accepted: false, reason: 'bad-check-digit' };
|
|
74
|
+
}
|
|
75
|
+
const lastAt = cooldownFrom.get(code);
|
|
76
|
+
if (lastAt !== undefined && at - lastAt < cooldownMs) {
|
|
77
|
+
return { accepted: false, reason: 'cooldown' };
|
|
78
|
+
}
|
|
79
|
+
cooldownFrom.set(code, at);
|
|
80
|
+
options.onAccept(code, symbology);
|
|
81
|
+
return { accepted: true };
|
|
82
|
+
};
|
|
83
|
+
return { offer, reset: () => { cooldownFrom.clear(); } };
|
|
84
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { useEffect, useRef } from 'react';
|
|
2
|
+
import { createWedgeDetector, DEFAULT_MIN_SCAN_CHARS, DEFAULT_WEDGE_SETTINGS } from './wedge-detector';
|
|
3
|
+
|
|
4
|
+
export interface UseBarcodeScannerOptions {
|
|
5
|
+
onScan: (code: string) => void;
|
|
6
|
+
/** Listen only while true (default true). */
|
|
7
|
+
enabled?: boolean;
|
|
8
|
+
threshold?: number;
|
|
9
|
+
prefix?: string;
|
|
10
|
+
suffix?: string;
|
|
11
|
+
minChars?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Listen for keyboard-wedge scans outside INPUT/TEXTAREA, with a minimum length gate.
|
|
15
|
+
* Ported from WCPOS v2 packages/core/src/screens/main/hooks/barcodes/use-barcode-detection.ts (monorepo 5ac185b0).
|
|
16
|
+
* @example
|
|
17
|
+
* useBarcodeScanner({ onScan: (code) => {
|
|
18
|
+
* const twin = retailCodeTwin(code);
|
|
19
|
+
* const entry = findEntryByCode(entries, code)
|
|
20
|
+
* ?? (twin ? entries.find(({ variant }) => variant.barcode === twin) : undefined);
|
|
21
|
+
* if (entry) addEntryToCart(builder, entry, traits, currency);
|
|
22
|
+
* else setSearchTerm(code); // searchProducts returns just the exact barcode/SKU matches
|
|
23
|
+
* } });
|
|
24
|
+
*/
|
|
25
|
+
export function useBarcodeScanner(options: UseBarcodeScannerOptions): void {
|
|
26
|
+
const latest = useRef(options);
|
|
27
|
+
latest.current = options;
|
|
28
|
+
const enabled = options.enabled ?? true;
|
|
29
|
+
useEffect(() => {
|
|
30
|
+
if (!enabled) return;
|
|
31
|
+
const detectorOptions = {
|
|
32
|
+
getSettings: () => ({
|
|
33
|
+
threshold: latest.current.threshold ?? DEFAULT_WEDGE_SETTINGS.threshold,
|
|
34
|
+
prefix: latest.current.prefix ?? '',
|
|
35
|
+
suffix: latest.current.suffix ?? '',
|
|
36
|
+
}),
|
|
37
|
+
onScan: (code: string) => {
|
|
38
|
+
if (code.length >= (latest.current.minChars ?? DEFAULT_MIN_SCAN_CHARS)) {
|
|
39
|
+
latest.current.onScan(code);
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
let detector = createWedgeDetector(detectorOptions);
|
|
44
|
+
const handler = (e: KeyboardEvent) => {
|
|
45
|
+
const tagName = (e.target as HTMLElement | null)?.tagName;
|
|
46
|
+
if (tagName === 'INPUT' || tagName === 'TEXTAREA') {
|
|
47
|
+
detector.dispose();
|
|
48
|
+
detector = createWedgeDetector(detectorOptions);
|
|
49
|
+
} else if (detector.handleKey(e.key)) {
|
|
50
|
+
e.preventDefault();
|
|
51
|
+
e.stopPropagation();
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
// v2 uses keydown because keyup gave lowercase.
|
|
55
|
+
window.addEventListener('keydown', handler, { capture: true });
|
|
56
|
+
return () => {
|
|
57
|
+
window.removeEventListener('keydown', handler, { capture: true });
|
|
58
|
+
detector.dispose();
|
|
59
|
+
};
|
|
60
|
+
}, [enabled]);
|
|
61
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Ported from WCPOS v2 packages/scanner/src/wedge-detector.ts (monorepo 5ac185b0).
|
|
2
|
+
/** The wedge detector distinguishes scanner bursts from typing using a folded
|
|
3
|
+
* running average of inter-key gaps. Live and replay paths share the reducer. */
|
|
4
|
+
export interface WedgeSettings {
|
|
5
|
+
/** Folded-average gap (ms) below which input latches as a scan. */
|
|
6
|
+
threshold: number;
|
|
7
|
+
/** Stripped only when it equals the first key. */
|
|
8
|
+
prefix: string;
|
|
9
|
+
/** Stripped only when it equals the last key. */
|
|
10
|
+
suffix: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** v2 store defaults: threshold 24 ms (stores.ts barcode_scanning_avg_time_input_threshold), no prefix/suffix. */
|
|
14
|
+
export const DEFAULT_WEDGE_SETTINGS: WedgeSettings = { threshold: 24, prefix: '', suffix: '' };
|
|
15
|
+
/** v2 store default barcode_scanning_min_chars. */
|
|
16
|
+
export const DEFAULT_MIN_SCAN_CHARS = 8;
|
|
17
|
+
/** End-of-scan settle: a burst is complete this long after its last key. */
|
|
18
|
+
export const WEDGE_END_OF_SCAN_MS = 150;
|
|
19
|
+
|
|
20
|
+
export interface WedgeState {
|
|
21
|
+
avg: number;
|
|
22
|
+
detecting: boolean;
|
|
23
|
+
stack: string[];
|
|
24
|
+
lastTimeMs: number | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createWedgeState(): WedgeState {
|
|
28
|
+
return { avg: 0, detecting: false, stack: [], lastTimeMs: null };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Fold one key, mutating and returning state. Kept bug-for-bug with v2:
|
|
32
|
+
* only length-1 keys advance timing; the first gap is +Infinity; the average
|
|
33
|
+
* folds as (avg + gap) / 2. Scanning latches below threshold for the burst;
|
|
34
|
+
* a slow key outside a burst resets the average and restarts the stack. */
|
|
35
|
+
export function foldWedgeKey(state: WedgeState, key: string, timeMs: number, threshold: number): WedgeState {
|
|
36
|
+
if (key.length !== 1) return state;
|
|
37
|
+
let gap = Number.POSITIVE_INFINITY;
|
|
38
|
+
if (state.lastTimeMs !== null) gap = timeMs - state.lastTimeMs;
|
|
39
|
+
state.avg = state.avg === 0 ? gap : (state.avg + gap) / 2;
|
|
40
|
+
if (state.detecting || state.avg < threshold) {
|
|
41
|
+
state.detecting = true;
|
|
42
|
+
state.stack.push(key);
|
|
43
|
+
} else {
|
|
44
|
+
state.avg = 0;
|
|
45
|
+
state.stack = [key];
|
|
46
|
+
}
|
|
47
|
+
state.lastTimeMs = timeMs;
|
|
48
|
+
return state;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Strip a configured prefix/suffix only when it equals the single key at
|
|
52
|
+
* that edge of the stack — never as a substring. */
|
|
53
|
+
export function stripBoundary(stack: string[], settings: WedgeSettings): string {
|
|
54
|
+
const inputStack = [...stack];
|
|
55
|
+
if (settings.prefix && inputStack[0] === settings.prefix) inputStack.shift();
|
|
56
|
+
if (settings.suffix && inputStack[inputStack.length - 1] === settings.suffix) inputStack.pop();
|
|
57
|
+
return inputStack.join('');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface TraceKey { key: string; timeMs: number; }
|
|
61
|
+
export interface WedgeReplayResult {
|
|
62
|
+
/** Whether the detector would latch onto this trace as a scan. */
|
|
63
|
+
detectedAsScan: boolean;
|
|
64
|
+
/** The barcode the detector would emit, with prefix/suffix stripped. */
|
|
65
|
+
code: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Replay the detector over a completed keystroke trace. */
|
|
69
|
+
export function replayWedgeDetector(keys: TraceKey[], settings: WedgeSettings): WedgeReplayResult {
|
|
70
|
+
const state = createWedgeState();
|
|
71
|
+
for (const entry of keys) foldWedgeKey(state, entry.key, entry.timeMs, settings.threshold);
|
|
72
|
+
if (!state.detecting) return { detectedAsScan: false, code: '' };
|
|
73
|
+
return { detectedAsScan: true, code: stripBoundary(state.stack, settings) };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface WedgeDetectorOptions {
|
|
77
|
+
/** Read current settings per keystroke so live changes apply. */
|
|
78
|
+
getSettings: () => WedgeSettings;
|
|
79
|
+
/** A completed burst, prefix/suffix already stripped. */
|
|
80
|
+
onScan: (code: string) => void;
|
|
81
|
+
/** Injectable clock/timers so hosts and tests control time. */
|
|
82
|
+
now?: () => number;
|
|
83
|
+
setTimeout?: (fn: () => void, ms: number) => unknown;
|
|
84
|
+
clearTimeout?: (handle: unknown) => void;
|
|
85
|
+
}
|
|
86
|
+
export interface WedgeDetector {
|
|
87
|
+
/** True for a latched burst key: the host must prevent its default action. */
|
|
88
|
+
handleKey: (key: string, timeMs?: number) => boolean;
|
|
89
|
+
/** Cancel any pending end-of-scan timer on host teardown. */
|
|
90
|
+
dispose: () => void;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Stream keys through the reducer, emitting after the settle window and
|
|
94
|
+
* once the quiet period exceeds the threshold, mirroring the original hook. */
|
|
95
|
+
export function createWedgeDetector(options: WedgeDetectorOptions): WedgeDetector {
|
|
96
|
+
const now = options.now ?? Date.now;
|
|
97
|
+
const schedule = options.setTimeout ?? ((fn: () => void, ms: number) => setTimeout(fn, ms));
|
|
98
|
+
const cancel = options.clearTimeout ?? ((handle: unknown) => clearTimeout(handle as never));
|
|
99
|
+
let state = createWedgeState();
|
|
100
|
+
let timer: unknown = null;
|
|
101
|
+
const clearTimer = () => {
|
|
102
|
+
if (timer !== null) {
|
|
103
|
+
cancel(timer);
|
|
104
|
+
timer = null;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
const handleKey = (key: string, timeMs?: number) => {
|
|
108
|
+
const time = timeMs ?? now();
|
|
109
|
+
const sinceLastMs = state.lastTimeMs === null ? Number.POSITIVE_INFINITY : time - state.lastTimeMs;
|
|
110
|
+
if (key.length !== 1) {
|
|
111
|
+
// Non-printable keys never advance the burst; only its terminator is consumed.
|
|
112
|
+
return (key === 'Enter' || key === 'Tab') && state.detecting && sinceLastMs <= WEDGE_END_OF_SCAN_MS;
|
|
113
|
+
}
|
|
114
|
+
const settings = options.getSettings();
|
|
115
|
+
foldWedgeKey(state, key, time, settings.threshold);
|
|
116
|
+
if (!state.detecting) return false;
|
|
117
|
+
clearTimer();
|
|
118
|
+
function settle() {
|
|
119
|
+
timer = null;
|
|
120
|
+
const current = options.getSettings();
|
|
121
|
+
if (state.detecting && now() - (state.lastTimeMs || 0) > current.threshold) {
|
|
122
|
+
const code = stripBoundary(state.stack, current);
|
|
123
|
+
// Reset for the next burst, deliberately keeping lastTimeMs.
|
|
124
|
+
const lastTimeMs = state.lastTimeMs;
|
|
125
|
+
state = createWedgeState();
|
|
126
|
+
state.lastTimeMs = lastTimeMs;
|
|
127
|
+
options.onScan(code);
|
|
128
|
+
} else if (state.detecting) {
|
|
129
|
+
// A threshold at or above the settle window must not latch forever.
|
|
130
|
+
timer = schedule(settle, WEDGE_END_OF_SCAN_MS);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
timer = schedule(settle, WEDGE_END_OF_SCAN_MS);
|
|
134
|
+
return state.detecting && sinceLastMs <= WEDGE_END_OF_SCAN_MS;
|
|
135
|
+
};
|
|
136
|
+
return { handleKey, dispose: clearTimer };
|
|
137
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Port of v2's cash rounding: packages/order-math/src/payments/rounding.ts and
|
|
3
|
+
* packages/core/src/screens/main/pos/checkout/tender/tender-figures.ts.
|
|
4
|
+
* v2's tender LEDGER: "a partial or short cash entry and every other method keep full precision".
|
|
5
|
+
* Local figures only; writing the rounding as an order line is unit 24.
|
|
6
|
+
*/
|
|
7
|
+
import type { PaymentMethodDescriptor, PaymentRounding } from '@tallyui/core';
|
|
8
|
+
import { appliedMinor, type TenderState } from './tender-state';
|
|
9
|
+
|
|
10
|
+
/** How the method rounds to its increment. */
|
|
11
|
+
export type RoundingMode = NonNullable<PaymentRounding>['mode'];
|
|
12
|
+
|
|
13
|
+
/** v2 roundToIncrement; also the identity for an increment that is not an integer. */
|
|
14
|
+
export function roundToIncrement(minor: number, incrementMinor: number, mode: RoundingMode): number {
|
|
15
|
+
if (!Number.isInteger(incrementMinor) || incrementMinor <= 1) return minor;
|
|
16
|
+
const remainder = minor % incrementMinor;
|
|
17
|
+
if (remainder === 0) return minor;
|
|
18
|
+
const down = minor - remainder;
|
|
19
|
+
if (mode === 'down') return down;
|
|
20
|
+
if (mode === 'up') return down + incrementMinor;
|
|
21
|
+
return remainder * 2 >= incrementMinor ? down + incrementMinor : down;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The balance under a manual method's rounding, with its signed difference. */
|
|
25
|
+
export function roundedDue(
|
|
26
|
+
balanceMinor: number,
|
|
27
|
+
method: PaymentMethodDescriptor | null,
|
|
28
|
+
): { dueMinor: number; roundingMinor: number } {
|
|
29
|
+
const rounding = method?.capture.mode === 'manual' ? method.defaults.rounding : null;
|
|
30
|
+
if (!rounding) return { dueMinor: balanceMinor, roundingMinor: 0 };
|
|
31
|
+
const dueMinor = roundToIncrement(balanceMinor, rounding.incrementMinor, rounding.mode);
|
|
32
|
+
return { dueMinor, roundingMinor: dueMinor - balanceMinor };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether the leg reaches the rounded due and the tendered amount covers it. */
|
|
36
|
+
export function settlesAtRoundedDue(facts: {
|
|
37
|
+
amountMinor: number;
|
|
38
|
+
tenderedMinor: number;
|
|
39
|
+
balanceMinor: number;
|
|
40
|
+
dueMinor: number;
|
|
41
|
+
}): boolean {
|
|
42
|
+
const { amountMinor, tenderedMinor, balanceMinor, dueMinor } = facts;
|
|
43
|
+
return amountMinor >= Math.min(balanceMinor, dueMinor) && tenderedMinor >= dueMinor;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Local tender figures under the method's cash rounding. */
|
|
47
|
+
export interface TenderRounding {
|
|
48
|
+
/** The balance under the method's rounding (the balance itself when none applies). */
|
|
49
|
+
roundedDueMinor: number;
|
|
50
|
+
/** `roundedDueMinor - balanceMinor` when the entry settles at the rounded due, else 0. Signed. */
|
|
51
|
+
roundingMinor: number;
|
|
52
|
+
/** The entry as the cashier sees it: an untouched prefill of the balance shows the rounded due. */
|
|
53
|
+
entryMinor: number;
|
|
54
|
+
/** What the entry applies to the order: the rounded due when rounding applies, else the capped entry. */
|
|
55
|
+
appliedMinor: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Figure the displayed entry and applied amount, rounding only a leg that settles at the due. */
|
|
59
|
+
export function tenderRounding(
|
|
60
|
+
state: Pick<TenderState, 'entryMinor' | 'entryDirty'>,
|
|
61
|
+
balanceMinor: number,
|
|
62
|
+
method: PaymentMethodDescriptor | null,
|
|
63
|
+
): TenderRounding {
|
|
64
|
+
const roundedDueMinor = roundedDue(balanceMinor, method).dueMinor;
|
|
65
|
+
const entryMinor = !state.entryDirty && state.entryMinor === balanceMinor ? roundedDueMinor : state.entryMinor;
|
|
66
|
+
const legMinor = appliedMinor(entryMinor, balanceMinor);
|
|
67
|
+
const roundingMinor = settlesAtRoundedDue({
|
|
68
|
+
amountMinor: legMinor,
|
|
69
|
+
tenderedMinor: entryMinor,
|
|
70
|
+
balanceMinor,
|
|
71
|
+
dueMinor: roundedDueMinor,
|
|
72
|
+
}) ? roundedDueMinor - balanceMinor : 0;
|
|
73
|
+
return { roundedDueMinor, roundingMinor, entryMinor, appliedMinor: roundingMinor !== 0 ? roundedDueMinor : legMinor };
|
|
74
|
+
}
|
package/src/tender/index.ts
CHANGED
|
@@ -2,3 +2,7 @@ export { tenderReducer, initTenderState, initialTenderState, appliedMinor, chang
|
|
|
2
2
|
export type { PaymentTransport, TenderView, TenderLineId, TenderPlan, SplitTab, TenderState, TenderKey, TenderAction, PlanLeg } from './tender-state';
|
|
3
3
|
export { tenderVoidSchema, tenderVoidCollection } from './tender-void';
|
|
4
4
|
export type { TenderVoid } from './tender-void';
|
|
5
|
+
export { roundedDue, tenderRounding } from './cash-rounding';
|
|
6
|
+
export type { TenderRounding } from './cash-rounding';
|
|
7
|
+
export { legStatus, countsTowardPaid, isInMotion, capturedMinor, inMotionMinor, canMoveLeg, canVoidLeg } from './payment-legs';
|
|
8
|
+
export type { PaymentLegStatus } from './payment-legs';
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** Local sale state; the order.create wire does not carry payment status yet. */
|
|
2
|
+
import type { PaymentMethodDescriptor } from '@tallyui/core';
|
|
3
|
+
|
|
4
|
+
export type PaymentLegStatus = 'pending' | 'authorized' | 'captured' | 'failed' | 'voided';
|
|
5
|
+
type Leg = { amountMinor: number; status?: PaymentLegStatus };
|
|
6
|
+
|
|
7
|
+
const moves: Record<PaymentLegStatus, readonly PaymentLegStatus[]> = {
|
|
8
|
+
pending: ['authorized', 'captured', 'failed', 'voided'],
|
|
9
|
+
authorized: ['captured', 'failed', 'voided'],
|
|
10
|
+
captured: ['voided'],
|
|
11
|
+
failed: [],
|
|
12
|
+
voided: [],
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Defaults legacy legs to captured using v2 payments/types.ts PaymentStatus. */
|
|
16
|
+
export function legStatus(leg: { status?: PaymentLegStatus }): PaymentLegStatus {
|
|
17
|
+
return leg.status ?? 'captured';
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Only captured money is paid: v2 payments/derive.ts countsTowardPaid (ADR 0040 D6). */
|
|
21
|
+
export function countsTowardPaid(leg: { status?: PaymentLegStatus }): boolean {
|
|
22
|
+
return legStatus(leg) === 'captured';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Pending and authorized are in motion: v2 payments/ledger.ts isInMotionPaymentStatus. */
|
|
26
|
+
export function isInMotion(leg: { status?: PaymentLegStatus }): boolean {
|
|
27
|
+
return legStatus(leg) === 'pending' || legStatus(leg) === 'authorized';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Sums integer minor units using v2 payments/derive.ts countsTowardPaid. */
|
|
31
|
+
export function capturedMinor(legs: readonly Leg[]): number {
|
|
32
|
+
return legs.reduce((sum, leg) => sum + (countsTowardPaid(leg) ? leg.amountMinor : 0), 0);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Sums holds in integer minor units using v2 payments/ledger.ts isInMotionPaymentStatus. */
|
|
36
|
+
export function inMotionMinor(legs: readonly Leg[]): number {
|
|
37
|
+
return legs.reduce((sum, leg) => sum + (isInMotion(leg) ? leg.amountMinor : 0), 0);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Local transitions for v2 payments/ledger.ts isInMotionPaymentStatus and isFinalPaymentStatus. */
|
|
41
|
+
export function canMoveLeg(from: PaymentLegStatus, to: PaymentLegStatus): boolean {
|
|
42
|
+
return moves[from].includes(to);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Voids live legs, captured only manually: v2 payments/ledger.ts partitionVoidableRows. */
|
|
46
|
+
export function canVoidLeg(leg: { status?: PaymentLegStatus }, method: PaymentMethodDescriptor): boolean {
|
|
47
|
+
return method.capabilities.void && (isInMotion(leg) || (legStatus(leg) === 'captured' && method.capture.mode === 'manual'));
|
|
48
|
+
}
|