@tallyui/pos 3.11.0 → 3.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/index.d.ts +1621 -358
  2. package/dist/index.js +6515 -4314
  3. package/package.json +12 -6
  4. package/src/app-settings/app-settings.ts +93 -0
  5. package/src/app-settings/index.ts +8 -0
  6. package/src/app-settings/use-app-settings.ts +23 -0
  7. package/src/cashier/can.ts +12 -0
  8. package/src/cashier/index.ts +2 -0
  9. package/src/cashier/use-cashier.ts +81 -0
  10. package/src/csv/csv.ts +33 -0
  11. package/src/csv/index.ts +2 -0
  12. package/src/customer-display/display-state.ts +30 -0
  13. package/src/customer-display/index.ts +8 -0
  14. package/src/customer-display/protocol.ts +87 -0
  15. package/src/customer-display/snapshot.ts +65 -0
  16. package/src/index.ts +68 -11
  17. package/src/order/order-builder.ts +19 -2
  18. package/src/order/order-drafts.ts +17 -0
  19. package/src/order/types.ts +10 -3
  20. package/src/outbox/index.ts +5 -1
  21. package/src/outbox/outbox-health.ts +40 -0
  22. package/src/outbox/register-outbox.ts +59 -6
  23. package/src/outbox/safe-error.ts +11 -0
  24. package/src/outbox/types.ts +3 -1
  25. package/src/outbox/use-outbox-health.ts +22 -0
  26. package/src/outbox/use-register-outbox.ts +6 -0
  27. package/src/payment-driver/index.ts +8 -0
  28. package/src/payment-driver/registry.ts +39 -0
  29. package/src/payment-driver/simulated-driver.ts +104 -0
  30. package/src/payment-driver/types.ts +73 -0
  31. package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
  32. package/src/pos-order/command.ts +39 -17
  33. package/src/pos-order/finalize.ts +11 -3
  34. package/src/pos-order/index.ts +1 -0
  35. package/src/pos-order/note-delivery.ts +13 -0
  36. package/src/pos-order/reopen.ts +4 -2
  37. package/src/pos-order/schema.ts +7 -4
  38. package/src/pos-order/types.ts +5 -2
  39. package/src/print/index.ts +10 -0
  40. package/src/print/print-queue.ts +67 -0
  41. package/src/print/printer-profiles.ts +71 -0
  42. package/src/print/system-transport.ts +101 -0
  43. package/src/print/types.ts +40 -0
  44. package/src/receipt/index.ts +1 -0
  45. package/src/receipt/reprint.ts +149 -0
  46. package/src/receipt/types.ts +2 -0
  47. package/src/receipt-template/default-templates.ts +78 -0
  48. package/src/receipt-template/index.ts +15 -0
  49. package/src/receipt-template/parse-xml.ts +175 -0
  50. package/src/receipt-template/render-html.ts +152 -0
  51. package/src/receipt-template/render-receipt.ts +19 -0
  52. package/src/receipt-template/render-template.ts +35 -0
  53. package/src/receipt-template/sanitize-html.ts +146 -0
  54. package/src/receipt-template/template-data.ts +97 -0
  55. package/src/receipt-template/types.ts +49 -0
  56. package/src/refund/index.ts +2 -0
  57. package/src/refund/refundable-lines.ts +91 -0
  58. package/src/register/export-csv.ts +24 -35
  59. package/src/register/float-suggestion.ts +22 -0
  60. package/src/register/index.ts +8 -3
  61. package/src/register/register-adoption.ts +71 -2
  62. package/src/register/register-commands.ts +7 -4
  63. package/src/register/register-count.helpers.ts +4 -0
  64. package/src/register/session-store.ts +4 -1
  65. package/src/register/use-register-session.ts +112 -28
  66. package/src/reports/adapters.ts +67 -0
  67. package/src/reports/index.ts +5 -0
  68. package/src/reports/presets.ts +27 -0
  69. package/src/reports/sales-figures.ts +173 -0
  70. package/src/reports/types.ts +63 -0
  71. package/src/sale/cart.ts +15 -3
  72. package/src/sale/catalogue.ts +5 -1
  73. package/src/sale/index.ts +3 -1
  74. package/src/sale/open-sales.ts +40 -0
  75. package/src/sale/use-sale.ts +72 -8
  76. package/src/scanner/index.ts +6 -0
  77. package/src/scanner/scan-session.ts +84 -0
  78. package/src/scanner/use-barcode-scanner.ts +61 -0
  79. package/src/scanner/wedge-detector.ts +137 -0
  80. package/src/tender/cash-rounding.ts +74 -0
  81. package/src/tender/index.ts +4 -0
  82. package/src/tender/payment-legs.ts +48 -0
