@tallyui/pos 3.20.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/index.d.ts +1005 -110
  2. package/dist/index.js +3156 -907
  3. package/package.json +6 -6
  4. package/src/app-settings/app-settings.ts +77 -0
  5. package/src/app-settings/index.ts +2 -0
  6. package/src/currency/currency-provider.tsx +5 -7
  7. package/src/currency/index.ts +1 -1
  8. package/src/customer/customer-patch.ts +70 -0
  9. package/src/customer-display/display-client.ts +11 -17
  10. package/src/customer-display/display-link.ts +10 -5
  11. package/src/customer-display/index.ts +3 -1
  12. package/src/customer-display/protocol.ts +1 -1
  13. package/src/customer-display/sale-display.ts +6 -8
  14. package/src/customer-display/snapshot-fallback.ts +14 -1
  15. package/src/customer-display/till-device.ts +62 -0
  16. package/src/customer-display/till-display-service.ts +44 -42
  17. package/src/customer-display/till-pairing.ts +20 -23
  18. package/src/customer-display/use-customer-display.ts +2 -1
  19. package/src/customer-display/use-till-pairing.ts +4 -4
  20. package/src/index.ts +37 -18
  21. package/src/order/allocate-order-discount.ts +5 -17
  22. package/src/order/apportion.ts +29 -0
  23. package/src/order/from-store-order.ts +115 -0
  24. package/src/order/index.ts +1 -0
  25. package/src/order/order-builder.ts +239 -52
  26. package/src/order/order-drafts.ts +45 -6
  27. package/src/order/order-manager.ts +2 -1
  28. package/src/order/tax-ids.ts +27 -0
  29. package/src/order/types.ts +59 -5
  30. package/src/order/woocommerce-tax.ts +9 -0
  31. package/src/outbox/index.ts +1 -1
  32. package/src/outbox/order-outbox.ts +138 -43
  33. package/src/outbox/register-outbox.ts +4 -3
  34. package/src/outbox/retry-delay.ts +8 -0
  35. package/src/outbox/use-order-outbox.ts +8 -2
  36. package/src/pos-order/__fixtures__/order-create-v10.json +97 -0
  37. package/src/pos-order/__fixtures__/order-create-v11.json +90 -0
  38. package/src/pos-order/__fixtures__/order-create-v12.json +95 -0
  39. package/src/pos-order/__fixtures__/order-create-v9.json +89 -0
  40. package/src/pos-order/attention-handled.ts +24 -0
  41. package/src/pos-order/command.ts +132 -12
  42. package/src/pos-order/extras-delivery.ts +14 -0
  43. package/src/pos-order/finalize.ts +138 -29
  44. package/src/pos-order/index.ts +7 -3
  45. package/src/pos-order/money-divergence.ts +19 -0
  46. package/src/pos-order/needs-attention.ts +9 -1
  47. package/src/pos-order/refund-due.ts +35 -0
  48. package/src/pos-order/reopen.ts +96 -12
  49. package/src/pos-order/schema.ts +35 -10
  50. package/src/pos-order/till-payments.ts +4 -0
  51. package/src/pos-order/types.ts +44 -5
  52. package/src/print/escpos/__fixtures__/thermal-every-node.xml +33 -0
  53. package/src/print/escpos/commands.ts +79 -0
  54. package/src/print/escpos/drawer.ts +25 -0
  55. package/src/print/escpos/encode.ts +1 -0
  56. package/src/print/escpos/index.ts +6 -1
  57. package/src/print/escpos/network-sinks.ts +130 -0
  58. package/src/print/escpos/render-escpos.ts +155 -0
  59. package/src/print/escpos/transport.ts +2 -1
  60. package/src/print/index.ts +5 -2
  61. package/src/print/resolve-printer.ts +46 -0
  62. package/src/print/types.ts +1 -1
  63. package/src/product/index.ts +2 -0
  64. package/src/product/terms.ts +42 -0
  65. package/src/product/tile-fields.ts +27 -0
  66. package/src/receipt/build-receipt-data.ts +12 -7
  67. package/src/receipt/carried-rows.ts +29 -0
  68. package/src/receipt/index.ts +1 -0
  69. package/src/receipt/reprint.ts +14 -8
  70. package/src/receipt/types.ts +3 -1
  71. package/src/receipt-template/default-templates.ts +3 -0
  72. package/src/receipt-template/template-data.ts +3 -0
  73. package/src/receipt-template/wcpos/build.ts +1 -0
  74. package/src/receipt-template/wcpos/format.ts +2 -2
  75. package/src/receipt-template/wcpos/from-orders.ts +6 -2
  76. package/src/receipt-template/wcpos/types.ts +5 -1
  77. package/src/register/closure-document.ts +42 -4
  78. package/src/register/closure-rows.ts +3 -2
  79. package/src/register/document-labels.ts +25 -0
  80. package/src/register/expected.ts +49 -10
  81. package/src/register/index.ts +5 -5
  82. package/src/register/money.ts +23 -0
  83. package/src/register/register-adoption.ts +6 -5
  84. package/src/register/register-commands.ts +4 -3
  85. package/src/register/schemas.ts +11 -3
  86. package/src/register/session-store.ts +44 -23
  87. package/src/register/settled-figures.ts +5 -19
  88. package/src/register/use-register-session.ts +18 -19
  89. package/src/reopen/index.ts +3 -0
  90. package/src/reopen/reopen-entry.ts +48 -0
  91. package/src/reopen/reopen-store-order.ts +78 -0
  92. package/src/reopen/send-order-reopen.ts +61 -0
  93. package/src/reports/adapters.ts +15 -7
  94. package/src/reports/sales-figures.ts +15 -1
  95. package/src/reports/types.ts +2 -0
  96. package/src/sale/cart.ts +4 -2
  97. package/src/sale/index.ts +1 -1
  98. package/src/sale/open-sales.ts +3 -0
  99. package/src/sale/use-sale.ts +388 -83
  100. package/src/sale/woocommerce/coupon-refetch.ts +1 -0
  101. package/src/sale/woocommerce/coupon-source.ts +4 -4
  102. package/src/sale/woocommerce/coupons.ts +6 -0
  103. package/src/sale/woocommerce/discount-codes.ts +1 -6
  104. package/src/scanner/analyze-trace.ts +86 -0
  105. package/src/scanner/device-scanner.ts +57 -0
  106. package/src/scanner/hid-scanner.ts +14 -41
  107. package/src/scanner/index.ts +2 -0
  108. package/src/scanner/serial-scanner.ts +15 -42
  109. package/src/scanner/use-barcode-scanner.ts +107 -5
  110. package/src/scanner/wedge-detector.ts +33 -15
  111. package/src/tax/exact.ts +1 -13
  112. package/src/tax/taxed-lines.ts +26 -0
  113. package/src/tender/index.ts +6 -1
  114. package/src/tender/split-units.ts +109 -0
  115. package/src/tender/tender-figures.ts +114 -0
  116. package/src/tender/tender-state.ts +105 -17
  117. package/src/currency/format-money-with.ts +0 -45
