@tallyui/pos 3.12.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.
Files changed (79) hide show
  1. package/dist/index.d.ts +1545 -300
  2. package/dist/index.js +4259 -2218
  3. package/package.json +12 -6
  4. package/src/app-settings/app-settings.ts +93 -0
  5. package/src/app-settings/index.ts +8 -0
  6. package/src/app-settings/use-app-settings.ts +23 -0
  7. package/src/cashier/can.ts +12 -0
  8. package/src/cashier/index.ts +2 -0
  9. package/src/cashier/use-cashier.ts +81 -0
  10. package/src/csv/csv.ts +33 -0
  11. package/src/csv/index.ts +2 -0
  12. package/src/customer-display/display-state.ts +30 -0
  13. package/src/customer-display/index.ts +8 -0
  14. package/src/customer-display/protocol.ts +87 -0
  15. package/src/customer-display/snapshot.ts +65 -0
  16. package/src/index.ts +67 -10
  17. package/src/order/order-builder.ts +11 -1
  18. package/src/order/order-drafts.ts +16 -0
  19. package/src/order/types.ts +6 -3
  20. package/src/outbox/index.ts +5 -1
  21. package/src/outbox/outbox-health.ts +40 -0
  22. package/src/outbox/register-outbox.ts +59 -6
  23. package/src/outbox/safe-error.ts +11 -0
  24. package/src/outbox/types.ts +3 -1
  25. package/src/outbox/use-outbox-health.ts +22 -0
  26. package/src/outbox/use-register-outbox.ts +6 -0
  27. package/src/payment-driver/index.ts +8 -0
  28. package/src/payment-driver/registry.ts +39 -0
  29. package/src/payment-driver/simulated-driver.ts +104 -0
  30. package/src/payment-driver/types.ts +73 -0
  31. package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
  32. package/src/pos-order/command.ts +36 -16
  33. package/src/pos-order/finalize.ts +7 -3
  34. package/src/pos-order/index.ts +1 -0
  35. package/src/pos-order/note-delivery.ts +13 -0
  36. package/src/pos-order/reopen.ts +3 -2
  37. package/src/pos-order/schema.ts +5 -4
  38. package/src/pos-order/types.ts +3 -2
  39. package/src/print/index.ts +10 -0
  40. package/src/print/print-queue.ts +67 -0
  41. package/src/print/printer-profiles.ts +71 -0
  42. package/src/print/system-transport.ts +101 -0
  43. package/src/print/types.ts +40 -0
  44. package/src/receipt/reprint.ts +2 -1
  45. package/src/receipt/types.ts +2 -0
  46. package/src/receipt-template/default-templates.ts +78 -0
  47. package/src/receipt-template/index.ts +15 -0
  48. package/src/receipt-template/parse-xml.ts +175 -0
  49. package/src/receipt-template/render-html.ts +152 -0
  50. package/src/receipt-template/render-receipt.ts +19 -0
  51. package/src/receipt-template/render-template.ts +35 -0
  52. package/src/receipt-template/sanitize-html.ts +146 -0
  53. package/src/receipt-template/template-data.ts +97 -0
  54. package/src/receipt-template/types.ts +49 -0
  55. package/src/refund/index.ts +2 -0
  56. package/src/refund/refundable-lines.ts +91 -0
  57. package/src/register/export-csv.ts +24 -35
  58. package/src/register/float-suggestion.ts +22 -0
  59. package/src/register/index.ts +8 -3
  60. package/src/register/register-adoption.ts +71 -2
  61. package/src/register/register-commands.ts +7 -4
  62. package/src/register/register-count.helpers.ts +4 -0
  63. package/src/register/session-store.ts +4 -1
  64. package/src/register/use-register-session.ts +112 -28
  65. package/src/reports/adapters.ts +67 -0
  66. package/src/reports/index.ts +5 -0
  67. package/src/reports/presets.ts +27 -0
  68. package/src/reports/sales-figures.ts +173 -0
  69. package/src/reports/types.ts +63 -0
  70. package/src/sale/index.ts +3 -1
  71. package/src/sale/open-sales.ts +40 -0
  72. package/src/sale/use-sale.ts +72 -8
  73. package/src/scanner/index.ts +6 -0
  74. package/src/scanner/scan-session.ts +84 -0
  75. package/src/scanner/use-barcode-scanner.ts +61 -0
  76. package/src/scanner/wedge-detector.ts +137 -0
  77. package/src/tender/cash-rounding.ts +74 -0
  78. package/src/tender/index.ts +4 -0
  79. 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.12.0",
