@tallyui/pos 3.12.0 → 3.14.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 +1844 -359
- package/dist/index.js +4620 -2211
- package/package.json +12 -6
- package/src/app-settings/app-settings.ts +108 -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-link.ts +72 -0
- package/src/customer-display/display-state.ts +30 -0
- package/src/customer-display/index.ts +13 -0
- package/src/customer-display/protocol.ts +87 -0
- package/src/customer-display/snapshot.ts +65 -0
- package/src/customer-display/transport.ts +54 -0
- package/src/customer-display/use-customer-display.ts +36 -0
- package/src/index.ts +73 -10
- package/src/order/order-builder.ts +11 -1
- package/src/order/order-drafts.ts +16 -0
- package/src/order/types.ts +6 -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 +36 -16
- package/src/pos-order/finalize.ts +7 -3
- package/src/pos-order/index.ts +1 -0
- package/src/pos-order/note-delivery.ts +13 -0
- package/src/pos-order/reopen.ts +3 -2
- package/src/pos-order/schema.ts +5 -4
- package/src/pos-order/types.ts +3 -2
- package/src/print/escpos/code-page.ts +48 -0
- package/src/print/escpos/commands.ts +53 -0
- package/src/print/escpos/encode.ts +127 -0
- package/src/print/escpos/index.ts +7 -0
- package/src/print/escpos/transport.ts +45 -0
- package/src/print/index.ts +12 -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 +44 -0
- package/src/receipt/reprint.ts +2 -1
- 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/handover.ts +103 -0
- package/src/register/index.ts +10 -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 +187 -0
- package/src/reports/types.ts +63 -0
- package/src/sale/in-cart.ts +18 -0
- package/src/sale/index.ts +5 -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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/pos",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.14.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Shared POS business logic for Tally UI — tax, orders, payments, discounts, receipts",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -27,21 +27,27 @@
|
|
|
27
27
|
"url": "git+https://github.com/TallyUI/tallyui.git",
|
|
28
28
|
"directory": "packages/pos"
|
|
29
29
|
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@types/mustache": "^4.2.6",
|
|
32
|
+
"@xmldom/xmldom": "0.9.12",
|
|
33
|
+
"dompurify": "^3.4.17",
|
|
34
|
+
"mustache": "^4.2.0"
|
|
35
|
+
},
|
|
30
36
|
"peerDependencies": {
|
|
31
|
-
"@tallyui/core": "^3.
|
|
37
|
+
"@tallyui/core": "^3.14.0",
|
|
32
38
|
"react": ">=18",
|
|
33
39
|
"rxdb": "~17.5.0",
|
|
34
40
|
"rxjs": ">=7"
|
|
35
41
|
},
|
|
36
42
|
"devDependencies": {
|
|
37
|
-
"@tallyui/core": "3.
|
|
43
|
+
"@tallyui/core": "3.14.0",
|
|
38
44
|
"@types/react": ">=18",
|
|
39
45
|
"react": "^19.2.4",
|
|
40
46
|
"rxdb": "17.5.0",
|
|
41
47
|
"rxjs": "7.8.2",
|
|
42
|
-
"@tallyui/connector-medusa": "3.
|
|
43
|
-
"@tallyui/connector-woocommerce": "3.
|
|
44
|
-
"@tallyui/database": "3.
|
|
48
|
+
"@tallyui/connector-medusa": "3.14.0",
|
|
49
|
+
"@tallyui/connector-woocommerce": "3.14.0",
|
|
50
|
+
"@tallyui/database": "3.14.0"
|
|
45
51
|
},
|
|
46
52
|
"scripts": {
|
|
47
53
|
"build": "tsup",
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device UI preferences, one JSON-encoded value per key. Local only, never replicated;
|
|
3
|
+
* the app adds the collection as `app_settings`.
|
|
4
|
+
* v2 provenance: WCPOS monorepo `packages/database/src/collections/schemas/stores.ts`
|
|
5
|
+
* keeps scale (auto|compact|regular|spacious, default auto) and fonts (default auto)
|
|
6
|
+
* device-local beside the theme, never server-owned. TallyUI has no replicated
|
|
7
|
+
* store document for them; TallyUI CLAUDE.md forbids local writes to replicated collections.
|
|
8
|
+
*/
|
|
9
|
+
import type { RxCollection, RxJsonSchema } from 'rxdb';
|
|
10
|
+
import { map, type Observable } from 'rxjs';
|
|
11
|
+
|
|
12
|
+
export const UI_SCALES = ['auto', 'compact', 'regular', 'spacious'] as const;
|
|
13
|
+
export type UiScale = (typeof UI_SCALES)[number];
|
|
14
|
+
/** v2's first three themes (`core/screens/main/settings/theme.tsx`); TallyUI's tokens define light and dark. */
|
|
15
|
+
export const UI_THEMES = ['system', 'light', 'dark'] as const;
|
|
16
|
+
export type UiTheme = (typeof UI_THEMES)[number];
|
|
17
|
+
|
|
18
|
+
/** The typed key map. Add a key here and in APP_SETTING_DEFINITIONS; no schema change is needed. */
|
|
19
|
+
export interface AppSettings {
|
|
20
|
+
/** The app applies it (e.g. Uniwind's setTheme); this store only records it. */
|
|
21
|
+
'ui.theme': UiTheme;
|
|
22
|
+
'ui.scale': UiScale;
|
|
23
|
+
/** A font id; `'auto'` follows the theme. Not an enum: the font list lives in the UI layer. */
|
|
24
|
+
'ui.font': string;
|
|
25
|
+
/**
|
|
26
|
+
* The cart's quick-discount keys in percent, for `Cart`'s `quickDiscounts`. v2 keeps them per screen,
|
|
27
|
+
* `pos-cart.quickDiscounts: [5, 10, 15]` (`core/src/screens/main/contexts/ui-settings/initial-settings.json`).
|
|
28
|
+
*/
|
|
29
|
+
'cart.quickDiscounts': readonly number[];
|
|
30
|
+
}
|
|
31
|
+
export type AppSettingKey = keyof AppSettings;
|
|
32
|
+
|
|
33
|
+
/** One key's default and its check: `parse` returns the value when valid, else `undefined`. */
|
|
34
|
+
export interface AppSettingDefinition<T> {
|
|
35
|
+
default: T;
|
|
36
|
+
parse: (value: unknown) => T | undefined;
|
|
37
|
+
}
|
|
38
|
+
export const APP_SETTING_DEFINITIONS: { [K in AppSettingKey]: AppSettingDefinition<AppSettings[K]> } = {
|
|
39
|
+
'ui.theme': { default: 'system', parse: (value) => UI_THEMES.find((theme) => theme === value) },
|
|
40
|
+
'ui.scale': { default: 'auto', parse: (value) => UI_SCALES.find((scale) => scale === value) },
|
|
41
|
+
'ui.font': {
|
|
42
|
+
default: 'auto',
|
|
43
|
+
parse: (value) => typeof value === 'string' && value.length > 0 && value.length <= 64 ? value : undefined,
|
|
44
|
+
},
|
|
45
|
+
'cart.quickDiscounts': {
|
|
46
|
+
default: [5, 10, 15],
|
|
47
|
+
// As v2's `ensureNumberArray`: only real percentages (0 < n <= 100) survive; an empty list is no keys.
|
|
48
|
+
parse: (value) => Array.isArray(value)
|
|
49
|
+
? value.filter((n): n is number => typeof n === 'number' && Number.isFinite(n) && n > 0 && n <= 100)
|
|
50
|
+
: undefined,
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
export const DEFAULT_APP_SETTINGS: AppSettings = {
|
|
54
|
+
'ui.theme': APP_SETTING_DEFINITIONS['ui.theme'].default,
|
|
55
|
+
'ui.scale': APP_SETTING_DEFINITIONS['ui.scale'].default,
|
|
56
|
+
'ui.font': APP_SETTING_DEFINITIONS['ui.font'].default,
|
|
57
|
+
'cart.quickDiscounts': APP_SETTING_DEFINITIONS['cart.quickDiscounts'].default,
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/** One stored setting. `value` is the JSON encoding of the setting's value, so the schema never changes when a key is added. */
|
|
61
|
+
export interface AppSettingDoc { key: string; value: string }
|
|
62
|
+
export const appSettingSchema: RxJsonSchema<AppSettingDoc> = {
|
|
63
|
+
title: 'App settings', version: 0, primaryKey: 'key', type: 'object', additionalProperties: false,
|
|
64
|
+
properties: {
|
|
65
|
+
key: { type: 'string', maxLength: 64 },
|
|
66
|
+
value: { type: 'string' },
|
|
67
|
+
},
|
|
68
|
+
required: ['key', 'value'],
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export function appSettingCollection(): { readonly schema: RxJsonSchema<AppSettingDoc> } {
|
|
72
|
+
return { schema: appSettingSchema } as const;
|
|
73
|
+
}
|
|
74
|
+
export type AppSettingCollection = RxCollection<AppSettingDoc>;
|
|
75
|
+
|
|
76
|
+
export function resolveAppSettings(docs: readonly AppSettingDoc[]): AppSettings {
|
|
77
|
+
const settings = { ...DEFAULT_APP_SETTINGS };
|
|
78
|
+
for (const doc of docs) {
|
|
79
|
+
if (!Object.hasOwn(APP_SETTING_DEFINITIONS, doc.key)) continue;
|
|
80
|
+
const key = doc.key as AppSettingKey;
|
|
81
|
+
try {
|
|
82
|
+
const value = APP_SETTING_DEFINITIONS[key].parse(JSON.parse(doc.value));
|
|
83
|
+
if (value !== undefined) Object.assign(settings, { [key]: value });
|
|
84
|
+
} catch {
|
|
85
|
+
// Unreadable stored values leave the default in place.
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return settings;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function readAppSettings(collection: AppSettingCollection): Promise<AppSettings> {
|
|
92
|
+
return resolveAppSettings((await collection.find().exec()).map((doc) => doc.toJSON()));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function appSettings$(collection: AppSettingCollection): Observable<AppSettings> {
|
|
96
|
+
return collection.find().$.pipe(map((docs) => resolveAppSettings(docs.map((doc) => doc.toJSON()))));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function writeAppSetting<K extends AppSettingKey>(
|
|
100
|
+
collection: AppSettingCollection, key: K, value: AppSettings[K],
|
|
101
|
+
): Promise<void> {
|
|
102
|
+
// The parsed value is stored, so a list keeps only what a read would keep.
|
|
103
|
+
const parsed = APP_SETTING_DEFINITIONS[key].parse(value);
|
|
104
|
+
if (parsed === undefined) {
|
|
105
|
+
throw new Error(`writeAppSetting: invalid value for ${key}`);
|
|
106
|
+
}
|
|
107
|
+
await collection.upsert({ key, value: JSON.stringify(parsed) });
|
|
108
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export {
|
|
2
|
+
UI_SCALES, UI_THEMES, APP_SETTING_DEFINITIONS, DEFAULT_APP_SETTINGS, appSettingSchema,
|
|
3
|
+
appSettingCollection, resolveAppSettings, readAppSettings, appSettings$, writeAppSetting,
|
|
4
|
+
} from './app-settings';
|
|
5
|
+
export type {
|
|
6
|
+
UiScale, UiTheme, AppSettings, AppSettingKey, AppSettingDefinition, AppSettingDoc, AppSettingCollection,
|
|
7
|
+
} from './app-settings';
|
|
8
|
+
export { useAppSettings } from './use-app-settings';
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react';
|
|
2
|
+
import {
|
|
3
|
+
appSettings$, DEFAULT_APP_SETTINGS, writeAppSetting,
|
|
4
|
+
type AppSettingCollection, type AppSettingKey, type AppSettings,
|
|
5
|
+
} from './app-settings';
|
|
6
|
+
|
|
7
|
+
export function useAppSettings(collection: AppSettingCollection | undefined): {
|
|
8
|
+
settings: AppSettings;
|
|
9
|
+
setSetting: <K extends AppSettingKey>(key: K, value: AppSettings[K]) => Promise<void>;
|
|
10
|
+
} {
|
|
11
|
+
const [settings, setSettings] = useState<AppSettings>(DEFAULT_APP_SETTINGS);
|
|
12
|
+
useEffect(() => {
|
|
13
|
+
if (!collection) { setSettings(DEFAULT_APP_SETTINGS); return; }
|
|
14
|
+
const subscription = appSettings$(collection).subscribe(setSettings);
|
|
15
|
+
return () => subscription.unsubscribe();
|
|
16
|
+
}, [collection]);
|
|
17
|
+
|
|
18
|
+
const setSetting = async <K extends AppSettingKey>(key: K, value: AppSettings[K]): Promise<void> => {
|
|
19
|
+
if (!collection) throw new Error('useAppSettings: setSetting() needs the app settings collection');
|
|
20
|
+
await writeAppSetting(collection, key, value);
|
|
21
|
+
};
|
|
22
|
+
return { settings, setSetting };
|
|
23
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { isCashierPermission, type Cashier, type CashierPermission } from '@tallyui/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Whether `cashier` may do `permission`. A `null` or `undefined` cashier (a connector with no `cashier()`, or one
|
|
5
|
+
* that resolved `null`) is allowed everything: today's behaviour, before connectors had permissions. A name that is
|
|
6
|
+
* not a `CashierPermission` is never allowed, and a permission the cashier's list does not name is denied.
|
|
7
|
+
*/
|
|
8
|
+
export function can(cashier: Cashier | null | undefined, permission: CashierPermission): boolean {
|
|
9
|
+
if (!isCashierPermission(permission)) return false;
|
|
10
|
+
if (!cashier) return true;
|
|
11
|
+
return cashier.permissions.includes(permission);
|
|
12
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { useEffect, useMemo, useState } from 'react';
|
|
2
|
+
import { cashierPermissions } from '@tallyui/core';
|
|
3
|
+
import type { Cashier, CashierPermission, SyncContext, TallyConnector } from '@tallyui/core';
|
|
4
|
+
import { can } from './can';
|
|
5
|
+
|
|
6
|
+
export interface CashierState {
|
|
7
|
+
/** The cashier with unknown permission names dropped; `null` while loading, after an error, with no `cashier()`, or when it resolved `null`. */
|
|
8
|
+
cashier: Cashier | null;
|
|
9
|
+
/** `can(cashier, permission)` once known; `false` while loading or after an error, so nothing flashes. */
|
|
10
|
+
can: (permission: CashierPermission) => boolean;
|
|
11
|
+
/** `cashier()` is in flight, or there is no connector or context yet. */
|
|
12
|
+
loading: boolean;
|
|
13
|
+
/** What `cashier()` rejected with; `undefined` otherwise. */
|
|
14
|
+
error: unknown;
|
|
15
|
+
/** For `useRegisterSession`'s `blind` option: `!can('viewReports')`, as v2's blind count. */
|
|
16
|
+
blind: boolean;
|
|
17
|
+
/** The Reports gate: `'pending'` while loading, `'allowed'` with `viewReports`, else `'denied'`. */
|
|
18
|
+
reports: 'pending' | 'allowed' | 'denied';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type Read = { connector: TallyConnector; context: SyncContext } & (
|
|
22
|
+
| { status: 'ready'; cashier: Cashier | null }
|
|
23
|
+
| { status: 'error'; error: unknown }
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
const deny = () => false;
|
|
27
|
+
const LOADING: CashierState = { cashier: null, can: deny, loading: true, error: undefined, blind: true, reports: 'pending' };
|
|
28
|
+
|
|
29
|
+
function resolved(cashier: Cashier | null): CashierState {
|
|
30
|
+
const reports = can(cashier, 'viewReports');
|
|
31
|
+
return {
|
|
32
|
+
cashier, can: (permission) => can(cashier, permission), loading: false, error: undefined,
|
|
33
|
+
blind: !reports, reports: reports ? 'allowed' : 'denied',
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The signed-in cashier's permissions (v2 parity A12): reads `connector.cashier(context)` on mount, and again when
|
|
39
|
+
* `connector` or `context` changes by identity (memoise both); the last read wins. A connector without `cashier()`
|
|
40
|
+
* allows everything at once, as before. While the read is in flight, and after it rejects, `can` is `false` and the
|
|
41
|
+
* count is blind, so a blind cashier never sees figures flash; nothing is retried.
|
|
42
|
+
*
|
|
43
|
+
* ```tsx
|
|
44
|
+
* const cashier = useCashier(connector, context);
|
|
45
|
+
* const register = useRegisterSession({ ...options, blind: cashier.blind });
|
|
46
|
+
* if (cashier.reports === 'denied') return <NoReportsAccess />;
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export function useCashier(connector: TallyConnector | null, context: SyncContext | null): CashierState {
|
|
50
|
+
const [read, setRead] = useState<Read | null>(null);
|
|
51
|
+
|
|
52
|
+
useEffect(() => {
|
|
53
|
+
if (!connector?.cashier || !context) return;
|
|
54
|
+
let live = true;
|
|
55
|
+
Promise.resolve().then(() => connector.cashier?.(context) ?? null).then(
|
|
56
|
+
(cashier) => {
|
|
57
|
+
if (live) setRead({
|
|
58
|
+
connector, context, status: 'ready',
|
|
59
|
+
cashier: cashier && { id: cashier.id, name: cashier.name, permissions: cashierPermissions(cashier.permissions) },
|
|
60
|
+
});
|
|
61
|
+
},
|
|
62
|
+
(error: unknown) => {
|
|
63
|
+
if (live) setRead({ connector, context, status: 'error', error });
|
|
64
|
+
},
|
|
65
|
+
);
|
|
66
|
+
// Discards the in-flight read on a connector or context change, or unmount.
|
|
67
|
+
return () => {
|
|
68
|
+
live = false;
|
|
69
|
+
};
|
|
70
|
+
}, [connector, context]);
|
|
71
|
+
|
|
72
|
+
return useMemo(() => {
|
|
73
|
+
if (!connector || !context) return LOADING;
|
|
74
|
+
if (!connector.cashier) return resolved(null);
|
|
75
|
+
// A read for another connector or context is stale: the current one is still loading.
|
|
76
|
+
if (!read || read.connector !== connector || read.context !== context) return LOADING;
|
|
77
|
+
if (read.status === 'error')
|
|
78
|
+
return { cashier: null, can: deny, loading: false, error: read.error, blind: true, reports: 'denied' };
|
|
79
|
+
return resolved(read.cashier);
|
|
80
|
+
}, [connector, context, read]);
|
|
81
|
+
}
|
package/src/csv/csv.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every cell is quoted (RFC 4180 style, so commas, quotes, CR and LF are safe). Lines use
|
|
3
|
+
* CRLF, with no BOM or trailing line ending, matching the register export. The formula guard
|
|
4
|
+
* prefixes `'` to text starting with `=`, `+`, `-`, `@`, tab, CR or LF, including formula
|
|
5
|
+
* markers after leading whitespace/control characters, as WCPOS v2's `csvCell` in the monorepo
|
|
6
|
+
* `reports/closures/export-csv.ts`. Numbers are NOT exempt: -5 exports as `'-5`, matching v2,
|
|
7
|
+
* which runs the guard on `String(value)`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** One CSV column: a header and either a row key or an accessor. */
|
|
11
|
+
export type CsvColumn<Row> =
|
|
12
|
+
| { header: string; key: keyof Row & string }
|
|
13
|
+
| { header: string; value: (row: Row) => unknown };
|
|
14
|
+
|
|
15
|
+
/** One cell, quoted and formula-guarded. */
|
|
16
|
+
export function csvCell(value: unknown): string {
|
|
17
|
+
const text = String(value ?? '');
|
|
18
|
+
// eslint-disable-next-line no-control-regex -- Control prefixes are intentional CSV-injection guards.
|
|
19
|
+
return `"${(/^(?:[\t\r\n]|[\s\x00-\x1f\x7f-\x9f]*[=+\-@])/.test(text) ? "'" + text : text).replace(/"/g, '""')}"`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Rows of already-ordered cells (the first row is usually the header) to a CSV string. */
|
|
23
|
+
export function csvFromCells(lines: readonly (readonly unknown[])[]): string {
|
|
24
|
+
return lines.map((line) => line.map(csvCell).join(',')).join('\r\n');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Header row from `columns`, then one line per row. */
|
|
28
|
+
export function toCsv<Row>(rows: readonly Row[], columns: readonly CsvColumn<Row>[]): string {
|
|
29
|
+
return csvFromCells([
|
|
30
|
+
columns.map((c) => c.header),
|
|
31
|
+
...rows.map((row) => columns.map((c) => 'key' in c ? row[c.key] : c.value(row))),
|
|
32
|
+
]);
|
|
33
|
+
}
|
package/src/csv/index.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { ReceiptData } from '../receipt/types';
|
|
2
|
+
import { displayCart, makeEnvelope, type DisplayConfig, type DisplayEnvelope, type DisplayPayment } from './protocol';
|
|
3
|
+
import type { DisplayTransport } from './transport';
|
|
4
|
+
|
|
5
|
+
export interface DisplayClock { setTimeout(run: () => void, ms: number): unknown; clearTimeout(handle: unknown): void }
|
|
6
|
+
|
|
7
|
+
const systemClock: DisplayClock = {
|
|
8
|
+
setTimeout: (run, ms) => setTimeout(run, ms),
|
|
9
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export interface DisplayLink {
|
|
13
|
+
/** The order as it stands; null, or no lines, fees or shipping, shows idle. */
|
|
14
|
+
showCart(receipt: ReceiptData | null): void;
|
|
15
|
+
showPayment(receipt: ReceiptData, payment: DisplayPayment): void;
|
|
16
|
+
close(): void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The till's side of the customer display. Ported from WCPOS v2 (monorepo main 51e7c43,
|
|
21
|
+
* core/services/customer-display/display-session.ts and service.ts) without the WebRTC: each `display.hello` is
|
|
22
|
+
* answered with `display.config` under the hello's id, then the current state; a completed payment stays up for
|
|
23
|
+
* `config.idle.afterCompleteMs` before `display.idle`, and an empty cart inside that window waits for it.
|
|
24
|
+
*/
|
|
25
|
+
export function createDisplayLink(transport: DisplayTransport, options: { config: DisplayConfig; clock?: DisplayClock }): DisplayLink {
|
|
26
|
+
const { config, clock = systemClock } = options;
|
|
27
|
+
let current: DisplayEnvelope | null = null;
|
|
28
|
+
let lastKey = '';
|
|
29
|
+
let idleTimer: unknown = null;
|
|
30
|
+
const cancelIdle = () => {
|
|
31
|
+
if (idleTimer !== null) clock.clearTimeout(idleTimer);
|
|
32
|
+
idleTimer = null;
|
|
33
|
+
};
|
|
34
|
+
// As v2's lastPublished: the same state twice is sent once.
|
|
35
|
+
const publish = (envelope: DisplayEnvelope) => {
|
|
36
|
+
const key = JSON.stringify([envelope.action, envelope.payload]);
|
|
37
|
+
if (key === lastKey) return;
|
|
38
|
+
lastKey = key;
|
|
39
|
+
current = envelope;
|
|
40
|
+
transport.send(envelope);
|
|
41
|
+
};
|
|
42
|
+
const idle = () => publish(makeEnvelope('display.idle', { reason: 'no_cart' }));
|
|
43
|
+
const unsubscribe = transport.onMessage((envelope) => {
|
|
44
|
+
if (envelope.action !== 'display.hello') return;
|
|
45
|
+
transport.send(makeEnvelope('display.config', { ...config, template: envelope.payload.template }, envelope.id));
|
|
46
|
+
if (current) transport.send(current);
|
|
47
|
+
});
|
|
48
|
+
return {
|
|
49
|
+
showCart(receipt) {
|
|
50
|
+
if (!receipt || receipt.lineItems.length + receipt.fees.length + receipt.shipping.length === 0) {
|
|
51
|
+
if (idleTimer === null) idle();
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
cancelIdle();
|
|
55
|
+
publish(makeEnvelope('cart.updated', displayCart(receipt)));
|
|
56
|
+
},
|
|
57
|
+
showPayment(receipt, payment) {
|
|
58
|
+
cancelIdle();
|
|
59
|
+
publish(makeEnvelope('payment.state', { ...displayCart(receipt), ...payment }));
|
|
60
|
+
if (payment.state === 'complete') {
|
|
61
|
+
idleTimer = clock.setTimeout(() => {
|
|
62
|
+
idleTimer = null;
|
|
63
|
+
idle();
|
|
64
|
+
}, config.idle.afterCompleteMs);
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
close() {
|
|
68
|
+
cancelIdle();
|
|
69
|
+
unsubscribe();
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { DisplayCart, DisplayConfig, DisplayEnvelope, DisplayPayment } from './protocol';
|
|
2
|
+
|
|
3
|
+
/** What the customer display shows: nothing to sell, the cart, or a payment in progress or complete. */
|
|
4
|
+
export type DisplayView =
|
|
5
|
+
| { screen: 'idle'; reason: string }
|
|
6
|
+
| { screen: 'cart'; cart: DisplayCart }
|
|
7
|
+
| { screen: 'payment'; cart: DisplayCart; payment: DisplayPayment };
|
|
8
|
+
export interface DisplayState { config: DisplayConfig | null; view: DisplayView }
|
|
9
|
+
|
|
10
|
+
export const initialDisplayState: DisplayState = { config: null, view: { screen: 'idle', reason: 'no_cart' } };
|
|
11
|
+
|
|
12
|
+
/** The display side's state, driven by decoded messages from the till. */
|
|
13
|
+
export function displayReducer(state: DisplayState, envelope: DisplayEnvelope): DisplayState {
|
|
14
|
+
switch (envelope.action) {
|
|
15
|
+
case 'display.config':
|
|
16
|
+
return { ...state, config: envelope.payload };
|
|
17
|
+
case 'display.idle':
|
|
18
|
+
return { ...state, view: { screen: 'idle', reason: envelope.payload.reason } };
|
|
19
|
+
case 'cart.updated':
|
|
20
|
+
return { ...state, view: { screen: 'cart', cart: envelope.payload } };
|
|
21
|
+
case 'payment.state': {
|
|
22
|
+
const { receipt, linesTruncated, state: phase, leg, message } = envelope.payload;
|
|
23
|
+
const payment: DisplayPayment = { state: phase, ...(leg ? { leg } : {}), ...(message !== undefined ? { message } : {}) };
|
|
24
|
+
return { ...state, view: { screen: 'payment', cart: { receipt, linesTruncated }, payment } };
|
|
25
|
+
}
|
|
26
|
+
case 'display.hello':
|
|
27
|
+
// Travels from the display to the till, so the display's own state does not change.
|
|
28
|
+
return state;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { DISPLAY_PROTOCOL_VERSION, DISPLAY_ACTIONS, makeEnvelope, displayCart, decode } from './protocol';
|
|
2
|
+
export type {
|
|
3
|
+
PaymentPhase, DisplayTemplate, DisplayCart, DisplayPayment, DisplayConfig, DisplayPayloads, DisplayAction,
|
|
4
|
+
DisplayEnvelope, DecodeRefusal, DecodeResult,
|
|
5
|
+
} from './protocol';
|
|
6
|
+
export { MAX_MESSAGE_BYTES, messageBytes, encode } from './snapshot';
|
|
7
|
+
export { displayReducer, initialDisplayState } from './display-state';
|
|
8
|
+
export type { DisplayView, DisplayState } from './display-state';
|
|
9
|
+
export { DISPLAY_CHANNEL, createBroadcastDisplayTransport } from './transport';
|
|
10
|
+
export type { DisplayTransport, BroadcastChannelLike } from './transport';
|
|
11
|
+
export { createDisplayLink } from './display-link';
|
|
12
|
+
export type { DisplayLink, DisplayClock } from './display-link';
|
|
13
|
+
export { useCustomerDisplay, DISPLAY_TEMPLATE, HELLO_RETRY_MS } from './use-customer-display';
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { uuidv7 } from '../pos-order/uuidv7';
|
|
2
|
+
import type { ReceiptData } from '../receipt/types';
|
|
3
|
+
|
|
4
|
+
// Ported from WCPOS v2 (monorepo main 51e7c43, core/services/customer-display/envelope.ts). v2's envelope key
|
|
5
|
+
// `wcpos: 1` is `tally: 1` here: same place and value, so a v2 message is refused by version, never misread.
|
|
6
|
+
export const DISPLAY_PROTOCOL_VERSION = 1;
|
|
7
|
+
|
|
8
|
+
export type PaymentPhase = 'started' | 'approved' | 'declined' | 'complete';
|
|
9
|
+
export interface DisplayTemplate { id: string | number; version: number }
|
|
10
|
+
/** The cart snapshot: the receipt as it stands, and whether lines were dropped to fit the message cap. */
|
|
11
|
+
export interface DisplayCart { receipt: ReceiptData; linesTruncated: boolean }
|
|
12
|
+
export interface DisplayPayment { state: PaymentPhase; leg?: { method: string; amountMinor: number }; message?: string }
|
|
13
|
+
export interface DisplayConfig {
|
|
14
|
+
contract: '1.0';
|
|
15
|
+
display: { id: string; name: string };
|
|
16
|
+
store: { id: string; name: string; currency: string; locale: string; timezone?: string; logo?: string };
|
|
17
|
+
presentation_hints: Record<string, unknown>;
|
|
18
|
+
i18n: Record<string, string>;
|
|
19
|
+
template?: DisplayTemplate;
|
|
20
|
+
idle: { afterCompleteMs: number };
|
|
21
|
+
}
|
|
22
|
+
export interface DisplayPayloads {
|
|
23
|
+
'cart.updated': DisplayCart;
|
|
24
|
+
'payment.state': DisplayCart & DisplayPayment;
|
|
25
|
+
'display.idle': { reason: string };
|
|
26
|
+
/** Sent by the display to the till. */
|
|
27
|
+
'display.hello': { template: DisplayTemplate };
|
|
28
|
+
'display.config': DisplayConfig;
|
|
29
|
+
}
|
|
30
|
+
export type DisplayAction = keyof DisplayPayloads;
|
|
31
|
+
export const DISPLAY_ACTIONS: readonly DisplayAction[] = [
|
|
32
|
+
'cart.updated', 'payment.state', 'display.idle', 'display.hello', 'display.config',
|
|
33
|
+
];
|
|
34
|
+
export type DisplayEnvelope<A extends DisplayAction = DisplayAction> =
|
|
35
|
+
{ [K in A]: { tally: 1; id: string; action: K; payload: DisplayPayloads[K] } }[A];
|
|
36
|
+
|
|
37
|
+
export function makeEnvelope<A extends DisplayAction>(action: A, payload: DisplayPayloads[A], id = uuidv7()): DisplayEnvelope<A> {
|
|
38
|
+
return { tally: DISPLAY_PROTOCOL_VERSION, id, action, payload } as DisplayEnvelope<A>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function displayCart(receipt: ReceiptData): DisplayCart {
|
|
42
|
+
return { receipt, linesTruncated: false };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type DecodeRefusal = 'malformed' | 'version' | 'action' | 'payload';
|
|
46
|
+
export type DecodeResult = { ok: true; envelope: DisplayEnvelope } | { ok: false; refusal: DecodeRefusal };
|
|
47
|
+
|
|
48
|
+
type Obj = Record<string, unknown>;
|
|
49
|
+
const isObj = (v: unknown): v is Obj => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
50
|
+
const isStr = (v: unknown): v is string => typeof v === 'string';
|
|
51
|
+
const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
|
52
|
+
const isTemplate = (v: unknown) => isObj(v) && (isStr(v.id) || isNum(v.id)) && isNum(v.version);
|
|
53
|
+
const isLine = (v: unknown) => isObj(v) && isStr(v.name) && isNum(v.quantity) && isNum(v.displayAmountMinor);
|
|
54
|
+
const isCart = (p: Obj) => typeof p.linesTruncated === 'boolean' && isObj(p.receipt) && isStr(p.receipt.currency)
|
|
55
|
+
&& isObj(p.receipt.totals) && isNum(p.receipt.totals.totalMinor)
|
|
56
|
+
&& Array.isArray(p.receipt.lineItems) && p.receipt.lineItems.every(isLine);
|
|
57
|
+
const PHASES: readonly unknown[] = ['started', 'approved', 'declined', 'complete'];
|
|
58
|
+
|
|
59
|
+
const PAYLOAD_CHECKS: { [A in DisplayAction]: (p: Obj) => boolean } = {
|
|
60
|
+
'cart.updated': isCart,
|
|
61
|
+
'payment.state': (p) => isCart(p) && PHASES.includes(p.state) && (p.message === undefined || isStr(p.message))
|
|
62
|
+
&& (p.leg === undefined || (isObj(p.leg) && isStr(p.leg.method) && isNum(p.leg.amountMinor))),
|
|
63
|
+
'display.idle': (p) => isStr(p.reason),
|
|
64
|
+
'display.hello': (p) => isTemplate(p.template),
|
|
65
|
+
'display.config': (p) => p.contract === '1.0'
|
|
66
|
+
&& isObj(p.display) && isStr(p.display.id) && isStr(p.display.name)
|
|
67
|
+
&& isObj(p.store) && isStr(p.store.id) && isStr(p.store.name) && isStr(p.store.currency) && isStr(p.store.locale)
|
|
68
|
+
&& isObj(p.presentation_hints) && isObj(p.i18n) && (p.template === undefined || isTemplate(p.template))
|
|
69
|
+
&& isObj(p.idle) && isNum(p.idle.afterCompleteMs),
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/** Reads a message from the other side. Never throws: anything it cannot trust comes back as a refusal. */
|
|
73
|
+
export function decode(text: unknown): DecodeResult {
|
|
74
|
+
if (!isStr(text)) return { ok: false, refusal: 'malformed' };
|
|
75
|
+
let message: unknown;
|
|
76
|
+
try {
|
|
77
|
+
message = JSON.parse(text);
|
|
78
|
+
} catch {
|
|
79
|
+
return { ok: false, refusal: 'malformed' };
|
|
80
|
+
}
|
|
81
|
+
if (!isObj(message) || !isStr(message.id)) return { ok: false, refusal: 'malformed' };
|
|
82
|
+
if (message.tally !== DISPLAY_PROTOCOL_VERSION) return { ok: false, refusal: 'version' };
|
|
83
|
+
const action = message.action as DisplayAction;
|
|
84
|
+
if (!DISPLAY_ACTIONS.includes(action)) return { ok: false, refusal: 'action' };
|
|
85
|
+
if (!isObj(message.payload) || !PAYLOAD_CHECKS[action](message.payload)) return { ok: false, refusal: 'payload' };
|
|
86
|
+
return { ok: true, envelope: message as unknown as DisplayEnvelope };
|
|
87
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { DisplayCart, DisplayEnvelope } from './protocol';
|
|
2
|
+
|
|
3
|
+
// Trimming ported from WCPOS v2's serialiseSnapshot (monorepo main 51e7c43, core/services/customer-display/snapshot.ts).
|
|
4
|
+
/** The display contract caps each message at 200 KiB: UTF-8 bytes of the JSON text. */
|
|
5
|
+
export const MAX_MESSAGE_BYTES = 200 * 1024;
|
|
6
|
+
/** v2 bounds the note first, so totals and payments are never displaced. */
|
|
7
|
+
const MAX_NOTE_BYTES = 1024;
|
|
8
|
+
/** v2 keeps eight metadata entries per line; here a line's attributes. */
|
|
9
|
+
const MAX_LINE_ATTRIBUTES = 8;
|
|
10
|
+
|
|
11
|
+
const encoder = new TextEncoder();
|
|
12
|
+
export function messageBytes(text: string): number {
|
|
13
|
+
return encoder.encode(text).byteLength;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function truncateUtf8(text: string, limit: number): string {
|
|
17
|
+
if (messageBytes(text) <= limit) return text;
|
|
18
|
+
let bytes = 0;
|
|
19
|
+
let result = '';
|
|
20
|
+
for (const character of text) {
|
|
21
|
+
bytes += messageBytes(character);
|
|
22
|
+
if (bytes > limit) break;
|
|
23
|
+
result += character;
|
|
24
|
+
}
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function trimCart(cart: DisplayCart, size: () => number): void {
|
|
29
|
+
const { receipt } = cart;
|
|
30
|
+
if (typeof receipt.footer?.note === 'string') receipt.footer.note = truncateUtf8(receipt.footer.note, MAX_NOTE_BYTES);
|
|
31
|
+
if (size() <= MAX_MESSAGE_BYTES) return;
|
|
32
|
+
for (const line of receipt.lineItems) {
|
|
33
|
+
if (line.attributes) line.attributes = Object.fromEntries(Object.entries(line.attributes).slice(0, MAX_LINE_ATTRIBUTES));
|
|
34
|
+
}
|
|
35
|
+
if (size() <= MAX_MESSAGE_BYTES) return;
|
|
36
|
+
cart.linesTruncated = true;
|
|
37
|
+
let excess = size() - MAX_MESSAGE_BYTES;
|
|
38
|
+
// Oldest lines go first and the newest stay, as in v2. The drop is counted from the line sizes (each line plus
|
|
39
|
+
// its comma), so a huge cart is not re-serialised once per line. At least one goes, as linesTruncated says.
|
|
40
|
+
let drop = 0;
|
|
41
|
+
while ((excess > 0 || drop === 0) && drop < receipt.lineItems.length) excess -= messageBytes(JSON.stringify(receipt.lineItems[drop++])) + 1;
|
|
42
|
+
receipt.lineItems.splice(0, drop);
|
|
43
|
+
while (size() > MAX_MESSAGE_BYTES && receipt.lineItems.length > 0) receipt.lineItems.shift();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Serialises a message within MAX_MESSAGE_BYTES, trimming a copy in v2's order. If it is still over after every
|
|
48
|
+
* step (a non-cart action, or a receipt whose fixed fields alone are too big), the text is returned anyway, as v2
|
|
49
|
+
* sends it; check with messageBytes.
|
|
50
|
+
*/
|
|
51
|
+
export function encode(envelope: DisplayEnvelope): string {
|
|
52
|
+
let text = JSON.stringify(envelope);
|
|
53
|
+
if (messageBytes(text) <= MAX_MESSAGE_BYTES) return text;
|
|
54
|
+
const copy = JSON.parse(text) as DisplayEnvelope;
|
|
55
|
+
const size = () => messageBytes(text = JSON.stringify(copy));
|
|
56
|
+
if (copy.action === 'cart.updated' || copy.action === 'payment.state') trimCart(copy.payload, size);
|
|
57
|
+
else if (copy.action === 'display.config') {
|
|
58
|
+
copy.payload.i18n = {};
|
|
59
|
+
if (size() > MAX_MESSAGE_BYTES) {
|
|
60
|
+
copy.payload.presentation_hints = {};
|
|
61
|
+
size();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return text;
|
|
65
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { decode, type DisplayEnvelope } from './protocol';
|
|
2
|
+
import { encode } from './snapshot';
|
|
3
|
+
|
|
4
|
+
/** How the till and the customer display reach each other. The first is a second window on this device (ADR-084 3). */
|
|
5
|
+
export interface DisplayTransport {
|
|
6
|
+
/** False when the channel refuses (closed); never throws. */
|
|
7
|
+
send(envelope: DisplayEnvelope): boolean;
|
|
8
|
+
/** Decoded messages from the other window; returns the unsubscribe. */
|
|
9
|
+
onMessage(listener: (envelope: DisplayEnvelope) => void): () => void;
|
|
10
|
+
close(): void;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const DISPLAY_CHANNEL = 'tallyui.customer-display';
|
|
14
|
+
|
|
15
|
+
/** The structural part of BroadcastChannel the transport uses (a test passes a fake). */
|
|
16
|
+
export interface BroadcastChannelLike {
|
|
17
|
+
postMessage(message: unknown): void;
|
|
18
|
+
close(): void;
|
|
19
|
+
onmessage: ((event: MessageEvent) => void) | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A same-origin second window over BroadcastChannel. Whatever arrives is decoded; anything refused is dropped. */
|
|
23
|
+
export function createBroadcastDisplayTransport(
|
|
24
|
+
channelName = DISPLAY_CHANNEL,
|
|
25
|
+
open: (name: string) => BroadcastChannelLike = (name) => new BroadcastChannel(name),
|
|
26
|
+
): DisplayTransport {
|
|
27
|
+
const channel = open(channelName);
|
|
28
|
+
const listeners = new Set<(envelope: DisplayEnvelope) => void>();
|
|
29
|
+
channel.onmessage = (event) => {
|
|
30
|
+
const result = decode(event.data);
|
|
31
|
+
if (result.ok) listeners.forEach((listener) => listener(result.envelope));
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
send(envelope) {
|
|
35
|
+
try {
|
|
36
|
+
channel.postMessage(encode(envelope));
|
|
37
|
+
return true;
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
onMessage(listener) {
|
|
43
|
+
listeners.add(listener);
|
|
44
|
+
return () => {
|
|
45
|
+
listeners.delete(listener);
|
|
46
|
+
};
|
|
47
|
+
},
|
|
48
|
+
close() {
|
|
49
|
+
listeners.clear();
|
|
50
|
+
channel.onmessage = null;
|
|
51
|
+
channel.close();
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|