@@ -13,7 +13,9 @@
13
13
  * date-fns/`@date-fns/tz` become `Intl`, following a2's `businessDayOf`; a cashier id stays a2's
14
14
  * string id (not WCPOS's numeric one).
15
15
  */
16
- import { minorToDecimal } from './money';
16
+ import { minorUnitDigits } from '@tallyui/core';
17
+ import { ENGLISH_CLOSURE_LABELS } from './document-labels';
18
+ import { minorToDecimal, formatDecimalMoney } from './money';
17
19
  import type { Closure, RegisterSession } from './schemas';
18
20
 
19
21
  type Values = Record<string, unknown>;
@@ -23,6 +25,8 @@ type Values = Record<string, unknown>;
23
25
  * desk, 2026-09-30). The closure template lives in the apps, so the document carries it ready to print.
24
26
  */
25
27
  export const TAX_ROUNDING_MIXED_NOTE = "This register's sales used more than one tax rounding method. Each sale's tax is as its receipt showed.";
28
+ /** The Z report's line when the session holds a reopened sale: its tax rates are the whole order's (ADR-090 ruling 38). */
29
+ export const TAX_STORE_PAID_NOTE = 'Tax rates include tax on amounts paid earlier in the store.';
26
30
  /** `writeClosure`'s own `breakdowns.movements` shape (session-store.ts): every entry carries at
27
31
  * least a string `id` and `reason`, so callers can read them without a cast. */
28
32
  type BreakdownMovement = Values & { id: string; reason: string };
@@ -47,6 +51,38 @@ export type ClosureContext = {
47
51
  breakdowns?: Values;
48
52
  };
49
53
 
54
+ export type CreateClosureContextOptions = {
55
+ currency: string;
56
+ store: Record<string, unknown>;
57
+ /** Defaults to minorUnitDigits(currency) from @tallyui/core. */
58
+ exponent?: number;
59
+ /** Defaults to the runtime's Intl locale. */
60
+ locale?: string;
61
+ /** Defaults to 'device' (formatClosureDate then uses the runtime's zone). */
62
+ timezone?: string;
63
+ /** Defaults to new Date().toISOString(). */
64
+ printedAt?: string;
65
+ /** Merged over ENGLISH_CLOSURE_LABELS; extra keys pass through to i18n. */
66
+ labels?: Record<string, string>;
67
+ expected?: Record<string, number>;
68
+ breakdowns?: Record<string, unknown>;
69
+ };
70
+
71
+ export function createClosureContext(options: CreateClosureContextOptions): ClosureContext {
72
+ const currency = options.currency.toUpperCase();
73
+ const exponent = options.exponent ?? minorUnitDigits(currency);
74
+ const locale = options.locale ?? new Intl.NumberFormat().resolvedOptions().locale;
75
+ return {
76
+ store: options.store, currency, exponent, locale,
77
+ timezone: options.timezone ?? 'device',
78
+ printedAt: options.printedAt ?? new Date().toISOString(),
79
+ formatMoney: (v) => formatDecimalMoney(v, { currency, exponent, locale }),
80
+ i18n: { ...ENGLISH_CLOSURE_LABELS, ...options.labels },
81
+ ...(options.expected !== undefined ? { expected: options.expected } : {}),
82
+ ...(options.breakdowns !== undefined ? { breakdowns: options.breakdowns } : {}),
83
+ };
84
+ }
85
+
50
86
  const decimalMap = (minor: Record<string, number>, exponent: number): Record<string, string> =>
51
87
  Object.fromEntries(Object.entries(minor).map(([key, value]) => [key, minorToDecimal(value, exponent)]));
52
88
 