3
+ "version": "3.13.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
+ "@xmldom/xmldom": "0.9.12",
32
+ "dompurify": "^3.4.17",
33
+ "mustache": "^4.2.0"
34
+ },
30
35
  "peerDependencies": {
31
- "@tallyui/core": "^3.12.0",
36
+ "@tallyui/core": "^3.13.0",
32
37
  "react": ">=18",
33
38
  "rxdb": "~17.5.0",
34
39
  "rxjs": ">=7"
35
40
  },
36
41
  "devDependencies": {
37
- "@tallyui/core": "3.12.0",
42
+ "@tallyui/core": "3.13.0",
43
+ "@types/mustache": "^4.2.6",
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.12.0",
43
- "@tallyui/connector-woocommerce": "3.12.0",
44
- "@tallyui/database": "3.12.0"
48
+ "@tallyui/connector-medusa": "3.13.0",
49
+ "@tallyui/connector-woocommerce": "3.13.0",
50
+ "@tallyui/database": "3.13.0"
45
51
  },
46
52
  "scripts": {
47
53
  "build": "tsup",
@@ -0,0 +1,93 @@
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
+ export type AppSettingKey = keyof AppSettings;
27
+
28
+ /** One key's default and its check: `parse` returns the value when valid, else `undefined`. */
29
+ export interface AppSettingDefinition<T> {
30
+ default: T;
31
+ parse: (value: unknown) => T | undefined;
32
+ }
33
+ export const APP_SETTING_DEFINITIONS: { [K in AppSettingKey]: AppSettingDefinition<AppSettings[K]> } = {
34
+ 'ui.theme': { default: 'system', parse: (value) => UI_THEMES.find((theme) => theme === value) },
35
+ 'ui.scale': { default: 'auto', parse: (value) => UI_SCALES.find((scale) => scale === value) },
36
+ 'ui.font': {
37
+ default: 'auto',
38
+ parse: (value) => typeof value === 'string' && value.length > 0 && value.length <= 64 ? value : undefined,
39
+ },
40
+ };
41
+ export const DEFAULT_APP_SETTINGS: AppSettings = {
42
+ 'ui.theme': APP_SETTING_DEFINITIONS['ui.theme'].default,
43
+ 'ui.scale': APP_SETTING_DEFINITIONS['ui.scale'].default,
44
+ 'ui.font': APP_SETTING_DEFINITIONS['ui.font'].default,
45
+ };
46
+
47
+ /** One stored setting. `value` is the JSON encoding of the setting's value, so the schema never changes when a key is added. */
48
+ export interface AppSettingDoc { key: string; value: string }
49
+ export const appSettingSchema: RxJsonSchema<AppSettingDoc> = {
50
+ title: 'App settings', version: 0, primaryKey: 'key', type: 'object', additionalProperties: false,
51
+ properties: {
52
+ key: { type: 'string', maxLength: 64 },
53
+ value: { type: 'string' },
54
+ },
55
+ required: ['key', 'value'],
56
+ };
57
+
58
+ export function appSettingCollection(): { readonly schema: RxJsonSchema<AppSettingDoc> } {
59
+ return { schema: appSettingSchema } as const;
60
+ }
61
+ export type AppSettingCollection = RxCollection<AppSettingDoc>;
62
+
63
+ export function resolveAppSettings(docs: readonly AppSettingDoc[]): AppSettings {
64
+ const settings = { ...DEFAULT_APP_SETTINGS };
65
+ for (const doc of docs) {
66
+ if (!Object.hasOwn(APP_SETTING_DEFINITIONS, doc.key)) continue;
67
+ const key = doc.key as AppSettingKey;
68
+ try {
69
+ const value = APP_SETTING_DEFINITIONS[key].parse(JSON.parse(doc.value));
70
+ if (value !== undefined) Object.assign(settings, { [key]: value });
71
+ } catch {
72
+ // Unreadable stored values leave the default in place.
73
+ }
74
+ }
75
+ return settings;
76
+ }
77
+
78
+ export async function readAppSettings(collection: AppSettingCollection): Promise<AppSettings> {
79
+ return resolveAppSettings((await collection.find().exec()).map((doc) => doc.toJSON()));
80
+ }
81
+
82
+ export function appSettings$(collection: AppSettingCollection): Observable<AppSettings> {
83
+ return collection.find().$.pipe(map((docs) => resolveAppSettings(docs.map((doc) => doc.toJSON()))));
84
+ }
85
+
86
+ export async function writeAppSetting<K extends AppSettingKey>(
87
+ collection: AppSettingCollection, key: K, value: AppSettings[K],
88
+ ): Promise<void> {
89
+ if (APP_SETTING_DEFINITIONS[key].parse(value) === undefined) {
90
+ throw new Error(`writeAppSetting: invalid value for ${key}`);
91
+ }
92
+ await collection.upsert({ key, value: JSON.stringify(value) });
93
+ }
@@ -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,2 @@
1
+ export { can } from './can';
2
+ export { useCashier, type CashierState } from './use-cashier';
@@ -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
+ }
@@ -0,0 +1,2 @@
1
+ export { csvCell, csvFromCells, toCsv } from './csv';
2
+ export type { CsvColumn } from './csv';
@@ -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,8 @@
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';
@@ -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
+ }
package/src/index.ts CHANGED
@@ -2,6 +2,10 @@
2
2
  export { createLogger, consoleSink, callbackSink } from './logging';
