@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
@@ -1,12 +1,13 @@
1
1
  /**
2
2
  * A CSV export of the closures currently shown: one column per tender the visible rows use, an
3
- * expected-only tender kept as a zero-counted shortage, quoted/escaped cells with a CRLF line
4
- * ending, and a leading `'` on formula- or control-prefixed text so a spreadsheet reads it as
5
- * text (LEDGER.md #26, #27). Port provenance (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`
3
+ * expected-only tender kept as a zero-counted shortage, quoting and formula guarding from
4
+ * `../csv`, and CRLF between lines (LEDGER.md #26, #27).
5
+ * Port provenance (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`
6
6
  * `export-csv.ts`. Money is a2's integer minor units: an `exponent` parameter (as in a1's
7
7
  * `parseMinor`/`varianceText`) formats each cell back to the decimal string WCPOS's server sent,
8
8
  * e.g. `1250` at exponent 2 becomes `'12.50'`.
9
9
  */
10
+ import { toCsv, type CsvColumn } from '../csv';
10
11
  import { minorToDecimal } from './money';
11
12
  import type { Closure } from './schemas';
12
13
 
@@ -29,32 +30,16 @@ export function exportCsv(
29
30
  ]),
30
31
  ),
31
32
  ];
32
- const cell = (value: unknown) => {
33
- const text = String(value ?? '');
34
- return `"${(/^(?:[\t\r\n]|[\s\x00-\x1f\x7f-\x9f]*[=+\-@])/.test(text) ? "'" + text : text).replace(/"/g, '""')}"`;
35
- };
36
- const header = ['business_day', 'closure', 'register', 'store', 'opened', 'closed', 'closer'].map((key) =>
37
- t(`reports.csv_${key}`),
38
- );
39
- header.push(
40
- ...tenders.flatMap((method) => [
41
- `${t('reports.document.expected')} (${method})`,
42
- `${t('register.counted')} (${method})`,
43
- `${t('register.variance')} (${method})`,
44
- ]),
45
- t('reports.csv_status'),
46
- );
47
- return [
48
- header,
49
- ...rows.map((row) => [
50
- row.business_day,
51
- row.number,
52
- row.breakdowns.register_name || names[row.register_id] || row.register_id.slice(0, 8),
53
- row.breakdowns.store_name || storeName || row.store_key,
54
- row.opened_at,
55
- row.closed_at,
56
- row.breakdowns.closed_by_name || t('register.unknown_cashier'),
57
- ...tenders.flatMap((method) => {
33
+ const columns: CsvColumn<Closure>[] = [
34
+ { header: t('reports.csv_business_day'), value: (row) => row.business_day },
35
+ { header: t('reports.csv_closure'), value: (row) => row.number },
36
+ { header: t('reports.csv_register'), value: (row) => row.breakdowns.register_name || names[row.register_id] || row.register_id.slice(0, 8) },
37
+ { header: t('reports.csv_store'), value: (row) => row.breakdowns.store_name || storeName || row.store_key },
38
+ { header: t('reports.csv_opened'), value: (row) => row.opened_at },
39
+ { header: t('reports.csv_closed'), value: (row) => row.closed_at },
40
+ { header: t('reports.csv_closer'), value: (row) => row.breakdowns.closed_by_name || t('register.unknown_cashier') },
41
+ ...tenders.flatMap((method): CsvColumn<Closure>[] => {
42
+ const values = (row: Closure) => {
58
43
  const expected = at(row.expected, method);
59
44
  const counted = at(row.counted, method) ?? (expected === undefined ? undefined : 0);
60
45
  const value = at(row.variance, method) ?? (expected === undefined ? undefined : (counted ?? 0) - expected);
@@ -65,10 +50,14 @@ export function exportCsv(
65
50
  ? ''
66
51
  : `${minorToDecimal(Math.abs(value), exponent)} ${t(value < 0 ? 'register.short' : value > 0 ? 'register.over' : 'reports.exact')}`,
67
52
  ];
68
- }),
69
- row.unsynced_count > 0 ? t('register.unsynced') : row.corrections_count ? t('reports.corrected') : '',
70
- ]),
71
- ]
72
- .map((row) => row.map(cell).join(','))
73
- .join('\r\n');
53
+ };
54
+ return [
55
+ { header: `${t('reports.document.expected')} (${method})`, value: (row) => values(row)[0] },
56
+ { header: `${t('register.counted')} (${method})`, value: (row) => values(row)[1] },
57
+ { header: `${t('register.variance')} (${method})`, value: (row) => values(row)[2] },
58
+ ];
59
+ }),
60
+ { header: t('reports.csv_status'), value: (row) => row.unsynced_count > 0 ? t('register.unsynced') : row.corrections_count ? t('reports.corrected') : '' },
61
+ ];
62
+ return toCsv(rows, columns);
74
63
  }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The opening float the open-register card suggests (v2 parity A4): the register's default float, else the cash
