@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
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import type { OrderCreateEnvelope } from '@tallyui/core';
|
|
1
|
+
import type { OrderCreateEnvelope, OrderUpdateEnvelope } from '@tallyui/core';
|
|
2
2
|
import { deepEqual, type RxCollection, type RxDocumentData } from 'rxdb';
|
|
3
3
|
import { BehaviorSubject, type Observable, type Subscription } from 'rxjs';
|
|
4
4
|
import { outboxLogger } from './logger';
|
|
5
5
|
import type { LogSyncRecord, SyncRecordOutcome } from '../logging';
|
|
6
|
-
import { toOrderCreateEnvelope, UnsupportedOrderVersionError, uuidv7, replacedOrderIds, type PosOrder, type PosOrderServerFailures } from '../pos-order';
|
|
6
|
+
import { toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, uuidv7, replacedOrderIds, type PosOrder, type PosOrderServerFailures } from '../pos-order';
|
|
7
7
|
import { freezeSentForm } from '../pos-order/finalize';
|
|
8
8
|
import { countFresh, readFresh } from '../rxdb';
|
|
9
9
|
import { createBackendNotFound, type BackendNotFound } from './backend-not-found';
|
|
10
|
+
import { DEFAULT_INITIAL_BACKOFF_MS, DEFAULT_MAX_BACKOFF_MS, retryDelay } from './retry-delay';
|
|
10
11
|
import type { CommandTransport, OutboxState } from './types';
|
|
11
12
|
|
|
12
13
|
// Pause after three 401s since the server last accepted credentials.
|
|
@@ -21,6 +22,17 @@ export function isRequeueable(code: string | undefined): boolean {
|
|
|
21
22
|
return !NOT_REQUEUEABLE.has(code ?? '');
|
|
22
23
|
}
|
|
23
24
|
|
|
25
|
+
/**
|
|
26
|
+
* Whether `requeue()` will send this order again. A rejected order: its code is requeueable, except that a reopened
|
|
27
|
+
* sale (`storeOrderId`) refused with `reopen_required` or `revision_conflict` needs a fresh reopen, not a resend
|
|
28
|
+
* (ADR-090 gate 5). A pending order the outbox could not build as an update (`UPDATE_UNSENDABLE`): yes, it is tried again.
|
|
29
|
+
*/
|
|
30
|
+
export function isRequeueableOrder(order: Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error'>): boolean {
|
|
31
|
+
return order.syncStatus === 'pending' ? order.error?.code === UPDATE_UNSENDABLE
|
|
32
|
+
: order.syncStatus === 'rejected' && isRequeueable(order.error?.code)
|
|
33
|
+
&& !(order.storeOrderId !== undefined && ['reopen_required', 'revision_conflict'].includes(order.error?.code ?? ''));
|
|
34
|
+
}
|
|
35
|
+
|
|
24
36
|
// The store's message in the refusal log is cut to this many characters, the cap connectors use for a foreign 426 message.
|
|
25
37
|
const REFUSAL_LOG_MESSAGE_MAX = 200;
|
|
26
38
|
|
|
@@ -42,7 +54,7 @@ const validMax = (max: unknown) => (typeof max === 'number' && Number.isSafeInte
|
|
|
42
54
|
|
|
43
55
|
export interface OrderOutboxOptions {
|
|
44
56
|
collection: RxCollection<PosOrder>;
|
|
45
|
-
transport: CommandTransport<OrderCreateEnvelope>;
|
|
57
|
+
transport: CommandTransport<OrderCreateEnvelope | OrderUpdateEnvelope>;
|
|
46
58
|
deviceId: string;
|
|
47
59
|
getMaxOrderCreateVersion?: () => number | undefined | Promise<number | undefined>;
|
|
48
60
|
refreshCapabilities?: () => Promise<void>;
|
|
@@ -62,9 +74,12 @@ export interface OrderOutboxOptions {
|
|
|
62
74
|
export interface OrderOutbox {
|
|
63
75
|
/** Sends pending orders until empty or retrying. Concurrent calls share one run. */
|
|
64
76
|
flush(): Promise<void>;
|
|
65
|
-
/**
|
|
66
|
-
* Orders
|
|
77
|
+
/** Requeues rejected orders with a new commandId, or clears a pending update's unsendable mark, then flushes.
|
|
78
|
+
* Orders isRequeueableOrder refuses are left alone. Resolves to the number requeued. */
|
|
67
79
|
requeue(orderIds?: string[]): Promise<number>;
|
|
80
|
+
/** Removes the rejected order `orderId` from the collection, after any running flush ends. Resolves to true when
|
|
81
|
+
* removed; false, with nothing changed, when the id is unknown or the order is not rejected. */
|
|
82
|
+
discard(orderId: string): Promise<boolean>;
|
|
68
83
|
/** Watches for pending orders and sends them. */
|
|
69
84
|
start(): void;
|
|
70
85
|
/** Stops watching and retrying. */
|
|
@@ -74,9 +89,12 @@ export interface OrderOutbox {
|
|
|
74
89
|
|
|
75
90
|
export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
76
91
|
const { collection, transport, deviceId } = options;
|
|
92
|
+
// A reopened sale goes as order.update, never order.create (ADR-090 decision 4).
|
|
93
|
+
const toEnvelope = (order: PosOrder, attempt: number, maxVersion: number) => order.storeOrderId !== undefined
|
|
94
|
+
? toOrderUpdateEnvelope(order, deviceId, attempt, { maxVersion }) : toOrderCreateEnvelope(order, deviceId, attempt, { maxVersion });
|
|
77
95
|
const batchSize = Math.min(options.batchSize ?? 10, 10);
|
|
78
|
-
const initialBackoff = options.initialBackoffMs ??
|
|
79
|
-
const maxBackoff = options.maxBackoffMs ??
|
|
96
|
+
const initialBackoff = options.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS;
|
|
97
|
+
const maxBackoff = options.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
|
|
80
98
|
const random = options.random ?? Math.random;
|
|
81
99
|
const now = options.now ?? Date.now;
|
|
82
100
|
const state$ = new BehaviorSubject<OutboxState>({ pending: 0, sending: false });
|
|
@@ -199,7 +217,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
199
217
|
|
|
200
218
|
function isolate(id: string, reason: string, retryAfterMs = 0) {
|
|
201
219
|
const entry = isolated.get(id) ?? { backoff: initialBackoff };
|
|
202
|
-
const delay =
|
|
220
|
+
const delay = retryDelay(entry.backoff, retryAfterMs, maxBackoff, random);
|
|
203
221
|
isolated.set(id, { reason, backoff: Math.min(entry.backoff * 2, maxBackoff), nextAt: now() + delay });
|
|
204
222
|
}
|
|
205
223
|
|
|
@@ -228,7 +246,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
228
246
|
function scheduleRetry(reason: string, retryAfterMs = 0, wait?: number) {
|
|
229
247
|
state$.next({ ...state$.value, lastRetryReason: reason });
|
|
230
248
|
if (stopped) { stoppedDuringRun = true; return; }
|
|
231
|
-
const delay = wait ??
|
|
249
|
+
const delay = wait ?? retryDelay(backoff, retryAfterMs, maxBackoff, random);
|
|
232
250
|
if (wait === undefined) backoff = Math.min(backoff * 2, maxBackoff);
|
|
233
251
|
isolatedWait = wait !== undefined;
|
|
234
252
|
// A timer firing while a run is still finishing finds it busy: the run's end flushes again.
|
|
@@ -236,24 +254,38 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
236
254
|
state$.next({ ...state$.value, sending: false, nextAttemptAt: now() + delay });
|
|
237
255
|
}
|
|
238
256
|
|
|
257
|
+
// A failed refresh is logged; the caller reads whatever capabilities are cached.
|
|
258
|
+
async function refreshCapabilities() {
|
|
259
|
+
try { await options.refreshCapabilities?.(); } catch (cause) { outboxLogger.warn('Failed to refresh capabilities', { cause }); }
|
|
260
|
+
}
|
|
261
|
+
|
|
239
262
|
async function run() {
|
|
240
263
|
stoppedDuringRun = false;
|
|
241
264
|
runProgressed = false;
|
|
242
265
|
const sentAlone = new Set<string>();
|
|
243
266
|
while (!stopped) try {
|
|
267
|
+
const unsendable = await readFresh(collection, { selector: { syncStatus: 'pending', 'error.code': UPDATE_UNSENDABLE } });
|
|
268
|
+
const holds = new Map<string, string>();
|
|
269
|
+
for (const order of unsendable) if (order.storeOrderId !== undefined
|
|
270
|
+
&& (!holds.has(order.storeOrderId) || order.createdAt < holds.get(order.storeOrderId)!)) holds.set(order.storeOrderId, order.createdAt);
|
|
271
|
+
const hold = holds.size ? { $or: [
|
|
272
|
+
{ storeOrderId: { $exists: false } },
|
|
273
|
+
{ storeOrderId: { $nin: [...holds.keys()] } },
|
|
274
|
+
...[...holds].map(([storeOrderId, createdAt]) => ({ storeOrderId, createdAt: { $lt: createdAt } })),
|
|
275
|
+
] } : {};
|
|
244
276
|
if (!restored) await restore();
|
|
245
277
|
await updateState({ sending: true, nextAttemptAt: undefined });
|
|
246
278
|
insertedDuringRun = false;
|
|
247
279
|
// An order no longer pending under its commandId leaves the isolated set and loses its stuck clock.
|
|
248
280
|
const tracked = [...new Set([...isolated.keys(), ...clocks.keys()])];
|
|
249
|
-
const held = tracked.length ? await readFresh(collection, { selector: { syncStatus: 'pending', commandId: { $in: tracked } },
|
|
281
|
+
const held = tracked.length ? await readFresh(collection, { selector: { syncStatus: 'pending', ...hold, commandId: { $in: tracked } },
|
|
250
282
|
sort: [{ createdAt: 'asc' }] }) : [];
|
|
251
283
|
for (const id of tracked) if (!held.some((order) => order.commandId === id)) { isolated.delete(id); clocks.delete(id); }
|
|
252
284
|
// During a walk, the oldest pending order neither probed nor isolated, alone. A sale rung up during
|
|
253
285
|
// a walk triggers its next probe: still one request per sale. None left: the store is down.
|
|
254
286
|
let probe: PosOrder | undefined;
|
|
255
287
|
if (walk) {
|
|
256
|
-
[probe] = await readFresh(collection, { selector: { syncStatus: 'pending',
|
|
288
|
+
[probe] = await readFresh(collection, { selector: { syncStatus: 'pending', ...hold,
|
|
257
289
|
commandId: { $nin: [...isolated.keys(), ...walk.failed.keys()] } }, sort: [{ createdAt: 'asc' }], limit: 1 });
|
|
258
290
|
if (!probe) { walk = undefined; head = undefined; }
|
|
259
291
|
}
|
|
@@ -263,7 +295,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
263
295
|
const [due] = held.filter((order) => isDue(order.commandId) && !sentAlone.has(order.commandId))
|
|
264
296
|
.sort((a, b) => isolated.get(a.commandId)!.nextAt - isolated.get(b.commandId)!.nextAt);
|
|
265
297
|
let orders = turn === 'isolated' && due ? [due] : probe ? [probe] : await readFresh(collection, {
|
|
266
|
-
selector: { syncStatus: 'pending', ...(isolated.size ? { commandId: { $nin: [...isolated.keys()] } } : {}) },
|
|
298
|
+
selector: { syncStatus: 'pending', ...hold, ...(isolated.size ? { commandId: { $nin: [...isolated.keys()] } } : {}) },
|
|
267
299
|
sort: [{ createdAt: 'asc' }], limit: batchSize,
|
|
268
300
|
});
|
|
269
301
|
if (!orders.length && due) orders = [due];
|
|
@@ -279,30 +311,63 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
279
311
|
// An order goes out, on every attempt, at the version it first went out at: a retry's bytes never change, even
|
|
280
312
|
// after the store upgrades (#286). A first send takes the server's max, read once per batch; unknown is 3.
|
|
281
313
|
const firstSend = orders.some((order) => order.sentVersion === undefined);
|
|
282
|
-
const
|
|
283
|
-
.catch((cause) => { outboxLogger.warn('Failed to read capabilities', { cause }); }))
|
|
314
|
+
const readMax = firstSend ? validMax(await Promise.resolve().then(() => options.getMaxOrderCreateVersion?.())
|
|
315
|
+
.catch((cause) => { outboxLogger.warn('Failed to read capabilities', { cause }); })) : undefined;
|
|
316
|
+
const serverMax = readMax || 3;
|
|
284
317
|
const localOrders = new Map<string, PosOrder>();
|
|
285
|
-
const
|
|
318
|
+
const built = orders.map((order): { order: PosOrder; unsendable: unknown }
|
|
319
|
+
| { order: PosOrder; frozen: PosOrder; attempt: number; envelope: OrderCreateEnvelope | OrderUpdateEnvelope } => {
|
|
286
320
|
const frozen = freezeSentForm(order);
|
|
287
321
|
const attempt = (attempts.get(order.commandId) ?? 0) + 1;
|
|
288
|
-
|
|
289
|
-
let envelope: OrderCreateEnvelope;
|
|
322
|
+
let envelope: OrderCreateEnvelope | OrderUpdateEnvelope;
|
|
290
323
|
try {
|
|
291
|
-
envelope =
|
|
324
|
+
envelope = toEnvelope(frozen, attempt, order.sentVersion ?? serverMax);
|
|
292
325
|
} catch (cause) {
|
|
326
|
+
if (order.storeOrderId !== undefined && (!(cause instanceof UnsupportedOrderVersionError)
|
|
327
|
+
|| order.sentVersion !== undefined || readMax !== undefined)) return { order, unsendable: cause };
|
|
293
328
|
// Content that cannot downgrade goes at its required version: the server's refusal rejects it.
|
|
294
329
|
if (!(cause instanceof UnsupportedOrderVersionError)) throw cause;
|
|
295
|
-
|
|
330
|
+
let max = cause.needed >= 5 ? cause.needed : 3;
|
|
331
|
+
// Including the first build above, try at most three times, only while the needed version rises.
|
|
332
|
+
for (let build = 2; ; build++) {
|
|
333
|
+
try { envelope = toEnvelope(frozen, attempt, max); break; }
|
|
334
|
+
catch (error) {
|
|
335
|
+
if (build < 3 && error instanceof UnsupportedOrderVersionError && error.needed > max) {
|
|
336
|
+
max = error.needed; continue;
|
|
337
|
+
}
|
|
338
|
+
if (order.storeOrderId !== undefined) return { order, unsendable: error };
|
|
339
|
+
throw error;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
296
342
|
}
|
|
343
|
+
return { order, frozen, attempt, envelope };
|
|
344
|
+
});
|
|
345
|
+
for (const entry of built) if ('unsendable' in entry) {
|
|
346
|
+
const { storeOrderId, createdAt } = entry.order;
|
|
347
|
+
if (!holds.has(storeOrderId!) || createdAt < holds.get(storeOrderId!)!) holds.set(storeOrderId!, createdAt);
|
|
348
|
+
}
|
|
349
|
+
for (const entry of built) if ('unsendable' in entry) {
|
|
350
|
+
const { order, unsendable: cause } = entry;
|
|
351
|
+
await (await collection.findOne(order.id).exec())?.incrementalModify((data) =>
|
|
352
|
+
data.syncStatus === 'pending' && data.commandId === order.commandId
|
|
353
|
+
? { ...data, error: { code: UPDATE_UNSENDABLE, message: UPDATE_UNSENDABLE_MESSAGE } } : data);
|
|
354
|
+
outboxLogger.warn('Order update cannot be built; held until a person acts', { orderId: order.id, storeOrderId: order.storeOrderId, cause });
|
|
355
|
+
}
|
|
356
|
+
const batch = await Promise.all(built.filter((entry) => 'envelope' in entry)
|
|
357
|
+
.filter(({ order }) => !(order.storeOrderId !== undefined && holds.has(order.storeOrderId) && order.createdAt >= holds.get(order.storeOrderId)!))
|
|
358
|
+
.map(async ({ order, frozen, attempt, envelope }) => {
|
|
359
|
+
attempts.set(order.commandId, attempt);
|
|
297
360
|
// Bounds apply when frozen: persist older tills' sent forms before sending (Front desk, 2026-09-29). A first
|
|
298
361
|
// send's version is stored, awaited, before the batch request leaves, so a crash in between keeps it.
|
|
299
362
|
if (frozen !== order || order.sentVersion === undefined) {
|
|
300
363
|
await (await collection.findOne(order.id).exec())?.incrementalModify((data) =>
|
|
301
|
-
({ ...freezeSentForm(data), sentVersion: data.sentVersion ?? envelope.version }));
|
|
364
|
+
({ ...freezeSentForm(data), sentVersion: data.sentVersion ?? (envelope.type === 'order.update' ? envelope.payload.createVersion : envelope.version) }));
|
|
302
365
|
}
|
|
303
366
|
localOrders.set(envelope.id, frozen);
|
|
304
367
|
return envelope;
|
|
305
368
|
}));
|
|
369
|
+
if (!batch.length) continue;
|
|
370
|
+
orders = orders.filter((order) => localOrders.has(order.commandId));
|
|
306
371
|
let outcome = await transport.send(batch, { local: { orders: localOrders } });
|
|
307
372
|
// A 404 answers the whole batch (the route is missing); any other answer resets the count. Offline changes nothing.
|
|
308
373
|
backendNotFound.record(outcome, now());
|
|
@@ -338,9 +403,8 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
338
403
|
if (outcome.kind === 'refused' && outcome.status === 400 && options.getMaxOrderCreateVersion) {
|
|
339
404
|
const match = /^Invalid commands\[(\d+)\]\.version$/.exec(outcome.reason);
|
|
340
405
|
if (match) {
|
|
341
|
-
|
|
342
|
-
const
|
|
343
|
-
const max = typeof advertised === 'number' && Number.isSafeInteger(advertised) && advertised > 0 ? advertised : undefined;
|
|
406
|
+
await refreshCapabilities();
|
|
407
|
+
const max = validMax(await options.getMaxOrderCreateVersion());
|
|
344
408
|
if (max !== undefined && max < batch[Number(match[1])]?.version) {
|
|
345
409
|
batchMax = max;
|
|
346
410
|
capabilitiesRefreshed = true;
|
|
@@ -373,13 +437,11 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
373
437
|
const current = await collection.findOne(order.id).exec();
|
|
374
438
|
if (!current) continue;
|
|
375
439
|
let error = result.error;
|
|
376
|
-
if (result.status === 'rejected' && error?.code === 'unsupported_version' && options.getMaxOrderCreateVersion) {
|
|
440
|
+
if (stored.storeOrderId === undefined && result.status === 'rejected' && error?.code === 'unsupported_version' && options.getMaxOrderCreateVersion) {
|
|
377
441
|
if (!capabilitiesRefreshed) {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
? advertised : await options.getMaxOrderCreateVersion();
|
|
382
|
-
batchMax = typeof max === 'number' && Number.isSafeInteger(max) && max > 0 ? max : undefined;
|
|
442
|
+
await refreshCapabilities();
|
|
443
|
+
// The rejection's own advertised max wins; otherwise ask the store's capabilities.
|
|
444
|
+
batchMax = validMax(validMax(error.data?.orderCreate) ?? await options.getMaxOrderCreateVersion());
|
|
383
445
|
capabilitiesRefreshed = true;
|
|
384
446
|
}
|
|
385
447
|
const max = batchMax;
|
|
@@ -387,18 +449,24 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
387
449
|
if (max !== undefined && max < (stored.sentVersion ?? from)) {
|
|
388
450
|
try {
|
|
389
451
|
const to = toOrderCreateEnvelope(stored, deviceId, 1, { maxVersion: max }).version;
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
452
|
+
// Each downgrade strictly lowers sentVersion and stays within the store's cap; sentVersion runs 12 down to 1,
|
|
453
|
+
// so an order downgrades at most 11 times. A pick that doesn't is terminal, never a resend at a version the store refused.
|
|
454
|
+
if (to <= max && to < (stored.sentVersion ?? from)) {
|
|
455
|
+
let changed = false;
|
|
456
|
+
await current.incrementalModify((data) => {
|
|
457
|
+
changed = data.syncStatus === 'pending' && data.commandId === order.commandId && max < (data.sentVersion ?? from)
|
|
458
|
+
&& to < (data.sentVersion ?? from);
|
|
459
|
+
if (changed) { data.sentVersion = to; data.downgradedFrom ??= from; delete data.serverFailures; }
|
|
460
|
+
return data;
|
|
461
|
+
});
|
|
462
|
+
if (changed) {
|
|
463
|
+
outboxLogger.warn('Sent an order at a lower order.create version', { orderId: order.id, from, to });
|
|
464
|
+
progressed = downgraded = true;
|
|
465
|
+
clocks.delete(order.commandId);
|
|
466
|
+
}
|
|
467
|
+
continue;
|
|
400
468
|
}
|
|
401
|
-
|
|
469
|
+
error = { code: 'unsupported_version', message: `order.create ${to} is the lowest this order can go; the store takes ${max}` };
|
|
402
470
|
} catch (cause) {
|
|
403
471
|
if (!(cause instanceof UnsupportedOrderVersionError)) throw cause;
|
|
404
472
|
error = { code: 'unsupported_version', message: cause.message };
|
|
@@ -485,17 +553,23 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
485
553
|
state$,
|
|
486
554
|
flush,
|
|
487
555
|
async requeue(orderIds) {
|
|
488
|
-
const orders = (await readFresh(collection, { selector: { syncStatus: 'rejected',
|
|
556
|
+
const orders = (await readFresh(collection, { selector: { $or: [{ syncStatus: 'rejected' }, { syncStatus: 'pending', 'error.code': UPDATE_UNSENDABLE }],
|
|
489
557
|
...(orderIds ? { id: { $in: orderIds } } : {}) } }))
|
|
490
|
-
.filter(
|
|
558
|
+
.filter(isRequeueableOrder);
|
|
491
559
|
let count = 0;
|
|
492
560
|
for (const order of orders) {
|
|
493
561
|
const oldCommandId = order.commandId;
|
|
494
562
|
let changed = false;
|
|
495
563
|
// The modifier sees the stored state, even when findOne's cached result is stale.
|
|
496
564
|
await (await collection.findOne(order.id).exec())?.incrementalModify((data) => {
|
|
497
|
-
|
|
565
|
+
// A row discard removed is not requeued.
|
|
566
|
+
changed = !data._deleted && isRequeueableOrder(data);
|
|
498
567
|
if (!changed) return data;
|
|
568
|
+
if (data.syncStatus === 'pending') {
|
|
569
|
+
delete data.error;
|
|
570
|
+
data.updatedAt = new Date(now()).toISOString();
|
|
571
|
+
return data;
|
|
572
|
+
}
|
|
499
573
|
data.syncStatus = 'pending';
|
|
500
574
|
delete data.error;
|
|
501
575
|
delete data.serverFailures;
|
|
@@ -514,6 +588,27 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
514
588
|
if (count && !stopped) flush().catch(() => {});
|
|
515
589
|
return count;
|
|
516
590
|
},
|
|
591
|
+
async discard(orderId) {
|
|
592
|
+
// Decide on the stored result of any send in flight.
|
|
593
|
+
await running?.catch(() => {});
|
|
594
|
+
// Rejected only: a pending order may already have reached the store (a timeout, a network drop after the send),
|
|
595
|
+
// so removing it could hide a sale the store took; a rejected one the store refused.
|
|
596
|
+
let commandId: string | undefined;
|
|
597
|
+
// Check and remove in one write, as RxDB's incrementalRemove() does: the modifier sees the stored state, so a
|
|
598
|
+
// requeue that won the race leaves its pending order in place.
|
|
599
|
+
await (await collection.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
600
|
+
// The modifier runs again on a write conflict, so it decides on each run.
|
|
601
|
+
commandId = data.syncStatus === 'rejected' ? data.commandId : undefined;
|
|
602
|
+
if (commandId === undefined) return data;
|
|
603
|
+
data._deleted = true;
|
|
604
|
+
return data;
|
|
605
|
+
});
|
|
606
|
+
if (commandId === undefined) return false;
|
|
607
|
+
attempts.delete(commandId); isolated.delete(commandId); clocks.delete(commandId); walk?.failed.delete(commandId);
|
|
608
|
+
if (head?.id === commandId) head = undefined;
|
|
609
|
+
await updateState();
|
|
610
|
+
return true;
|
|
611
|
+
},
|
|
517
612
|
start() {
|
|
518
613
|
stopped = false;
|
|
519
614
|
watchBackendMissing();
|
|
@@ -6,6 +6,7 @@ import type { RegisterSessionCollection } from '../register/session-store';
|
|
|
6
6
|
import { countFresh, readFresh } from '../rxdb';
|
|
7
7
|
import { createBackendNotFound, type BackendNotFound } from './backend-not-found';
|
|
8
8
|
import { STUCK_AFTER_MS } from './order-outbox';
|
|
9
|
+
import { DEFAULT_INITIAL_BACKOFF_MS, DEFAULT_MAX_BACKOFF_MS, retryDelay } from './retry-delay';
|
|
9
10
|
import { safeErrorMessage, safeErrorString } from './safe-error';
|
|
10
11
|
import type { CommandTransport, OutboxState } from './types';
|
|
11
12
|
|
|
@@ -71,8 +72,8 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
|
|
|
71
72
|
const { collection, sessions, transport, deviceId } = options;
|
|
72
73
|
const size = options.batchSize;
|
|
73
74
|
const batchSize = Math.max(1, Math.min(typeof size === 'number' && Number.isFinite(size) ? Math.floor(size) : 10, 10));
|
|
74
|
-
const initialBackoff = options.initialBackoffMs ??
|
|
75
|
-
const maxBackoff = options.maxBackoffMs ??
|
|
75
|
+
const initialBackoff = options.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS;
|
|
76
|
+
const maxBackoff = options.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
|
|
76
77
|
const random = options.random ?? Math.random;
|
|
77
78
|
const now = options.now ?? Date.now;
|
|
78
79
|
const state$ = new BehaviorSubject<OutboxState>({ pending: 0, sending: false });
|
|
@@ -151,7 +152,7 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
|
|
|
151
152
|
function scheduleRetry(reason: string, retryAfterMs = 0) {
|
|
152
153
|
state$.next({ ...state$.value, lastRetryReason: reason, stuck: stuckState() });
|
|
153
154
|
if (stopped) { stoppedDuringRun = true; return; }
|
|
154
|
-
const delay =
|
|
155
|
+
const delay = retryDelay(backoff, retryAfterMs, maxBackoff, random);
|
|
155
156
|
backoff = Math.min(backoff * 2, maxBackoff);
|
|
156
157
|
timer = setTimeout(() => { timer = undefined; flush().catch(() => {}); }, delay);
|
|
157
158
|
state$.next({ ...state$.value, sending: false, nextAttemptAt: now() + delay });
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Outbox retry defaults: the first retry waits about this long, doubling after each failure up to the cap.
|
|
2
|
+
export const DEFAULT_INITIAL_BACKOFF_MS = 1000;
|
|
3
|
+
export const DEFAULT_MAX_BACKOFF_MS = 60_000;
|
|
4
|
+
|
|
5
|
+
/** The wait before a retry: `backoff` with ±10 % jitter, never shorter than the store's Retry-After, never longer than `maxBackoff`. */
|
|
6
|
+
export function retryDelay(backoff: number, retryAfterMs: number, maxBackoff: number, random: () => number): number {
|
|
7
|
+
return Math.min(Math.max(retryAfterMs, backoff * (0.9 + 0.2 * random())), maxBackoff);
|
|
8
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { OrderCreateEnvelope } from '@tallyui/core';
|
|
1
|
+
import type { OrderCreateEnvelope, OrderUpdateEnvelope } from '@tallyui/core';
|
|
2
2
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
3
3
|
import type { RxCollection, RxError } from 'rxdb';
|
|
4
4
|
import { outboxLogger } from './logger';
|
|
@@ -17,7 +17,7 @@ export interface UseOrderOutboxOptions {
|
|
|
17
17
|
/** Opens the order store for `storeKey`; `close()` is called when the key or device id changes, or on unmount. */
|
|
18
18
|
open(storeKey: string): Promise<{ orders: RxCollection<PosOrder>; close(): Promise<void> }>;
|
|
19
19
|
/** Builds the command transport for `storeKey` (the app's HTTP transport and auth headers). Read once per open. */
|
|
20
|
-
transport(storeKey: string): CommandTransport<OrderCreateEnvelope>;
|
|
20
|
+
transport(storeKey: string): CommandTransport<OrderCreateEnvelope | OrderUpdateEnvelope>;
|
|
21
21
|
/** The device id sent on every command (see `getDeviceId`). A change reopens. */
|
|
22
22
|
deviceId: string;
|
|
23
23
|
/** Presence is fixed when the store opens; calls use the latest function. Reopen to add or remove. */
|
|
@@ -54,6 +54,8 @@ export interface UseOrderOutboxResult {
|
|
|
54
54
|
flush(): Promise<void>;
|
|
55
55
|
/** Moves rejected orders back to pending (see `OrderOutbox.requeue`); resolves to 0 before the current store is ready. */
|
|
56
56
|
requeue(orderIds?: string[]): Promise<number>;
|
|
57
|
+
/** Removes one rejected order (see `OrderOutbox.discard`); resolves to false before the current store is ready. */
|
|
58
|
+
discard(orderId: string): Promise<boolean>;
|
|
57
59
|
/**
|
|
58
60
|
* The count of `record()` calls not yet settled (resolved or rejected). An app holds sign-out
|
|
59
61
|
* (closing the store) while this is above 0, because a close that lands under a write stuck in
|
|
@@ -129,6 +131,10 @@ export function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxRe
|
|
|
129
131
|
const opened = current.current;
|
|
130
132
|
return opened && opened.storeKey === storeKey ? opened.outbox.requeue(orderIds) : 0;
|
|
131
133
|
},
|
|
134
|
+
async discard(orderId) {
|
|
135
|
+
const opened = current.current;
|
|
136
|
+
return opened && opened.storeKey === storeKey ? opened.outbox.discard(orderId) : false;
|
|
137
|
+
},
|
|
132
138
|
savesInFlight: savesInFlightCount,
|
|
133
139
|
stuckCommandIds,
|
|
134
140
|
async record(posOrder) {
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "019f8a40-7800-7000-8000-000000000005",
|
|
3
|
+
"type": "order.create",
|
|
4
|
+
"version": 10,
|
|
5
|
+
"createdAt": "2026-11-18T10:00:00.000Z",
|
|
6
|
+
"deviceId": "device_golden",
|
|
7
|
+
"attempt": 1,
|
|
8
|
+
"payload": {
|
|
9
|
+
"clientOrderId": "019f8a40-7800-7000-8000-000000000001",
|
|
10
|
+
"createdAt": "2026-11-18T10:00:00.000Z",
|
|
11
|
+
"currency": "EUR",
|
|
12
|
+
"pricesIncludeTax": true,
|
|
13
|
+
"lines": [
|
|
14
|
+
{
|
|
15
|
+
"clientLineId": "019f8a40-7800-7000-8000-000000000002",
|
|
16
|
+
"variantId": "p",
|
|
17
|
+
"title": "p",
|
|
18
|
+
"quantity": 1,
|
|
19
|
+
"unitPriceMinor": 1190,
|
|
20
|
+
"discountMinor": 100
|
|
21
|
+
}
|
|
22
|
+
],
|
|
23
|
+
"coupons": [
|
|
24
|
+
{
|
|
25
|
+
"code": "c",
|
|
26
|
+
"couponId": "promo_1",
|
|
27
|
+
"discountMinor": 84,
|
|
28
|
+
"discountTaxMinor": 16,
|
|
29
|
+
"lines": [
|
|
30
|
+
{
|
|
31
|
+
"clientLineId": "019f8a40-7800-7000-8000-000000000002",
|
|
32
|
+
"discountMinor": 84,
|
|
33
|
+
"discountTaxMinor": 16
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
],
|
|
38
|
+
"payments": [
|
|
39
|
+
{
|
|
40
|
+
"clientPaymentId": "019f8a40-7800-7000-8000-000000000003",
|
|
41
|
+
"method": "external",
|
|
42
|
+
"amountMinor": 500,
|
|
43
|
+
"reference": "T-1",
|
|
44
|
+
"methodId": "stripe_terminal_for_woocommerce"
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
"clientPaymentId": "019f8a40-7800-7000-8000-000000000004",
|
|
48
|
+
"method": "cash",
|
|
49
|
+
"amountMinor": 471,
|
|
50
|
+
"tenderedMinor": 571,
|
|
51
|
+
"changeMinor": 100,
|
|
52
|
+
"methodId": "cod"
|
|
53
|
+
}
|
|
54
|
+
],
|
|
55
|
+
"subtotalMinor": 816,
|
|
56
|
+
"discountMinor": 100,
|
|
57
|
+
"taxMinor": 155,
|
|
58
|
+
"totalMinor": 971,
|
|
59
|
+
"display": {
|
|
60
|
+
"currency": "EUR",
|
|
61
|
+
"exponent": 2,
|
|
62
|
+
"taxInclusive": true,
|
|
63
|
+
"subtotalMinor": 1190,
|
|
64
|
+
"discountMinor": 219,
|
|
65
|
+
"taxMinor": 155,
|
|
66
|
+
"totalMinor": 971,
|
|
67
|
+
"lines": [
|
|
68
|
+
{
|
|
69
|
+
"clientLineId": "019f8a40-7800-7000-8000-000000000002",
|
|
70
|
+
"amountMinor": 1190,
|
|
71
|
+
"discounts": [
|
|
72
|
+
{
|
|
73
|
+
"discountId": "discount_line",
|
|
74
|
+
"amountMinor": 119
|
|
75
|
+
}
|
|
76
|
+
]
|
|
77
|
+
}
|
|
78
|
+
],
|
|
79
|
+
"orderDiscountMinor": 0,
|
|
80
|
+
"coupons": [
|
|
81
|
+
{
|
|
82
|
+
"code": "c",
|
|
83
|
+
"amountMinor": 100
|
|
84
|
+
}
|
|
85
|
+
]
|
|
86
|
+
},
|
|
87
|
+
"taxByRate": [
|
|
88
|
+
{
|
|
89
|
+
"ratePpm": 190000,
|
|
90
|
+
"netMinor": 816,
|
|
91
|
+
"taxMinor": 155,
|
|
92
|
+
"grossMinor": 971
|
|
93
|
+
}
|
|
94
|
+
],
|
|
95
|
+
"customer": null
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "019f8f66-7800-7000-8000-000000000004",
|
|
3
|
+
"type": "order.create",
|
|
4
|
+
"version": 11,
|
|
5
|
+
"createdAt": "2026-11-19T10:00:00.000Z",
|
|
6
|
+
"deviceId": "device_golden",
|
|
7
|
+
"attempt": 1,
|
|
8
|
+
"payload": {
|
|
9
|
+
"clientOrderId": "019f8f66-7800-7000-8000-000000000001",
|
|
10
|
+
"createdAt": "2026-11-19T10:00:00.000Z",
|
|
11
|
+
"currency": "EUR",
|
|
12
|
+
"pricesIncludeTax": true,
|
|
13
|
+
"lines": [
|
|
14
|
+
{
|
|
15
|
+
"clientLineId": "019f8f66-7800-7000-8000-000000000002",
|
|
16
|
+
"variantId": "p",
|
|
17
|
+
"title": "p",
|
|
18
|
+
"quantity": 1,
|
|
19
|
+
"unitPriceMinor": 1190,
|
|
20
|
+
"discountMinor": 100
|
|
21
|
+
}
|
|
22
|
+
],
|
|
23
|
+
"payments": [
|
|
24
|
+
{
|
|
25
|
+
"clientPaymentId": "019f8f66-7800-7000-8000-000000000003",
|
|
26
|
+
"method": "cash",
|
|
27
|
+
"amountMinor": 1071,
|
|
28
|
+
"tenderedMinor": 1071,
|
|
29
|
+
"changeMinor": 0
|
|
30
|
+
}
|
|
31
|
+
],
|
|
32
|
+
"subtotalMinor": 900,
|
|
33
|
+
"discountMinor": 100,
|
|
34
|
+
"taxMinor": 171,
|
|
35
|
+
"totalMinor": 1071,
|
|
36
|
+
"display": {
|
|
37
|
+
"currency": "EUR",
|
|
38
|
+
"exponent": 2,
|
|
39
|
+
"taxInclusive": true,
|
|
40
|
+
"subtotalMinor": 1190,
|
|
41
|
+
"discountMinor": 119,
|
|
42
|
+
"taxMinor": 171,
|
|
43
|
+
"totalMinor": 1071,
|
|
44
|
+
"lines": [
|
|
45
|
+
{
|
|
46
|
+
"clientLineId": "019f8f66-7800-7000-8000-000000000002",
|
|
47
|
+
"amountMinor": 1190,
|
|
48
|
+
"discounts": [
|
|
49
|
+
{
|
|
50
|
+
"discountId": "discount_line",
|
|
51
|
+
"amountMinor": 119
|
|
52
|
+
}
|
|
53
|
+
]
|
|
54
|
+
}
|
|
55
|
+
],
|
|
56
|
+
"orderDiscountMinor": 0
|
|
57
|
+
},
|
|
58
|
+
"taxByRate": [
|
|
59
|
+
{
|
|
60
|
+
"ratePpm": 190000,
|
|
61
|
+
"netMinor": 900,
|
|
62
|
+
"taxMinor": 171,
|
|
63
|
+
"grossMinor": 1071
|
|
64
|
+
}
|
|
65
|
+
],
|
|
66
|
+
"customer": {
|
|
67
|
+
"email": "ann@example.com",
|
|
68
|
+
"customerId": "42",
|
|
69
|
+
"billing": {
|
|
70
|
+
"firstName": "Ann",
|
|
71
|
+
"lastName": "Lee",
|
|
72
|
+
"address1": "1 State St",
|
|
73
|
+
"city": "Albany",
|
|
74
|
+
"state": "NY",
|
|
75
|
+
"postcode": "12207",
|
|
76
|
+
"country": "US",
|
|
77
|
+
"phone": "+1 518 555 0100"
|
|
78
|
+
},
|
|
79
|
+
"shipping": {
|
|
80
|
+
"firstName": "Ann",
|
|
81
|
+
"lastName": "Lee",
|
|
82
|
+
"address1": "9 River Rd",
|
|
83
|
+
"city": "Troy",
|
|
84
|
+
"state": "NY",
|
|
85
|
+
"postcode": "12180",
|
|
86
|
+
"country": "US"
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|