@@ -3,6 +3,7 @@ import { resolvePrice, woocommerceTax, type woocommerceCoupons, type ProductTrai
3
3
  import type { TaxContext } from '../tax/types';
4
4
  import { taxMicros, roundMicrosToMinor, roundedTaxByRate } from '../tax/exact';
5
5
  import { taxLogger } from '../tax/tax-provider';
6
+ import { capturedMinor, canMoveLeg, legStatus, type PaymentLegStatus } from '../tender/payment-legs';
6
7
  import { allocateOrderDiscount } from './allocate-order-discount';
7
8
  import { woocommerceLine, woocommerceTotals, woocommerceCouponReplay } from './woocommerce-tax';
8
9
  import type {
@@ -62,6 +63,12 @@ export function assertDisplayResidue(residue: number, convertedLines: number, co
62
63
  if (Math.abs(residue) > bound) throw new Error(`Display residue ${residue} exceeds its bound of ${bound} (ADR-063)`);
63
64
  }
64
65
 
66
+ /** Whether two lines carry the same "Any" picks (#495): the same names in the same order with equal values; none matches none. */
67
+ export function samePicks(a: Pick<LineItem, 'anyAttributes' | 'attributes'>, b: Pick<LineItem, 'anyAttributes' | 'attributes'>): boolean {
68
+ const names = a.anyAttributes ?? [], other = b.anyAttributes ?? [];
69
+ return names.length === other.length && names.every((name, i) => name === other[i] && a.attributes?.[name] === b.attributes?.[name]);
70
+ }
71
+
65
72
  /** The regular unit price to store with a catalogue line (ADR-077 d3): the base price when on sale, else the price charged. */
66
73
  export function regularUnitPriceMinor(resolved: ResolvedPrice): number | undefined {
67
74
  return resolved.was === undefined ? resolved.current.amount : resolved.was.taxInclusive === resolved.current.taxInclusive ? resolved.was.amount : undefined;
@@ -99,6 +106,7 @@ export interface OrderBuilder {
99
106
  applyOrderDiscount(discount: Discount): void;
100
107
  removeDiscount(discountId: string): void;
101
108
  addPayment(payment: Omit<Payment, 'id'>): string;
109
+ setPaymentStatus(paymentId: string, status: PaymentLegStatus): boolean;
102
110
  removePayment(paymentId: string): void;
103
111
  setCustomer(customer: CustomerSummary | null): void;
104
112
  setNote(note: string): void;
@@ -295,7 +303,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
295
303
  ...(fees.length ? { fees: displayFees } : {}),
296
304
  ...(shipping.length ? { shipping: displayShipping } : {}),
297
305
  };
298
- const paidMinor = payments.reduce((sum, p) => sum + p.amountMinor, 0);
306
+ const paidMinor = capturedMinor(payments);
299
307
  const balanceDueMinor = Math.max(0, totalMinor - paidMinor);
300
308
  const changeDueMinor = Math.max(0, paidMinor - totalMinor);
301
309
 
@@ -379,7 +387,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
379
387
  const existing = lineItems.find(
380
388
  (li) => !input.custom && !li.custom && li.productId === productId && li.variantId === variantId && li.taxInclusive === taxInclusive
381
389
  && (!woo || li.taxClass === input.taxClass && (li.taxStatus === 'none') === (input.taxStatus === 'none'))
382
- && li.regularUnitPriceMinor === input.regularUnitPriceMinor
390
+ && li.regularUnitPriceMinor === input.regularUnitPriceMinor && samePicks(li, input)
383
391
  && li.unitPriceMinor === unitPrice.amount && li.taxLines.length === taxRates.length
384
392
  && li.taxLines.every((tax, index) => tax.code === taxRates[index].code && tax.ratePpm === taxRates[index].ratePpm),
385
393
  );
@@ -402,6 +410,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
402
410
  variantId,
403
411
  name: input.name,
404
412
  ...(input.attributes && Object.keys(input.attributes).length ? { attributes: { ...input.attributes } } : {}),
413
+ ...(input.anyAttributes?.length ? { anyAttributes: [...input.anyAttributes] } : {}),
405
414
  sku: input.sku ?? '',
406
415
  imageUrl: input.imageUrl,
407
416
  unitPriceMinor: unitPrice.amount,
@@ -557,6 +566,14 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
557
566
  return id;
558
567
  },
559
568
 
569
+ setPaymentStatus(paymentId, status) {
570
+ const payment = payments.find((p) => p.id === paymentId);
571
+ if (!payment || !canMoveLeg(legStatus(payment), status)) return false;
572
+ payments = payments.map((p) => p.id === paymentId ? { ...p, status } : p);
573
+ emit();
574
+ return true;
575
+ },
576
+
560
577
  removePayment(paymentId) {
561
578
  payments = payments.filter((p) => p.id !== paymentId);
562
579
  emit();
@@ -2,6 +2,7 @@ import { map, type Observable } from 'rxjs';
2
2
  import type { RxCollection, RxJsonSchema } from 'rxdb';
3
3
  import type { TaxContext } from '../tax/types';
4
4
  import { customerRefusal } from '../pos-order/command';
5
+ import { capturedMinor } from '../tender/payment-legs';
5
6
  import { createOrderBuilder, type OrderBuilder } from './order-builder';
6
7
  import type { Order } from './types';
7
8
 
@@ -30,6 +31,19 @@ export interface ParkedOrderSummary {
30
31
  totalMinor: number;
31
32
  parkedAt: string;
32
33
  source: 'local' | 'server';
34
+ /** Read from the draft's data (open-sale tabs, u19): the captured money, the balance still due and the first line's name. */
35
+ paidMinor?: number;
36
+ balanceDueMinor?: number;
37
+ firstItem?: string;
38
+ }
39
+
40
+ function draftExtras(data: unknown): Pick<ParkedOrderSummary, 'paidMinor' | 'balanceDueMinor' | 'firstItem'> {
41
+ try {
42
+ const saved = JSON.parse(String(data)) as Partial<Order>;
43
+ return { paidMinor: capturedMinor(saved.payments ?? []), balanceDueMinor: saved.balanceDueMinor, firstItem: saved.lineItems?.[0]?.name };
44
+ } catch {
45
+ return {}; // an unreadable draft still lists, without these figures
46
+ }
33
47
  }
34
48
 
35
49
  export async function writeOrderDraft(drafts: RxCollection, snapshot: Order): Promise<string> {
@@ -71,6 +85,7 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
71
85
  variantId: line.variantId,
72
86
  name: line.name,
73
87
  ...(line.attributes !== undefined ? { attributes: line.attributes } : {}),
88
+ ...(line.anyAttributes !== undefined ? { anyAttributes: line.anyAttributes } : {}),
74
89
  sku: line.sku,
75
90
  imageUrl: line.imageUrl,
76
91
  unitPrice: { amount: line.unitPriceMinor, currency, taxInclusive: line.taxInclusive },
@@ -110,6 +125,7 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
110
125
  tenderedMinor: payment.tenderedMinor,
111
126
  changeMinor: payment.changeMinor,
112
127
  reference: payment.reference,
128
+ ...(payment.status !== undefined ? { status: payment.status } : {}),
113
129
  });
114
130
  }
115
131
  return builder;
@@ -127,6 +143,7 @@ export function parkedOrderSummaries$(drafts: RxCollection): Observable<ParkedOr
127
143
  totalMinor: json.total ?? 0,
128
144
  parkedAt: json.parkedAt ?? '',
129
145
  source: 'local' as const,
146
+ ...draftExtras(json.data),
130
147
  };