3
+ * counted at the last close, else none. Port provenance: WCPOS v2 monorepo `main` `5ac185b0e`,
4
+ * `packages/core/src/screens/main/pos/cart/open-register-card.tsx:40-50` (`defaultFloat ?? lastCount ?? null`), with
5
+ * `seedAmount` from `packages/core/src/services/register-session/count-money.ts`. Money is TallyUI's integer
6
+ * minor-units convention, so `seedAmount`'s rounding of four-decimal server strings has no counterpart here.
7
+ */
8
+ import type { RegisterInfo } from '@tallyui/core';
9
+
10
+ export type FloatSuggestion =
11
+ | { amountMinor: number; source: 'default' | 'last_count' }
12
+ | { amountMinor: null; source: null };
13
+
14
+ /** A default float of zero is still the default, as in v2 (`??`, not `||`). */
15
+ export function suggestFloat({ register, lastCountedCashMinor }: {
16
+ register?: Pick<RegisterInfo, 'defaultFloatMinor'> | null;
17
+ lastCountedCashMinor?: number | null;
18
+ }): FloatSuggestion {
19
+ if (register?.defaultFloatMinor != null) return { amountMinor: register.defaultFloatMinor, source: 'default' };
20
+ if (lastCountedCashMinor != null) return { amountMinor: lastCountedCashMinor, source: 'last_count' };
21
+ return { amountMinor: null, source: null };
22
+ }
@@ -2,7 +2,7 @@ export { normalizeAmount, isServerDecimal, movementFieldError } from './movement
2
2
  export type { MovementType } from './movement-input';
3
3
  export { deriveExpected } from './expected';
4
4
  export type { LedgerRow, Movement } from './expected';
5
- export { parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, denominationTotal, varianceText } from './register-count.helpers';
5
+ export { parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, closureVariance, denominationTotal, varianceText } from './register-count.helpers';
6
6
  export { denominations } from './register-count.denominations';
7
7
  export { registerSessionSchema, registerSessionCollection, cashMovementSchema, closureSchema } from './schemas';
8
8
  export { addRegisterSessionCollection, RegisterSessionOpenClosedError, registerSessionsLogger, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS } from './open';
@@ -18,6 +18,8 @@ export {
18
18
  } from './session-store';
19
19
  export type { RegisterSessionCollection, CashMovementCollection, ClosureCollection } from './session-store';
20
20
  export { deriveSettled } from './settled-figures';
21
+ export { suggestFloat } from './float-suggestion';
22
+ export type { FloatSuggestion } from './float-suggestion';
21
23
  export type { Correction, RecordedFigures } from './settled-figures';
22
24
  export { exportCsv } from './export-csv';
23
25
  export { labelKeys } from './document-labels';
@@ -28,7 +30,10 @@ export { formatClosureDate, buildClosureDocument, buildXReportDocument, TAX_ROUN
28
30
  export type { ClosureContext } from './closure-document';
29
31
  export { registerFactsLogger, recordRegisterFact, type Actor, type RegisterFact } from './facts';
30
32
  export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError } from './use-register-session';
31
- export type { UseRegisterSessionOptions } from './use-register-session';
33
+ export type { ApprovalNeeded, UseRegisterSessionOptions } from './use-register-session';
32
34
  export { registerCommandSchema, registerCommandCollection, registerCommandsLogger, sessionOpenCommand, sessionTransitionCommand, movementCommand, closureCommand, reconcileRegisterCommands } from './register-commands';
33
- export { adoptRegisterResults, takeOverSession, abandonSession } from './register-adoption';
35
+ export {
36
+ adoptRegisterResults, takeOverSession, abandonSession, isLiveAtStore, closureApprovalStatus, reapproveClosure, RegisterReapproveError,
37
+ } from './register-adoption';
38
+ export type { ClosureApprovalStatus } from './register-adoption';
34
39
  export type { RegisterCommand, RegisterCommandCollection } from './register-commands';
@@ -1,7 +1,10 @@
1
+ import type { ServerCapabilities } from '@tallyui/core';
2
+ import { CLOSURE_HOLDING_REJECTIONS } from '../outbox/register-outbox';
1
3
  import { readFresh } from '../rxdb';
2
4
  import { uuidv7 } from '../pos-order/uuidv7';
3
- import { registerCommandsLogger, type RegisterCommandCollection } from './register-commands';
4
- import type { RegisterSession } from './schemas';
5
+ import { countVariance, overThreshold } from './register-count.helpers';
6
+ import { registerCommandsLogger, type RegisterCommand, type RegisterCommandCollection } from './register-commands';
7
+ import type { Closure, RegisterSession } from './schemas';
5
8
  import { isKnownSessionStatus, RegisterSessionRequiredError, RegisterTakeOverError, type RegisterSessionCollection } from './session-store';
6
9
 
7
10
  const chains = new WeakMap<RegisterCommandCollection, Promise<void>>();
@@ -103,3 +106,69 @@ export async function abandonSession(input: SessionTarget): Promise<void> {
103
106
  chains.set(commands, run.then(() => undefined, () => undefined));
104
107
  return run;
105
108
  }