3
3
  export type { Logger, LogSink, LogEntry, LogLevel } from './logging';
4
4
 
5
+ // CSV
6
+ export { csvCell, csvFromCells, toCsv } from './csv';
7
+ export type { CsvColumn } from './csv';
8
+
5
9
  // Currency
6
10
  export { CurrencyProvider, useCurrencyFormatter, useCurrencyCode } from './currency';
7
11
  export type { CurrencyProviderProps } from './currency';
@@ -17,6 +21,19 @@ export type { TaxRateMap, TaxContext } from './tax';
17
21
  export { resolveStoreSettings, useStoreSettings, withPricingContext, taxProviderProps } from './store-settings';
18
22
  export type { StoreSettingsResolution, ResolveStoreSettingsOptions, StoreSettingsState } from './store-settings';
19
23
 
24
+ // Cashier permissions (v2 parity A12)
25
+ export { can, useCashier } from './cashier';
26
+ export type { CashierState } from './cashier';
27
+
28
+ // App settings
29
+ export {
30
+ UI_SCALES, UI_THEMES, APP_SETTING_DEFINITIONS, DEFAULT_APP_SETTINGS, appSettingSchema,
31
+ appSettingCollection, resolveAppSettings, readAppSettings, appSettings$, writeAppSetting, useAppSettings,
32
+ } from './app-settings';
33
+ export type {
34
+ UiScale, UiTheme, AppSettings, AppSettingKey, AppSettingDefinition, AppSettingDoc, AppSettingCollection,
35
+ } from './app-settings';
36
+
20
37
  // RxDB reads past the query cache, and live lists that can't leave it stale (RxDB 16.21.1 bug 4)
21
38
  export { readFresh, countFresh, watchFresh } from './rxdb';
22
39
 