131
148
  }),
132
149
  ),
@@ -1,4 +1,5 @@
1
1
  import type { Money, TaxRounding } from '@tallyui/core';
2
+ import type { PaymentLegStatus } from '../tender/payment-legs';
2
3
 
3
4
  export interface OrderCoupon {
4
5
  code: string; // lower-case code
@@ -29,9 +30,9 @@ export interface Order {
29
30
  taxMinor: number; // settlement: rounded once per order, unless taxRounding says otherwise (#287)
30
31
  totalMinor: number; // settlement: what the customer pays
31
32
  display: DisplayTotals;
32
- paidMinor: number;
33
- balanceDueMinor: number; // max(0, total − paid)
34
- changeDueMinor: number; // max(0, paid − total)
33
+ paidMinor: number; // captured legs only
34
+ balanceDueMinor: number; // max(0, total − paid), counting captured legs only
35
+ changeDueMinor: number; // max(0, paid − total), counting captured legs only
35
36
  createdAt: string;
36
37
  updatedAt: string;
37
38
  }
@@ -77,6 +78,8 @@ export interface LineItem {
77
78
  name: string;
78
79
  /** The variant's chosen options, name to value (#495). */
79
80
  attributes?: Record<string, string>;
81
+ /** The names in attributes the cashier picked for the variant's "Any" option groups (#495); absent when none. */
82
+ anyAttributes?: string[];
80
83
  sku: string;
81
84
  imageUrl?: string;
82
85
  unitPriceMinor: number; // as sold, integer
@@ -133,6 +136,8 @@ export interface AppliedDiscount extends Discount {
133
136
  export interface Payment {
134
137
  id: string;
135
138
  method: string;
139
+ /** Absent means captured; only captured legs count toward paidMinor. */
140
+ status?: PaymentLegStatus;
136
141
  // For cash, record the full amount tendered here, not the capped amount: `finalizeOrder`
137
142
  // caps it at the balance due and writes out `tenderedMinor`/`changeMinor` itself.
138
143
  amountMinor: number;
@@ -162,6 +167,8 @@ export interface AddLineInput {
162
167
  name: string;
163
168
  /** The variant's chosen options, name to value (#495). */
164
169
  attributes?: Record<string, string>;
170
+ /** The names in attributes the cashier picked for the variant's "Any" option groups (#495); absent when none. */
171
+ anyAttributes?: string[];
165
172
  sku?: string;
166
173
  imageUrl?: string;
167
174
  unitPrice: Money & { taxInclusive?: boolean }; // currency must equal the order currency; taxInclusive wins over the order's pricesIncludeTax
@@ -2,10 +2,14 @@ export { createHttpCommandTransport } from './http-transport';
2
2
  export type { HttpTransportOptions } from './http-transport';
3
3
  export { createOrderOutbox, isRequeueable } from './order-outbox';
4
4
  export type { OrderOutboxOptions, OrderOutbox } from './order-outbox';
5
- export { createRegisterOutbox } from './register-outbox';
5
+ export { createRegisterOutbox, isRegisterRequeueable } from './register-outbox';
6
6
  export type { RegisterOutboxOptions, RegisterOutbox } from './register-outbox';
7
7
  export { useRegisterOutbox } from './use-register-outbox';
8
8
  export type { UseRegisterOutboxOptions, UseRegisterOutboxResult } from './use-register-outbox';
9
9
  export type { TransportOutcome, CommandTransport, OrderTransportContext, OutboxState } from './types';
10
10
  export { useOrderOutbox, outboxLogger } from './use-order-outbox';
11
11
  export type { UseOrderOutboxOptions, UseOrderOutboxResult } from './use-order-outbox';
12
+ export { summarizeOutboxHealth, watchOutboxHealth } from './outbox-health';
13
+ export type { OutboxCounts, OutboxHealth } from './outbox-health';
14
+ export { useOutboxHealth } from './use-outbox-health';
15
+ export type { UseOutboxHealthOptions, UseOutboxHealthResult } from './use-outbox-health';
@@ -0,0 +1,40 @@
1
+ import { combineLatest, distinctUntilChanged, map, type Observable } from 'rxjs';
2
+ import type { OutboxState } from './types';
3
+
4
+ export interface OutboxCounts {
5
+ /** `OutboxState.pending`. */
6
+ pending: number;
7
+ /** `OutboxState.rejected`, 0 when unset. */
8
+ rejected: number;
9
+ /** `OutboxState.stuck.commandIds.length`, 0 when unset. These rows are pending too. */
10
+ stuck: number;
11
+ }
12
+ export interface OutboxHealth {
13
+ /** The order outbox (`useOrderOutbox`): sales. */
14
+ sales: OutboxCounts;
15
+ /** The register outbox (`useRegisterOutbox`): till updates. */
16
+ tillUpdates: OutboxCounts;
17
+ /** Rejected plus stuck rows across both outboxes. Not `needsAttention()`'s list, which also holds applied orders with warnings. */
18
+ attention: number;
19
+ /** Either outbox parked after repeated 401s (`OutboxState.authRequired`): the cashier signs in again, then both flush. */
20
+ authRequired: boolean;
21
+ }
22
+ /** The health of both outboxes from their states. Pure. */
23
+ export function summarizeOutboxHealth(sales: OutboxState, tillUpdates: OutboxState): OutboxHealth {
24
+ const salesCounts = { pending: sales.pending, rejected: sales.rejected ?? 0, stuck: sales.stuck?.commandIds.length ?? 0 };
25
+ const tillCounts = { pending: tillUpdates.pending, rejected: tillUpdates.rejected ?? 0, stuck: tillUpdates.stuck?.commandIds.length ?? 0 };
26
+ return { sales: salesCounts, tillUpdates: tillCounts,
27
+ attention: salesCounts.rejected + salesCounts.stuck + tillCounts.rejected + tillCounts.stuck,
28
+ authRequired: !!(sales.authRequired || tillUpdates.authRequired) };
29
+ }
30
+
31
+ /** summarizeOutboxHealth over both state streams (combineLatest), emitting only when a field changes. */
32
+ export function watchOutboxHealth(sales$: Observable<OutboxState>, tillUpdates$: Observable<OutboxState>): Observable<OutboxHealth> {
33
+ return combineLatest([sales$, tillUpdates$]).pipe(
34
+ map(([sales, tillUpdates]) => summarizeOutboxHealth(sales, tillUpdates)),
35
+ distinctUntilChanged((a, b) => a.sales.pending === b.sales.pending && a.sales.rejected === b.sales.rejected &&
36
+ a.sales.stuck === b.sales.stuck && a.tillUpdates.pending === b.tillUpdates.pending &&
37
+ a.tillUpdates.rejected === b.tillUpdates.rejected && a.tillUpdates.stuck === b.tillUpdates.stuck &&
38
+ a.attention === b.attention && a.authRequired === b.authRequired),
39
+ );
40
+ }
@@ -6,11 +6,29 @@ 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 { safeErrorMessage, safeErrorString } from './safe-error';
9
10
  import type { CommandTransport, OutboxState } from './types';
10
11
 
11
12
  /** Final rejections that do not stop their register's ledger (ADR-078): the commands behind them are still sent. */
12
13
  export const NON_BLOCKING_REJECTIONS: ReadonlySet<string> = new Set(['register_session_superseded', 'register_session_abandoned']);
13
14
 
15
+ /** Refused approvals (ADR-082 decision 6). Like NON_BLOCKING_REJECTIONS they do not stop their register's ledger,
16
+ * but its next `register.closure.submit` and every command after it wait: the store numbers closures in order. */
17
+ export const CLOSURE_HOLDING_REJECTIONS: ReadonlySet<string> = new Set(['register_approval_required', 'register_approval_invalid']);
18
+
19
+ // Codes the register requeue never resends (ADR-068 decision 5, ADR-078 decisions 4, 6 and 8): the store recorded
20
+ // these business conflicts, so the same id replays the refusal; superseded and abandoned are final; an already-open
21
+ // refusal has its own exits (Take over, Choose another register); idempotency_mismatch means the bytes differ.
22
+ // A refused approval replays at the store for its command id; recovery is a new command id (ADR-082 decisions 6 and 7).
23
+ const REGISTER_NOT_REQUEUEABLE: ReadonlySet<string> = new Set(['register_session_already_open',
24
+ 'register_session_closed', 'register_approval_required', 'register_approval_invalid', 'register_closure_exists',
25
+ 'register_closure_number_invalid', 'register_session_superseded', 'register_session_abandoned',
26
+ 'register_supersede_forbidden', 'idempotency_mismatch']);
27
+ /** Whether the register outbox's requeue() resends a rejection with this code. */
28
+ export function isRegisterRequeueable(code: string | undefined): boolean {
29
+ return !REGISTER_NOT_REQUEUEABLE.has(code ?? '');
30
+ }
31
+
14
32
  export interface RegisterOutboxOptions {
15
33
  collection: RxCollection<RegisterCommand>;
16
34
  /** The till's `register_sessions`. With it, a refused open (`register_session_already_open`) stops blocking its register
@@ -34,6 +52,10 @@ export interface RegisterOutboxOptions {
34
52
  }
35
53
  export interface RegisterOutbox {
36
54
  flush(): Promise<void>;
55
+ /** Moves rejected commands (all, or those whose commandId is listed) back to pending in their ledger place, under
56
+ * the same commandId and payload, then flushes: a refusal the store did not record is weighed again on a resend
57
+ * of the same id (ADR-068 decision 5). Codes isRegisterRequeueable refuses are left. Resolves to the number requeued. */
58
+ requeue(commandIds?: string[]): Promise<number>;
37
59
  start(): void;
38
60
  stop(): void;
39
61
  state$: Observable<OutboxState>;
@@ -77,7 +99,8 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
77
99
  // pauses every clock (`pausedAt`), and the next answer of any kind resumes them, moving `since` on by the offline
78
100
  // gap, so `since` is now minus the answered time. A clock clears when its command is no longer pending under its
79
101
  // commandId (applied or rejected), or when a blocking rejected command comes ahead of it in its ledger (it is not being
80
- // sent: Front desk, 2026-09-30); commands never sent have none. Nothing is isolated: a stuck command at the head
102
+ // sent: Front desk, 2026-09-30), or when it is a held closure or comes after one, behind a refused approval in its
103
+ // ledger (ADR-082 decision 6); commands never sent have none. Nothing is isolated: a stuck command at the head
81
104
  // of a register's ledger holds up the commands behind it, by design, since register facts apply in `seq` order.
82
105
  // In memory only: a restart starts with no clocks, and the first answered failure after it starts them afresh
83
106
  // (accepted: register commands are few, and a restart re-sends at once).
@@ -99,25 +122,31 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
99
122
 
100
123
  function isNonBlocking(command: RegisterCommand, abandoned: ReadonlySet<string>): boolean {
101
124
  return NON_BLOCKING_REJECTIONS.has(command.error?.code ?? '') ||
125
+ CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? '') ||
102
126
  (command.error?.code === 'register_session_already_open' &&
103
127
  typeof command.payload.sessionId === 'string' && abandoned.has(command.payload.sessionId));
104
128
  }
105
129
 
106
130
  async function updateState(patch: Partial<OutboxState> = {}) {
107
- const abandoned = new Set(sessions && clocks.size
131
+ const rejectedRows = await readFresh(collection, { selector: { syncStatus: 'rejected' } });
132
+ const abandoned = new Set(sessions && (clocks.size || rejectedRows.some((row) => row.error?.code === 'register_session_already_open'))
108
133
  ? (await readFresh(sessions, { selector: { status: 'abandoned' } })).map((session) => session.id) : []);
109
134
  const pending = await countFresh(collection, { syncStatus: 'pending' });
135
+ const rejected = rejectedRows.filter((row) => !isNonBlocking(row, abandoned)).length;
110
136
  // Only commands in a register's sendable prefix (pending, before its first rejected command) keep a clock.
111
137
  const sendable = new Set<string>();
112
138
  const blocked = new Set<string>();
139
+ const held = new Set<string>();
113
140
  if (clocks.size) for (const command of await readFresh(collection, { selector: { syncStatus: { $in: ['pending', 'rejected'] } },
114
141
  sort: [{ seq: 'asc' }, { key: 'asc' }] })) {
115
142
  if (command.syncStatus === 'rejected') {
143
+ if (CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? '')) held.add(command.registerId);
116
144
  if (!isNonBlocking(command, abandoned)) blocked.add(command.registerId);
117
- } else if (!blocked.has(command.registerId)) sendable.add(command.commandId);
145
+ } else if (held.has(command.registerId) && command.type === 'register.closure.submit') blocked.add(command.registerId);
146
+ else if (!blocked.has(command.registerId)) sendable.add(command.commandId);
118
147
  }
119
148
  for (const id of clocks.keys()) if (!sendable.has(id)) clocks.delete(id);
120
- state$.next({ ...state$.value, ...patch, pending, stuck: stuckState() });
149
+ state$.next({ ...state$.value, ...patch, pending, rejected, stuck: stuckState() });
121
150
  }
122
151
  function scheduleRetry(reason: string, retryAfterMs = 0) {
123
152
  state$.next({ ...state$.value, lastRetryReason: reason, stuck: stuckState() });
@@ -145,9 +174,12 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
145
174
  sort: [{ seq: 'asc' }, { key: 'asc' }],
146
175
  });
147
176
  const commands: RegisterCommand[] = [];
177
+ let held = false;
148
178
  for (const command of ledger) {
179
+ if (command.syncStatus === 'rejected' && CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? '')) held = true;
149
180
  if (command.syncStatus === 'rejected' && isNonBlocking(command, abandoned)) continue;
150
181
  if (command.syncStatus === 'rejected') break;
182
+ if (held && command.type === 'register.closure.submit') break;
151
183
  commands.push(command);
152
184
  if (command.type === 'register.session.open' || commands.length >= batchSize) break;
153
185
  }
@@ -202,7 +234,7 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
202
234
  ? { id: result.id, status: 'rejected', error }
203
235
  : { ...result, ...(error ? { error } : {}) };
204
236
  try { await options.onResult?.(plainCommand(stored), normalized); }
205
- catch (cause) { registerCommandsLogger.warn('Failed to apply register command result', { commandId: command.commandId, cause }); }
237
+ catch (cause) { registerCommandsLogger.warn('Failed to apply register command result', { commandId: command.commandId, error: safeErrorString(cause) }); }
206
238
  const updatedAt = new Date(now()).toISOString();
207
239
  await current.incrementalModify((row) => {
208
240
  if (row.syncStatus !== 'pending' || row.commandId !== command.commandId) return row;
@@ -223,7 +255,7 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
223
255
  }
224
256
  if (!sent) return;
225
257
  } catch (error) {
226
- scheduleRetry('error: ' + (error instanceof Error ? error.message : String(error)));
258
+ scheduleRetry('error: ' + safeErrorMessage(error));
227
259
  return;
228
260
  }
229
261
  stoppedDuringRun = true;
@@ -246,6 +278,27 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
246
278
  return {
247
279
  state$,
248
280
  flush,
281
+ async requeue(commandIds) {
282
+ const commands = (await readFresh(collection, { selector: { syncStatus: 'rejected',
283
+ ...(commandIds ? { commandId: { $in: commandIds } } : {}) } }))
284
+ .filter((row) => isRegisterRequeueable(row.error?.code));
285
+ let count = 0;
286
+ for (const command of commands) {
287
+ let changed = false;
288
+ await (await collection.findOne(command.key).exec())?.incrementalModify((row) => {
289
+ changed = row.syncStatus === 'rejected' && row.commandId === command.commandId && isRegisterRequeueable(row.error?.code);
290
+ if (!changed) return row;
291
+ row.syncStatus = 'pending';
292
+ delete row.error;
293
+ row.updatedAt = new Date(now()).toISOString();
294
+ return row;
295
+ });
296
+ if (changed) count++;
297
+ }
298
+ await updateState();
299
+ if (count && !stopped) flush().catch(() => {});
300
+ return count;
301
+ },
249
302
  start() {
250
303
  stopped = false;
251
304
  watchBackendMissing();
@@ -0,0 +1,11 @@
1
+ // An RxError's message carries its parameters, which can hold a payload with the approval proof (ADR-082 d2).
2
+
3
+ /** Renders an error for logging without RxDB parameters. */
4
+ export function safeErrorString(error: unknown): string {
5
+ return (error as { rxdb?: unknown })?.rxdb === true ? (error as Error).name : String(error);
6
+ }
7
+
8
+ /** Renders an error message without RxDB parameters. */
9
+ export function safeErrorMessage(error: unknown): string {
10
+ return (error as { rxdb?: unknown })?.rxdb === true ? (error as Error).name : error instanceof Error ? error.message : String(error);
11
+ }
@@ -22,7 +22,9 @@ export interface CommandTransport<E extends AnyCommandEnvelope = CommandEnvelope
22
22
  export interface OutboxState {
23
23
  pending: number;
24
24
  /** The order outbox's count of `pos_orders` the store refused (`syncStatus: 'rejected'`), read with `pending`. Each
25
- * stays until requeue() sends it again. The register outbox leaves it unset. */
25
+ * stays until requeue() sends it again. The register outbox's count of rejected `register_commands` that stop their
26
+ * register's ledger (superseded, abandoned and an abandoned session's already-open refusal are left out, ADR-078, and so
27
+ * are the two refused closure approvals, which hold only their register's next closure, ADR-082 decision 6). */
26
28
  rejected?: number;
27
29
  sending: boolean;
28
30
  lastRetryReason?: string;
@@ -0,0 +1,22 @@
1
+ import { useMemo } from 'react';
2
+ import { summarizeOutboxHealth, type OutboxHealth } from './outbox-health';
3
+ import type { UseOrderOutboxResult } from './use-order-outbox';
4
+ import type { UseRegisterOutboxResult } from './use-register-outbox';
5
+
6
+ export interface UseOutboxHealthOptions {
7
+ /** `useOrderOutbox()`'s result; only `state` and `flush` are read. */
8
+ sales: Pick<UseOrderOutboxResult, 'state' | 'flush'>;
9
+ /** `useRegisterOutbox()`'s result; only `state` and `flush` are read. */
10
+ tillUpdates: Pick<UseRegisterOutboxResult, 'state' | 'flush'>;
11
+ }
12
+ export interface UseOutboxHealthResult {
13
+ /** summarizeOutboxHealth of the two states; a new object only when a state changes. */
14
+ health: OutboxHealth;
15
+ /** Flushes both outboxes at once (after the cashier signs in again); rejects if either flush rejects. */
16
+ flush(): Promise<void>;
17
+ }
18
+ export function useOutboxHealth(options: UseOutboxHealthOptions): UseOutboxHealthResult {
19
+ const { sales, tillUpdates } = options;
20
+ const health = useMemo(() => summarizeOutboxHealth(sales.state, tillUpdates.state), [sales.state, tillUpdates.state]);
21
+ return { health, async flush() { await Promise.all([sales.flush(), tillUpdates.flush()]); } };
22
+ }
@@ -27,6 +27,8 @@ export interface UseRegisterOutboxResult {
27
27
  state: OutboxState;
28
28
  /** Sends pending till updates; does nothing while there is no collection. */
29
29
  flush(): Promise<void>;
30
+ /** Moves rejected till updates back to pending (see RegisterOutbox.requeue); resolves to 0 while there is no collection. */
31
+ requeue(commandIds?: string[]): Promise<number>;
30
32
  }
31
33
 
32
34
  export function useRegisterOutbox(options: UseRegisterOutboxOptions): UseRegisterOutboxResult {
@@ -55,5 +57,9 @@ export function useRegisterOutbox(options: UseRegisterOutboxOptions): UseRegiste
55
57
  async flush() {
56
58
  const active = current.current;
57
59
  if (active?.commands === commands && active.deviceId === deviceId) await active.outbox.flush();
60
+ },
61
+ async requeue(commandIds) {
62
+ const active = current.current;
63
+ return active?.commands === commands && active.deviceId === deviceId ? active.outbox.requeue(commandIds) : 0;
58
64
  } };
59
65
  }
@@ -0,0 +1,8 @@
1
+ export { createPaymentDriverRegistry, driverForMethod } from './registry';
2
+ export { createSimulatedDriver, SIMULATED_PROVIDER, SIMULATED_TIMING } from './simulated-driver';
3
+ export type {
4
+ DriverCapabilities, ReaderInfo, DriverStatus, DriverAvailability, CollectInput,
5
+ CollectOutcome, CollectResult, DriverStatusSource, PaymentDriver,
6
+ } from './types';
7
+ export type { PaymentDriverRegistry } from './registry';
8
+ export type { SimulatedReaderId, SimulatedDriverOptions } from './simulated-driver';
@@ -0,0 +1,39 @@
1
+ // Ported from WCPOS v2 packages/core/src/services/payment-drivers/registry.ts (monorepo 5ac185b0).
2
+ import type { PaymentMethodDescriptor } from '@tallyui/core';
3
+ import type { PaymentDriver } from './types';
4
+
5
+ export interface PaymentDriverRegistry {
6
+ /** Adds the driver under its `provider`, replacing any driver already there, then notifies subscribers. */
7
+ register(driver: PaymentDriver): void;
8
+ get(provider: string | null): PaymentDriver | undefined;
9
+ has(provider: string | null): boolean;
10
+ list(): PaymentDriver[];
11
+ /** Called after every `register`; returns an unsubscribe function. */
12
+ subscribe(listener: () => void): () => void;
13
+ }
14
+
15
+ export function createPaymentDriverRegistry(): PaymentDriverRegistry {
16
+ const drivers = new Map<string, PaymentDriver>();
17
+ const listeners = new Set<() => void>();
18
+ return {
19
+ register(driver) {
20
+ drivers.set(driver.provider, driver);
21
+ listeners.forEach((listener) => listener());
22
+ },
23
+ get: (provider) => provider === null ? undefined : drivers.get(provider),
24
+ has: (provider) => provider !== null && drivers.has(provider),
25
+ list: () => [...drivers.values()],
26
+ subscribe(listener) {
27
+ listeners.add(listener);
28
+ return () => { listeners.delete(listener); };
29
+ },
30
+ };
31
+ }
32
+
33
+ /** The driver for a method taken on a device: `capture.mode === 'device'` and a driver registered under `capture.provider`. */
34
+ export function driverForMethod(
35
+ registry: PaymentDriverRegistry,
36
+ method: PaymentMethodDescriptor | null | undefined,
37
+ ): PaymentDriver | undefined {
38
+ return method?.capture.mode === 'device' ? registry.get(method.capture.provider) : undefined;
39
+ }
@@ -0,0 +1,104 @@
1
+ // Ported from WCPOS v2 packages/core/src/services/payment-drivers/simulated-driver.ts (monorepo 5ac185b0).
2
+ import type { CollectResult, DriverAvailability, DriverStatus, PaymentDriver, ReaderInfo } from './types';
3
+
4
+ export const SIMULATED_PROVIDER = 'simulated';
5
+ export const SIMULATED_TIMING = { connectMs: 300, decisionMs: 500, readWindowMs: 1500 } as const;
6
+ export type SimulatedReaderId = 'sim-approve' | 'sim-decline' | 'sim-cancel' | 'sim-timeout' | 'sim-tip' | 'sim-tap';
7
+ export interface SimulatedDriverOptions {
8
+ /** Override any of the delays in SIMULATED_TIMING. */
9
+ timing?: Partial<{ connectMs: number; decisionMs: number; readWindowMs: number }>;
10
+ /** Timer functions; default to globalThis.setTimeout / clearTimeout. */
11
+ timers?: {
12
+ setTimeout: (fn: () => void, ms: number) => unknown;
13
+ clearTimeout: (handle: unknown) => void;
14
+ };
15
+ /** What `availability()` returns; default `{ available: true }`. */
16
+ availability?: DriverAvailability;
17
+ }
18
+
19
+ export function createSimulatedDriver(options: SimulatedDriverOptions = {}): PaymentDriver {
20
+ const timing = { ...SIMULATED_TIMING, ...options.timing };
21
+ const timers = options.timers ?? {
22
+ setTimeout: (fn: () => void, ms: number) => globalThis.setTimeout(fn, ms),
23
+ clearTimeout: (handle: unknown) => globalThis.clearTimeout(handle as ReturnType<typeof setTimeout>),
24
+ };
25
+ const ids: SimulatedReaderId[] = ['sim-approve', 'sim-decline', 'sim-cancel', 'sim-timeout', 'sim-tip', 'sim-tap'];
26
+ const readers: ReaderInfo[] = ids.map((id) => ({
27
+ id,
28
+ label: `Simulated ${id.slice(4)}`,
29
+ model: 'Simulated reader',
30
+ battery: 82,
31
+ transport: id === 'sim-tap' ? 'tap_to_pay' : 'bluetooth',
32
+ }));
33
+ let status: DriverStatus = { connection: 'disconnected', reader: null };
34
+ const listeners = new Set<(status: DriverStatus) => void>();
35
+ let cancelCollection: (() => void) | undefined;
36
+ const publish = (next: DriverStatus) => {
37
+ status = next;
38
+ listeners.forEach((listener) => listener(status));
39
+ };
40
+ return {
41
+ provider: SIMULATED_PROVIDER,
42
+ capabilities: { discovery: 'harness', cancel: 'app', refund: false },
43
+ availability: () => options.availability ?? { available: true },
44
+ async discoverReaders(transport) {
45
+ return readers.filter((reader) => reader.transport === transport);
46
+ },
47
+ async connect(reader) {
48
+ publish({ connection: 'connecting', reader });
49
+ await new Promise<void>((resolve) => { timers.setTimeout(resolve, timing.connectMs); });
50
+ publish({ connection: 'connected', reader });
51
+ },
52
+ async disconnect() {
53
+ cancelCollection?.();
54
+ publish({ connection: 'disconnected', reader: null });
55
+ },
56
+ status$: {
57
+ get: () => status,
58
+ subscribe(listener) {
59
+ listeners.add(listener);
60
+ return () => { listeners.delete(listener); };
61
+ },
62
+ },
63
+ collect(input) {
64
+ const reader = status.reader;
65
+ if (status.connection !== 'connected' || !reader) return Promise.reject(new Error('No reader connected'));
66
+ if (cancelCollection) return Promise.reject(new Error('Reader is in use'));
67
+ return new Promise<CollectResult>((resolve) => {
68
+ const pending: { timer?: unknown } = {};
69
+ const base = {
70
+ providerRefs: { reference: 'sim_' + input.legId },
71
+ receipt: { brand: 'visa', last4: '4242' },
72
+ amountMinor: input.amountMinor,
73
+ transport: input.transport,
74
+ };
75
+ const finish = (result: CollectResult) => {
76
+ if (pending.timer !== undefined) timers.clearTimeout(pending.timer);
77
+ cancelCollection = undefined;
78
+ resolve(result);
79
+ };
80
+ cancelCollection = () => finish({ ...base, outcome: 'cancelled' });
81
+ const result: CollectResult = { ...base, outcome: 'captured' };
82
+ switch (reader.id) {
83
+ case 'sim-cancel':
84
+ return;
85
+ case 'sim-decline':
86
+ result.outcome = 'declined';
87
+ result.failureReason = 'card_declined';
88
+ break;
89
+ case 'sim-timeout':
90
+ result.outcome = 'cancelled';
91
+ result.failureReason = 'timed_out';
92
+ break;
93
+ case 'sim-tip':
94
+ result.amountMinor = input.amountMinor + (input.tipEligibleMinor === null ? 0 : Math.round(input.tipEligibleMinor / 10));
95
+ break;
96
+ }
97
+ pending.timer = timers.setTimeout(() => finish(result), reader.id === 'sim-timeout' ? timing.readWindowMs : timing.decisionMs);
98
+ });
99
+ },
100
+ async cancel() {
101
+ cancelCollection?.();
102
+ },
103
+ };
104
+ }