109
+
110
+ /**
111
+ * ADR-082 d4: the store holds this session, so the app's approval route can be used for it. Its open row is applied (a
112
+ * resumed open and an error-free duplicate are recorded applied), and it is not conflict, superseded or abandoned. A
113
+ * closed session still counts: the route accepts it.
114
+ */
115
+ export function isLiveAtStore(session: Pick<RegisterSession, 'id' | 'status'> | null | undefined,
116
+ openRow: Pick<RegisterCommand, 'key' | 'syncStatus'> | null | undefined): boolean {
117
+ return !!session && openRow?.key === `session.open:${session.id}` && openRow.syncStatus === 'applied'
118
+ && session.status !== 'conflict' && session.status !== 'superseded' && session.status !== 'abandoned';
119
+ }
120
+
121
+ /** `verified` once the store has applied a version 3 closure carrying a proof; `not_required` for a close the store does not check. */
122
+ export type ClosureApprovalStatus = 'verified' | 'unverified' | 'not_required';
123
+
124
+ /**
125
+ * ADR-082 d9, derived from the closure's `register.closure.submit` row; nothing is stored. A verified approval is
126
+ * needed at register contract 3 with the store's `registerApproval`, over its threshold on cash (the store's rule).
127
+ * Until the store applies a version 3 row with a proof, a recorded approver is `unverified`: no row yet, pending,
128
+ * refused, or a version 1 row the store recorded without checking.
129
+ */
130
+ export function closureApprovalStatus(closure: Pick<Closure, 'counted' | 'till_expected'>,
131
+ row: Pick<RegisterCommand, 'syncStatus' | 'version' | 'payload'> | null | undefined,
132
+ capabilities: Pick<ServerCapabilities, 'register' | 'registerApproval'> | undefined): ClosureApprovalStatus {
133
+ const threshold = capabilities?.registerApproval?.thresholdMinor;
134
+ if ((capabilities?.register ?? 0) < 3 || threshold == null
135
+ || !overThreshold(countVariance(closure.counted.cash ?? 0, closure.till_expected.cash ?? 0), threshold)) return 'not_required';
136
+ return row?.syncStatus === 'applied' && row.version >= 3 && typeof row.payload.approval === 'string' && row.payload.approval
137
+ ? 'verified' : 'unverified';
138
+ }
139
+
140
+ /** `reapproveClosure` refused. Its message can be shown to a cashier as it is. */
141
+ export class RegisterReapproveError extends Error {
142
+ constructor(readonly code: 'REGISTER_REAPPROVE_UNSUPPORTED' | 'REGISTER_REAPPROVE_NOT_REFUSED' | 'REGISTER_REAPPROVE_PROOF_MISSING') {
143
+ super(code === 'REGISTER_REAPPROVE_UNSUPPORTED' ? 'This store cannot check a manager approval.'
144
+ : code === 'REGISTER_REAPPROVE_NOT_REFUSED' ? 'This closure is not waiting for a manager approval.'
145
+ : 'Manager approval needed. Ask a manager to approve.');
146
+ this.name = 'RegisterReapproveError';
147
+ }
148
+ }
149
+
150
+ /**
151
+ * ADR-082 d7: requeues a closure the store refused with either approval code, in its ledger place (the same key and
152
+ * `seq`), with a new command id (the store replays a stored refusal for the old one), version 3, the new proof and
153
+ * approver, and every other payload field as it was. The local closure, its Z and the session are not rewritten.
154
+ */
155
+ export async function reapproveClosure({ commands, closureId, approval, approvedBy, registerContract, now }: {
156
+ commands: RegisterCommandCollection; closureId: string; approval: string; approvedBy: string; registerContract?: number; now?: string;
157
+ }): Promise<void> {
158
+ if ((registerContract ?? 0) < 3) throw new RegisterReapproveError('REGISTER_REAPPROVE_UNSUPPORTED');
159
+ if (typeof approval !== 'string' || !approval || typeof approvedBy !== 'string' || !approvedBy) {
160
+ throw new RegisterReapproveError('REGISTER_REAPPROVE_PROOF_MISSING');
161
+ }
162
+ const run = (chains.get(commands) ?? Promise.resolve()).then(async () => {
163
+ const row = await commands.findOne(`closure.submit:${closureId}`).exec();
164
+ if (!row) throw new RegisterReapproveError('REGISTER_REAPPROVE_NOT_REFUSED');
165
+ await row.incrementalModify((doc) => {
166
+ if (doc.syncStatus !== 'rejected' || !CLOSURE_HOLDING_REJECTIONS.has(doc.error?.code ?? '')) throw new RegisterReapproveError('REGISTER_REAPPROVE_NOT_REFUSED');
167
+ const { error: _refusal, ...rest } = doc;
168
+ return { ...rest, commandId: uuidv7(), version: 3, syncStatus: 'pending',
169
+ payload: { ...doc.payload, approval, approvedBy }, updatedAt: now ?? new Date().toISOString() };
170
+ });
171
+ });
172
+ chains.set(commands, run.then(() => undefined, () => undefined));
173
+ return run;
174
+ }
@@ -38,7 +38,7 @@ export const registerCommandSchema: RxJsonSchema<RegisterCommand> = {
38
38
  };
39
39
  export const registerCommandCollection = () => ({ schema: registerCommandSchema });
40
40
 
41
- type BuiltCommand = Pick<RegisterCommand, 'key' | 'type' | 'payload'> & { version: 1 | 2 };
41
+ type BuiltCommand = Pick<RegisterCommand, 'key' | 'type' | 'payload'> & { version: 1 | 2 | 3 };
42
42
 
43
43
  /** ADR-078: 1 to 64 characters after trim. */