@@ -55,34 +72,67 @@ export type {
55
72
  export { buildReceiptData, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, RECEIPT_SCHEMA_VERSION } from './receipt';
56
73
  export type { ReceiptData, ReceiptLineItem, ReceiptConfig, ReceiptSoftware, ReceiptRegister, ReceiptFiscal } from './receipt';
57
74
 
75
+ // Receipt templates
76
+ export { parseXml, renderHtml, sanitizeHtml, renderReceiptTemplate, renderLogiclessTemplate, renderThermalPreview, receiptTemplateData, DEFAULT_RECEIPT_TEMPLATES, PAPER_COLUMNS, renderReceiptHtml } from './receipt-template';
77
+ export type { ThermalNode, ReceiptNode, SanitizeHtmlOptions, RenderSanitizeOptions, ReceiptTemplateRow, ReceiptTemplateLine, ReceiptTemplateData, ReceiptTemplateOptions, ReceiptPaper, RenderReceiptOptions } from './receipt-template';
78
+
79
+ // Customer display
80
+ export { DISPLAY_PROTOCOL_VERSION, DISPLAY_ACTIONS, makeEnvelope, displayCart, decode as decodeDisplayMessage, encode as encodeDisplayMessage, messageBytes, MAX_MESSAGE_BYTES, displayReducer, initialDisplayState } from './customer-display';
81
+ export type { PaymentPhase, DisplayTemplate, DisplayCart, DisplayPayment, DisplayConfig, DisplayPayloads, DisplayAction, DisplayEnvelope, DecodeRefusal, DecodeResult, DisplayView, DisplayState } from './customer-display';
82
+
58
83
  // Product
59
84
  export { searchProducts, sortProducts, productSortValue, PRODUCT_SORT_FIELDS, type ProductSort, type ProductSortValue, catalogueViewReducer, normalizeCatalogueViewState, resolveGridColumns, DEFAULT_CATALOGUE_VIEW_STATE, type CatalogueView, type CatalogueGridColumns, type CatalogueViewState, type CatalogueViewAction, withStockOverlay, getProductStock, stockOverlay$, stockOverlayAsOf$, productCategories, listCategories, inCategory } from './product';
60
85
 
86
+ // Scanner
87
+ export { DEFAULT_WEDGE_SETTINGS, DEFAULT_MIN_SCAN_CHARS, WEDGE_END_OF_SCAN_MS, createWedgeState, foldWedgeKey, stripBoundary, replayWedgeDetector, createWedgeDetector, DEFAULT_COOLDOWN_MS, normalizeRetailCode, hasValidRetailCheckDigit, retailCodeTwin, createScanSession, useBarcodeScanner } from './scanner';
88
+ export type { WedgeSettings, WedgeState, TraceKey, WedgeReplayResult, WedgeDetectorOptions, WedgeDetector, ScanRejectReason, ScanOfferResult, ScanSessionOptions, ScanSession, UseBarcodeScannerOptions } from './scanner';
89
+
90
+ // Payment drivers
91
+ export { createPaymentDriverRegistry, driverForMethod, createSimulatedDriver, SIMULATED_PROVIDER, SIMULATED_TIMING } from './payment-driver';
92
+ export type {
93
+ DriverCapabilities, ReaderInfo, DriverStatus, DriverAvailability, CollectInput,
94
+ CollectOutcome, CollectResult, DriverStatusSource, PaymentDriver, PaymentDriverRegistry,
95
+ SimulatedReaderId, SimulatedDriverOptions,
96
+ } from './payment-driver';
97
+
98
+ // Printing
99
+ export {
100
+ PrintError, toPrintError, createPrintQueue, SYSTEM_PRINTER_ID, PRINTER_PROFILES_COLLECTION, printerProfileSchema,
101
+ printerProfileCollection, addPrinterProfileCollection, createSystemPrintTransport, SYSTEM_PRINT_TIMING,
102
+ } from './print';
103
+ export type {
104
+ PrintJob, PrintJobKind, PrintErrorCode, PrintTransport, PrintQueue, PrintQueueOptions, PrintQueueState,
105
+ PrinterProfile, PrinterProfileCollection, SystemPrintTransportOptions,
106
+ } from './print';
107
+
61
108
  // Sale
62
- export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED } from './sale';
63
- export type { SaleStage, CatalogueEntry, SaleDiscountCodes, SaleDiscountState } from './sale';
109
+ export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, openSales, isPartlyPaid, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED } from './sale';
110
+ export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState } from './sale';
64
111
 
65
112
  export { uuidv7, finalizeOrder, toOrderCreateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
66
113
  export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './pos-order';
114
+ export { noteDelivery, type NoteDelivery } from './pos-order';
67
115
  export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, FinalizeOptions } from './pos-order';
68
116
  export { createHttpCommandTransport, createOrderOutbox, isRequeueable, useOrderOutbox, outboxLogger } from './outbox';
69
- export { createRegisterOutbox, useRegisterOutbox } from './outbox';
117
+ export { createRegisterOutbox, isRegisterRequeueable, useRegisterOutbox, summarizeOutboxHealth, watchOutboxHealth, useOutboxHealth } from './outbox';
70
118
  export type { RegisterOutboxOptions, RegisterOutbox, UseRegisterOutboxOptions, UseRegisterOutboxResult } from './outbox';
119
+ export type { OutboxCounts, OutboxHealth, UseOutboxHealthOptions, UseOutboxHealthResult } from './outbox';
71
120
  export { createBackendNotFound } from './outbox/backend-not-found';
72
121
  export type { BackendNotFound } from './outbox/backend-not-found';
73
122
  export type { HttpTransportOptions, OrderOutboxOptions, OrderOutbox, TransportOutcome, CommandTransport, OrderTransportContext, OutboxState, UseOrderOutboxOptions, UseOrderOutboxResult } from './outbox';
74
- export { sendOrderRefund, type OrderRefundOutcome, posRefundSchema, posRefundCollection, submitOrderRefund, RefundAnswerPendingError, type PosRefund, type PosRefundStatus, type PosRefundCollection } from './refund';
75
- export { tenderReducer, initTenderState, initialTenderState, appliedMinor, changeMinor, quickTenderedAmounts, evenSplitShareMinor, activePlan, planLegs, MAX_TENDER_MINOR, tenderVoidSchema, tenderVoidCollection } from './tender';
76
- export type { PaymentTransport, TenderView, TenderLineId, TenderPlan, SplitTab, TenderState, TenderKey, TenderAction, PlanLeg, TenderVoid } from './tender';
123
+ export { sendOrderRefund, type OrderRefundOutcome, posRefundSchema, posRefundCollection, submitOrderRefund, RefundAnswerPendingError, type PosRefund, type PosRefundStatus, type PosRefundCollection, refundableLines, priceRefund } from './refund';
124
+ export type { RefundableOrderLine, EarlierRefund, RefundableLine, PricedRefundLine, PricedRefund } from './refund';
125
+ export { tenderReducer, initTenderState, initialTenderState, appliedMinor, changeMinor, quickTenderedAmounts, evenSplitShareMinor, activePlan, planLegs, MAX_TENDER_MINOR, tenderVoidSchema, tenderVoidCollection, legStatus, countsTowardPaid, isInMotion, capturedMinor, inMotionMinor, canMoveLeg, canVoidLeg } from './tender';
126
+ export type { PaymentTransport, TenderView, TenderLineId, TenderPlan, SplitTab, TenderState, TenderKey, TenderAction, PlanLeg, TenderVoid, PaymentLegStatus } from './tender';
77
127
 
