@tallyui/pos 3.20.0 → 4.0.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 +1005 -110
- package/dist/index.js +3156 -907
- package/package.json +6 -6
- package/src/app-settings/app-settings.ts +77 -0
- package/src/app-settings/index.ts +2 -0
- package/src/currency/currency-provider.tsx +5 -7
- package/src/currency/index.ts +1 -1
- package/src/customer/customer-patch.ts +70 -0
- package/src/customer-display/display-client.ts +11 -17
- package/src/customer-display/display-link.ts +10 -5
- package/src/customer-display/index.ts +3 -1
- package/src/customer-display/protocol.ts +1 -1
- package/src/customer-display/sale-display.ts +6 -8
- package/src/customer-display/snapshot-fallback.ts +14 -1
- package/src/customer-display/till-device.ts +62 -0
- package/src/customer-display/till-display-service.ts +44 -42
- package/src/customer-display/till-pairing.ts +20 -23
- package/src/customer-display/use-customer-display.ts +2 -1
- package/src/customer-display/use-till-pairing.ts +4 -4
- package/src/index.ts +37 -18
- package/src/order/allocate-order-discount.ts +5 -17
- package/src/order/apportion.ts +29 -0
- package/src/order/from-store-order.ts +115 -0
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +239 -52
- package/src/order/order-drafts.ts +45 -6
- package/src/order/order-manager.ts +2 -1
- package/src/order/tax-ids.ts +27 -0
- package/src/order/types.ts +59 -5
- package/src/order/woocommerce-tax.ts +9 -0
- package/src/outbox/index.ts +1 -1
- package/src/outbox/order-outbox.ts +138 -43
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/retry-delay.ts +8 -0
- package/src/outbox/use-order-outbox.ts +8 -2
- package/src/pos-order/__fixtures__/order-create-v10.json +97 -0
- package/src/pos-order/__fixtures__/order-create-v11.json +90 -0
- package/src/pos-order/__fixtures__/order-create-v12.json +95 -0
- package/src/pos-order/__fixtures__/order-create-v9.json +89 -0
- package/src/pos-order/attention-handled.ts +24 -0
- package/src/pos-order/command.ts +132 -12
- package/src/pos-order/extras-delivery.ts +14 -0
- package/src/pos-order/finalize.ts +138 -29
- package/src/pos-order/index.ts +7 -3
- package/src/pos-order/money-divergence.ts +19 -0
- package/src/pos-order/needs-attention.ts +9 -1
- package/src/pos-order/refund-due.ts +35 -0
- package/src/pos-order/reopen.ts +96 -12
- package/src/pos-order/schema.ts +35 -10
- package/src/pos-order/till-payments.ts +4 -0
- package/src/pos-order/types.ts +44 -5
- package/src/print/escpos/__fixtures__/thermal-every-node.xml +33 -0
- package/src/print/escpos/commands.ts +79 -0
- package/src/print/escpos/drawer.ts +25 -0
- package/src/print/escpos/encode.ts +1 -0
- package/src/print/escpos/index.ts +6 -1
- package/src/print/escpos/network-sinks.ts +130 -0
- package/src/print/escpos/render-escpos.ts +155 -0
- package/src/print/escpos/transport.ts +2 -1
- package/src/print/index.ts +5 -2
- package/src/print/resolve-printer.ts +46 -0
- package/src/print/types.ts +1 -1
- package/src/product/index.ts +2 -0
- package/src/product/terms.ts +42 -0
- package/src/product/tile-fields.ts +27 -0
- package/src/receipt/build-receipt-data.ts +12 -7
- package/src/receipt/carried-rows.ts +29 -0
- package/src/receipt/index.ts +1 -0
- package/src/receipt/reprint.ts +14 -8
- package/src/receipt/types.ts +3 -1
- package/src/receipt-template/default-templates.ts +3 -0
- package/src/receipt-template/template-data.ts +3 -0
- package/src/receipt-template/wcpos/build.ts +1 -0
- package/src/receipt-template/wcpos/format.ts +2 -2
- package/src/receipt-template/wcpos/from-orders.ts +6 -2
- package/src/receipt-template/wcpos/types.ts +5 -1
- package/src/register/closure-document.ts +42 -4
- package/src/register/closure-rows.ts +3 -2
- package/src/register/document-labels.ts +25 -0
- package/src/register/expected.ts +49 -10
- package/src/register/index.ts +5 -5
- package/src/register/money.ts +23 -0
- package/src/register/register-adoption.ts +6 -5
- package/src/register/register-commands.ts +4 -3
- package/src/register/schemas.ts +11 -3
- package/src/register/session-store.ts +44 -23
- package/src/register/settled-figures.ts +5 -19
- package/src/register/use-register-session.ts +18 -19
- package/src/reopen/index.ts +3 -0
- package/src/reopen/reopen-entry.ts +48 -0
- package/src/reopen/reopen-store-order.ts +78 -0
- package/src/reopen/send-order-reopen.ts +61 -0
- package/src/reports/adapters.ts +15 -7
- package/src/reports/sales-figures.ts +15 -1
- package/src/reports/types.ts +2 -0
- package/src/sale/cart.ts +4 -2
- package/src/sale/index.ts +1 -1
- package/src/sale/open-sales.ts +3 -0
- package/src/sale/use-sale.ts +388 -83
- package/src/sale/woocommerce/coupon-refetch.ts +1 -0
- package/src/sale/woocommerce/coupon-source.ts +4 -4
- package/src/sale/woocommerce/coupons.ts +6 -0
- package/src/sale/woocommerce/discount-codes.ts +1 -6
- package/src/scanner/analyze-trace.ts +86 -0
- package/src/scanner/device-scanner.ts +57 -0
- package/src/scanner/hid-scanner.ts +14 -41
- package/src/scanner/index.ts +2 -0
- package/src/scanner/serial-scanner.ts +15 -42
- package/src/scanner/use-barcode-scanner.ts +107 -5
- package/src/scanner/wedge-detector.ts +33 -15
- package/src/tax/exact.ts +1 -13
- package/src/tax/taxed-lines.ts +26 -0
- package/src/tender/index.ts +6 -1
- package/src/tender/split-units.ts +109 -0
- package/src/tender/tender-figures.ts +114 -0
- package/src/tender/tender-state.ts +105 -17
- package/src/currency/format-money-with.ts +0 -45
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/pos",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.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",
|
|
@@ -34,20 +34,20 @@
|
|
|
34
34
|
"mustache": "^4.2.0"
|
|
35
35
|
},
|
|
36
36
|
"peerDependencies": {
|
|
37
|
-
"@tallyui/core": "^
|
|
37
|
+
"@tallyui/core": "^4.0.0",
|
|
38
38
|
"react": ">=18",
|
|
39
39
|
"rxdb": "~17.5.0",
|
|
40
40
|
"rxjs": ">=7"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@tallyui/core": "
|
|
43
|
+
"@tallyui/core": "4.0.0",
|
|
44
44
|
"@types/react": ">=18",
|
|
45
45
|
"react": "^19.2.4",
|
|
46
46
|
"rxdb": "17.5.0",
|
|
47
47
|
"rxjs": "7.8.2",
|
|
48
|
-
"@tallyui/connector-medusa": "
|
|
49
|
-
"@tallyui/connector-woocommerce": "
|
|
50
|
-
"@tallyui/database": "
|
|
48
|
+
"@tallyui/connector-medusa": "4.0.0",
|
|
49
|
+
"@tallyui/connector-woocommerce": "4.0.0",
|
|
50
|
+
"@tallyui/database": "4.0.0"
|
|
51
51
|
},
|
|
52
52
|
"scripts": {
|
|
53
53
|
"build": "tsup",
|
|
@@ -8,12 +8,32 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import type { RxCollection, RxJsonSchema } from 'rxdb';
|
|
10
10
|
import { map, type Observable } from 'rxjs';
|
|
11
|
+
import { DEFAULT_TILE_FIELDS, normalizeTileFields, type TileFields } from '../product/tile-fields';
|
|
11
12
|
|
|
12
13
|
export const UI_SCALES = ['auto', 'compact', 'regular', 'spacious'] as const;
|
|
13
14
|
export type UiScale = (typeof UI_SCALES)[number];
|
|
14
15
|
/** v2's first three themes (`core/screens/main/settings/theme.tsx`); TallyUI's tokens define light and dark. */
|
|
15
16
|
export const UI_THEMES = ['system', 'light', 'dark'] as const;
|
|
16
17
|
export type UiTheme = (typeof UI_THEMES)[number];
|
|
18
|
+
/** The same ids, in the same default order, as `@tallyui/components` `CartColumnSettings` (`cart/cart-columns.tsx`);
|
|
19
|
+
* pos cannot import components, so keep the two in step. */
|
|
20
|
+
export const CART_COLUMN_IDS = ['quantity', 'image', 'name', 'sku', 'price', 'regularPrice', 'total'] as const;
|
|
21
|
+
export type CartColumnId = (typeof CART_COLUMN_IDS)[number];
|
|
22
|
+
/** v2 `openOrdersPosition`, default bottom (`initial-settings.json:153`). */
|
|
23
|
+
export const OPEN_ORDERS_POSITIONS = ['top', 'bottom'] as const;
|
|
24
|
+
export type OpenOrdersPosition = (typeof OPEN_ORDERS_POSITIONS)[number];
|
|
25
|
+
|
|
26
|
+
/** Structurally the same as `@tallyui/components` `CartColumnSettings`, so a stored value passes straight to `Cart`. */
|
|
27
|
+
export interface CartColumnsSetting {
|
|
28
|
+
quantity?: { show?: boolean; split?: boolean };
|
|
29
|
+
image?: { show?: boolean };
|
|
30
|
+
name?: { show?: boolean; sku?: boolean };
|
|
31
|
+
sku?: { show?: boolean };
|
|
32
|
+
price?: { show?: boolean; onSale?: boolean };
|
|
33
|
+
regularPrice?: { show?: boolean };
|
|
34
|
+
total?: { show?: boolean };
|
|
35
|
+
order?: readonly CartColumnId[];
|
|
36
|
+
}
|
|
17
37
|
|
|
18
38
|
/** The typed key map. Add a key here and in APP_SETTING_DEFINITIONS; no schema change is needed. */
|
|
19
39
|
export interface AppSettings {
|
|
@@ -27,6 +47,21 @@ export interface AppSettings {
|
|
|
27
47
|
* `pos-cart.quickDiscounts: [5, 10, 15]` (`core/src/screens/main/contexts/ui-settings/initial-settings.json`).
|
|
28
48
|
*/
|
|
29
49
|
'cart.quickDiscounts': readonly number[];
|
|
50
|
+
/** Cart Settings › Columns (v2 `pos-cart.columns`), for `Cart`'s `columns`; per device, unlike v2's
|
|
51
|
+
* per store × login (desk, 19 Nov). */
|
|
52
|
+
'cart.columns': CartColumnsSetting;
|
|
53
|
+
'cart.openOrdersPosition': OpenOrdersPosition;
|
|
54
|
+
/**
|
|
55
|
+
* Which words a catalogue grid tile shows. v2 keeps them per screen as `pos-products.gridFields`.
|
|
56
|
+
* Desk 19 Nov (Q6): per device, camelCase keys, and the default is today's tile.
|
|
57
|
+
*/
|
|
58
|
+
'catalogue.tileFields': TileFields;
|
|
59
|
+
/** Print the receipt after checkout without asking (v2 `pos-cart.autoPrintReceipt`, default false).
|
|
60
|
+
* The app runs the print; this store only records it. Per device (desk, 19 Nov). */
|
|
61
|
+
'print.autoPrintReceipt': boolean;
|
|
62
|
+
/** Template id to printer profile id: the device's routing overrides, for `PrintingSettings`'s `routing`
|
|
63
|
+
* and `resolvePrinter`. A template with no entry uses Auto. Per device. */
|
|
64
|
+
'print.templatePrinters': Readonly<Record<string, string>>;
|
|
30
65
|
}
|
|
31
66
|
export type AppSettingKey = keyof AppSettings;
|
|
32
67
|
|
|
@@ -35,6 +70,38 @@ export interface AppSettingDefinition<T> {
|
|
|
35
70
|
default: T;
|
|
36
71
|
parse: (value: unknown) => T | undefined;
|
|
37
72
|
}
|
|
73
|
+
/** Each column's known fields; parseCartColumns keeps only these, and only when boolean. */
|
|
74
|
+
const CART_COLUMN_FIELDS: Record<CartColumnId, readonly string[]> = {
|
|
75
|
+
quantity: ['show', 'split'], image: ['show'], name: ['show', 'sku'], sku: ['show'],
|
|
76
|
+
price: ['show', 'onSale'], regularPrice: ['show'], total: ['show'],
|
|
77
|
+
};
|
|
78
|
+
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
|
|
79
|
+
typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
80
|
+
|
|
81
|
+
/** Known columns and boolean fields only; `order` keeps known ids, first occurrence. */
|
|
82
|
+
function parseCartColumns(value: unknown): CartColumnsSetting | undefined {
|
|
83
|
+
if (!isPlainObject(value)) return undefined;
|
|
84
|
+
const parsed: Record<string, unknown> = {};
|
|
85
|
+
for (const id of CART_COLUMN_IDS) {
|
|
86
|
+
const column = value[id];
|
|
87
|
+
if (!isPlainObject(column)) continue;
|
|
88
|
+
parsed[id] = Object.fromEntries(CART_COLUMN_FIELDS[id]
|
|
89
|
+
.filter((field) => typeof column[field] === 'boolean').map((field) => [field, column[field]]));
|
|
90
|
+
}
|
|
91
|
+
if (Array.isArray(value.order)) {
|
|
92
|
+
const known = value.order.filter((id): id is CartColumnId => (CART_COLUMN_IDS as readonly unknown[]).includes(id));
|
|
93
|
+
parsed.order = [...new Set(known)];
|
|
94
|
+
}
|
|
95
|
+
return parsed as CartColumnsSetting;
|
|
96
|
+
}
|
|
97
|
+
const isIdString = (value: unknown): value is string =>
|
|
98
|
+
typeof value === 'string' && value.length > 0 && value.length <= 128;
|
|
99
|
+
/** Non-empty string keys and values of at most 128 characters only; a fresh object. */
|
|
100
|
+
function parseTemplatePrinters(value: unknown): Record<string, string> | undefined {
|
|
101
|
+
if (!isPlainObject(value)) return undefined;
|
|
102
|
+
return Object.fromEntries(Object.entries(value)
|
|
103
|
+
.filter((entry): entry is [string, string] => isIdString(entry[0]) && isIdString(entry[1])));
|
|
104
|
+
}
|
|
38
105
|
export const APP_SETTING_DEFINITIONS: { [K in AppSettingKey]: AppSettingDefinition<AppSettings[K]> } = {
|
|
39
106
|
'ui.theme': { default: 'system', parse: (value) => UI_THEMES.find((theme) => theme === value) },
|
|
40
107
|
'ui.scale': { default: 'auto', parse: (value) => UI_SCALES.find((scale) => scale === value) },
|
|
@@ -49,12 +116,22 @@ export const APP_SETTING_DEFINITIONS: { [K in AppSettingKey]: AppSettingDefiniti
|
|
|
49
116
|
? value.filter((n): n is number => typeof n === 'number' && Number.isFinite(n) && n > 0 && n <= 100)
|
|
50
117
|
: undefined,
|
|
51
118
|
},
|
|
119
|
+
'cart.columns': { default: {}, parse: parseCartColumns },
|
|
120
|
+
'cart.openOrdersPosition': { default: 'bottom', parse: (value) => OPEN_ORDERS_POSITIONS.find((p) => p === value) },
|
|
121
|
+
'catalogue.tileFields': { default: DEFAULT_TILE_FIELDS, parse: normalizeTileFields },
|
|
122
|
+
'print.autoPrintReceipt': { default: false, parse: (value) => typeof value === 'boolean' ? value : undefined },
|
|
123
|
+
'print.templatePrinters': { default: {}, parse: parseTemplatePrinters },
|
|
52
124
|
};
|
|
53
125
|
export const DEFAULT_APP_SETTINGS: AppSettings = {
|
|
54
126
|
'ui.theme': APP_SETTING_DEFINITIONS['ui.theme'].default,
|
|
55
127
|
'ui.scale': APP_SETTING_DEFINITIONS['ui.scale'].default,
|
|
56
128
|
'ui.font': APP_SETTING_DEFINITIONS['ui.font'].default,
|
|
57
129
|
'cart.quickDiscounts': APP_SETTING_DEFINITIONS['cart.quickDiscounts'].default,
|
|
130
|
+
'cart.columns': APP_SETTING_DEFINITIONS['cart.columns'].default,
|
|
131
|
+
'cart.openOrdersPosition': APP_SETTING_DEFINITIONS['cart.openOrdersPosition'].default,
|
|
132
|
+
'catalogue.tileFields': APP_SETTING_DEFINITIONS['catalogue.tileFields'].default,
|
|
133
|
+
'print.autoPrintReceipt': APP_SETTING_DEFINITIONS['print.autoPrintReceipt'].default,
|
|
134
|
+
'print.templatePrinters': APP_SETTING_DEFINITIONS['print.templatePrinters'].default,
|
|
58
135
|
};
|
|
59
136
|
|
|
60
137
|
/** One stored setting. `value` is the JSON encoding of the setting's value, so the schema never changes when a key is added. */
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
export {
|
|
2
2
|
UI_SCALES, UI_THEMES, APP_SETTING_DEFINITIONS, DEFAULT_APP_SETTINGS, appSettingSchema,
|
|
3
3
|
appSettingCollection, resolveAppSettings, readAppSettings, appSettings$, writeAppSetting,
|
|
4
|
+
CART_COLUMN_IDS, OPEN_ORDERS_POSITIONS,
|
|
4
5
|
} from './app-settings';
|
|
5
6
|
export type {
|
|
6
7
|
UiScale, UiTheme, AppSettings, AppSettingKey, AppSettingDefinition, AppSettingDoc, AppSettingCollection,
|
|
8
|
+
CartColumnId, CartColumnsSetting, OpenOrdersPosition,
|
|
7
9
|
} from './app-settings';
|
|
8
10
|
export { useAppSettings } from './use-app-settings';
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { createContext, useContext, useMemo, useCallback } from 'react';
|
|
2
2
|
import type { ReactNode } from 'react';
|
|
3
|
-
import { formatMoney, type Money } from '@tallyui/core';
|
|
4
|
-
import { formatMoneyWith, type CurrencyFormat } from './format-money-with';
|
|
3
|
+
import { formatMoney, MoneyFormatProvider, type Money, type MoneyFormat } from '@tallyui/core';
|
|
5
4
|
|
|
6
5
|
interface CurrencyContext {
|
|
7
6
|
currencyCode: string;
|
|
8
7
|
locale?: string;
|
|
9
|
-
format?:
|
|
8
|
+
format?: MoneyFormat;
|
|
10
9
|
}
|
|
11
10
|
|
|
12
11
|
const CurrencyCtx = createContext<CurrencyContext | null>(null);
|
|
@@ -15,13 +14,13 @@ export interface CurrencyProviderProps {
|
|
|
15
14
|
currencyCode: string;
|
|
16
15
|
locale?: string;
|
|
17
16
|
/** The store's own money format; without it, money reads as Intl formats it for `locale`. */
|
|
18
|
-
format?:
|
|
17
|
+
format?: MoneyFormat;
|
|
19
18
|
children: ReactNode;
|
|
20
19
|
}
|
|
21
20
|
|
|
22
21
|
export function CurrencyProvider({ currencyCode, locale, format, children }: CurrencyProviderProps) {
|
|
23
22
|
const value = useMemo(() => ({ currencyCode, locale, format }), [currencyCode, locale, format]);
|
|
24
|
-
return <CurrencyCtx.Provider value={value}>{children}</CurrencyCtx.Provider>;
|
|
23
|
+
return <CurrencyCtx.Provider value={value}><MoneyFormatProvider locale={locale} format={format}>{children}</MoneyFormatProvider></CurrencyCtx.Provider>;
|
|
25
24
|
}
|
|
26
25
|
|
|
27
26
|
export function useCurrencyFormatter(): (money: Money) => string {
|
|
@@ -32,8 +31,7 @@ export function useCurrencyFormatter(): (money: Money) => string {
|
|
|
32
31
|
const { locale, format } = ctx;
|
|
33
32
|
return useCallback(
|
|
34
33
|
(money: Money) =>
|
|
35
|
-
(
|
|
36
|
-
`${money.amount} ${money.currency}`,
|
|
34
|
+
formatMoney(money, locale, format) ?? `${money.amount} ${money.currency}`,
|
|
37
35
|
[locale, format],
|
|
38
36
|
);
|
|
39
37
|
}
|
package/src/currency/index.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { CurrencyProvider, useCurrencyFormatter, useCurrencyCode } from './currency-provider';
|
|
2
2
|
export type { CurrencyProviderProps } from './currency-provider';
|
|
3
|
-
export type { CurrencyFormat } from '
|
|
3
|
+
export type { MoneyFormat as CurrencyFormat } from '@tallyui/core';
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** Customer form values to a create input or an update patch, with WCPOS v2's rules (MIT, WCPOS). Pure: writes nothing. */
|
|
2
|
+
import type { Customer, CustomerAddress, CustomerInput, CustomerPatch } from '@tallyui/core';
|
|
3
|
+
|
|
4
|
+
/** The customers screen's form values. `shipping` undefined is "Same as billing" (ShippingAddressFields' convention). */
|
|
5
|
+
export interface CustomerEditValues {
|
|
6
|
+
firstName: string; lastName: string; email: string; phone: string; company?: string;
|
|
7
|
+
billing?: CustomerAddress; shipping?: CustomerAddress;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
type Part = keyof CustomerAddress;
|
|
11
|
+
// v2 SHIPPING_PARTS (address-rows.tsx:26). Must match PARTS in packages/components/src/customer/address-fields.tsx:13.
|
|
12
|
+
const SHIPPING_PARTS: readonly Part[] = ['firstName', 'lastName', 'company', 'phone', 'address1', 'address2', 'city', 'postcode', 'country', 'state'];
|
|
13
|
+
// v2 BILLING_PARTS (address-rows.tsx:28): a billing address also has email.
|
|
14
|
+
const BILLING_PARTS: readonly Part[] = [...SHIPPING_PARTS, 'email'];
|
|
15
|
+
const IDENTITY = ['firstName', 'lastName', 'email'] as const;
|
|
16
|
+
const TOP_LEVEL = ['firstName', 'lastName', 'email', 'phone', 'company'] as const;
|
|
17
|
+
|
|
18
|
+
const same = (parts: readonly Part[], a: CustomerAddress | undefined, b: CustomerAddress | undefined) =>
|
|
19
|
+
parts.every((p) => (a?.[p] ?? '') === (b?.[p] ?? ''));
|
|
20
|
+
/** Shipping follows billing while no part is set, or every part equals billing's; email is never compared. */
|
|
21
|
+
export function shipsToBilling(shipping: CustomerAddress | undefined, billing: CustomerAddress | undefined): boolean {
|
|
22
|
+
// v2 address-rows.tsx:39-41,46-47: !hasAny(shipping) || sameAddress(shipping, billing), absent reading as ''.
|
|
23
|
+
return SHIPPING_PARTS.every((p) => !shipping?.[p]) || same(SHIPPING_PARTS, shipping, billing);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// v2 asShipping (address-rows.tsx:43-44): billing as the shipping address, without email.
|
|
27
|
+
function asShipping(billing: CustomerAddress | undefined): CustomerAddress {
|
|
28
|
+
const shipping: CustomerAddress = { ...billing };
|
|
29
|
+
delete shipping.email;
|
|
30
|
+
return shipping;
|
|
31
|
+
}
|
|
32
|
+
/** The address without its empty and undefined parts; undefined when nothing is left. */
|
|
33
|
+
function clean(address: CustomerAddress | undefined): CustomerAddress | undefined {
|
|
34
|
+
const kept = Object.entries(address ?? {}).filter(([, v]) => v !== undefined && v !== '');
|
|
35
|
+
return kept.length ? (Object.fromEntries(kept) as CustomerAddress) : undefined;
|
|
36
|
+
}
|
|
37
|
+
const linked = (values: CustomerEditValues) => values.shipping === undefined || shipsToBilling(values.shipping, values.billing);
|
|
38
|
+
|
|
39
|
+
/** Form values to what `createCustomer` takes. */
|
|
40
|
+
export function toCustomerInput(values: CustomerEditValues): CustomerInput {
|
|
41
|
+
const billing: CustomerAddress = { ...values.billing };
|
|
42
|
+
// v2 customer-form.tsx:61-66: an empty billing name or email is filled from the customer's.
|
|
43
|
+
for (const x of IDENTITY) if (!billing[x]) billing[x] = values[x];
|
|
44
|
+
// v2 customer-form.tsx:67-68: a shipping that follows billing is stored as the filled billing's copy.
|
|
45
|
+
const shipping = clean(linked(values) ? asShipping(billing) : values.shipping);
|
|
46
|
+
const input: CustomerInput = { email: values.email };
|
|
47
|
+
for (const x of ['firstName', 'lastName', 'phone', 'company'] as const) if (values[x]) input[x] = values[x];
|
|
48
|
+
const cleanBilling = clean(billing);
|
|
49
|
+
if (cleanBilling) input.billing = cleanBilling;
|
|
50
|
+
if (shipping) input.shipping = shipping;
|
|
51
|
+
return input;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Form values to what `updateCustomer` takes: only what changed; an address is sent whole. Does not validate. */
|
|
55
|
+
export function toCustomerPatch(before: Customer, values: CustomerEditValues): CustomerPatch {
|
|
56
|
+
const patch: CustomerPatch = {};
|
|
57
|
+
// A field is in the patch only when it changed, absent reading as ''; clearing one sends ''.
|
|
58
|
+
for (const x of TOP_LEVEL) if ((values[x] ?? '') !== (before[x] ?? '')) patch[x] = values[x] ?? '';
|
|
59
|
+
const billing: CustomerAddress = { ...values.billing };
|
|
60
|
+
// v2 edit/form.tsx:50-52,69-72: a billing identity part follows a changed top-level part while empty or still equal to the old one.
|
|
61
|
+
for (const x of IDENTITY) if (x in patch && (!billing[x] || billing[x] === before[x])) billing[x] = values[x];
|
|
62
|
+
const cleanBilling = clean(billing);
|
|
63
|
+
// An emptied billing is sent as {}: the contract's whole-replace clear (core customers.ts:41-44).
|
|
64
|
+
if (!same(BILLING_PARTS, cleanBilling, clean(before.billing))) patch.billing = cleanBilling ?? {};
|
|
65
|
+
if (linked(values)) {
|
|
66
|
+
// v2 edit/form.tsx:56-63: while linked, a billing write carries shipping as billing's copy; so does linking it.
|
|
67
|
+
if ('billing' in patch || !shipsToBilling(before.shipping, before.billing)) patch.shipping = clean(asShipping(billing)) ?? {};
|
|
68
|
+
} else if (!same(SHIPPING_PARTS, clean(values.shipping), clean(before.shipping))) patch.shipping = clean(values.shipping) ?? {};
|
|
69
|
+
return patch;
|
|
70
|
+
}
|
|
@@ -4,16 +4,21 @@ import {
|
|
|
4
4
|
import type { DisplayClock } from './display-link';
|
|
5
5
|
import { displayReducer, initialDisplayState, type DisplayState } from './display-state';
|
|
6
6
|
import { decode, makeEnvelope, type DisplayConfig, type DisplayEnvelope } from './protocol';
|
|
7
|
+
import { systemClock, SALE_ACTIONS, quietly } from './snapshot-fallback';
|
|
7
8
|
import { DISPLAY_TEMPLATE, HELLO_RETRY_MS } from './use-customer-display';
|
|
8
9
|
import { createDisplayPeerLink, type PeerFactory, type PeerLink, type PeerLinkState } from './webrtc';
|
|
9
10
|
|
|
10
|
-
/** TallyUI's choice: how often a waiting display asks whether the cashier has confirmed.
|
|
11
|
+
/** TallyUI's choice: how often a waiting display asks whether the cashier has confirmed.
|
|
12
|
+
* @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
|
|
11
13
|
export const COLLECT_POLL_MS = 2000;
|
|
12
|
-
/** TallyUI's choice: how often a paired display drains its inbox while no link is open.
|
|
14
|
+
/** TallyUI's choice: how often a paired display drains its inbox while no link is open.
|
|
15
|
+
* @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
|
|
13
16
|
export const DISPLAY_SIGNAL_POLL_MS = 1000;
|
|
14
|
-
/** TallyUI's choice: how often it drains its inbox while a link is open, so a re-linking till's offer is still seen.
|
|
17
|
+
/** TallyUI's choice: how often it drains its inbox while a link is open, so a re-linking till's offer is still seen.
|
|
18
|
+
* @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
|
|
15
19
|
export const OPEN_SIGNAL_POLL_MS = 5000;
|
|
16
|
-
/** TallyUI's choice: how often it reads the snapshot fallback while no link is open.
|
|
20
|
+
/** TallyUI's choice: how often it reads the snapshot fallback while no link is open.
|
|
21
|
+
* @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
|
|
17
22
|
export const SNAPSHOT_POLL_MS = 2000;
|
|
18
23
|
|
|
19
24
|
/** Where the display keeps its token; U8 binds it to a local collection that is never replicated (ADR-085 d5). */
|
|
@@ -53,11 +58,6 @@ export interface DisplayClient {
|
|
|
53
58
|
close(): void;
|
|
54
59
|
}
|
|
55
60
|
|
|
56
|
-
const systemClock: DisplayClock = {
|
|
57
|
-
setTimeout: (run, ms) => setTimeout(run, ms),
|
|
58
|
-
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
59
|
-
};
|
|
60
|
-
const SNAPSHOT_EVENTS: readonly string[] = ['cart.updated', 'payment.state', 'display.idle'];
|
|
61
61
|
const codeOf = (error: unknown) => (error instanceof DisplaySignallingError ? error.code : undefined);
|
|
62
62
|
|
|
63
63
|
/** U4's snapshot body as two envelopes, or null when any part of it cannot be trusted (ADR-085 d8). */
|
|
@@ -69,7 +69,7 @@ function parseSnapshot(body: unknown): { seq: number; config: DisplayEnvelope; e
|
|
|
69
69
|
const configResult = decode(JSON.stringify(makeEnvelope('display.config', config as DisplayConfig, 'snapshot')));
|
|
70
70
|
const eventResult = decode(JSON.stringify(event));
|
|
71
71
|
if (!configResult.ok || configResult.envelope.action !== 'display.config') return null;
|
|
72
|
-
if (!eventResult.ok || !
|
|
72
|
+
if (!eventResult.ok || !SALE_ACTIONS.has(eventResult.envelope.action)) return null;
|
|
73
73
|
return { seq, config: configResult.envelope, event: eventResult.envelope };
|
|
74
74
|
} catch {
|
|
75
75
|
return null;
|
|
@@ -106,13 +106,7 @@ export function createDisplayClient(options: DisplayClientOptions): DisplayClien
|
|
|
106
106
|
const next: Paired = { ...phase, ...patch };
|
|
107
107
|
if (next.link !== phase.link || next.source !== phase.source || next.online !== phase.online) setPhase(next);
|
|
108
108
|
};
|
|
109
|
-
const report = (error: unknown) =>
|
|
110
|
-
try {
|
|
111
|
-
onError?.(error);
|
|
112
|
-
} catch {
|
|
113
|
-
// A failing error handler must not break the client.
|
|
114
|
-
}
|
|
115
|
-
};
|
|
109
|
+
const report = (error: unknown) => quietly(() => onError?.(error));
|
|
116
110
|
const live = (session: number) => !closed && session === epoch;
|
|
117
111
|
const after = (ms: number, run: () => void) => {
|
|
118
112
|
const handle = clock.setTimeout(() => {
|
|
@@ -1,14 +1,10 @@
|
|
|
1
1
|
import type { ReceiptData } from '../receipt/types';
|
|
2
2
|
import { displayCart, makeEnvelope, type DisplayConfig, type DisplayEnvelope, type DisplayPayment } from './protocol';
|
|
3
|
+
import { systemClock } from './snapshot-fallback';
|
|
3
4
|
import type { DisplayTransport } from './transport';
|
|
4
5
|
|
|
5
6
|
export interface DisplayClock { setTimeout(run: () => void, ms: number): unknown; clearTimeout(handle: unknown): void }
|
|
6
7
|
|
|
7
|
-
const systemClock: DisplayClock = {
|
|
8
|
-
setTimeout: (run, ms) => setTimeout(run, ms),
|
|
9
|
-
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
10
|
-
};
|
|
11
|
-
|
|
12
8
|
export interface DisplayLink {
|
|
13
9
|
/** The order as it stands; null, or no lines, fees or shipping, shows idle. */
|
|
14
10
|
showCart(receipt: ReceiptData | null): void;
|
|
@@ -16,6 +12,15 @@ export interface DisplayLink {
|
|
|
16
12
|
close(): void;
|
|
17
13
|
}
|
|
18
14
|
|
|
15
|
+
/** One `DisplayLink` call as data: the cart (null shows idle) or a payment. */
|
|
16
|
+
export type DisplayCall = ['cart', ReceiptData | null] | ['payment', ReceiptData, DisplayPayment];
|
|
17
|
+
|
|
18
|
+
/** Makes `call` on `link`. */
|
|
19
|
+
export function callDisplay(link: DisplayLink, call: DisplayCall): void {
|
|
20
|
+
if (call[0] === 'cart') link.showCart(call[1]);
|
|
21
|
+
else link.showPayment(call[1], call[2]);
|
|
22
|
+
}
|
|
23
|
+
|
|
19
24
|
/**
|
|
20
25
|
* The till's side of the customer display. Ported from WCPOS v2 (monorepo main 51e7c43,
|
|
21
26
|
* core/services/customer-display/display-session.ts and service.ts) without the WebRTC: each `display.hello` is
|
|
@@ -26,8 +26,10 @@ export type { DisplayClientView } from './use-display-client';
|
|
|
26
26
|
export { createSnapshotSender, SNAPSHOT_MIN_INTERVAL_MS, SNAPSHOT_RESEND_MS, SNAPSHOT_LIFETIME_MS } from './snapshot-fallback';
|
|
27
27
|
export type { SnapshotSender, SnapshotSenderOptions, SnapshotBody } from './snapshot-fallback';
|
|
28
28
|
export { createTillDisplayService, SIGNAL_POLL_MS, LIST_POLL_MS, CONNECT_TIMEOUT_MS } from './till-display-service';
|
|
29
|
-
export type { TillDisplayService, TillDisplayServiceOptions, TillDisplayStatus, TillDisplayEntry, ServiceClock } from './till-display-service';
|
|
29
|
+
export type { TillDisplayService, TillDisplayServiceOptions, TillDisplayStatus, TillDisplayPauseReason, TillDisplayEntry, ServiceClock } from './till-display-service';
|
|
30
30
|
export { createTillPairing, PENDING_POLL_MS } from './till-pairing';
|
|
31
31
|
export type { TillPairing, TillPairingOptions, PairingPhase, PairingError } from './till-pairing';
|
|
32
32
|
export { useTillPairing, useTillDisplays } from './use-till-pairing';
|
|
33
33
|
export type { TillPairingView, TillDisplaysView } from './use-till-pairing';
|
|
34
|
+
export { createTillDevice } from './till-device';
|
|
35
|
+
export type { TillDeviceHandle, TillDeviceKeyStore, TillDeviceOptions } from './till-device';
|
|
@@ -9,7 +9,7 @@ export type PaymentPhase = 'started' | 'approved' | 'declined' | 'complete';
|
|
|
9
9
|
export interface DisplayTemplate { id: string | number; version: number }
|
|
10
10
|
/** The cart snapshot: the receipt as it stands, and whether lines were dropped to fit the message cap. */
|
|
11
11
|
export interface DisplayCart { receipt: ReceiptData; linesTruncated: boolean }
|
|
12
|
-
export interface DisplayPayment { state: PaymentPhase; leg?: { method: string; amountMinor: number }; message?: string }
|
|
12
|
+
export interface DisplayPayment { state: PaymentPhase; leg?: { method: string; amountMinor: number; tenderedMinor?: number; changeMinor?: number }; message?: string }
|
|
13
13
|
export interface DisplayConfig {
|
|
14
14
|
contract: '1.0';
|
|
15
15
|
display: { id: string; name: string };
|
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import type { Order, Payment, SentOrder } from '../order';
|
|
7
7
|
import { buildReceiptData } from '../receipt/build-receipt-data';
|
|
8
|
-
import type { ReceiptConfig
|
|
8
|
+
import type { ReceiptConfig } from '../receipt/types';
|
|
9
9
|
import type { SaleStage } from '../sale/use-sale';
|
|
10
|
-
import { legStatus } from '../tender/payment-legs';
|
|
11
|
-
import type
|
|
10
|
+
import { countsTowardPaid, legStatus } from '../tender/payment-legs';
|
|
11
|
+
import { callDisplay, type DisplayCall, type DisplayLink } from './display-link';
|
|
12
12
|
import type { DisplayPayment } from './protocol';
|
|
13
13
|
|
|
14
14
|
export interface SaleDisplayOptions {
|
|
@@ -37,6 +37,7 @@ export function derivePaymentEvent(
|
|
|
37
37
|
): DisplayPayment | null {
|
|
38
38
|
const leg = (payment: Payment) => ({
|
|
39
39
|
method: options.methodTitle ? options.methodTitle(payment.method) : payment.method, amountMinor: payment.amountMinor,
|
|
40
|
+
...(payment.tenderedMinor !== undefined ? { tenderedMinor: payment.tenderedMinor, changeMinor: payment.changeMinor } : {}),
|
|
40
41
|
});
|
|
41
42
|
if (!wasCompleted && completed) {
|
|
42
43
|
const last = next.filter((payment) => legStatus(payment) === 'captured').at(-1);
|
|
@@ -60,8 +61,6 @@ export function derivePaymentEvent(
|
|
|
60
61
|
return null;
|
|
61
62
|
}
|
|
62
63
|
|
|
63
|
-
type DisplayCall = ['cart', ReceiptData | null] | ['payment', ReceiptData, DisplayPayment];
|
|
64
|
-
|
|
65
64
|
/** v2's CustomerDisplaySnapshotSource without React: each `update` shows the sale's cart, payment or idle. */
|
|
66
65
|
export function createSaleDisplayPublisher(link: DisplayLink, options: SaleDisplayOptions = {}): SaleDisplayPublisher {
|
|
67
66
|
let prior: { orderId: string; payments: readonly Payment[]; completed: boolean } | null = null;
|
|
@@ -73,8 +72,7 @@ export function createSaleDisplayPublisher(link: DisplayLink, options: SaleDispl
|
|
|
73
72
|
const key = JSON.stringify(call);
|
|
74
73
|
if (key === lastKey) return;
|
|
75
74
|
lastKey = key;
|
|
76
|
-
|
|
77
|
-
else link.showPayment(call[1], call[2]);
|
|
75
|
+
callDisplay(link, call);
|
|
78
76
|
};
|
|
79
77
|
return {
|
|
80
78
|
update({ order, stage }) {
|
|
@@ -89,7 +87,7 @@ export function createSaleDisplayPublisher(link: DisplayLink, options: SaleDispl
|
|
|
89
87
|
send('cart', null);
|
|
90
88
|
return remember();
|
|
91
89
|
}
|
|
92
|
-
const receipt = buildReceiptData(shown, options.receipt ?? { storeName: '' });
|
|
90
|
+
const receipt = buildReceiptData({ ...shown, payments: shown.payments.filter(countsTowardPaid) }, options.receipt ?? { storeName: '' });
|
|
93
91
|
// A switch to another sale is never a payment event.
|
|
94
92
|
const event = sameOrder ? derivePaymentEvent(prior?.payments ?? [], shown.payments, prior?.completed ?? false,
|
|
95
93
|
completed, shown.balanceDueMinor, options) : null;
|
|
@@ -6,6 +6,16 @@ import { encode, MAX_MESSAGE_BYTES, messageBytes } from './snapshot';
|
|
|
6
6
|
/** A display clock that also tells the time, for the snapshot re-send and the idle clear. */
|
|
7
7
|
export interface ServiceClock extends DisplayClock { now(): number }
|
|
8
8
|
|
|
9
|
+
/** The real timers and `Date.now`: every display module's default clock. */
|
|
10
|
+
export const systemClock: ServiceClock = {
|
|
11
|
+
now: () => Date.now(),
|
|
12
|
+
setTimeout: (run, ms) => setTimeout(run, ms),
|
|
13
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** The sale states a display shows: its current event, which the snapshot carries. */
|
|
17
|
+
export const SALE_ACTIONS: ReadonlySet<string> = new Set(['cart.updated', 'payment.state', 'display.idle']);
|
|
18
|
+
|
|
9
19
|
export interface SnapshotBody { v: 1; seq: number; config: DisplayConfig; event: DisplayEnvelope }
|
|
10
20
|
|
|
11
21
|
export interface SnapshotSenderOptions {
|
|
@@ -21,9 +31,12 @@ export interface SnapshotSender {
|
|
|
21
31
|
}
|
|
22
32
|
|
|
23
33
|
// Rate and re-send follow WCPOS v2's display-session.ts (ADR-085 context and d8).
|
|
34
|
+
/** @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
|
|
24
35
|
export const SNAPSHOT_MIN_INTERVAL_MS = 1000;
|
|
36
|
+
/** @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
|
|
25
37
|
export const SNAPSHOT_RESEND_MS = 20_000;
|
|
26
|
-
/** The server keeps a snapshot for at most 60 s (ADR-085 d8).
|
|
38
|
+
/** The server keeps a snapshot for at most 60 s (ADR-085 d8).
|
|
39
|
+
* @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
|
|
27
40
|
export const SNAPSHOT_LIFETIME_MS = 60_000;
|
|
28
41
|
|
|
29
42
|
type State = Parameters<SnapshotSender['update']>[0];
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { DisplaySignallingError, type DisplaySignalling, type SyncContext, type TillDevice } from '@tallyui/core';
|
|
2
|
+
import { quietly } from './snapshot-fallback';
|
|
3
|
+
|
|
4
|
+
/** Where the till keeps its device key (TallyUI#754): next to its device id, never replicated. Its errors never carry the key. */
|
|
5
|
+
export interface TillDeviceKeyStore {
|
|
6
|
+
load(): Promise<string | null>;
|
|
7
|
+
save(key: string): Promise<void>;
|
|
8
|
+
clear(): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
export interface TillDeviceOptions {
|
|
11
|
+
signalling: DisplaySignalling;
|
|
12
|
+
/** The till's device id: an identifier, not a credential. */
|
|
13
|
+
deviceId: string;
|
|
14
|
+
keys: TillDeviceKeyStore;
|
|
15
|
+
/** A key store failure on save or clear, for logs; never throws into the handle. A key that fails to save is held only in memory, so after a restart the till is refused until an admin resets it. */
|
|
16
|
+
onError?: (error: unknown) => void;
|
|
17
|
+
}
|
|
18
|
+
/** The till's credential for every till-side call; `createTillPairing` and `createTillDisplayService` share one. */
|
|
19
|
+
export interface TillDeviceHandle {
|
|
20
|
+
/** The stored key with the device id, registering first when none is stored (one registration for concurrent callers). */
|
|
21
|
+
device(ctx: SyncContext): Promise<TillDevice>;
|
|
22
|
+
/** Clears the stored key after the server refused it, so the next `device` registers again. */
|
|
23
|
+
refused(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The till side of the device key (ADR-085, TallyUI#754): it loads the key, or registers once and saves it. */
|
|
27
|
+
export function createTillDevice(options: TillDeviceOptions): TillDeviceHandle {
|
|
28
|
+
const { signalling, deviceId, keys } = options;
|
|
29
|
+
const report = (error: unknown) => quietly(() => options.onError?.(error));
|
|
30
|
+
let loading: Promise<string> | null = null;
|
|
31
|
+
let held: string | null = null;
|
|
32
|
+
const key = async (ctx: SyncContext): Promise<string> => {
|
|
33
|
+
const stored = held ?? (await keys.load());
|
|
34
|
+
if (stored) return (held = stored);
|
|
35
|
+
const { deviceKey } = await signalling.registerDevice(ctx, deviceId);
|
|
36
|
+
held = deviceKey;
|
|
37
|
+
await keys.save(deviceKey).catch(report);
|
|
38
|
+
return deviceKey;
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
async device(ctx) {
|
|
42
|
+
loading ??= key(ctx).finally(() => { loading = null; });
|
|
43
|
+
return { deviceId, deviceKey: await loading };
|
|
44
|
+
},
|
|
45
|
+
refused: async () => { held = null; await keys.clear().catch(report); },
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Runs one till call with the till's device. On `device_refused` it clears the refused key, unless a concurrent call
|
|
51
|
+
* already replaced it, and tries once more with a new registration; a refused registration is not retried.
|
|
52
|
+
*/
|
|
53
|
+
export async function withTillDevice<T>(handle: TillDeviceHandle, ctx: SyncContext, work: (device: TillDevice) => Promise<T>): Promise<T> {
|
|
54
|
+
const device = await handle.device(ctx);
|
|
55
|
+
try {
|
|
56
|
+
return await work(device);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (!(error instanceof DisplaySignallingError && error.code === 'device_refused')) throw error;
|
|
59
|
+
if ((await handle.device(ctx)).deviceKey === device.deviceKey) await handle.refused();
|
|
60
|
+
return work(await handle.device(ctx));
|
|
61
|
+
}
|
|
62
|
+
}
|