44
44
  export function deviceNameOf(name: string | null | undefined): string | undefined {
@@ -82,8 +82,10 @@ export function movementCommand(m: CashMovement): BuiltCommand {
82
82
  payload: { ...common, type: m.type, amountMinor: m.amountMinor, reason: m.reason } satisfies RegisterMovementRecordPayload };
83
83
  }
84
84
 
85
- export function closureCommand(c: Closure): BuiltCommand {
86
- return { key: `closure.submit:${c.id}`, type: 'register.closure.submit', version: 1, payload: {
85
+ /** ADR-082 d1: version 3 with the store's opaque approval at register contract 3; below 3 or unknown, version 1 and today's bytes. */
86
+ export function closureCommand(c: Closure, v3: { registerContract?: number; approval?: string | null } = {}): BuiltCommand {
87
+ const at3 = (v3.registerContract ?? 0) >= 3;
88
+ return { key: `closure.submit:${c.id}`, type: 'register.closure.submit', version: at3 ? 3 : 1, payload: {
87
89
  closureId: c.id, sessionId: c.session_id, registerId: c.register_id, number: c.number,
88
90
  openedAt: c.opened_at, closedAt: c.closed_at,
89
91
  ...(c.business_day == null ? {} : { businessDay: c.business_day }),
@@ -94,6 +96,7 @@ export function closureCommand(c: Closure): BuiltCommand {
94
96
  perpetualSalesTotalMinor: c.perpetual_sales_total_minor, perpetualRefundsTotalMinor: c.perpetual_refunds_total_minor,
95
97
  unsyncedCount: c.unsynced_count, unsyncedTotalMinor: c.unsynced_total_minor, softwareVersion: c.software_version,
96
98
  orderIds: c.order_ids, movementIds: c.movement_ids,
99
+ ...(at3 && v3.approval ? { approval: v3.approval } : {}),
97
100
  } satisfies RegisterClosureSubmitPayload };
98
101
  }
99
102
 
@@ -133,7 +136,7 @@ export function reconcileRegisterCommands({ commands, sessions, movements, closu
133
136
  ...entries.filter((entry) => entry.type === 'void').map(movementCommand));
134
137
  if (session.status_at != null && sentStatus(session)) events.push(sessionTransitionCommand({ ...session, status_at: session.status_at }));
135
138
  return { session, number: closureRows[0]?.number, built: [(registerContract ?? 0) >= 2 ? sessionOpenCommand(session, { deviceName }) : sessionOpenCommand(session), ...events,
136
- ...closureRows.map((closure) => closureCommand(closure))] };
139
+ ...closureRows.map((closure) => closureCommand(closure, { registerContract, approval: session.approver_token }))] };
137
140
  }));
138
141
  facts.sort((a, b) => Number(a.session.status !== 'closed') - Number(b.session.status !== 'closed')
139
142
  || (a.number ?? Infinity) - (b.number ?? Infinity)
@@ -40,6 +40,10 @@ export const overThreshold = (variance: number, thresholdMinor?: number | null)
40
40
  export const closeNeedsApproval = (countedCashMinor: number, expectedCashMinor: number, thresholdMinor?: number | null) =>
41
41
  overThreshold(countVariance(countedCashMinor, expectedCashMinor), thresholdMinor);
42
42
 
43
+ /** ADR-082 d3: counted minus till-expected for each key of `counted`, the variance a store approval is bound to. */
44
+ export const closureVariance = (counted: Record<string, number>, tillExpected: Record<string, number>) =>
45
+ Object.fromEntries(Object.entries(counted).map(([method, value]) => [method, countVariance(value, tillExpected[method] ?? 0)]));
46
+
43
47
  /** Sums denomination face values (already minor units) by piece count. */
44
48
  export const denominationTotal = (pieces: Record<number, number>) =>
45
49
  Object.entries(pieces).reduce((sum, [value, count]) => sum + Number(value) * count, 0);
@@ -309,11 +309,13 @@ export const backToSelling = (sessions: RegisterSessionCollection, id: string) =
309
309
  * Closes the session with its counted tenders (minor units); `timezone` dates a session opened
310
310
  * without a business day. `approvedBy`, the manager who approved the count, is written in the same
311
311
  * write as the close, and a repeat close keeps the first close's approver as it keeps its count.
312
+ * `approval`, the store's opaque proof (ADR-082), is written to `approver_token` in the same
313
+ * write; it never reaches the closure or its breakdowns.
312
314
  */
313
315
  export async function closeSession(
314
316
  sessions: RegisterSessionCollection,
315
317
  id: string,
316
- input: { counted: Record<string, number>; closedBy?: string; approvedBy?: string; timezone?: string },
318
+ input: { counted: Record<string, number>; closedBy?: string; approvedBy?: string; approval?: string; timezone?: string },
317
319
  ) {
318
320
  const session = await sessions.findOne(id).exec();
319
321
  if (!session) throw new RegisterSessionRequiredError();
@@ -322,6 +324,7 @@ export async function closeSession(
322
324
  counted: input.counted,
323
325
  closed_by: input.closedBy ?? null,
324
326
  ...(input.approvedBy ? { approved_by: input.approvedBy } : {}),
327
+ ...(input.approval ? { approver_token: input.approval } : {}),
325
328
  closure_id: id,
326
329
  });
327
330
  }
