@tallyui/core 3.17.0 → 3.19.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/{chunk-CSXNXRBA.js → chunk-27L7XLTT.js} +48 -0
- package/dist/command-result-BZd1YFMP.d.ts +1956 -0
- package/dist/index.d.ts +51 -1085
- package/dist/index.js +145 -9
- package/dist/server/index.d.ts +46 -5
- package/dist/server/index.js +594 -114
- package/package.json +1 -1
- package/src/customer-display/advertisement.ts +57 -0
- package/src/customer-display/index.ts +2 -0
- package/src/customer-display/rate-limit-source.ts +40 -0
- package/src/index.ts +13 -2
- package/src/order-filters.ts +58 -0
- package/src/server/batch.ts +4 -0
- package/src/server/display-signalling/contract.ts +254 -0
- package/src/server/display-signalling/index.ts +3 -0
- package/src/server/display-signalling/memory-server.ts +250 -0
- package/src/server/index.ts +2 -0
- package/src/server/order-payload-shape.ts +25 -1
- package/src/server/versions.ts +2 -2
- package/src/tax/woocommerce/index.ts +2 -0
- package/src/tax/woocommerce/tax-location.ts +59 -0
- package/src/types/commands.ts +27 -4
- package/src/types/connector.ts +41 -7
- package/src/types/customers.ts +9 -0
- package/src/types/display-signalling.ts +123 -0
- package/src/types/index.ts +6 -1
- package/src/types/orders.ts +23 -0
- package/src/types/receipt-templates.ts +26 -0
- package/src/types/store-settings.ts +42 -1
- package/dist/command-result-CoCa8PXJ.d.ts +0 -544
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// The in-memory reference server for the display signalling seam (ADR-085 U2). It uses Web Crypto only
|
|
2
|
+
// (globalThis.crypto.getRandomValues and crypto.subtle.digest) and no `node:` import, so U6 can run it in a browser.
|
|
3
|
+
import type { SyncContext } from '../../types/connector';
|
|
4
|
+
import {
|
|
5
|
+
DISPLAY_PAIR_CAPABILITY, DisplaySignallingError,
|
|
6
|
+
type DisplaySignalling, type DisplaySignallingContext, type DisplaySignallingErrorCode, type SignalMessage,
|
|
7
|
+
} from '../../types/display-signalling';
|
|
8
|
+
import { rateLimitSource } from '../../customer-display/rate-limit-source';
|
|
9
|
+
|
|
10
|
+
/** What the contract suite drives; each plugin's U7 implements it for its own routes. */
|
|
11
|
+
export interface DisplaySignallingHarness {
|
|
12
|
+
signalling: DisplaySignalling;
|
|
13
|
+
/** A cashier session on the server, with or without `customer_display.pair`. */
|
|
14
|
+
till(cashier: { cashierId: string; canPair: boolean }): SyncContext | Promise<SyncContext>;
|
|
15
|
+
/** A display-side context whose requests come from `source`, an IPv4 or IPv6 address. */
|
|
16
|
+
display(source: string): DisplaySignallingContext;
|
|
17
|
+
/** Moves the server's clock. */
|
|
18
|
+
advance(ms: number): Promise<void>;
|
|
19
|
+
/** Everything the server persists, serialised. */
|
|
20
|
+
storedText(): Promise<string>;
|
|
21
|
+
storedCounts(): Promise<{ codes: number; pending: number; displays: number; snapshots: number }>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const MINUTE = 60_000;
|
|
25
|
+
const CODE_TTL = 10 * MINUTE, MAX_UNSPENT = 5, SNAPSHOT_TTL = MINUTE, SNAPSHOT_MAX_BYTES = 204_800;
|
|
26
|
+
const SOURCE_WINDOW = MINUTE, SOURCE_MAX = 10, STORE_WINDOW = 10 * MINUTE, STORE_MAX = 100;
|
|
27
|
+
/** `CONNECTED_MS` is the reference server's rule for `connected`; a plugin may be stricter. */
|
|
28
|
+
const CONNECTED_MS = 30_000, ROW_TTL = 30 * 24 * 60 * MINUTE;
|
|
29
|
+
const SESSION_HEADER = 'x-memory-display-session', BASE_URL = 'memory://display-signalling';
|
|
30
|
+
|
|
31
|
+
const randomBytes = (length: number): Uint8Array => globalThis.crypto.getRandomValues(new Uint8Array(length));
|
|
32
|
+
const toHex = (bytes: Uint8Array): string => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
33
|
+
const newId = (): string => toHex(randomBytes(16));
|
|
34
|
+
/** 128 bits, base64url without padding: 22 characters. */
|
|
35
|
+
const newSecret = (): string =>
|
|
36
|
+
btoa(String.fromCharCode(...randomBytes(16))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
37
|
+
|
|
38
|
+
/** SHA-256 of the UTF-8 text, as lower-case hex. */
|
|
39
|
+
export const sha256Hex = async (text: string): Promise<string> =>
|
|
40
|
+
toHex(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))));
|
|
41
|
+
|
|
42
|
+
/** `digits` uniform random decimal digits, by rejection sampling so no value is favoured. */
|
|
43
|
+
function randomDigits(digits: number): string {
|
|
44
|
+
const range = 10 ** digits, limit = Math.floor(2 ** 32 / range) * range;
|
|
45
|
+
for (;;) {
|
|
46
|
+
const [value] = globalThis.crypto.getRandomValues(new Uint32Array(1));
|
|
47
|
+
if (value < limit) return String(value % range).padStart(digits, '0');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const fail = (code: DisplaySignallingErrorCode): DisplaySignallingError => new DisplaySignallingError(code);
|
|
52
|
+
const iso = (ms: number): string => new Date(ms).toISOString();
|
|
53
|
+
/** Empties an inbox, giving what it held in send order. */
|
|
54
|
+
const drain = <T>(map: Map<string, T[]>, key: string): T[] => {
|
|
55
|
+
const box = map.get(key) ?? [];
|
|
56
|
+
map.delete(key);
|
|
57
|
+
return box;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
interface Code { deviceId: string; expiresAt: number; spent: boolean }
|
|
61
|
+
interface Pending { deviceId: string; secretHash: string; displayName: string; checkCode: string; expiresAt: number; movingDisplayId: string | null }
|
|
62
|
+
interface Row { deviceId: string; name: string; cashierId: string; confirmedAt: number; lastSeenAt: number | null; tokenHash: string | null; secretHash: string | null }
|
|
63
|
+
interface Window { openedAt: number; failures: number }
|
|
64
|
+
|
|
65
|
+
/** The ADR-085 U2 reference server: every rule of the seam, in memory, with lazy pruning on every call. */
|
|
66
|
+
export function createMemoryDisplaySignalling(options: { now?: () => number } = {}): { signalling: DisplaySignalling; harness: DisplaySignallingHarness } {
|
|
67
|
+
let offset = 0;
|
|
68
|
+
const clock = (): number => (options.now ?? Date.now)() + offset;
|
|
69
|
+
const sessions = new Map<string, { cashierId: string; capabilities: string[] }>();
|
|
70
|
+
const sourceOf = new WeakMap<DisplaySignallingContext, string>();
|
|
71
|
+
const codes = new Map<string, Code>(), pending = new Map<string, Pending>(), displays = new Map<string, Row>();
|
|
72
|
+
const snapshots = new Map<string, { text: string; postedAt: number }>(), sources = new Map<string, Window>();
|
|
73
|
+
const displayInbox = new Map<string, SignalMessage[]>(), tillInbox = new Map<string, Array<SignalMessage & { displayId: string }>>();
|
|
74
|
+
let storeWindow: Window | null = null;
|
|
75
|
+
const dropDisplay = (displayId: string): void => [displays, snapshots, displayInbox].forEach((map) => map.delete(displayId));
|
|
76
|
+
|
|
77
|
+
/** Deletes whatever has expired, and gives the time the call runs at. */
|
|
78
|
+
const prune = (): number => {
|
|
79
|
+
const now = clock();
|
|
80
|
+
for (const [code, entry] of codes) if (now >= entry.expiresAt) codes.delete(code);
|
|
81
|
+
for (const [claimId, entry] of pending) if (now >= entry.expiresAt) pending.delete(claimId);
|
|
82
|
+
for (const [displayId, entry] of snapshots) if (now >= entry.postedAt + SNAPSHOT_TTL) snapshots.delete(displayId);
|
|
83
|
+
for (const [displayId, row] of displays) if (now >= (row.lastSeenAt ?? row.confirmedAt) + ROW_TTL) dropDisplay(displayId);
|
|
84
|
+
for (const [key, window] of sources) if (now >= window.openedAt + SOURCE_WINDOW) sources.delete(key);
|
|
85
|
+
if (storeWindow && now >= storeWindow.openedAt + STORE_WINDOW) storeWindow = null;
|
|
86
|
+
return now;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/** Prunes, then admits a session holding `customer_display.pair`: the call's time and its cashier. */
|
|
90
|
+
const admit = (ctx: SyncContext): { now: number; cashierId: string } => {
|
|
91
|
+
const now = prune();
|
|
92
|
+
const session = sessions.get(ctx.headers?.[SESSION_HEADER] ?? '');
|
|
93
|
+
if (!session || !session.capabilities.includes(DISPLAY_PAIR_CAPABILITY)) throw fail('forbidden');
|
|
94
|
+
return { now, cashierId: session.cashierId };
|
|
95
|
+
};
|
|
96
|
+
/** The entry under `id` when `deviceId` owns it; `not_found` otherwise. */
|
|
97
|
+
const ownedIn = <T extends { deviceId: string }>(map: Map<string, T>, deviceId: string, id: string): T => {
|
|
98
|
+
const entry = map.get(id);
|
|
99
|
+
if (!entry || entry.deviceId !== deviceId) throw fail('not_found');
|
|
100
|
+
return entry;
|
|
101
|
+
};
|
|
102
|
+
const findByTokenHash = (tokenHash: string): [string, Row] | undefined => [...displays].find(([, row]) => row.tokenHash === tokenHash);
|
|
103
|
+
/** The display a token names; a successful call marks it seen. */
|
|
104
|
+
const byToken = async (token: string): Promise<[string, Row]> => {
|
|
105
|
+
const tokenHash = await sha256Hex(token);
|
|
106
|
+
const now = prune();
|
|
107
|
+
const found = findByTokenHash(tokenHash);
|
|
108
|
+
if (!found) throw fail('token_refused');
|
|
109
|
+
found[1].lastSeenAt = now;
|
|
110
|
+
return found;
|
|
111
|
+
};
|
|
112
|
+
/** Counts a failed claim in its source's window and the store-wide one, each opened by its first failure; gives the refusal. */
|
|
113
|
+
const failedClaim = (key: string, now: number): DisplaySignallingError => {
|
|
114
|
+
const window = sources.get(key);
|
|
115
|
+
sources.set(key, { openedAt: window?.openedAt ?? now, failures: (window?.failures ?? 0) + 1 });
|
|
116
|
+
storeWindow = { openedAt: storeWindow?.openedAt ?? now, failures: (storeWindow?.failures ?? 0) + 1 };
|
|
117
|
+
return fail('claim_refused');
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const signalling: DisplaySignalling = {
|
|
121
|
+
async mint(ctx, deviceId) {
|
|
122
|
+
const { now } = admit(ctx);
|
|
123
|
+
const unspent = [...codes.values()].filter((entry) => entry.deviceId === deviceId && !entry.spent).length;
|
|
124
|
+
if (unspent >= MAX_UNSPENT) throw fail('limit');
|
|
125
|
+
let code: string;
|
|
126
|
+
do code = randomDigits(6); while (codes.has(code));
|
|
127
|
+
codes.set(code, { deviceId, expiresAt: now + CODE_TTL, spent: false });
|
|
128
|
+
return { code, expiresAt: iso(now + CODE_TTL) };
|
|
129
|
+
},
|
|
130
|
+
async pending(ctx, deviceId) {
|
|
131
|
+
admit(ctx);
|
|
132
|
+
return [...pending].filter(([, entry]) => entry.deviceId === deviceId)
|
|
133
|
+
.map(([claimId, entry]) => ({ claimId, displayName: entry.displayName, checkCode: entry.checkCode, expiresAt: iso(entry.expiresAt) }));
|
|
134
|
+
},
|
|
135
|
+
async confirm(ctx, deviceId, claimId) {
|
|
136
|
+
const { now, cashierId } = admit(ctx);
|
|
137
|
+
const entry = ownedIn(pending, deviceId, claimId);
|
|
138
|
+
pending.delete(claimId);
|
|
139
|
+
// A moving display: its old row, token and snapshot go in this same step, and its id carries over.
|
|
140
|
+
const moving = entry.movingDisplayId !== null && displays.has(entry.movingDisplayId) ? entry.movingDisplayId : null;
|
|
141
|
+
if (moving !== null) dropDisplay(moving);
|
|
142
|
+
// The token itself is made at the first collect, so only its hash is ever stored; the claim secret's hash waits here.
|
|
143
|
+
const row: Row = { deviceId, name: entry.displayName, cashierId, confirmedAt: now, lastSeenAt: null, tokenHash: null, secretHash: entry.secretHash };
|
|
144
|
+
displays.set(moving ?? newId(), row);
|
|
145
|
+
},
|
|
146
|
+
async decline(ctx, deviceId, claimId) {
|
|
147
|
+
admit(ctx);
|
|
148
|
+
ownedIn(pending, deviceId, claimId);
|
|
149
|
+
pending.delete(claimId);
|
|
150
|
+
},
|
|
151
|
+
async list(ctx, deviceId) {
|
|
152
|
+
const { now } = admit(ctx);
|
|
153
|
+
return [...displays].filter(([, row]) => row.deviceId === deviceId).map(([displayId, row]) => ({
|
|
154
|
+
displayId, name: row.name, cashierId: row.cashierId,
|
|
155
|
+
lastSeenAt: row.lastSeenAt === null ? null : iso(row.lastSeenAt),
|
|
156
|
+
connected: row.lastSeenAt !== null && now - row.lastSeenAt <= CONNECTED_MS,
|
|
157
|
+
}));
|
|
158
|
+
},
|
|
159
|
+
async forget(ctx, deviceId, displayId) {
|
|
160
|
+
admit(ctx);
|
|
161
|
+
ownedIn(displays, deviceId, displayId);
|
|
162
|
+
dropDisplay(displayId);
|
|
163
|
+
},
|
|
164
|
+
async sendSignal(ctx, deviceId, displayId, message) {
|
|
165
|
+
admit(ctx);
|
|
166
|
+
ownedIn(displays, deviceId, displayId);
|
|
167
|
+
displayInbox.set(displayId, [...(displayInbox.get(displayId) ?? []), { type: message.type, payload: message.payload }]);
|
|
168
|
+
},
|
|
169
|
+
async receiveSignals(ctx, deviceId) {
|
|
170
|
+
admit(ctx);
|
|
171
|
+
return drain(tillInbox, deviceId).filter((message) => displays.get(message.displayId)?.deviceId === deviceId);
|
|
172
|
+
},
|
|
173
|
+
async postSnapshot(ctx, deviceId, displayId, body) {
|
|
174
|
+
const { now } = admit(ctx);
|
|
175
|
+
ownedIn(displays, deviceId, displayId);
|
|
176
|
+
const text = JSON.stringify(body) ?? 'null';
|
|
177
|
+
if (new TextEncoder().encode(text).length > SNAPSHOT_MAX_BYTES) throw fail('too_large');
|
|
178
|
+
snapshots.set(displayId, { text, postedAt: now });
|
|
179
|
+
},
|
|
180
|
+
async claim(dctx, { code, displayName, token }) {
|
|
181
|
+
// Hash first, so the check and the spend below run with no await between them.
|
|
182
|
+
const claimSecret = newSecret();
|
|
183
|
+
const secretHash = await sha256Hex(claimSecret);
|
|
184
|
+
const tokenHash = token ? await sha256Hex(token) : null;
|
|
185
|
+
const now = prune();
|
|
186
|
+
const key = rateLimitSource(sourceOf.get(dctx) ?? '');
|
|
187
|
+
if ((storeWindow?.failures ?? 0) >= STORE_MAX || (sources.get(key)?.failures ?? 0) >= SOURCE_MAX) throw fail('claim_refused');
|
|
188
|
+
const entry = codes.get(code);
|
|
189
|
+
if (!entry || entry.spent) throw failedClaim(key, now);
|
|
190
|
+
entry.spent = true;
|
|
191
|
+
let checkCode: string;
|
|
192
|
+
do checkCode = randomDigits(4); while ([...pending.values()].some((other) => other.checkCode === checkCode));
|
|
193
|
+
const movingDisplayId = tokenHash === null ? null : (findByTokenHash(tokenHash)?.[0] ?? null);
|
|
194
|
+
pending.set(newId(), { deviceId: entry.deviceId, secretHash, displayName, checkCode, expiresAt: entry.expiresAt, movingDisplayId });
|
|
195
|
+
return { claimSecret, checkCode };
|
|
196
|
+
},
|
|
197
|
+
async collect(_dctx, claimSecret) {
|
|
198
|
+
const secretHash = await sha256Hex(claimSecret);
|
|
199
|
+
const token = newSecret();
|
|
200
|
+
const tokenHash = await sha256Hex(token);
|
|
201
|
+
prune();
|
|
202
|
+
const waiting = [...pending.values()].find((entry) => entry.secretHash === secretHash);
|
|
203
|
+
if (waiting) return { status: 'pending', checkCode: waiting.checkCode };
|
|
204
|
+
const found = [...displays].find(([, row]) => row.secretHash === secretHash && row.tokenHash === null);
|
|
205
|
+
if (!found) throw fail('collect_refused');
|
|
206
|
+
found[1].secretHash = null;
|
|
207
|
+
found[1].tokenHash = tokenHash;
|
|
208
|
+
return { status: 'paired', displayId: found[0], token };
|
|
209
|
+
},
|
|
210
|
+
async displaySendSignal(_dctx, token, message) {
|
|
211
|
+
const [displayId, row] = await byToken(token);
|
|
212
|
+
tillInbox.set(row.deviceId, [...(tillInbox.get(row.deviceId) ?? []), { type: message.type, payload: message.payload, displayId }]);
|
|
213
|
+
},
|
|
214
|
+
async displayReceiveSignals(_dctx, token) {
|
|
215
|
+
const [displayId] = await byToken(token);
|
|
216
|
+
return drain(displayInbox, displayId);
|
|
217
|
+
},
|
|
218
|
+
async readSnapshot(_dctx, token) {
|
|
219
|
+
const [displayId] = await byToken(token);
|
|
220
|
+
const held = snapshots.get(displayId);
|
|
221
|
+
return held ? (JSON.parse(held.text) as unknown) : null;
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const harness: DisplaySignallingHarness = {
|
|
226
|
+
signalling,
|
|
227
|
+
till({ cashierId, canPair }) {
|
|
228
|
+
const sessionId = newId();
|
|
229
|
+
sessions.set(sessionId, { cashierId, capabilities: canPair ? [DISPLAY_PAIR_CAPABILITY] : [] });
|
|
230
|
+
return { connectorId: 'memory-display-signalling', baseUrl: BASE_URL, headers: { [SESSION_HEADER]: sessionId } };
|
|
231
|
+
},
|
|
232
|
+
display(source) {
|
|
233
|
+
const dctx: DisplaySignallingContext = { baseUrl: BASE_URL };
|
|
234
|
+
sourceOf.set(dctx, source);
|
|
235
|
+
return dctx;
|
|
236
|
+
},
|
|
237
|
+
advance: async (ms) => { offset += ms; },
|
|
238
|
+
async storedText() {
|
|
239
|
+
prune();
|
|
240
|
+
return JSON.stringify({
|
|
241
|
+
sessions: [...sessions], codes: [...codes], pending: [...pending], displays: [...displays], snapshots: [...snapshots], displayInbox: [...displayInbox], tillInbox: [...tillInbox], sources: [...sources], storeWindow,
|
|
242
|
+
});
|
|
243
|
+
},
|
|
244
|
+
async storedCounts() {
|
|
245
|
+
prune();
|
|
246
|
+
return { codes: codes.size, pending: pending.size, displays: displays.size, snapshots: snapshots.size };
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
return { signalling, harness };
|
|
250
|
+
}
|
package/src/server/index.ts
CHANGED
|
@@ -19,3 +19,5 @@ export { deriveSessionFigures, deriveVariance } from './register-figures'
|
|
|
19
19
|
export type { RegisterConflictCode, RegisterOutcome } from './register-outcome'
|
|
20
20
|
export { platformErrorResult, internalErrorResult } from './rejection-codes'
|
|
21
21
|
export type { CommandRejectionCode } from './rejection-codes'
|
|
22
|
+
export { createMemoryDisplaySignalling, displaySignallingContract } from './display-signalling'
|
|
23
|
+
export type { DisplaySignallingHarness } from './display-signalling'
|
|
@@ -68,6 +68,23 @@ export function payloadShapeErrors(payload: unknown): string[] {
|
|
|
68
68
|
const id = payload.customer.customerId
|
|
69
69
|
check(typeof id === 'string' && id.length > 0 && id.length <= 64, 'customer.customerId', 'a string of at most 64 characters')
|
|
70
70
|
}
|
|
71
|
+
for (const kind of ['billing', 'shipping']) {
|
|
72
|
+
const address = object(payload.customer) ? payload.customer[kind] : undefined
|
|
73
|
+
if (address === undefined) continue
|
|
74
|
+
check(object(address), `customer.${kind}`, 'an object')
|
|
75
|
+
if (object(address)) for (const [key, value] of Object.entries(address)) {
|
|
76
|
+
check(ORDER_ADDRESS_KEYS.includes(key), `customer.${kind}.${key}`, 'no unknown key')
|
|
77
|
+
check(typeof value === 'string', `customer.${kind}.${key}`, 'a string')
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// Version 8 (#722): the address the till taxed on; precheckCommand requires it at 8 and refuses it below.
|
|
82
|
+
if (payload.taxAddress !== undefined) {
|
|
83
|
+
const kind = payload.taxAddress
|
|
84
|
+
const known = kind === 'billing' || kind === 'shipping'
|
|
85
|
+
check(known, 'taxAddress', 'billing or shipping')
|
|
86
|
+
const address = known && object(payload.customer) ? payload.customer[kind] : undefined
|
|
87
|
+
if (known) check(object(address) && typeof address.country === 'string' && address.country.length > 0, `customer.${kind}.country`, 'a non-empty string')
|
|
71
88
|
}
|
|
72
89
|
if (payload.sessionId !== undefined) {
|
|
73
90
|
check(typeof payload.sessionId === 'string' && payload.sessionId.length > 0 && payload.sessionId.length <= 36,
|
|
@@ -152,9 +169,12 @@ export function payloadShapeErrors(payload: unknown): string[] {
|
|
|
152
169
|
return errors
|
|
153
170
|
}
|
|
154
171
|
|
|
172
|
+
/** OrderAddress's keys (#722). */
|
|
173
|
+
const ORDER_ADDRESS_KEYS = ['firstName', 'lastName', 'company', 'address1', 'address2', 'city', 'state', 'postcode', 'country', 'phone']
|
|
174
|
+
|
|
155
175
|
/** Length-bound errors of an order.create payload, e.g. ['lines[0].title: expected at most 255
|
|
156
176
|
* characters']; [] when every string is within its bound, at most ten. Bounds in UTF-16 code units:
|
|
157
|
-
* `note` ORDER_NOTE_MAX (1000), `customer.email` 254, v5 ids 36 and class/sku/method 64, other strings 255 (`customerId` and `sessionId` keep theirs in
|
|
177
|
+
* `note` ORDER_NOTE_MAX (1000), `customer.email` 254, v8 address fields 255, v5 ids 36 and class/sku/method 64, other strings 255 (`customerId` and `sessionId` keep theirs in
|
|
158
178
|
* payloadShapeErrors); only strings are checked. A plugin calls it through precheckCommand, after
|
|
159
179
|
* its replay lookup, so a bound tightened later never turns an applied command's resend into
|
|
160
180
|
* `invalid_payload`. */
|
|
@@ -210,6 +230,10 @@ function payloadStrings(payload: Record<string, unknown>): Array<[string, string
|
|
|
210
230
|
if (object(line) && Array.isArray(line.anyAttributes)) line.anyAttributes.forEach((name, i) => found.push([name, `lines[${index}].anyAttributes[${i}]`, 255]))
|
|
211
231
|
})
|
|
212
232
|
if (object(payload.customer)) found.push([payload.customer.email, 'customer.email', 254], [payload.customer.customerId, 'customer.customerId', undefined])
|
|
233
|
+
if (object(payload.customer)) for (const kind of ['billing', 'shipping']) {
|
|
234
|
+
const address = payload.customer[kind]
|
|
235
|
+
if (object(address)) for (const [key, value] of Object.entries(address)) found.push([value, `customer.${kind}.${key}`, 255])
|
|
236
|
+
}
|
|
213
237
|
found.push([payload.sessionId, 'sessionId', undefined])
|
|
214
238
|
return found.filter((entry): entry is [string, string, number | undefined] => typeof entry[0] === 'string')
|
|
215
239
|
}
|
package/src/server/versions.ts
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
* advertises it only once it handles it.
|
|
6
6
|
* 5 (ADR-075) adds fees, shipping and custom lines; 6 (ADR-077) adds coupons, regular prices, line
|
|
7
7
|
* attributes and Any picks (#495); a plugin advertises each only once it handles it.
|
|
8
|
-
* 7 (ADR-083) adds the sale note.
|
|
8
|
+
* 7 (ADR-083) adds the sale note; 8 (#722) adds `taxAddress` and the customer's addresses.
|
|
9
9
|
*/
|
|
10
|
-
export const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[] = [1, 2, 3, 4, 5, 6, 7]
|
|
10
|
+
export const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[] = [1, 2, 3, 4, 5, 6, 7, 8]
|
|
11
11
|
/** The till's capability for the contract versions shared by all five register commands; a server passes its own. */
|
|
12
12
|
export const SUPPORTED_REGISTER_VERSIONS: readonly number[] = [1]
|
|
13
13
|
/** The till's capability for order.refund versions (ADR-080); a server passes its own. */
|
|
@@ -12,3 +12,5 @@ export {
|
|
|
12
12
|
resolveInheritedShippingTaxClass, NO_SHIPPING_TAX, STANDARD_TAX_CLASS,
|
|
13
13
|
} from './tax-class';
|
|
14
14
|
export type { WooTaxRate, CalculateTaxesInput, CalculateTaxesResult, ItemizedTax } from './types';
|
|
15
|
+
export { orderTaxLocation, normalizeTaxBasedOn, TAX_BASED_ON_META_KEY } from './tax-location';
|
|
16
|
+
export type { TaxBasedOn, TaxAddress, TaxLocationOrder, ResolvedTaxLocation } from './tax-location';
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// WooCommerce tax parity (ADR-076): ported from WCPOS v2 cart-config-for-order.ts (`orderTaxLocation`), MIT, Copyright (c) 2021-2026 WCPOS.
|
|
2
|
+
|
|
3
|
+
/** WooCommerce's "Calculate tax based on" (`woocommerce_tax_based_on`). */
|
|
4
|
+
export type TaxBasedOn = 'base' | 'billing' | 'shipping';
|
|
5
|
+
|
|
6
|
+
/** The address WooCommerce matches tax rates against. */
|
|
7
|
+
export interface TaxAddress { country: string; state: string; city: string; postcode: string }
|
|
8
|
+
|
|
9
|
+
/** WooCommerce's per-order override meta key (WCPOS stamps the basis onto each order). */
|
|
10
|
+
export const TAX_BASED_ON_META_KEY = '_woocommerce_pos_tax_based_on';
|
|
11
|
+
|
|
12
|
+
function isTaxBasedOn(value: unknown): value is TaxBasedOn {
|
|
13
|
+
return value === 'base' || value === 'billing' || value === 'shipping';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Any non-TaxBasedOn value (missing, '', 'foo') → 'base', as WooCommerce and v2 normalizeStorePayload do. */
|
|
17
|
+
export function normalizeTaxBasedOn(value: unknown): TaxBasedOn {
|
|
18
|
+
return isTaxBasedOn(value) ? value : 'base';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type LooseAddress = { country?: unknown; state?: unknown; city?: unknown; postcode?: unknown };
|
|
22
|
+
|
|
23
|
+
export interface TaxLocationOrder {
|
|
24
|
+
billing?: LooseAddress;
|
|
25
|
+
shipping?: LooseAddress;
|
|
26
|
+
/** The order's own basis (its TAX_BASED_ON_META_KEY value); wins over the store's when valid. */
|
|
27
|
+
taxBasedOnOverride?: unknown;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ResolvedTaxLocation { taxBasedOn: TaxBasedOn; location: TaxAddress; addressUsed: TaxBasedOn }
|
|
31
|
+
|
|
32
|
+
function hasCountry(address: LooseAddress | undefined): boolean {
|
|
33
|
+
return typeof address?.country === 'string' && address.country.length > 0;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function text(value: unknown): string {
|
|
37
|
+
return typeof value === 'string' ? value : '';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* WC_Abstract_Order::get_tax_location(), as v2 cart-config-for-order.ts:25-61. `shipping` falls back to
|
|
42
|
+
* billing, then to the shop base; `billing` falls back to the shop base only. Without an order, the shop base.
|
|
43
|
+
*/
|
|
44
|
+
export function orderTaxLocation(base: TaxAddress, storeTaxBasedOn: unknown, order?: TaxLocationOrder): ResolvedTaxLocation {
|
|
45
|
+
const override = order?.taxBasedOnOverride;
|
|
46
|
+
const taxBasedOn = isTaxBasedOn(override) ? override : normalizeTaxBasedOn(storeTaxBasedOn);
|
|
47
|
+
let addressUsed: TaxBasedOn = 'base';
|
|
48
|
+
if (order && taxBasedOn !== 'base') {
|
|
49
|
+
if (taxBasedOn !== 'billing' && hasCountry(order.shipping)) addressUsed = 'shipping';
|
|
50
|
+
else if (hasCountry(order.billing)) addressUsed = 'billing';
|
|
51
|
+
}
|
|
52
|
+
const address = addressUsed === 'base' ? undefined : order?.[addressUsed];
|
|
53
|
+
if (!address) return { taxBasedOn, location: base, addressUsed };
|
|
54
|
+
return {
|
|
55
|
+
taxBasedOn,
|
|
56
|
+
addressUsed,
|
|
57
|
+
location: { country: text(address.country), state: text(address.state), city: text(address.city), postcode: text(address.postcode) },
|
|
58
|
+
};
|
|
59
|
+
}
|
package/src/types/commands.ts
CHANGED
|
@@ -8,8 +8,9 @@ export interface CommandEnvelope<P = unknown> {
|
|
|
8
8
|
/** 3 when the order carries ADR-065's `display` and `taxByRate` (the store accepts 3), else 2 when discounted, else 1;
|
|
9
9
|
* 4 is 3 with every `discountMinor` tax-exclusive, built only when capped at 4 or more (#286).
|
|
10
10
|
* 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one.
|
|
11
|
-
* 7 is 6 plus the sale's `note` (ADR-083), sent only for an order that has one.
|
|
12
|
-
|
|
11
|
+
* 7 is 6 plus the sale's `note` (ADR-083), sent only for an order that has one.
|
|
12
|
+
* 8 is 7 plus `taxAddress` and the customer's addresses (#722), sent only for a sale taxed on the customer's address. */
|
|
13
|
+
version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
|
|
13
14
|
payload: P;
|
|
14
15
|
createdAt: string; // ISO 8601, client clock
|
|
15
16
|
deviceId: string;
|
|
@@ -56,8 +57,8 @@ export interface OrderRefundOrderStateData { state: string }
|
|
|
56
57
|
export interface OrderRefundNoOpenSessionData { sessionId: string }
|
|
57
58
|
|
|
58
59
|
/** An order.create envelope: 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one.
|
|
59
|
-
* 7 is 6 plus the sale's note (ADR-083). */
|
|
60
|
-
export type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & { type: 'order.create'; version: 1 | 2 | 3 | 4 | 5 | 6 | 7 };
|
|
60
|
+
* 7 is 6 plus the sale's note (ADR-083). 8 is 7 plus `taxAddress` and the customer's addresses (#722). */
|
|
61
|
+
export type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & { type: 'order.create'; version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 };
|
|
61
62
|
|
|
62
63
|
/** Outcome of processing a command. */
|
|
63
64
|
export type CommandStatus = 'applied' | 'duplicate' | 'rejected';
|
|
@@ -388,7 +389,14 @@ export interface OrderCreatePayload {
|
|
|
388
389
|
email?: string;
|
|
389
390
|
/** Version 3+: the platform's id for the customer picked at the till, a soft reference of at most 64 characters. Absent for a guest sale, or when no customer was picked. */
|
|
390
391
|
customerId?: string;
|
|
392
|
+
/** Version 8 (#722): the customer's billing address, sent only with `taxAddress`. */
|
|
393
|
+
billing?: OrderAddress;
|
|
394
|
+
/** Version 8 (#722): the customer's shipping address, sent only with `taxAddress`. */
|
|
395
|
+
shipping?: OrderAddress;
|
|
391
396
|
} | null;
|
|
397
|
+
/** Version 8 (#722): the customer address the till taxed the sale on; always present at 8, and that address has a
|
|
398
|
+
* non-empty `country`. Absent: the store's base address. */
|
|
399
|
+
taxAddress?: 'billing' | 'shipping';
|
|
392
400
|
registerId?: string;
|
|
393
401
|
cashierRef?: string;
|
|
394
402
|
locationId?: string;
|
|
@@ -398,6 +406,21 @@ export interface OrderCreatePayload {
|
|
|
398
406
|
note?: string;
|
|
399
407
|
}
|
|
400
408
|
|
|
409
|
+
/** A customer's address on order.create v8 (#722): each field a string of at most 255 UTF-16 units; no email, which
|
|
410
|
+
* `customer.email` carries. */
|
|
411
|
+
export interface OrderAddress {
|
|
412
|
+
firstName?: string;
|
|
413
|
+
lastName?: string;
|
|
414
|
+
company?: string;
|
|
415
|
+
address1?: string;
|
|
416
|
+
address2?: string;
|
|
417
|
+
city?: string;
|
|
418
|
+
state?: string;
|
|
419
|
+
postcode?: string;
|
|
420
|
+
country?: string;
|
|
421
|
+
phone?: string;
|
|
422
|
+
}
|
|
423
|
+
|
|
401
424
|
/** Batch of commands submitted to the server. */
|
|
402
425
|
export interface CommandBatchRequest<E extends AnyCommandEnvelope = CommandEnvelope> {
|
|
403
426
|
commands: E[];
|
package/src/types/connector.ts
CHANGED
|
@@ -5,12 +5,15 @@ import type { CustomerTraits } from './traits/customer';
|
|
|
5
5
|
import type { ReplicationAdapter } from './replication';
|
|
6
6
|
import type { CatalogueReconcileAdapter, FingerprintReconcileAdapter, IdReconcileAdapter, StockReconcileAdapter } from './reconcile';
|
|
7
7
|
import type { StoreSettings, StoreSettingsChoice } from './store-settings';
|
|
8
|
-
import type { Customer, CustomerInput, CustomerPatch } from './customers';
|
|
9
|
-
import type { ListOrdersQuery, StoreOrder, StoreOrderPage } from './orders';
|
|
8
|
+
import type { Customer, CustomerInput, CustomerPage, CustomerPatch } from './customers';
|
|
9
|
+
import type { ListOrdersQuery, OrderFilterField, StoreOrder, StoreOrderPage } from './orders';
|
|
10
10
|
import type { PaymentMethodDescriptor } from './payment-methods';
|
|
11
|
+
import type { ReceiptTemplate, ReceiptTemplateKind } from './receipt-templates';
|
|
11
12
|
import type { RegisterInfo } from './registers';
|
|
12
13
|
import type { Cashier } from './cashier';
|
|
13
14
|
import type { FailureClass } from '../connectivity';
|
|
15
|
+
import type { DisplayAdvertisement, DisplaySignalling } from './display-signalling';
|
|
16
|
+
import { parseDisplayAdvertisement } from '../customer-display/advertisement';
|
|
14
17
|
|
|
15
18
|
/**
|
|
16
19
|
* Authentication configuration for a connector.
|
|
@@ -61,7 +64,8 @@ export interface ServerCapabilities {
|
|
|
61
64
|
lineTax?: { none: boolean; classes: boolean };
|
|
62
65
|
/**
|
|
63
66
|
* Whether the store accepts an order's coupons (ADR-077). Absent means it does not: the till refuses to apply a
|
|
64
|
-
* coupon. WooCommerce: true only when the woocommerce-pos plugin reports 1.9.0 or later.
|
|
67
|
+
* coupon. WooCommerce: true only when the woocommerce-pos plugin reports 1.9.0 or later. Other platforms report it as
|
|
68
|
+
* `/tally/v1/info`'s `coupons: true` (#709).
|
|
65
69
|
*/
|
|
66
70
|
coupons?: boolean;
|
|
67
71
|
/**
|
|
@@ -70,6 +74,11 @@ export interface ServerCapabilities {
|
|
|
70
74
|
* Absent means the store sets none, and the app's own threshold applies.
|
|
71
75
|
*/
|
|
72
76
|
registerApproval?: { thresholdMinor: number };
|
|
77
|
+
/**
|
|
78
|
+
* A store whose plugin signals second-device customer displays (ADR-085), from `/tally/v1/info`'s top-level
|
|
79
|
+
* `customerDisplay`. Absent means no second-device display.
|
|
80
|
+
*/
|
|
81
|
+
customerDisplay?: DisplayAdvertisement;
|
|
73
82
|
}
|
|
74
83
|
|
|
75
84
|
/** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
|
|
@@ -144,8 +153,9 @@ const maxVersion = (list: unknown): number | undefined => {
|
|
|
144
153
|
* Reads a 2xx body of `GET /tally/v1/info` (ADR-062): `orderCreate` is the max of
|
|
145
154
|
* `contracts["order.create"]`, or 1 when it's missing or malformed; `register` is the max of
|
|
146
155
|
* `contracts.register` when valid; `taxRounding` is the top-level sibling of `contracts` (#287); malformed `lineTax` is ignored.
|
|
147
|
-
* malformed `registerApproval` is ignored (ADR-082).
|
|
156
|
+
* malformed `registerApproval` is ignored (ADR-082). `coupons` is true only when the body says `coupons: true` (#709).
|
|
148
157
|
* `orderRefund` is the max of `contracts["order.refund"]` when valid, otherwise absent (ADR-080).
|
|
158
|
+
* `customerDisplay` is present only when `parseDisplayAdvertisement` accepts it; a malformed one warns (ADR-085).
|
|
149
159
|
* Absent `taxRounding` uses the default; a present malformed value is unknown, so settings wait.
|
|
150
160
|
* A non-object body is also unknown, not a statement of the store's defaults.
|
|
151
161
|
*/
|
|
@@ -154,7 +164,7 @@ export function parseInfoCapabilities(body: unknown, warn?: (reason: string) =>
|
|
|
154
164
|
warn?.('non-object info body: capabilities unknown');
|
|
155
165
|
return undefined;
|
|
156
166
|
}
|
|
157
|
-
const { contracts, taxRounding, lineTax, registerApproval } = body as { contracts?: Record<string, unknown> | null; taxRounding?: unknown; lineTax?: unknown; registerApproval?: unknown };
|
|
167
|
+
const { contracts, taxRounding, lineTax, registerApproval, coupons, customerDisplay } = body as { contracts?: Record<string, unknown> | null; taxRounding?: unknown; lineTax?: unknown; registerApproval?: unknown; coupons?: unknown; customerDisplay?: unknown };
|
|
158
168
|
const register = maxVersion(contracts?.register);
|
|
159
169
|
const orderRefund = maxVersion(contracts?.['order.refund']);
|
|
160
170
|
const rounding = parseTaxRounding(taxRounding);
|
|
@@ -164,11 +174,13 @@ export function parseInfoCapabilities(body: unknown, warn?: (reason: string) =>
|
|
|
164
174
|
}
|
|
165
175
|
const parsedLineTax = parseLineTax(lineTax, warn);
|
|
166
176
|
const parsed = parseRegisterApproval(registerApproval, warn);
|
|
177
|
+
const display = parseDisplayAdvertisement(customerDisplay, warn);
|
|
167
178
|
return { orderCreate: maxVersion(contracts?.['order.create']) ?? 1,
|
|
168
179
|
...(orderRefund !== undefined ? { orderRefund } : {}),
|
|
169
180
|
...(register !== undefined ? { register } : {}), ...(rounding ? { taxRounding: rounding } : {}),
|
|
170
181
|
...(parsedLineTax ? { lineTax: parsedLineTax } : {}),
|
|
171
|
-
...(parsed ? { registerApproval: parsed } : {}) }
|
|
182
|
+
...(parsed ? { registerApproval: parsed } : {}), ...(coupons === true ? { coupons: true } : {}),
|
|
183
|
+
...(display ? { customerDisplay: display } : {}) };
|
|
172
184
|
}
|
|
173
185
|
|
|
174
186
|
export interface AuthField {
|
|
@@ -219,6 +231,9 @@ export interface SyncContext {
|
|
|
219
231
|
pricingContext?: Record<string, string>;
|
|
220
232
|
/** The store's contract capabilities (ADR-062), copied from the sign-in result. */
|
|
221
233
|
capabilities?: ServerCapabilities;
|
|
234
|
+
/** The fetch the connector sends its requests with; defaults to globalThis.fetch. A host passes a wrapper
|
|
235
|
+
* here, for example @tallyui/database meteredFetch, to count requests. Resolved per request. */
|
|
236
|
+
fetch?: typeof globalThis.fetch;
|
|
222
237
|
}
|
|
223
238
|
|
|
224
239
|
/**
|
|
@@ -326,12 +341,23 @@ export interface TallyConnector {
|
|
|
326
341
|
* the store. `undefined` when the connector has none of its own: the till offers `defaultPaymentMethods()`.
|
|
327
342
|
*/
|
|
328
343
|
paymentMethods?: (context: SyncContext) => Promise<PaymentMethodDescriptor[]>;
|
|
344
|
+
/**
|
|
345
|
+
* The store's print templates of one kind (default `receipt`), in the store's own order: online only, read-only.
|
|
346
|
+
* Only templates the till can render are returned; `[]` when the store has none. `undefined` when the connector
|
|
347
|
+
* has no store templates (the till keeps its built-in layouts).
|
|
348
|
+
*/
|
|
349
|
+
receiptTemplates?: (context: SyncContext, kind?: ReceiptTemplateKind) => Promise<ReceiptTemplate[]>;
|
|
329
350
|
/**
|
|
330
351
|
* Customer search: online only. An empty or whitespace query may list a first page of the store's customers
|
|
331
352
|
* (recent ones, or in the store's own picker order); a connector that cannot list them returns `[]`.
|
|
332
353
|
* `undefined` when the connector has no customer support.
|
|
333
354
|
*/
|
|
334
355
|
searchCustomers?: (context: SyncContext, query: string, options?: { limit?: number }) => Promise<Customer[]>;
|
|
356
|
+
/**
|
|
357
|
+
* A page of a customer search, with the store's count of all matches: online only. The query and `limit` mean what
|
|
358
|
+
* they mean for `searchCustomers`; `page` is 1-based (default 1). `undefined` when the connector can't page or count.
|
|
359
|
+
*/
|
|
360
|
+
searchCustomersPage?: (context: SyncContext, query: string, options?: { limit?: number; page?: number }) => Promise<CustomerPage>;
|
|
335
361
|
/** Customer creation: online only; `undefined` when the connector has no customer support. */
|
|
336
362
|
createCustomer?: (context: SyncContext, input: CustomerInput) => Promise<Customer>;
|
|
337
363
|
/**
|
|
@@ -354,9 +380,12 @@ export interface TallyConnector {
|
|
|
354
380
|
/**
|
|
355
381
|
* The store's orders, newest first, one page per call (ADR-081): online only, read-only. Rejects as `emailReceipt`
|
|
356
382
|
* does (`ConnectorUnauthorizedError` for credentials; a connector's own errors otherwise, e.g. `CustomerServiceError`).
|
|
357
|
-
* `
|
|
383
|
+
* It rejects with `UnsupportedOrderFilterError` for a filter field outside `orderFilters`; calling
|
|
384
|
+
* `assertOrderFiltersSupported` first gives that. `undefined` when the connector has no order history.
|
|
358
385
|
*/
|
|
359
386
|
listOrders?: (context: SyncContext, query?: ListOrdersQuery) => Promise<StoreOrderPage>;
|
|
387
|
+
/** The ListOrdersQuery filter fields listOrders honours. Absent or empty: none; listOrders refuses any filter field. */
|
|
388
|
+
orderFilters?: readonly OrderFilterField[];
|
|
360
389
|
/**
|
|
361
390
|
* The given orders by store id (ADR-081), in the order asked; an id the store does not have is left out. Online only,
|
|
362
391
|
* read-only; rejects as `listOrders`. `undefined` when the connector has no order history.
|
|
@@ -381,4 +410,9 @@ export interface TallyConnector {
|
|
|
381
410
|
* method may also call for the failures it does not map.
|
|
382
411
|
*/
|
|
383
412
|
classifyFailure?: (error: unknown) => FailureClass;
|
|
413
|
+
/**
|
|
414
|
+
* Signalling for a customer display on a second device (ADR-085 d2). Absent means no second-device display; the
|
|
415
|
+
* same-device display still works.
|
|
416
|
+
*/
|
|
417
|
+
displaySignalling?: DisplaySignalling;
|
|
384
418
|
}
|
package/src/types/customers.ts
CHANGED
|
@@ -21,6 +21,15 @@ export interface Customer {
|
|
|
21
21
|
name: string;
|
|
22
22
|
firstName?: string; lastName?: string; email?: string; phone?: string; company?: string;
|
|
23
23
|
billing?: CustomerAddress; shipping?: CustomerAddress; taxIds?: CustomerTaxId[];
|
|
24
|
+
/** When the store created the customer: an ISO 8601 UTC instant (`2026-10-06T03:10:29Z`). Absent when the store doesn't say. */
|
|
25
|
+
createdAt?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** One page of a customer search: the customers on it, and how many the whole search matches when the store says. */
|
|
29
|
+
export interface CustomerPage {
|
|
30
|
+
customers: Customer[];
|
|
31
|
+
/** Every customer the query matches across all pages; undefined when the store gives no count. */
|
|
32
|
+
total?: number;
|
|
24
33
|
}
|
|
25
34
|
|
|
26
35
|
/** What the till collects to create a customer. v1 requires an email; addresses and tax ids are optional. */
|