@tallyui/pos 3.12.0 → 3.14.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 (89) hide show
  1. package/dist/index.d.ts +1844 -359
  2. package/dist/index.js +4620 -2211
  3. package/package.json +12 -6
  4. package/src/app-settings/app-settings.ts +108 -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-link.ts +72 -0
  13. package/src/customer-display/display-state.ts +30 -0
  14. package/src/customer-display/index.ts +13 -0
  15. package/src/customer-display/protocol.ts +87 -0
  16. package/src/customer-display/snapshot.ts +65 -0
  17. package/src/customer-display/transport.ts +54 -0
  18. package/src/customer-display/use-customer-display.ts +36 -0
  19. package/src/index.ts +73 -10
  20. package/src/order/order-builder.ts +11 -1
  21. package/src/order/order-drafts.ts +16 -0
  22. package/src/order/types.ts +6 -3
  23. package/src/outbox/index.ts +5 -1
  24. package/src/outbox/outbox-health.ts +40 -0
  25. package/src/outbox/register-outbox.ts +59 -6
  26. package/src/outbox/safe-error.ts +11 -0
  27. package/src/outbox/types.ts +3 -1
  28. package/src/outbox/use-outbox-health.ts +22 -0
  29. package/src/outbox/use-register-outbox.ts +6 -0
  30. package/src/payment-driver/index.ts +8 -0
  31. package/src/payment-driver/registry.ts +39 -0
  32. package/src/payment-driver/simulated-driver.ts +104 -0
  33. package/src/payment-driver/types.ts +73 -0
  34. package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
  35. package/src/pos-order/command.ts +36 -16
  36. package/src/pos-order/finalize.ts +7 -3
  37. package/src/pos-order/index.ts +1 -0
  38. package/src/pos-order/note-delivery.ts +13 -0
  39. package/src/pos-order/reopen.ts +3 -2
  40. package/src/pos-order/schema.ts +5 -4
  41. package/src/pos-order/types.ts +3 -2
  42. package/src/print/escpos/code-page.ts +48 -0
  43. package/src/print/escpos/commands.ts +53 -0
  44. package/src/print/escpos/encode.ts +127 -0
  45. package/src/print/escpos/index.ts +7 -0
  46. package/src/print/escpos/transport.ts +45 -0
  47. package/src/print/index.ts +12 -0
  48. package/src/print/print-queue.ts +67 -0
  49. package/src/print/printer-profiles.ts +71 -0
  50. package/src/print/system-transport.ts +101 -0
  51. package/src/print/types.ts +44 -0
  52. package/src/receipt/reprint.ts +2 -1
  53. package/src/receipt/types.ts +2 -0
  54. package/src/receipt-template/default-templates.ts +78 -0
  55. package/src/receipt-template/index.ts +15 -0
  56. package/src/receipt-template/parse-xml.ts +175 -0
  57. package/src/receipt-template/render-html.ts +152 -0
  58. package/src/receipt-template/render-receipt.ts +19 -0
  59. package/src/receipt-template/render-template.ts +35 -0
  60. package/src/receipt-template/sanitize-html.ts +146 -0
  61. package/src/receipt-template/template-data.ts +97 -0
  62. package/src/receipt-template/types.ts +49 -0
  63. package/src/refund/index.ts +2 -0
  64. package/src/refund/refundable-lines.ts +91 -0
  65. package/src/register/export-csv.ts +24 -35
  66. package/src/register/float-suggestion.ts +22 -0
  67. package/src/register/handover.ts +103 -0
  68. package/src/register/index.ts +10 -3
  69. package/src/register/register-adoption.ts +71 -2
  70. package/src/register/register-commands.ts +7 -4
  71. package/src/register/register-count.helpers.ts +4 -0
  72. package/src/register/session-store.ts +4 -1
  73. package/src/register/use-register-session.ts +112 -28
  74. package/src/reports/adapters.ts +67 -0
  75. package/src/reports/index.ts +5 -0
  76. package/src/reports/presets.ts +27 -0
  77. package/src/reports/sales-figures.ts +187 -0
  78. package/src/reports/types.ts +63 -0
  79. package/src/sale/in-cart.ts +18 -0
  80. package/src/sale/index.ts +5 -1
  81. package/src/sale/open-sales.ts +40 -0
  82. package/src/sale/use-sale.ts +72 -8
  83. package/src/scanner/index.ts +6 -0
  84. package/src/scanner/scan-session.ts +84 -0
  85. package/src/scanner/use-barcode-scanner.ts +61 -0
  86. package/src/scanner/wedge-detector.ts +137 -0
  87. package/src/tender/cash-rounding.ts +74 -0
  88. package/src/tender/index.ts +4 -0
  89. package/src/tender/payment-legs.ts +48 -0