@@ -12,20 +12,24 @@
12
12
  * - Refund parents and the close-time wait: a refund's record is the app's optional `refunds` collection, and one still pending at close is listed on the Z instead (ADR-080 amendment 1).
13
13
  * - Anchor invalidation, `server_expected` and `server_sales_count`: no server figures (c2).
14
14
  * - `unsyncedCount` and the `sync_status` filters: nothing is sent (c2).
15
- * - The binding (`useRegisterBinding`) and `blind` from WooCommerce capabilities: app inputs.
15
+ * - The binding (`useRegisterBinding`): an app input. `blind` is an app input too: `useCashier(...).blind`.
16
16
  */
17
17
  import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
18
18
  import { combineLatest, map, of, switchMap } from 'rxjs';
19
19
  import type { RxCollection } from 'rxdb';
20
20
  import type { RegisterSessionAlreadyOpenData, ServerCapabilities } from '@tallyui/core';
21
+ import { CLOSURE_HOLDING_REJECTIONS } from '../outbox/register-outbox';
22
+ import { safeErrorString } from '../outbox/safe-error';
21
23
  import type { PosOrder } from '../pos-order/types';
22
24
  import { replacedOrderIds } from '../pos-order/reopened';
23
25
  import type { PosRefund, PosRefundCollection } from '../refund/pos-refund';
24
26
  import { readFresh, watchFresh } from '../rxdb';
25
27
  import { deriveExpected, type LedgerRow } from './expected';
26
28
  import { recordRegisterFact, registerFactsLogger, type Actor } from './facts';
27
- import { closeNeedsApproval } from './register-count.helpers';
28
- import { abandonSession, adoptRegisterResults, takeOverSession } from './register-adoption';
29
+ import { closeNeedsApproval, closureVariance } from './register-count.helpers';
30
+ import {
31
+ abandonSession, adoptRegisterResults, closureApprovalStatus, isLiveAtStore, reapproveClosure, takeOverSession, type ClosureApprovalStatus,
32
+ } from './register-adoption';
29
33
  import { reconcileRegisterCommands, registerCommandsLogger, type RegisterCommand, type RegisterCommandCollection } from './register-commands';
30
34
  import { observeRegister$, readRegister, type RegisterBucket, type RegisterDocument, type RegisterHost } from './register-document';
31
35
  import type { CashMovement, Closure, RegisterSession } from './schemas';
@@ -109,11 +113,11 @@ export interface UseRegisterSessionOptions {
109
113
  softwareVersion: string;
110
114
  /** A sale is at tender (`sale.stage.kind === 'tender'`): counting and closing refuse. */
111
115
  tenderInProgress: boolean;
112
- /** The count variance, in minor units, over which the app asks for approval. */
116
+ /** The count variance, in minor units, over which the app asks for approval. The store's `capabilities.registerApproval.thresholdMinor` wins over it (ADR-082). */
113
117
  varianceThreshold?: number;
114
118
  /** `'HH:mm'` on the device's clock; an open session after it is `overdue`. */
115
119
  expectedCloseTime?: string;
116
- /** The cashier may not see expected figures while counting. */
120
+ /** The cashier may not see expected figures while counting: pass `useCashier(connector, context).blind` (no `viewReports`). */
117
121
  blind?: boolean;
118
122
  /** The closure's register name, and a person id's display name. */
119
123
  labels?: { registerName?: string; resolveCashierName?: (id: string) => string };
@@ -123,9 +127,41 @@ type Reservation = RegisterBucket['closure_reservation'];
123
127
  type Snapshot = {
124
128
  rows: RegisterSession[]; closureRows: Closure[]; reservation: Reservation;
125
129
  entries: CashMovement[]; sales: PosOrder[]; refundRows: PosRefund[];
126
- open?: RegisterCommand;
130
+ /** The register's open and closure command rows (ADR-082 d4, d7, d9). */
131
+ commandRows: RegisterCommand[];
127
132
  };
128
133
 
134
+ /** ADR-082 d7: a closure the store refused with either approval code, for the app's "Manager approval needed again" card. */
135
+ export interface ApprovalNeeded {
136
+ closureId: string; sessionId: string;
137
+ /** The variance to send to the approval route: the refusal's, else counted minus tillExpected from the row. */
138
+ variance: Record<string, number>;
139
+ code: 'register_approval_required' | 'register_approval_invalid';
140
+ reason?: string;
141
+ /** `isLiveAtStore` for the refused closure's session: the approval route can be used for it. */
142
+ liveAtStore: boolean;
143
+ }
144
+
145
+ const isTenderMap = (value: unknown): value is Record<string, number> => typeof value === 'object' && value !== null
146
+ && !Array.isArray(value) && Object.values(value).every((figure) => typeof figure === 'number');
147
+
148
+ /** The lowest-`seq` closure row refused with either approval code; the outbox holds every later closure behind it. */
149
+ function approvalNeededOf(commandRows: readonly RegisterCommand[], sessions: readonly RegisterSession[]): ApprovalNeeded | null {
150
+ const row = commandRows.filter((command) => command.type === 'register.closure.submit' && command.syncStatus === 'rejected'
151
+ && CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? '')).sort((a, b) => a.seq - b.seq)[0];
152
+ if (!row) return null;
153
+ const { closureId, sessionId, counted, tillExpected } = row.payload as { closureId: string; sessionId: string; counted?: unknown; tillExpected?: unknown };
154
+ const data = row.error?.data;
155
+ return {
156
+ closureId, sessionId, code: row.error!.code as ApprovalNeeded['code'],
157
+ variance: isTenderMap(data?.variance) ? data.variance
158
+ : closureVariance(isTenderMap(counted) ? counted : {}, isTenderMap(tillExpected) ? tillExpected : {}),
159
+ ...(typeof data?.reason === 'string' ? { reason: data.reason } : {}),
160
+ liveAtStore: isLiveAtStore(sessions.find((session) => session.id === sessionId),
161
+ commandRows.find((command) => command.key === `session.open:${sessionId}`)),
162
+ };
163
+ }
164
+
129
165
  const reservationOf = (register: RegisterDocument | null, storeKey: string, registerId: string) =>