78
128
  // Register
79
- export { normalizeAmount, isServerDecimal, movementFieldError, deriveExpected, parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, denominationTotal, varianceText, denominations } from './register';
129
+ export { normalizeAmount, isServerDecimal, movementFieldError, deriveExpected, parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, closureVariance, denominationTotal, varianceText, denominations } from './register';
80
130
  export type { MovementType, LedgerRow, Movement } from './register';
81
131
  export { registerSessionSchema, registerSessionCollection, cashMovementSchema, closureSchema } from './register';
82
132
  export { addRegisterSessionCollection, RegisterSessionOpenClosedError, registerSessionsLogger, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS } from './register';
83
133
  export type { RegisterSession, CashMovement, Closure } from './register';
84
- export { registerCommandSchema, registerCommandCollection, registerCommandsLogger, sessionOpenCommand, sessionTransitionCommand, movementCommand, closureCommand, reconcileRegisterCommands, adoptRegisterResults, takeOverSession, abandonSession } from './register';
85
- export type { RegisterCommand, RegisterCommandCollection } from './register';
134
+ export { registerCommandSchema, registerCommandCollection, registerCommandsLogger, sessionOpenCommand, sessionTransitionCommand, movementCommand, closureCommand, reconcileRegisterCommands, adoptRegisterResults, takeOverSession, abandonSession, isLiveAtStore, closureApprovalStatus, reapproveClosure, RegisterReapproveError } from './register';
135
+ export type { RegisterCommand, RegisterCommandCollection, ClosureApprovalStatus } from './register';
86
136
  export { mintUuid, readRegister, ensureRegister, observeRegister$, getBoundRegisterId, readBoundRegister, bindRegister, unbindRegister, nextSaleCounter, mintClosureNumber, advancePerpetual, RegisterIdInvalidError } from './register';
87
137
  export type { RegisterHost, RegisterCounters, RegisterBucket, RegisterStore, RegisterDocument } from './register';
88
138
  export { RegisterSessionRequiredError, RegisterSessionClosedError, RegisterNeedsUpgradeError, RegisterSessionConflictError, RegisterTakeOverError, isKnownSessionStatus, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, openSessionSelector, requireOpenSession, stampSession, openSession, startCounting, backToSelling, closeSession, recordMovement, voidMovement, writeClosure } from './register';
@@ -90,4 +140,11 @@ export type { RegisterSessionCollection, CashMovementCollection, ClosureCollecti
90
140
  export { deriveSettled, exportCsv, labelKeys, clampClosureScope, selectClosureRows } from './register';
91
141
  export type { Correction, RecordedFigures, ClosureScope } from './register';
92
142
  export { minorToDecimal, formatClosureDate, buildClosureDocument, buildXReportDocument, TAX_ROUNDING_MIXED_NOTE, registerFactsLogger, recordRegisterFact, type ClosureContext, type Actor, type RegisterFact } from './register';
93
- export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError, type UseRegisterSessionOptions } from './register';
143
+ export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError, type ApprovalNeeded, type UseRegisterSessionOptions } from './register';
144
+ export { roundedDue, tenderRounding } from './tender';
145
+ export type { TenderRounding } from './tender';
146
+ export { suggestFloat, type FloatSuggestion } from './register';
147
+
148
+ // Reports
149
+ export { salesFigures, marginOf, comparisonRange, daysOf, inRange, presetRange, DATE_PRESETS, reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund } from './reports';
150
+ export type { StoreDay, DayRange, ReportCategory, ReportLine, ReportPayment, ReportTax, ReportOrder, ReportRefund, LineJoin, Margin, SalesTotals, PaymentRow, GroupRow, TaxRow, DayPoint, SalesFiguresInput, SalesFigures, DatePreset } from './reports';