@@ -1,3 +1,5 @@
1
1
  export { sendOrderRefund, type OrderRefundOutcome } from './send-order-refund';
2
2
  export { posRefundSchema, posRefundCollection, type PosRefund, type PosRefundStatus, type PosRefundCollection } from './pos-refund';
3
3
  export { submitOrderRefund, RefundAnswerPendingError } from './submit-order-refund';
4
+ export { refundableLines, priceRefund } from './refundable-lines';
5
+ export type { RefundableOrderLine, EarlierRefund, RefundableLine, PricedRefundLine, PricedRefund } from './refundable-lines';
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Ports v2 calculate-refund.ts (calculateLineItemRefund, computeRemainingRefundQuantity).
3
+ * Amounts follow ADR-080 amendment 2's cumulative-share rule.
4
+ */
5
+ import type { StoreOrderLine, OrderRefundLine } from '@tallyui/core';
6
+ import { roundRatio } from '../tax/exact';
7
+
8
+ /** The fields of an order line this needs; a StoreOrderLine fits. */
9
+ export type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
10
+ /** Earlier refund lines; negative quantities count by magnitude. */
11
+ export interface EarlierRefund { lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>> }
12
+
13
+ /** Remaining quantities and amounts, with earlier refund magnitudes capped at the line quantity. */
14
+ export interface RefundableLine {
15
+ orderLineId: string;
16
+ refundedQuantity: number;
17
+ refundableQuantity: number;
18
+ netMinor: number;
19
+ taxMinor: number;
20
+ }
21
+
22
+ /** A selected quantity's cumulative shares of net and tax, and their sum. */
23
+ export interface PricedRefundLine {
24
+ orderLineId: string; quantity: number; netMinor: number; taxMinor: number;
25
+ totalMinor: number;
26
+ }
27
+
28
+ /** Payload-ready lines and their amounts; the caller adds shipping and adjustment to totalMinor. */
29
+ export interface PricedRefund {
30
+ /** Exactly orderLineId, quantity (>= 1), and restock. */
31
+ lines: OrderRefundLine[];
32
+ /** Amounts in the same order as lines. */
33
+ priced: PricedRefundLine[];
34
+ /** Requests cut to availability, including unknown lines cut to zero. */
35
+ clamped: Array<{ orderLineId: string; requestedQuantity: number; quantity: number }>;
36
+ netMinor: number; taxMinor: number; totalMinor: number;
37
+ }
38
+
39
+ /** Returns the quantities and amounts still refundable, in order-line order. */
40
+ export function refundableLines(
41
+ lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[],
42
+ ): RefundableLine[] {
43
+ const earlier = refunds.flatMap((refund) => refund.lines);
44
+ for (const refund of earlier) {
45
+ if (!Number.isSafeInteger(refund.quantity)) throw new RangeError('Earlier refund quantity must be a safe integer');
46
+ }
47
+ return lines.map((line) => {
48
+ if (!Number.isSafeInteger(line.quantity) || line.quantity < 0
49
+ || !Number.isSafeInteger(line.totalMinor) || !Number.isSafeInteger(line.taxMinor)) {
50
+ throw new RangeError('Order line values must be safe integers and quantity non-negative');
51
+ }
52
+ const refundedQuantity = earlier.reduce((sum, refund) => refund.orderLineId === line.id
53
+ ? Math.min(line.quantity, sum + Math.abs(refund.quantity)) : sum, 0);
54
+ const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) => line.quantity === 0 ? 0
55
+ : total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
56
+ return {
57
+ orderLineId: line.id, refundedQuantity, refundableQuantity: line.quantity - refundedQuantity, netMinor, taxMinor,
58
+ };
59
+ });
60
+ }
61
+
62
+ /** Prices requested quantities with cumulative shares, clamping them to what remains refundable. */
63
+ export function priceRefund(
64
+ lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[], request: readonly OrderRefundLine[],
65
+ ): PricedRefund {
66
+ const available = refundableLines(lines, refunds);
67
+ const seen = new Set<string>();
68
+ const result: PricedRefund = { lines: [], priced: [], clamped: [], netMinor: 0, taxMinor: 0, totalMinor: 0 };
69
+ for (const { orderLineId, quantity: requestedQuantity, restock } of request) {
70
+ if (!Number.isSafeInteger(requestedQuantity) || requestedQuantity < 0 || seen.has(orderLineId)) {
71
+ throw new RangeError('Request quantities must be non-negative safe integers and line ids unique');
72
+ }
73
+ seen.add(orderLineId);
74
+ const index = lines.findIndex((line) => line.id === orderLineId);
75
+ const quantity = Math.min(requestedQuantity, available[index]?.refundableQuantity ?? 0);
76
+ if (quantity < requestedQuantity) result.clamped.push({ orderLineId, requestedQuantity, quantity });
77
+ if (quantity < 1) continue;
78
+ const line = lines[index];
79
+ const refundedQuantity = available[index].refundedQuantity;
80
+ const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) =>
81
+ Number(roundRatio(BigInt(refundedQuantity + quantity) * BigInt(total), BigInt(line.quantity), 'half_up'))
82
+ - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
83
+ const totalMinor = netMinor + taxMinor;
84
+ result.lines.push({ orderLineId, quantity, restock });
85
+ result.priced.push({ orderLineId, quantity, netMinor, taxMinor, totalMinor });
86
+ result.netMinor += netMinor;
87
+ result.taxMinor += taxMinor;
88
+ result.totalMinor += totalMinor;
89
+ }
90
+ return result;
91
+ }
@@ -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
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * What a cashier switch, a register switch or a sign-out leaves behind, and the hand-over slip (v2 parity A4, A12).
3
+ * Port provenance: WCPOS v2 monorepo `main` 51e7c4351, `packages/core/src/screens/main/pos/cart/switch-confirm.tsx`
4
+ * (the warnings it shows) and `services/register-session/use-session-report.ts:26-65` with
5
+ * `closure-document.ts:206-273` (the slip is the open session's X report, marked as a hand-over, naming the cashier).
6
+ */
7
+ import type { Cashier } from '@tallyui/core';
8
+ import type { OutboxHealth } from '../outbox/outbox-health';
9
+ import { buildXReportDocument, type ClosureContext } from './closure-document';
10
+ import type { RegisterSession } from './schemas';
11
+
12
+ export type SwitchKind = 'cashier' | 'register' | 'signOut';
13
+ export type SwitchWarning =
14
+ | { code: 'unsentSales'; count: number }
15
+ | { code: 'unsentTillUpdates'; count: number }
16
+ | { code: 'parkedSales'; count: number }
17
+ | { code: 'partlyPaidSale' }
18
+ | { code: 'openSession' };
19
+ export interface SwitchWarningInput {
20
+ kind: SwitchKind;
21
+ /** `summarizeOutboxHealth`'s result (or `useOutboxHealth().health`). */
22
+ outbox: Pick<OutboxHealth, 'sales' | 'tillUpdates'>;
23
+ /** `useParkedSales(...).parked.length`. */
24
+ parkedSales: number;
25
+ /** Captured minor units on the sale in progress; 0 when nothing is paid. */
26
+ paidMinor: number;
27
+ /** The bound register's session status; `null` or absent when no session. */
28
+ sessionStatus?: RegisterSession['status'] | null;
29
+ }
30
+ export interface SwitchWarnings {
31
+ kind: SwitchKind;
32
+ /** In this order: unsentSales, unsentTillUpdates, parkedSales, partlyPaidSale, openSession; only those that apply. */
33
+ warnings: SwitchWarning[];
34
+ /** `outbox.sales.pending`: the confirm wording reads it. */
35
+ unsentSales: number;
36
+ /** An `open` or `counting` session, for `register` and `signOut` only (a cashier switch keeps the drawer open by design). */
37
+ sessionOpen: boolean;
38
+ }
39
+
40
+ /** What the switch would leave behind. Pure. */
41
+ export function switchWarnings({ kind, outbox, parkedSales, paidMinor, sessionStatus }: SwitchWarningInput): SwitchWarnings {
42
+ const unsentSales = outbox.sales.pending;
43
+ const sessionOpen = kind !== 'cashier' && (sessionStatus === 'open' || sessionStatus === 'counting');
44
+ const warnings: SwitchWarning[] = [];
45
+ if (unsentSales > 0) warnings.push({ code: 'unsentSales', count: unsentSales });
46
+ if (outbox.tillUpdates.pending > 0) warnings.push({ code: 'unsentTillUpdates', count: outbox.tillUpdates.pending });
47
+ if (parkedSales > 0) warnings.push({ code: 'parkedSales', count: parkedSales });
48
+ if (paidMinor > 0) warnings.push({ code: 'partlyPaidSale' });
49
+ if (sessionOpen) warnings.push({ code: 'openSession' });
50
+ return { kind, warnings, unsentSales, sessionOpen };
51
+ }
52
+
53
+ export interface HandoverSlipInput {
54
+ session: RegisterSession;
55
+ /** The cashier handing over. */
56
+ cashier: Pick<Cashier, 'name'>;
57
+ registerName: string;
58
+ /** Who opened the session; '' when unknown. */
59
+ openedByName?: string;
60
+ /** `useRegisterSession().salesCount`. */
61
+ salesCount: number;
62
+ /** `useRegisterSession().expected`, minor units per tender. */
63
+ expected: Record<string, number>;
64
+ /** `useRegisterSession().blind`: no expected figures on the slip. */
65
+ blind: boolean;
66
+ outbox: Pick<OutboxHealth, 'sales' | 'tillUpdates'>;
67
+ context: ClosureContext;
68
+ }
69
+ type XReportDocument = ReturnType<typeof buildXReportDocument>;
70
+ export interface HandoverSlipData {
71
+ registerName: string;
72
+ cashierName: string;
73
+ openedByName: string;
74
+ /** `document.closure.opened_at.time`. */
75
+ openedAtTime: string;
76
+ salesCount: number;
77
+ /** `null` while blind. */
78
+ expected: Record<string, number> | null;
79
+ unsentSales: number;
80
+ unsentTillUpdates: number;
81
+ /** The X-report envelope for the closure template and the print queue (`kind: 'report'`), marked as a hand-over. */
82
+ document: XReportDocument & { fiscal: XReportDocument['fiscal'] & { document_type: 'handover'; is_handover: true } };
83
+ }
84
+
85
+ /** The hand-over slip's data and its printable envelope. Pure. */
86
+ export function handoverSlip({
87
+ session, cashier, registerName, openedByName = '', salesCount, expected, blind, outbox, context,
88
+ }: HandoverSlipInput): HandoverSlipData {
89
+ const doc = buildXReportDocument(session, {
90
+ ...context,
91
+ expected: blind ? {} : expected,
92
+ breakdowns: {
93
+ ...context.breakdowns, register_name: registerName, cashier_name: cashier.name, opened_by_name: openedByName,
94
+ transaction_count: salesCount,
95
+ },
96
+ });
97
+ return {
98
+ registerName, cashierName: cashier.name, openedByName, openedAtTime: doc.closure.opened_at.time ?? '', salesCount,
99
+ expected: blind ? null : expected,
100
+ unsentSales: outbox.sales.pending, unsentTillUpdates: outbox.tillUpdates.pending,
101
+ document: { ...doc, fiscal: { ...doc.fiscal, document_type: 'handover', is_handover: true } },
102
+ };
103
+ }
@@ -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,12 @@ 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';
40
+ export { switchWarnings, handoverSlip } from './handover';
41
+ export type { SwitchKind, SwitchWarning, SwitchWarningInput, SwitchWarnings, HandoverSlipInput, HandoverSlipData } from './handover';
@@ -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
  }