130
166
  register?.stores[storeKey]?.registers?.[registerId]?.closure_reservation;
131
167
 
@@ -155,9 +191,17 @@ function ledgerRows(orders: readonly PosOrder[], replaced = replacedOrderIds(ord
155
191
  })));
156
192
  }
157
193
 
194
+ /** The closure's counted map, as `closeSession` hands it to `writeClosure`: cash is always present. */
195
+ const closedCount = (counted: Record<string, number>) => ({ ...counted, cash: counted.cash ?? 0 });
196
+ /** The store's match (ADR-082 d5): the same keys, and each the same figure. */
197
+ const sameVariance = (a: Record<string, number>, b: Record<string, number>) =>
198
+ Object.keys(a).length === Object.keys(b).length && Object.entries(b).every(([method, value]) => a[method] === value);
199
+
158
200
  export function useRegisterSession(options: UseRegisterSessionOptions) {
159
201
  const { sessions, movements, closures, orders, register, storeKey, registerId, enabled, actor, timezone, tenderInProgress, expectedCloseTime, labels } = options;
160
202
  const { commands, refunds } = options;
203
+ // ADR-082 d3: the store's threshold wins over the app's; the gate and RegisterCount use this one.
204
+ const varianceThreshold = options.capabilities?.registerApproval?.thresholdMinor ?? options.varianceThreshold;
161
205
  const commandEnabled = (options.capabilities?.register ?? 0) >= 1;
162
206
  const commandTarget = useMemo(() => enabled && commandEnabled && commands && sessions && movements && closures && register && registerId
163
207
  ? { commands, sessions, movements, closures, host: register, storeKey, registerId, registerContract: options.capabilities?.register, deviceName: options.deviceName } : null,
@@ -169,7 +213,7 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
169
213
  if (!target) return;
170
214
  void reconcileRegisterCommands({ ...target, observed: row ? [row] : undefined }).catch((error: unknown) => {
171
215
  try {
172
- registerCommandsLogger.error('Register command reconcile failed', { context: { registerId: target.registerId, error: String(error) } });
216
+ registerCommandsLogger.error('Register command reconcile failed', { context: { registerId: target.registerId, error: safeErrorString(error) } });
173
217
  } catch {
174
218
  // A failing log sink must not affect a register action either.
175
219
  }
@@ -189,15 +233,17 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
189
233
  watchFresh(sessions, { selector: { register_id: registerId } }),
190
234
  watchFresh(closures, { selector: { register_id: registerId } }),
191
235
  observeRegister$(register).pipe(map((document) => reservationOf(document, storeKey, registerId))),
192
- ]).pipe(switchMap(([rows, closureRows, reservation]) => {
236
+ commandTarget ? watchFresh(commandTarget.commands, { selector: {
237
+ registerId, type: { $in: ['register.session.open', 'register.closure.submit'] },
238
+ } }) : of([] as RegisterCommand[]),
239
+ ]).pipe(switchMap(([rows, closureRows, reservation, commandRows]) => {
193
240
  const current = currentSession(rows, closureRows, reservation);
194
- if (!current) return of({ rows, closureRows, reservation, entries: [], sales: [], refundRows: [] } as Snapshot);
241
+ if (!current) return of({ rows, closureRows, reservation, entries: [], sales: [], refundRows: [], commandRows } as Snapshot);
195
242
  return combineLatest([
196
243
  watchFresh(movements, { selector: { session_id: current.id } }),
197
244
  watchFresh(orders, { selector: { sessionId: current.id } }),
198
- commandTarget ? watchFresh(commandTarget.commands, { selector: { key: `session.open:${current.id}` } }) : of([]),
199
245
  refunds ? watchFresh(refunds, { selector: { sessionId: current.id } }) : of([]),
200
- ]).pipe(map(([entries, sales, opens, refundRows]) => ({ rows, closureRows, reservation, entries, sales, open: opens[0], refundRows })));
246
+ ]).pipe(map(([entries, sales, refundRows]) => ({ rows, closureRows, reservation, entries, sales, refundRows, commandRows })));
201
247
  }));
202
248
  }, [enabled, sessions, movements, closures, orders, register, storeKey, registerId, commandTarget, refunds]);
203
249
  // A latest-value ref: an `actions` object from an earlier render still sees the current flag.
@@ -269,11 +315,13 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
269
315
  }
270
316
  }, [data, source]);
271
317
  const session = data ? currentSession(data.rows, data.closureRows, data.reservation) : null;