@@ -153,14 +189,15 @@ function envelope<R extends Values>(row: R, context: ClosureContext, xreport = f
153
189
  const counted = (row.counted ?? {}) as Record<string, string>;
154
190
  const expected = (row.expected ?? {}) as Record<string, string>;
155
191
  const variances = (row.variance ?? {}) as Record<string, string>;
192
+ const own = <V>(map: Record<string, V>, key: string): V | undefined => (Object.hasOwn(map, key) ? map[key] : undefined);
156
193
  const tenders = [...new Set([...Object.keys(counted), ...Object.keys(expected)])].map((name) => {
157
- const variance = variances[name] ?? '';
158
- const method = Object.values(methods).find((m) => m.method === name) ?? methods[name];
194
+ const variance = own(variances, name) ?? '';
195
+ const method = Object.values(methods).find((m) => m.method === name) ?? own(methods, name);
159
196
  return money(
160
197
  {
161
198
  name,
162
199
  label: method?.name || name.charAt(0).toUpperCase() + name.slice(1),
163
- expected: expected[name] ?? '', counted: counted[name] ?? '', variance,
200
+ expected: own(expected, name) ?? '', counted: own(counted, name) ?? '', variance,
164
201
  has_variance: Number(variance || 0) !== 0,
165
202
  variance_label:
166
203
  variance === '' ? '' : context.i18n[Number(variance) > 0 ? 'over' : Number(variance) < 0 ? 'short' : 'exact'],
@@ -178,6 +215,7 @@ function envelope<R extends Values>(row: R, context: ClosureContext, xreport = f
178
215
  ['payment_methods', 'tax_rates', 'movements'].map((key) => [`has_${key}`, Object.keys((breakdowns[key] as Values) ?? {}).length > 0]),
179
216
  ),
180
217
  ...(breakdowns.tax_rounding_mixed === true ? { tax_rounding_note: TAX_ROUNDING_MIXED_NOTE } : {}),
218
+ ...(breakdowns.tax_includes_store_paid === true ? { tax_store_paid_note: TAX_STORE_PAID_NOTE } : {}),
181
219
  ...money(row, ['period_sales_total', 'period_refunds_total', 'perpetual_sales_total', 'perpetual_refunds_total', 'unsynced_total']),
182
220
  opened_at_gmt: row.opened_at,
183
221
  opened_by: breakdowns.opened_by ?? null,
@@ -45,7 +45,8 @@ export function clampClosureScope(
45
45
  * `business_day` (a legacy or remote row) gets one from `opened_at` in `timezone`, reusing a2's
46
46
  * `businessDayOf` rather than duplicating it. Register and cashier are optional filters; the
47
47
  * store is not — a row's `store_key` must equal `scope.storeKey` (both `null` when neither is
48
- * set), as WCPOS always compared `store_id`.
48
+ * set), as WCPOS always compared `store_id`. A closure with no `store_key` (absent or `null`)
49
+ * counts as this store's (#665), as `register-adoption.ts` does when it renumbers.
49
50
  */
50
51
  export function selectClosureRows(rows: readonly Closure[], scope: ClosureScope, timezone: string) {
51
52
  return rows
@@ -58,7 +59,7 @@ export function selectClosureRows(rows: readonly Closure[], scope: ClosureScope,
58
59
  row.business_day >= scope.from &&
59
60
  row.business_day <= scope.to &&
60
61
  (!scope.registerId || row.register_id === scope.registerId) &&
61
- (row.store_key ?? null) === (scope.storeKey ?? null) &&
62
+ (row.store_key ?? scope.storeKey ?? null) === (scope.storeKey ?? null) &&
62
63
  (scope.cashier === undefined || row.closed_by === scope.cashier),
63
64
  )
64
65
  .sort((a, b) => b.business_day.localeCompare(a.business_day) || b.closed_at.localeCompare(a.closed_at));
@@ -44,3 +44,28 @@ export const labelKeys = {
44
44
  void: 'register.void',
45
45
  copy: 'reports.document.copy',
46
46
  };
47
+
48
+ // The English wording for offline documents, keyed like `ClosureContext.i18n`.
49
+ export const ENGLISH_CLOSURE_LABELS: Record<keyof typeof labelKeys, string> = {
50
+ x_report: 'X report', closure: 'Closure',
51
+ opened: 'Opened', closed: 'Closed',
52
+ approver: 'Approver', opening_float: 'Opening float',
53
+ expected: 'Expected', counted: 'Counted',
54
+ variance: 'Variance', tenders: 'Tenders',
55
+ tender: 'Tender', cash_movements: 'Cash movements',
56
+ time: 'Time', type: 'Type',
57
+ amount: 'Amount', reason: 'Reason',
58
+ sales: 'Sales', period_sales: 'Period sales',
59
+ period_refunds: 'Period refunds', transactions: 'Transactions',
60
+ refunds: 'Refunds', payment_method: 'Payment method',
61
+ cashiers: 'Cashiers', tax_rates: 'Tax rates',
62
+ tax_rate: 'Tax rate', net: 'Net',
63
+ tax: 'Tax', gross: 'Gross',
64
+ perpetual_totals: 'Perpetual totals', perpetual_sales: 'Perpetual sales',
65
+ perpetual_refunds: 'Perpetual refunds', unsynced_sales: 'Unsynced sales',
66
+ short: 'Short', over: 'Over',
67
+ exact: 'Exact', voided: 'Voided',
68
+ paid_in: 'Paid in', paid_out: 'Paid out',
69
+ no_sale: 'No sale', void: 'Void',
70
+ copy: 'Copy',
71
+ };
@@ -7,6 +7,9 @@
7
7
  * (ADR-080 amendment 1), by the server's rule. WCPOS's `attributeRefunds` fallbacks (allocations,
8
8
  * `refunded_amount`) are not ported: the store attributes each refund to a tender in `byMethod`.
9
9
  */
10
+ import { legMethodId } from '@tallyui/core';
11
+ import { tillPayments } from '../pos-order/till-payments';
12
+ import type { PosOrder } from '../pos-order/types';
10
13
  import type { PosRefund } from '../refund/pos-refund';
11
14
 
12
15
  export type RefundRow = Pick<PosRefund, 'id' | 'sessionId' | 'status' | 'result'>;
@@ -30,6 +33,17 @@ export type LedgerRow = {
30
33
  amountMinor: number;
31
34
  };
32
35
 
36
+ /**
37
+ * The ledger rows of these orders' payments. Each payment is captured, and a cash payment's amount is already net of change.
38
+ * A locked store payment (storePaymentId set) is the store's earlier money, not this till's, and is left out (ADR-090 gate 11).
39
+ */
40
+ export function paymentLedgerRows(orders: readonly Pick<PosOrder, 'sessionId' | 'payments'>[]): LedgerRow[] {
41
+ return orders.flatMap((order) => tillPayments(order.payments).map((payment) => ({
42
+ session_id: order.sessionId, kind: payment.method === 'cash' ? 'cash' : 'other', method_id: payment.method,
43
+ status: 'captured', amountMinor: payment.amountMinor,
44
+ })));
45
+ }
46
+
33
47
  /** `type`, `voids` and `voided_by` are kept as WCPOS names them: neutral across backends. */
34
48
  export type Movement = {
35
49
  id: string;
@@ -59,11 +73,12 @@ export function deriveExpected({
59
73
  ledgerRowsBySession: readonly LedgerRow[];
60
74
  refunds?: readonly RefundRow[];
61
75
  }): Record<string, number> {
62
- const totals: Record<string, number> = { cash: session.countedFloatMinor };
76
+ // A Map, so a method id named like an Object.prototype member (`__proto__`) stays an ordinary key.
77
+ const totals = new Map<string, number>([['cash', session.countedFloatMinor]]);
78
+ const plus = (method: string, amount: number) => totals.set(method, (totals.get(method) ?? 0) + amount);
63
79
  for (const row of ledgerRowsBySession) {
64
80
  if (row.session_id !== session.id || row.status !== 'captured') continue;
65
- const method = row.kind === 'cash' ? 'cash' : row.method_id;
66
- totals[method] = (totals[method] ?? 0) + row.amountMinor;
81
+ plus(row.kind === 'cash' ? 'cash' : row.method_id, row.amountMinor);
67
82
  }
68
83
  const voids = new Set(
69
84
  movements
@@ -72,14 +87,14 @@ export function deriveExpected({
72
87
  );
73
88
  for (const row of movements) {
74
89
  if (row.session_id !== session.id || row.voided_by || voids.has(row.id)) continue;
75
- if (row.type === 'paid_in') totals.cash += row.amountMinor;
76
- if (row.type === 'paid_out') totals.cash -= row.amountMinor;
90
+ if (row.type === 'paid_in') plus('cash', row.amountMinor);
91
+ if (row.type === 'paid_out') plus('cash', -row.amountMinor);
77
92
  }
78
93
  for (const refund of refunds ?? []) {
79
94
  if (refund.status !== 'applied' || refund.sessionId !== session.id) continue;
80
- for (const [method, amount] of refundAmounts(refund)) totals[method] = (totals[method] ?? 0) - amount;
95
+ for (const [method, amount] of refundAmounts(refund)) plus(method, -amount);
81
96
  }
82
- return totals;
97
+ return Object.fromEntries(totals);
83
98
  }
84
99
 
85
100
  export interface DrawerTerm { amountMinor: number; count: number }
@@ -113,12 +128,14 @@ export function deriveDrawerTerms(input: Parameters<typeof deriveExpected>[0]):
113
128
  target.count += 1;
114
129
  };
115
130
  const [cashSales, cashRefunds, paidIn, paidOut] = [term(), term(), term(), term()];
116
- const otherTenders: Record<string, DrawerTerm> = {};
131
+ // A Map, so a `__proto__` method id never writes onto Object.prototype.
132
+ const others = new Map<string, DrawerTerm>();
133
+ const other = (method: string) => others.get(method) ?? others.set(method, term()).get(method)!;
117
134
  let noSales = 0;
118
135
  for (const row of ledgerRowsBySession) {
119
136
  if (row.session_id !== session.id || row.status !== 'captured') continue;
120
137
  const method = row.kind === 'cash' ? 'cash' : row.method_id;
121
- add(method === 'cash' ? cashSales : (otherTenders[method] ??= term()), row.amountMinor);
138
+ add(method === 'cash' ? cashSales : other(method), row.amountMinor);
122
139
  }
123
140
  const voids = new Set(movements.filter((row) => row.session_id === session.id && row.type === 'void').map((row) => row.voids));
124
141
  for (const row of movements) {
@@ -131,9 +148,10 @@ export function deriveDrawerTerms(input: Parameters<typeof deriveExpected>[0]):
131
148
  if (refund.status !== 'applied' || refund.sessionId !== session.id) continue;
132
149
  for (const [method, amount] of refundAmounts(refund)) {
133
150
  if (method === 'cash') add(cashRefunds, amount);
134
- else add((otherTenders[method] ??= term()), -amount);
151
+ else add(other(method), -amount);
135
152
  }
136
153
  }
154
+ const otherTenders = Object.fromEntries(others);
137
155
  const otherMinor = Object.values(otherTenders).reduce((sum, row) => sum + row.amountMinor, 0);
138
156
  return {
139
157
  floatMinor: session.countedFloatMinor, cashSales, cashRefunds, paidIn, paidOut, noSales, otherTenders,
@@ -141,3 +159,24 @@ export function deriveDrawerTerms(input: Parameters<typeof deriveExpected>[0]):
141
159
  expected: deriveExpected(input),
142
160
  };
143
161
  }
162
+
163
+ /**
164
+ * Takings per payment method for one session, for the closure sheet: this till's captured payments (`tillPayments`) of the
165
+ * orders whose `sessionId` is `sessionId`, keyed by `legMethodId`'s kind plus id (`external:stripe`), with the number of
166
+ * payments behind each. Local only, never synced: register rows and payloads keep `method_id: payment.method` (#256, ADR-070
167
+ * decision 1). A leg with no methodId keys exactly as deriveDrawerTerms does (`cash` or its method); the figures sum to
168
+ * deriveDrawerTerms' cash sales plus other tenders for the same orders. Refunds and movements are not here: they are keyed
169
+ * by the wire method. The map has no prototype, so a platform id such as `__proto__` or `toString` is a key like any other.
170
+ */
171
+ export function takingsByMethod(orders: readonly Pick<PosOrder, 'sessionId' | 'payments'>[], sessionId: string): Record<string, DrawerTerm> {
172
+ const takings: Record<string, DrawerTerm> = Object.create(null);
173
+ for (const order of orders) {
174
+ if (order.sessionId !== sessionId) continue;
175
+ for (const payment of tillPayments(order.payments)) {
176
+ const term = (takings[legMethodId(payment)] ??= { amountMinor: 0, count: 0 });
177
+ term.amountMinor += payment.amountMinor;
178
+ term.count += 1;
179
+ }
180
+ }
181
+ return takings;
182
+ }
@@ -1,6 +1,6 @@
1
1
  export { normalizeAmount, isServerDecimal, movementFieldError } from './movement-input';
2
2
  export type { MovementType } from './movement-input';
3
- export { deriveExpected, deriveDrawerTerms } from './expected';
3
+ export { deriveExpected, deriveDrawerTerms, takingsByMethod } from './expected';
4
4
  export type { LedgerRow, Movement, DrawerTerm, DrawerTerms } from './expected';
5
5
  export { parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, closureVariance, denominationTotal, varianceText } from './register-count.helpers';
6
6
  export { denominations } from './register-count.denominations';
@@ -22,12 +22,12 @@ export { suggestFloat } from './float-suggestion';
22
22
  export type { FloatSuggestion } from './float-suggestion';
23
23
  export type { Correction, RecordedFigures } from './settled-figures';
24
24
  export { exportCsv } from './export-csv';
25
- export { labelKeys } from './document-labels';
25
+ export { labelKeys, ENGLISH_CLOSURE_LABELS } from './document-labels';
26
26
  export { clampClosureScope, selectClosureRows } from './closure-rows';
27
27
  export type { ClosureScope } from './closure-rows';
28
- export { minorToDecimal } from './money';
29
- export { formatClosureDate, buildClosureDocument, buildXReportDocument, TAX_ROUNDING_MIXED_NOTE } from './closure-document';
30
- export type { ClosureContext } from './closure-document';
28
+ export { minorToDecimal, formatDecimalMoney } from './money';
29
+ export { formatClosureDate, buildClosureDocument, buildXReportDocument, TAX_ROUNDING_MIXED_NOTE, TAX_STORE_PAID_NOTE, createClosureContext } from './closure-document';
30
+ export type { ClosureContext, CreateClosureContextOptions } from './closure-document';
31
31
  export { registerFactsLogger, recordRegisterFact, type Actor, type RegisterFact } from './facts';
32
32
  export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError } from './use-register-session';
33
33
  export type { ApprovalNeeded, UseRegisterSessionOptions } from './use-register-session';
@@ -16,3 +16,26 @@ export function minorToDecimal(minor: number, exponent: number): string {
16
16
  const fraction = abs % scale;
17
17
  return exponent === 0 ? `${sign}${whole}` : `${sign}${whole}.${String(fraction).padStart(exponent, '0')}`;
18
18
  }
19
+
20
+ const decimalFormatters = new Map<string, Intl.NumberFormat>();
21
+
22
+ /** Formats a decimal amount as currency; preserves empty, non-finite or unformattable input. */
23
+ export function formatDecimalMoney(value: string, options: { currency: string; exponent: number; locale?: string }): string {
24
+ const { currency, exponent, locale } = options;
25
+ if (value === '') return '';
26
+ const amount = Number(value);
27
+ if (!Number.isFinite(amount) || currency === 'XXX') return value;
28
+ const key = `${currency}:${exponent}:${locale ?? ''}`;
29
+ let formatter = decimalFormatters.get(key);
30
+ if (!formatter) {
31
+ try {
32
+ formatter = new Intl.NumberFormat(locale, {
33
+ style: 'currency', currency, minimumFractionDigits: exponent, maximumFractionDigits: exponent,
34
+ });
35
+ } catch {
36
+ return value;
37
+ }
38
+ decimalFormatters.set(key, formatter);
39
+ }
40
+ return formatter.format(amount);
41
+ }
@@ -25,7 +25,8 @@ const counted = (number: unknown, sales: unknown, refunds: unknown): Counted | u
25
25
  * consecutively from the store's counter, the truth, with chained totals. Only the refused closure spends its retry
26
26
  * (`number_retried`). The register document, the closure rows and the command rows are rewritten in that order, the
27
27
  * refused closure's last, and each changed command is requeued under a new command id (ADR-068 d6). Any other
28
- * refusal, a second refusal of a renumbered closure, or malformed counters writes nothing.
28
+ * refusal, a second refusal of a renumbered closure, or malformed counters writes nothing. A closure with no store_key
29
+ * counts as this store's (#665).
29
30
  */
30
31
  async function renumberRefused(commands: RegisterCommandCollection, closures: ClosureCollection, host: RegisterHost,
31
32
  storeKey: string, registerId: string) {
@@ -34,12 +35,12 @@ async function renumberRefused(commands: RegisterCommandCollection, closures: Cl
34
35
  readFresh(closures, { selector: { register_id: registerId } }),
35
36
  ]);
36
37
  const refused = submits.find((submit) => submit.syncStatus === 'rejected' && !NON_BLOCKING_REJECTIONS.has(submit.error?.code ?? ''));
37
- const row = local.find(({ id, store_key }) => id === refused?.payload.closureId && (store_key ?? null) === storeKey);
38
+ const row = local.find(({ id, store_key }) => id === refused?.payload.closureId && (store_key ?? storeKey) === storeKey);
38
39
  if (refused?.error?.code !== 'register_closure_number_invalid' || !row) return;
39
40
  const sent = new Map(submits.map((submit) => [submit.payload.closureId, submit]));
40
41
  const unsent = (closure: Closure) => {
41
42
  const submit = sent.get(closure.id);
42
- return (closure.store_key ?? null) === storeKey && closure.closed_at >= row.closed_at && (!submit || submit.syncStatus === 'pending'
43
+ return (closure.store_key ?? storeKey) === storeKey && closure.closed_at >= row.closed_at && (!submit || submit.syncStatus === 'pending'
43
44
  || (submit.syncStatus === 'rejected' && submit.error?.code === 'register_closure_number_invalid'));
44
45
  };
45
46
  let queued = local.filter(unsent).sort((a, b) => a.closed_at.localeCompare(b.closed_at) || a.id.localeCompare(b.id));
@@ -128,7 +129,7 @@ export async function adoptRegisterResults({ commands, sessions, registerId, hos
128
129
  }
129
130
 
130
131
  export async function takeOverSession({ commands, sessions, sessionId, now, registerContract }: SessionTarget & {
131
- /** The store's register contract (`capabilities.register`); take over needs 2, and a missing value counts as below 2. */
132
+ /** The store's register contract (`capabilities.register`); take over needs 2, and a missing value counts as below 2; 3 sends the take-over as version 3 (#1105). */
132
133
  registerContract?: number;
133
134
  }): Promise<void> {
134
135
  if ((registerContract ?? 0) < 2) throw new RegisterTakeOverError('REGISTER_TAKEOVER_UNSUPPORTED');
@@ -140,7 +141,7 @@ export async function takeOverSession({ commands, sessions, sessionId, now, regi
140
141
  if (doc.syncStatus !== 'rejected' || doc.error?.code !== 'register_session_already_open'
141
142
  || typeof doc.error.data?.sessionId !== 'string') throw new RegisterSessionRequiredError();
142
143
  const { error, ...rest } = doc;
143
- return { ...rest, commandId: uuidv7(), version: 2, syncStatus: 'pending',
144
+ return { ...rest, commandId: uuidv7(), version: (registerContract ?? 0) >= 3 ? 3 : 2, syncStatus: 'pending',
144
145
  payload: { ...doc.payload, supersedes: error.data!.sessionId }, updatedAt: now ?? new Date().toISOString() };
145
146
  });
146
147
  });
@@ -50,9 +50,10 @@ export function deviceNameOf(name: string | null | undefined): string | undefine
50
50
  return trimmed || undefined;
51
51
  }
52
52
 
53
- export function sessionOpenCommand(s: RegisterSession, v2?: { deviceName?: string | null }): BuiltCommand {
53
+ /** The options make a v2 open, or version 3 at register contract 3 (#1105); the payload is v2's. */
54
+ export function sessionOpenCommand(s: RegisterSession, v2?: { deviceName?: string | null; registerContract?: number }): BuiltCommand {
54
55
  const deviceName = deviceNameOf(v2?.deviceName);
55
- return { key: `session.open:${s.id}`, type: 'register.session.open', version: v2 ? 2 : 1, payload: {
56
+ return { key: `session.open:${s.id}`, type: 'register.session.open', version: v2 ? ((v2.registerContract ?? 0) >= 3 ? 3 : 2) : 1, payload: {
56
57
  sessionId: s.id, registerId: s.register_id, openedAt: s.opened_at_gmt, countedFloatMinor: s.counted_float_minor,
57
58
  ...(s.store_key == null ? {} : { storeKey: s.store_key }),
58
59
  ...(s.business_day == null ? {} : { businessDay: s.business_day }),
@@ -135,7 +136,7 @@ export function reconcileRegisterCommands({ commands, sessions, movements, closu
135
136
  events.push(...entries.filter((entry) => entry.type !== 'void').map(movementCommand),
136
137
  ...entries.filter((entry) => entry.type === 'void').map(movementCommand));
137
138
  if (session.status_at != null && sentStatus(session)) events.push(sessionTransitionCommand({ ...session, status_at: session.status_at }));
138
- return { session, number: closureRows[0]?.number, built: [(registerContract ?? 0) >= 2 ? sessionOpenCommand(session, { deviceName }) : sessionOpenCommand(session), ...events,
139
+ return { session, number: closureRows[0]?.number, built: [(registerContract ?? 0) >= 2 ? sessionOpenCommand(session, { deviceName, registerContract }) : sessionOpenCommand(session), ...events,
139
140
  ...closureRows.map((closure) => closureCommand(closure, { registerContract, approval: session.approver_token }))] };
140
141
  }));
141
142
  facts.sort((a, b) => Number(a.session.status !== 'closed') - Number(b.session.status !== 'closed')
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The register's local collections (ADR-032): sessions, cash movements and closures. Port
3
3
  * provenance (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`, where they are at versions 1, 0
4
- * and 1; sessions are at version 1 here (ADR-078), movements and closures at version 0.
4
+ * and 1; sessions are at version 2 here (ADR-078, plus the count note, desk ruling 18 Nov), movements and
5
+ * closures at version 0.
5
6
  *
6
7
  * All three are local only, like `pos_orders`: the app creates them and never replicates them
7
8
  * (a replicated collection must never take local writes, #53). WCPOS's outbox fields
@@ -50,6 +51,8 @@ export interface RegisterSession {
50
51
  /** A server's expected figures; cleared before every money action (`requireOpenSession`). */
51
52
  server_expected?: TenderMap | null;
52
53
  server_sales_count?: number | null;
54
+ /** The cashier's note on the close count, written with the count; null when none. */
55
+ count_note?: string | null;
53
56
  }
54
57
 
55
58
  export interface CashMovement {
@@ -107,7 +110,7 @@ const nullableMinor: JsonSchema = { type: ['integer', 'null'] };
107
110
  const tenders: JsonSchema = { type: 'object', additionalProperties: minor };
108
111
 
109
112
  export const registerSessionSchema: RxJsonSchema<RegisterSession> = {
110
- title: 'Register sessions', version: 1, primaryKey: 'id', type: 'object', additionalProperties: false,
113
+ title: 'Register sessions', version: 2, primaryKey: 'id', type: 'object', additionalProperties: false,
111
114
  properties: {
112
115
  id, register_id: id, store_key: nullableText,
113
116
  status: { type: 'string', maxLength: 20 },
@@ -125,6 +128,7 @@ export const registerSessionSchema: RxJsonSchema<RegisterSession> = {
125
128
  approver_token: { ...nullableText, default: null },
126
129
  server_expected: { type: ['object', 'null'], additionalProperties: minor, default: null },
127
130
  server_sales_count: { type: ['integer', 'null'], default: null },
131
+ count_note: { ...nullableText, default: null },
128
132
  },
129
133
  required: ['id', 'register_id', 'status', 'opened_at_gmt', 'counted_float_minor'],
130
134
  indexes: [['register_id', 'status']],
@@ -142,6 +146,10 @@ export function registerSessionCreator(): RxCollectionCreator<RegisterSession> {
142
146
  // Every migrated row gets the field, the same shape a new row gets from the schema default.
143
147
  doc.server_session_id ??= null;
144
148
  return doc;
149
+ }, 2: (doc) => {
150
+ // Every migrated row gets the count note, null as on a session closed without one.
151
+ doc.count_note ??= null;
152
+ return doc;
145
153
  } } };
146
154
  }
147
155
 
@@ -150,7 +158,7 @@ export function registerSessionCreator(): RxCollectionCreator<RegisterSession> {
150
158
  * Kept so old callers compile but fail at start instead of migrating on RxDB's own path.
151
159
  */
152
160
  export function registerSessionCollection(): never {
153
- throw new Error('registerSessionCollection() is gone: open register_sessions with await addRegisterSessionCollection(db). Adding it with addCollections would run RxDB\'s own migration of schema version 1, which can lose sessions (ADR-078, #371).');
161
+ throw new Error('registerSessionCollection() is gone: open register_sessions with await addRegisterSessionCollection(db). Adding it with addCollections would run RxDB\'s own migration of an older schema version, which can lose sessions (ADR-078, #371).');
154
162
  }
155
163
 
156
164
  export const cashMovementSchema: RxJsonSchema<CashMovement> = {
@@ -12,11 +12,13 @@
12
12
  */
13
13
  import type { RxCollection } from 'rxdb';
14
14
  import { DEFAULT_TAX_ROUNDING, taxLinesByRate } from '../tax/exact';
15
+ import { taxedLinesFor } from '../tax/taxed-lines';
15
16
  import type { PosOrder } from '../pos-order/types';
16
17
  import { replacedOrderIds } from '../pos-order/reopened';
18
+ import { tillPayments } from '../pos-order/till-payments';
17
19
  import type { PosRefund } from '../refund/pos-refund';
18
20
  import { readFresh } from '../rxdb';
19
- import { deriveExpected, refundAmounts, type LedgerRow } from './expected';
21
+ import { deriveExpected, paymentLedgerRows, refundAmounts } from './expected';
20
22
  import { recordRegisterFact } from './facts';
21
23
  import { MAX_REASON_LENGTH } from './movement-input';
22
24
  import { countVariance } from './register-count.helpers';
@@ -161,6 +163,8 @@ export async function requireOpenSession(
161
163
  // the order stamped with it -- `finalizeOrder` is pure and never checks it. Refuses to re-stamp
162
164
  // an order that already carries a different session's id.
163
165
  export async function stampSession(order: PosOrder, sessionId: string, sessions: RegisterSessionCollection): Promise<PosOrder> {
166
+ // Its money is in that closed session's closure (ADR-077), so it joins no session.
167
+ if (order.countedInClosureOf !== undefined) return order;
164
168
  if (order.sessionId !== undefined && order.sessionId !== sessionId) throw new Error('session_already_stamped');
165
169
  const session = await requireLiveSession(sessions, sessionId);
166
170
  return { ...order, sessionId: session.id };
@@ -245,6 +249,9 @@ export function businessDayOf(atGmt: string, timezone: string) {
245
249
  return `${part.year}-${part.month}-${part.day}`;
246
250
  }
247
251
 
252
+ /** Set once `openSession` has warned about a missing `storeKey`, so it warns once per module instance. */
253
+ let warnedNoStoreKey = false;
254
+
248
255
  export function openSession(
249
256
  sessions: RegisterSessionCollection,
250
257
  input: {
@@ -254,9 +261,26 @@ export function openSession(
254
261
  openedBy: string;
255
262
  /** The store's day, not the device's UTC day. */
256
263
  businessDay: { year: number; month: number; day: number };
264
+ /**
265
+ * @deprecated when omitted. Omitting storeKey is deprecated: a session without one writes closures that count as
266
+ * any store's. It becomes required at the next major.
267
+ */
257
268
  storeKey?: string | null;
258
269
  },
259
270
  ) {
271
+ if ((input.storeKey ?? null) === null && !warnedNoStoreKey) {
272
+ let production = false;
273
+ try {
274
+ production = (globalThis as { process?: { env?: { NODE_ENV?: string } } }).process?.env?.NODE_ENV === 'production';
275
+ } catch {
276
+ // A host whose `process` getter throws is treated as not production.
277
+ }
278
+ if (!production) {
279
+ warnedNoStoreKey = true;
280
+ console.warn("[@tallyui/pos] openSession without storeKey is deprecated: its closures count as any store's. " +
281
+ 'Pass storeKey; it becomes required at the next major.');
282
+ }
283
+ }
260
284
  const { year, month, day } = input.businessDay;
261
285
  return sessions.insert({
262
286
  id: uuid(),
@@ -310,12 +334,13 @@ export const backToSelling = (sessions: RegisterSessionCollection, id: string) =
310
334
  * without a business day. `approvedBy`, the manager who approved the count, is written in the same
311
335
  * write as the close, and a repeat close keeps the first close's approver as it keeps its count.
312
336
  * `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.
337
+ * write; it never reaches the closure or its breakdowns. `note`, the cashier's note on the count, is
338
+ * written with the count (blank is stored as null); a repeat close keeps the first close's note, as it keeps its count.
314
339
  */
315
340
  export async function closeSession(
316
341
  sessions: RegisterSessionCollection,
317
342
  id: string,
318
- input: { counted: Record<string, number>; closedBy?: string; approvedBy?: string; approval?: string; timezone?: string },
343
+ input: { counted: Record<string, number>; closedBy?: string; approvedBy?: string; approval?: string; timezone?: string; note?: string },
319
344
  ) {
320
345
  const session = await sessions.findOne(id).exec();
321
346
  if (!session) throw new RegisterSessionRequiredError();
@@ -323,6 +348,7 @@ export async function closeSession(
323
348
  business_day: session.business_day || businessDayOf(session.opened_at_gmt, input.timezone ?? 'device'),
324
349
  counted: input.counted,
325
350
  closed_by: input.closedBy ?? null,
351
+ count_note: input.note?.trim() || null,
326
352
  ...(input.approvedBy ? { approved_by: input.approvedBy } : {}),
327
353
  ...(input.approval ? { approver_token: input.approval } : {}),
328
354
  closure_id: id,
@@ -497,16 +523,7 @@ export async function writeClosure({
497
523
  const replaced = replacedOrderIds(orders);
498
524
  const bound = orders.filter((order) => order.sessionId === session.id && !replaced.has(order.id));
499
525
  const countedRefunds = (refunds ?? []).filter((refund) => refund.status === 'applied' && refund.sessionId === session.id);
500
- // Each payment is captured, and a cash payment's amount is already net of change.
501
- const rows: LedgerRow[] = bound.flatMap((order) =>
502
- order.payments.map((payment) => ({
503
- session_id: order.sessionId,
504
- kind: payment.method === 'cash' ? 'cash' : 'other',
505
- method_id: payment.method,
506
- status: 'captured',
507
- amountMinor: payment.amountMinor,
508
- })),
509
- );
526
+ const rows = paymentLedgerRows(bound);
510
527
  const entries = movements.filter((row) => row.session_id === session.id);
511
528
  const till_expected =
512
529
  tillExpected ??
@@ -518,19 +535,21 @@ export async function writeClosure({
518
535
  });
519
536
  const counts = { cash: counted, ...otherTenders };
520
537
  const sum = (values: number[]) => values.reduce((total, value) => total + value, 0);
521
- const payment_methods: Record<string, { sales_minor: number; refunds_minor: number }> = {};
538
+ // A Map, so a method id named like an Object.prototype member (`__proto__`) stays an ordinary key.
539
+ const methodTotals = new Map<string, { sales_minor: number; refunds_minor: number }>();
522
540
  for (const row of rows) {
523
541
  const method = row.kind === 'cash' ? 'cash' : row.method_id;
524
- payment_methods[method] = { sales_minor: (payment_methods[method]?.sales_minor ?? 0) + row.amountMinor, refunds_minor: 0 };
542
+ methodTotals.set(method, { sales_minor: (methodTotals.get(method)?.sales_minor ?? 0) + row.amountMinor, refunds_minor: 0 });
525
543
  }
526
544
  for (const refund of countedRefunds) {
527
545
  for (const [method, amount] of refundAmounts(refund)) {
528
- payment_methods[method] = { sales_minor: payment_methods[method]?.sales_minor ?? 0, refunds_minor: (payment_methods[method]?.refunds_minor ?? 0) + amount };
546
+ methodTotals.set(method, { sales_minor: methodTotals.get(method)?.sales_minor ?? 0, refunds_minor: (methodTotals.get(method)?.refunds_minor ?? 0) + amount });
529
547
  }
530
548
  }
549
+ const payment_methods = Object.fromEntries(methodTotals);
531
550
  // Same per-rate split a receipt shows (`taxLinesByRate`), run per order so each order's rates
532
- // add up to its own taxMinor, then summed across the session's orders by rate. A line's own
533
- // taxInclusive overrides the order's, matching PosOrderLine's own fallback convention. Each order is split by the
551
+ // add up to its own taxMinor, then summed across the session's orders by rate. Each line is in the mode
552
+ // its receipt rounded it in (`taxedLinesFor`). Each order is split by the
534
553
  // tax rounding it recorded (#287), so its rows are its receipt's; absent is the default, today's split.
535
554
  const taxRates = new Map<string, { ratePpm: number; net_minor: number; tax_minor: number }>();
536
555
  const roundings = new Set<string>();
@@ -539,9 +558,7 @@ export async function writeClosure({
539
558
  const recorded = order.taxRounding ?? DEFAULT_TAX_ROUNDING;
540
559
  const rounding = recorded.granularity === 'custom' ? DEFAULT_TAX_ROUNDING : recorded;
541
560
  roundings.add(rounding.granularity === 'woocommerce' ? `woocommerce ${rounding.roundAtSubtotal}` : `${rounding.granularity} ${rounding.mode}`);
542
- const lines = order.lines.map((line) => ({ ...line, taxInclusive: line.taxInclusive ?? order.pricesIncludeTax }));
543
- const taxedLines = [...lines, ...[...(order.fees ?? []), ...(order.shipping ?? [])]
544
- .map((charge) => ({ ...charge, taxInclusive: order.pricesIncludeTax }))];
561
+ const taxedLines = taxedLinesFor(order.lines, [...(order.fees ?? []), ...(order.shipping ?? [])], order.pricesIncludeTax, order.taxRounding);
545
562
  for (const { ratePpm, netMinor, amountMinor } of taxLinesByRate(taxedLines, order.taxMinor, undefined, order.taxRounding)) {
546
563
  const existing = taxRates.get(String(ratePpm));
547
564
  taxRates.set(String(ratePpm), {
@@ -566,14 +583,14 @@ export async function writeClosure({
566
583
  expected: till_expected,
567
584
  counted: counts,
568
585
  variance: Object.fromEntries(
569
- Object.entries(counts).map(([method, value]) => [method, countVariance(value, till_expected[method] ?? 0)]),
586
+ Object.entries(counts).map(([method, value]) => [method, countVariance(value, Object.hasOwn(till_expected, method) ? till_expected[method] : 0)]),
570
587
  ),
571
588
  period_sales_total_minor: sum(rows.map((row) => row.amountMinor)),
572
589
  period_refunds_total_minor: sum(countedRefunds.flatMap((refund) => refundAmounts(refund).map(([, amount]) => amount))),
573
590
  perpetual_sales_total_minor: 0,
574
591
  perpetual_refunds_total_minor: 0,
575
592
  unsynced_count: unsynced.length,
576
- unsynced_total_minor: sum(unsynced.flatMap((order) => order.payments.map((payment) => payment.amountMinor))),
593
+ unsynced_total_minor: sum(unsynced.flatMap((order) => tillPayments(order.payments).map((payment) => payment.amountMinor))),
577
594
  software_version: softwareVersion,
578
595
  printed_at: null,
579
596
  print_count: 0,
@@ -581,6 +598,8 @@ export async function writeClosure({
581
598
  ...labels,
582
599
  opened_by: session.opened_by ?? null,
583
600
  approved_by: session.approved_by ?? null,
601
+ // v2's key; the Z shows it when it is not blank.
602
+ ...(session.count_note?.trim() ? { variance_note: session.count_note } : {}),
584
603
  payment_methods,
585
604
  tax_rates: Object.fromEntries(
586
605
  [...taxRates.values()].map(({ ratePpm, net_minor, tax_minor }) => [
@@ -589,6 +608,8 @@ export async function writeClosure({
589
608
  ),
590
609
  // The session's sales used more than one tax rounding (#287): the Z report says so.
591
610
  ...(roundings.size > 1 ? { tax_rounding_mixed: true } : {}),
611
+ // A reopened sale's tax rates are its whole order's, including tax on what was paid earlier in the store (ADR-090 ruling 38).
612
+ ...(bound.some((order) => tillPayments(order.payments).length < order.payments.length) ? { tax_includes_store_paid: true } : {}),
592
613
  opening_float: {
593
614
  expected_minor: session.expected_float_minor ?? null,
594
615
  counted_minor: session.counted_float_minor,