272
- const refusal = data?.open?.error?.data as RegisterSessionAlreadyOpenData | undefined;
318
+ const commandRows = data?.commandRows ?? [];
319
+ const open = session ? commandRows.find((row) => row.key === `session.open:${session.id}`) : undefined;
320
+ const refusal = open?.error?.data as RegisterSessionAlreadyOpenData | undefined;
273
321
  const conflict = session?.status !== 'conflict' || !commandTarget ? undefined
274
- : data?.open?.syncStatus === 'pending' && typeof data.open.payload.supersedes === 'string'
275
- ? { sessionId: data.open.payload.supersedes, takingOver: true }
276
- : data?.open?.syncStatus === 'rejected' && refusal
322
+ : open?.syncStatus === 'pending' && typeof open.payload.supersedes === 'string'
323
+ ? { sessionId: open.payload.supersedes, takingOver: true }
324
+ : open?.syncStatus === 'rejected' && refusal
277
325
  ? { sessionId: refusal.sessionId, openedAt: refusal.openedAt, openedBy: refusal.openedBy, deviceName: refusal.deviceName, takingOver: false } : undefined;
278
326
  const entries = data?.entries ?? [];
279
327
  const sales = data?.sales ?? [];
@@ -300,6 +348,16 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
300
348
  if (!session) throw new RegisterSessionRequiredError();
301
349
  return session;
302
350
  };
351
+ // As `writeClosure` derives the Z's expected figures, from the same rows, past the query cache.
352
+ const freshExpected = async (row: RegisterSession) => {
353
+ const { movements, orders, refunds } = live();
354
+ return deriveExpected({
355
+ session: { id: row.id, countedFloatMinor: row.counted_float_minor },
356
+ movements: await readFresh(movements, { selector: { session_id: row.id } }),
357
+ ledgerRowsBySession: ledgerRows(await readFresh(orders, { selector: { sessionId: row.id } })),
358
+ refunds: refunds ? await readFresh(refunds, { selector: { sessionId: row.id } }) : undefined,
359
+ });
360
+ };
303
361
  const refuseDuringTender = () => {
304
362
  if (tender.current) throw new RegisterTenderInProgressError();
305
363
  };
@@ -320,7 +378,14 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
320
378
  lastClosure: [...(data?.closureRows ?? [])].sort((a, b) => b.closed_at.localeCompare(a.closed_at))[0] ?? null,
321
379
  lastClosed: (data?.rows ?? []).filter((row) => row.status === 'closed')
322
380
  .sort((a, b) => (b.closed_at_gmt ?? '').localeCompare(a.closed_at_gmt ?? ''))[0] ?? null,
323
- varianceThreshold: options.varianceThreshold,
381
+ varianceThreshold,
382
+ /** ADR-082 d4: the store holds the current session (`isLiveAtStore`), so the app's approval route can be used. */
383
+ liveAtStore: isLiveAtStore(session, open),
384
+ /** ADR-082 d7: a closure the store refused with either approval code, or `null`; recover it with `actions.reapproveClosure`. */
385
+ approvalNeeded: approvalNeededOf(commandRows, data?.rows ?? []),
386
+ /** ADR-082 d9: each listed closure's approval status by closure id; show `unverified` beside the approver's name. */
387
+ closureApprovalStatus: Object.fromEntries((data?.closureRows ?? []).map((closure) => [closure.id, closureApprovalStatus(closure,
388
+ commandRows.find((row) => row.key === `closure.submit:${closure.id}`), options.capabilities)])) as Record<string, ClosureApprovalStatus>,
324
389
  enabled,
325
390
  blind: options.blind ?? false,
326
391
  /** Pass straight to useSale's `session` option: `complete()` then stamps through `stampSession`. */
@@ -346,6 +411,11 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
346
411
  if (row?.status !== 'conflict') throw new RegisterSessionRequiredError();
347
412
  await abandonSession({ ...commandTarget, sessionId: row.id });
348
413
  },
414
+ /** ADR-082 d7: sends `approvalNeeded`'s closure again with a new proof and approver; `RegisterReapproveError` unless it is refused with either approval code at contract 3. */
415
+ reapproveClosure: async (input: { closureId: string; approval: string; approvedBy: string }) => {
416
+ if (!commandTarget) throw new RegisterSessionRequiredError();
417
+ await reapproveClosure({ ...input, commands: commandTarget.commands, registerContract: options.capabilities?.register });
418
+ },
349
419
  /**
350
420
  * Refuses with `RegisterSessionAlreadyOpenError` while the register has a live session or
351
421
  * another open is running (in any hook instance), and with `RegisterCloseIncompleteError`
@@ -414,13 +484,18 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
414
484
  * `counted` maps each tender to its counted minor units. An interrupted close resumes with
415
485
  * the count persisted on the session, not the one passed to the retry (WCPOS uses the retry's).
416
486
  * Over `varianceThreshold` (`closeNeedsApproval`, as `RegisterCount`), a close without
417
- * `approvedBy` throws `RegisterApprovalRequiredError` before any write, blind or not; a
487
+ * `approvedBy` throws `RegisterApprovalRequiredError` before any write, blind or not; so does one without
488
+ * `approval` at contract 3 with the store's `registerApproval` while the session is `liveAtStore` (ADR-082 d5); a
418
489
  * resumed close (the stored session already closed) isn't gated again. `approvedBy` reaches the Z
419
490
  * (`breakdowns.approved_by`), and `approvedByName` its `approved_by_name`.
491
+ * `approval` is the store's opaque proof (ADR-082): it goes to the session's
492
+ * `approver_token` and from there only onto a version 3 closure command, never onto the Z, a fact or a log. With
493
+ * `approvedVariance` (the variance the app sent to its approval route), a close whose `closureVariance` differs
494
+ * throws `RegisterApprovalRequiredError` before any write. A resumed close checks neither.
420
495
  * One close per register runs at a time, in any hook instance: a call while one is in flight joins
421
496
  * it, getting its closure or error, and its own `counted`, `approvedBy` and `approvedByName` are ignored.
422
497
  */
423
- closeSession: async (input: { counted: Record<string, number>; approvedBy?: string; approvedByName?: string }) => {
498
+ closeSession: async (input: { counted: Record<string, number>; approvedBy?: string; approvedByName?: string; approval?: string; approvedVariance?: Record<string, number> }) => {
424
499
  refuseDuringTender();
425
500
  const key = registerId ?? '';
426
501
  if (closingByRegister.has(key)) return closingByRegister.get(key)!;
@@ -431,19 +506,22 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
431
506
  // render's snapshot, which can lag a sale or a close that already landed (#168 review).
432
507
  const stored = await store.readSession(sessions, open.id);
433
508
  if (!stored) throw new RegisterSessionRequiredError();
434
- if (stored.status !== 'closed' && !input.approvedBy) {
435
- // As `writeClosure` derives the Z's expected figures, from the same rows.
436
- const fresh = deriveExpected({
437
- session: { id: stored.id, countedFloatMinor: stored.counted_float_minor },
438
- movements: await readFresh(movements, { selector: { session_id: stored.id } }),
439
- ledgerRowsBySession: ledgerRows(await readFresh(orders, { selector: { sessionId: stored.id } })),
440
- refunds: refunds ? await readFresh(refunds, { selector: { sessionId: stored.id } }) : undefined,
441
- });
442
- if (closeNeedsApproval(input.counted.cash ?? 0, fresh.cash ?? 0, options.varianceThreshold)) throw new RegisterApprovalRequiredError();
509
+ // ADR-082 d5: at contract 3 with the store's threshold, a close without the store's proof may still need one.
510
+ const proofChecked = (options.capabilities?.register ?? 0) >= 3 && options.capabilities?.registerApproval != null && !input.approval;
511
+ if (stored.status !== 'closed' && (!input.approvedBy || input.approvedVariance || proofChecked)) {
512
+ const fresh = await freshExpected(stored);
513
+ const over = closeNeedsApproval(input.counted.cash ?? 0, fresh.cash ?? 0, varianceThreshold);
514
+ if (over && !input.approvedBy) throw new RegisterApprovalRequiredError();
515
+ // Live at the store, the route can be used, so `approvedBy` alone is not enough. Offline, or before the store
516
+ // applies the open, it closes with `approvedBy` and the store's refusal is recovered later (decision 7).
517
+ if (over && proofChecked && commandTarget && isLiveAtStore(stored,
518
+ (await readFresh(commandTarget.commands, { selector: { key: `session.open:${stored.id}` } }))[0])) throw new RegisterApprovalRequiredError();
519
+ // ADR-082 d5: a sale or a movement since the approval moved the variance the proof is bound to; ask again.
520
+ if (input.approvedVariance && !sameVariance(input.approvedVariance, closureVariance(closedCount(input.counted), fresh))) throw new RegisterApprovalRequiredError();
443
521
  }
444
522
  // By id, not `open` (plain data): `store.closeSession`'s guard runs again inside
445
523
  // `incrementalModify` on the stored document, so a close that already landed keeps its count, time, actor and approver.
446
- const closed = await store.closeSession(sessions, open.id, { counted: input.counted, closedBy: actor.id, approvedBy: input.approvedBy, timezone });
524
+ const closed = await store.closeSession(sessions, open.id, { counted: input.counted, closedBy: actor.id, approvedBy: input.approvedBy, approval: input.approval, timezone });
447
525
  // The session stores no approver name, so a close resumed without this call's name (after
448
526
  // a restart, say) falls back to `nameOf`.
449
527
  const approvedByName = (input.approvedBy && closed.approved_by === input.approvedBy && input.approvedByName) || nameOf(closed.approved_by);
@@ -487,6 +565,12 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
487
565
  reconcile();
488
566
  }
489
567
  },
568
+ /** ADR-082 d3: the variance this count would close with, read as the gate reads it; the app sends it to its approval route and back as `approvedVariance`. */
569
+ closureVariance: async (counted: Record<string, number>) => {
570
+ const stored = await store.readSession(live().sessions, current().id);
571
+ if (!stored) throw new RegisterSessionRequiredError();
572
+ return closureVariance(closedCount(counted), await freshExpected(stored));
573
+ },
490
574
  recordMovement: async (input: { type: 'paid_in' | 'paid_out' | 'no_sale'; amountMinor: number; reason: string }) => {
491
575
  try {
492
576
  // `live()` first: missing collections or host refuse before `requireOpen` writes anything.