@tallyui/pos 3.16.0 → 3.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/pos",
3
- "version": "3.16.0",
3
+ "version": "3.18.0",
4
4
  "type": "module",
5
5
  "description": "Shared POS business logic for Tally UI — tax, orders, payments, discounts, receipts",
6
6
  "main": "./dist/index.js",
@@ -34,20 +34,20 @@
34
34
  "mustache": "^4.2.0"
35
35
  },
36
36
  "peerDependencies": {
37
- "@tallyui/core": "^3.16.0",
37
+ "@tallyui/core": "^3.18.0",
38
38
  "react": ">=18",
39
39
  "rxdb": "~17.5.0",
40
40
  "rxjs": ">=7"
41
41
  },
42
42
  "devDependencies": {
43
- "@tallyui/core": "3.16.0",
43
+ "@tallyui/core": "3.18.0",
44
44
  "@types/react": ">=18",
45
45
  "react": "^19.2.4",
46
46
  "rxdb": "17.5.0",
47
47
  "rxjs": "7.8.2",
48
- "@tallyui/connector-medusa": "3.16.0",
49
- "@tallyui/connector-woocommerce": "3.16.0",
50
- "@tallyui/database": "3.16.0"
48
+ "@tallyui/connector-medusa": "3.18.0",
49
+ "@tallyui/connector-woocommerce": "3.18.0",
50
+ "@tallyui/database": "3.18.0"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsup",
@@ -1,10 +1,12 @@
1
1
  import { createContext, useContext, useMemo, useCallback } from 'react';
2
2
  import type { ReactNode } from 'react';
3
3
  import { formatMoney, type Money } from '@tallyui/core';
4
+ import { formatMoneyWith, type CurrencyFormat } from './format-money-with';
4
5
 
5
6
  interface CurrencyContext {
6
7
  currencyCode: string;
7
8
  locale?: string;
9
+ format?: CurrencyFormat;
8
10
  }
9
11
 
10
12
  const CurrencyCtx = createContext<CurrencyContext | null>(null);
@@ -12,11 +14,13 @@ const CurrencyCtx = createContext<CurrencyContext | null>(null);
12
14
  export interface CurrencyProviderProps {
13
15
  currencyCode: string;
14
16
  locale?: string;
17
+ /** The store's own money format; without it, money reads as Intl formats it for `locale`. */
18
+ format?: CurrencyFormat;
15
19
  children: ReactNode;
16
20
  }
17
21
 
18
- export function CurrencyProvider({ currencyCode, locale, children }: CurrencyProviderProps) {
19
- const value = useMemo(() => ({ currencyCode, locale }), [currencyCode, locale]);
22
+ export function CurrencyProvider({ currencyCode, locale, format, children }: CurrencyProviderProps) {
23
+ const value = useMemo(() => ({ currencyCode, locale, format }), [currencyCode, locale, format]);
20
24
  return <CurrencyCtx.Provider value={value}>{children}</CurrencyCtx.Provider>;
21
25
  }
22
26
 
@@ -25,9 +29,12 @@ export function useCurrencyFormatter(): (money: Money) => string {
25
29
  if (!ctx) {
26
30
  throw new Error('useCurrencyFormatter() must be used within a <CurrencyProvider>');
27
31
  }
32
+ const { locale, format } = ctx;
28
33
  return useCallback(
29
- (money: Money) => formatMoney(money, ctx.locale) ?? `${money.amount} ${money.currency}`,
30
- [ctx.locale],
34
+ (money: Money) =>
35
+ (format ? formatMoneyWith(money, format, locale) : formatMoney(money, locale)) ??
36
+ `${money.amount} ${money.currency}`,
37
+ [locale, format],
31
38
  );
32
39
  }
33
40
 
@@ -0,0 +1,45 @@
1
+ import { minorUnitDigits, type Money } from '@tallyui/core';
2
+
3
+ /** A store's own money format (WCPOS v2 General settings); a field left out keeps the locale's. */
4
+ export interface CurrencyFormat {
5
+ position?: 'left' | 'right' | 'left_space' | 'right_space';
6
+ thousandSeparator?: string;
7
+ decimalSeparator?: string;
8
+ decimals?: number;
9
+ }
10
+
11
+ /**
12
+ * Money in a store's format, ported from WCPOS v2 (MIT): the position map of
13
+ * `packages/core/src/screens/main/hooks/use-currency-format.tsx` and the separators and places
14
+ * of `use-number-format.ts`. As there, the places are always shown, the integer is grouped every
15
+ * three digits, and a minus leads the symbol. The symbol is Intl's for the currency and locale.
16
+ * Returns undefined for 'XXX' or a code Intl refuses, so callers can fall back.
17
+ */
18
+ export function formatMoneyWith(money: Money, format: CurrencyFormat, locale?: string): string | undefined {
19
+ if (money.currency === 'XXX') return undefined;
20
+ const minor = minorUnitDigits(money.currency);
21
+ const decimals = format.decimals ?? minor;
22
+ const abs = Math.abs(money.amount);
23
+ // Fewer places round whole minor units half away from zero, so -12.50 and 12.50 read alike.
24
+ const major = decimals >= minor ? abs / 10 ** minor : Math.round(abs / 10 ** (minor - decimals)) / 10 ** decimals;
25
+ let parts: Intl.NumberFormatPart[];
26
+ try {
27
+ parts = new Intl.NumberFormat(locale, {
28
+ style: 'currency', currency: money.currency, minimumFractionDigits: decimals, maximumFractionDigits: decimals,
29
+ }).formatToParts(major);
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ const text = (...types: string[]) => parts.filter((p) => types.includes(p.type)).map((p) => p.value).join('');
34
+ const { position, thousandSeparator, decimalSeparator } = format;
35
+ const integer = thousandSeparator === undefined
36
+ ? text('integer', 'group')
37
+ : text('integer').replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
38
+ const number = integer + (decimals > 0 ? (decimalSeparator ?? text('decimal')) + text('fraction') : '');
39
+ const symbol = text('currency');
40
+ const left = position
41
+ ? position.startsWith('left')
42
+ : parts.findIndex((p) => p.type === 'currency') < parts.findIndex((p) => p.type === 'integer');
43
+ const gap = position ? (position.endsWith('_space') ? ' ' : '') : text('literal');
44
+ return (money.amount < 0 && major > 0 ? '-' : '') + (left ? symbol + gap + number : number + gap + symbol);
45
+ }
@@ -1,2 +1,3 @@
1
1
  export { CurrencyProvider, useCurrencyFormatter, useCurrencyCode } from './currency-provider';
2
2
  export type { CurrencyProviderProps } from './currency-provider';
3
+ export type { CurrencyFormat } from './format-money-with';
package/src/index.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  // Logging
2
- export { createLogger, consoleSink, callbackSink } from './logging';
3
- export type { Logger, LogSink, LogEntry, LogLevel } from './logging';
2
+ export { createLogger, consoleSink, callbackSink, deriveStuckRecords, hasActor, matchesPresetFilters, presetFilters } from './logging';
3
+ export type {
4
+ Logger, LogSink, LogEntry, LogLevel, LogActor, LogMeta, LogSyncRecord, SyncRecordOutcome, LogPreset, LogPresetFilters, StuckRecord,
5
+ } from './logging';
4
6
 
5
7
  // CSV
6
8
  export { csvCell, csvFromCells, toCsv } from './csv';
@@ -8,7 +10,7 @@ export type { CsvColumn } from './csv';
8
10
 
9
11
  // Currency
10
12
  export { CurrencyProvider, useCurrencyFormatter, useCurrencyCode } from './currency';
11
- export type { CurrencyProviderProps } from './currency';
13
+ export type { CurrencyFormat, CurrencyProviderProps } from './currency';
12
14
 
13
15
  // Tax
14
16
  export { TaxProvider, useTax, taxLogger } from './tax';
@@ -1,3 +1,5 @@
1
1
  export { createLogger } from './logger';
2
2
  export { consoleSink, callbackSink } from './sinks';
3
- export type { Logger, LogSink, LogEntry, LogLevel } from './types';
3
+ export { deriveStuckRecords, hasActor, matchesPresetFilters, presetFilters } from './logs-logic';
4
+ export type { LogPreset, LogPresetFilters, StuckRecord } from './logs-logic';
5
+ export type { Logger, LogSink, LogEntry, LogLevel, LogActor, LogMeta, LogSyncRecord, SyncRecordOutcome } from './types';
@@ -1,42 +1,7 @@
1
- import type { Logger, LogEntry, LogLevel, LogSink } from './types';
1
+ import type { Logger, LogEntry, LogLevel, LogMeta, LogSink } from './types';
2
2
 
3
3
  export function createLogger(scope = 'root'): Logger {
4
- const sinks: Map<string, LogSink> = new Map();
5
-
6
- function log(level: LogLevel, message: string, data?: Record<string, unknown>) {
7
- const entry: LogEntry = {
8
- level,
9
- scope,
10
- message,
11
- data,
12
- timestamp: Date.now(),
13
- };
14
-
15
- for (const sink of sinks.values()) {
16
- if (!sink.levels.includes(level)) continue;
17
- if (sink.scopes && !sink.scopes.includes(scope)) continue;
18
- sink.write(entry);
19
- }
20
- }
21
-
22
- return {
23
- debug: (message, data) => log('debug', message, data),
24
- info: (message, data) => log('info', message, data),
25
- warn: (message, data) => log('warn', message, data),
26
- error: (message, data) => log('error', message, data),
27
-
28
- createScope(name: string): Logger {
29
- return createChildLogger(sinks, name);
30
- },
31
-
32
- addSink(sink: LogSink) {
33
- sinks.set(sink.id, sink);
34
- },
35
-
36
- removeSink(sinkId: string) {
37
- sinks.delete(sinkId);
38
- },
39
- };
4
+ return createChildLogger(new Map(), scope);
40
5
  }
41
6
 
42
7
  function logWithSinks(
@@ -45,8 +10,12 @@ function logWithSinks(
45
10
  scope: string,
46
11
  message: string,
47
12
  data?: Record<string, unknown>,
13
+ meta?: LogMeta,
48
14
  ) {
49
15
  const entry: LogEntry = { level, scope, message, data, timestamp: Date.now() };
16
+ // Set only when given, so an entry logged without them keeps its old shape.
17
+ if (meta?.actor) entry.actor = meta.actor;
18
+ if (meta?.syncRecord) entry.syncRecord = meta.syncRecord;
50
19
  for (const sink of sinks.values()) {
51
20
  if (!sink.levels.includes(level)) continue;
52
21
  if (sink.scopes && !sink.scopes.includes(scope)) continue;
@@ -56,12 +25,12 @@ function logWithSinks(
56
25
 
57
26
  function createChildLogger(sinks: Map<string, LogSink>, scope: string): Logger {
58
27
  return {
59
- debug: (message, data) => logWithSinks(sinks, 'debug', scope, message, data),
60
- info: (message, data) => logWithSinks(sinks, 'info', scope, message, data),
61
- warn: (message, data) => logWithSinks(sinks, 'warn', scope, message, data),
62
- error: (message, data) => logWithSinks(sinks, 'error', scope, message, data),
28
+ debug: (message, data, meta) => logWithSinks(sinks, 'debug', scope, message, data, meta),
29
+ info: (message, data, meta) => logWithSinks(sinks, 'info', scope, message, data, meta),
30
+ warn: (message, data, meta) => logWithSinks(sinks, 'warn', scope, message, data, meta),
31
+ error: (message, data, meta) => logWithSinks(sinks, 'error', scope, message, data, meta),
63
32
  createScope: (childName: string) => createChildLogger(sinks, childName),
64
- addSink: (sink: LogSink) => sinks.set(sink.id, sink),
65
- removeSink: (sinkId: string) => sinks.delete(sinkId),
33
+ addSink: (sink: LogSink) => { sinks.set(sink.id, sink); },
34
+ removeSink: (sinkId: string) => { sinks.delete(sinkId); },
66
35
  };
67
36
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Pure helpers for a Logs screen, ported from WCPOS v2 `packages/core/src/screens/main/logs/logs-logic.ts`
3
+ * (monorepo `main` 51e7c4351): `presetFilters` (its `has_actor` part) and `deriveStuckRecords`. v2 reads its
4
+ * stored log rows; these read TallyUI's `LogEntry`, with its typed `actor` and `syncRecord`. v2's `sync` preset
5
+ * filters on v2's `wcpos.sync` category, which TallyUI's log scopes have no counterpart for, so it is not ported.
6
+ */
7
+ import type { LogEntry, LogLevel } from './types';
8
+
9
+ export type LogPreset = 'all' | 'actions' | 'errors';
10
+
11
+ export interface LogPresetFilters {
12
+ level: LogLevel[];
13
+ /** Only entries a person did (`hasActor`). */
14
+ has_actor?: true;
15
+ }
16
+
17
+ /** Preset chip to filters. Debug entries count only while verbose diagnostics is on. */
18
+ export function presetFilters(preset: LogPreset, verbose: boolean): LogPresetFilters {
19
+ const level: LogLevel[] = verbose ? ['debug', 'info', 'warn', 'error'] : ['info', 'warn', 'error'];
20
+ switch (preset) {
21
+ case 'all':
22
+ return { level };
23
+ case 'actions':
24
+ return { level, has_actor: true };
25
+ case 'errors':
26
+ return { level: ['error'] };
27
+ }
28
+ }
29
+
30
+ /** A person did it: the entry's actor names an id or a name (v2 reads such a row as an action). */
31
+ export function hasActor(entry: Pick<LogEntry, 'actor'>): boolean {
32
+ return !!(entry.actor?.id || entry.actor?.name);
33
+ }
34
+
35
+ export function matchesPresetFilters(entry: LogEntry, filters: LogPresetFilters): boolean {
36
+ return filters.level.includes(entry.level) && (!filters.has_actor || hasActor(entry));
37
+ }
38
+
39
+ export interface StuckRecord {
40
+ /** `${collection}:${recordId}` */
41
+ key: string;
42
+ collection: string;
43
+ recordId: string;
44
+ /** `failed`: the store refused it. `pending`: the store keeps failing it, and it is still retrying. */
45
+ outcome: 'failed' | 'pending';
46
+ code?: string;
47
+ reason: string;
48
+ /** When its latest outcome was logged. */
49
+ lastSeen: number;
50
+ }
51
+
52
+ /**
53
+ * The records whose latest sync outcome is `failed` or `pending`; an `ok` clears. Entries without a `syncRecord`
54
+ * are no evidence either way. The latest is by timestamp, and on equal timestamps the entry later in `entries`
55
+ * (the order a sink receives them). Newest first.
56
+ */
57
+ export function deriveStuckRecords(entries: readonly LogEntry[]): StuckRecord[] {
58
+ const latest = new Map<string, LogEntry>();
59
+ for (const entry of entries) {
60
+ if (!entry.syncRecord) continue;
61
+ const key = `${entry.syncRecord.collection}:${entry.syncRecord.recordId}`;
62
+ const seen = latest.get(key);
63
+ if (!seen || entry.timestamp >= seen.timestamp) latest.set(key, entry);
64
+ }
65
+ const stuck: StuckRecord[] = [];
66
+ for (const [key, entry] of latest) {
67
+ const { collection, recordId, outcome, code, reason } = entry.syncRecord!;
68
+ if (outcome === 'ok') continue;
69
+ stuck.push({ key, collection, recordId, outcome, ...(code ? { code } : {}), reason: reason || entry.message,
70
+ lastSeen: entry.timestamp });
71
+ }
72
+ return stuck.sort((a, b) => b.lastSeen - a.lastSeen);
73
+ }
@@ -1,6 +1,35 @@
1
1
  export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
2
2
 
3
- export interface LogEntry {
3
+ /** Who did it: a person (a cashier or manager), not the system. WCPOS v2's log actor. */
4
+ export interface LogActor {
5
+ id?: string;
6
+ name?: string;
7
+ role?: string;
8
+ }
9
+
10
+ /** `ok`: the store applied the record. `failed`: the store refused it. `pending`: the store keeps failing it on its
11
+ * own, and it is still retrying. */
12
+ export type SyncRecordOutcome = 'ok' | 'failed' | 'pending';
13
+
14
+ /** One record's sync outcome (WCPOS v2's `sync.record` row). */
15
+ export interface LogSyncRecord {
16
+ /** The local collection, e.g. `pos_orders`. */
17
+ collection: string;
18
+ /** The record's durable id (a PosOrder's `id`, not its commandId). */
19
+ recordId: string;
20
+ outcome: SyncRecordOutcome;
21
+ /** The store's error code. */
22
+ code?: string;
23
+ reason?: string;
24
+ }
25
+
26
+ /** Typed fields a call site puts on the entry itself; each is set on the entry only when given. */
27
+ export interface LogMeta {
28
+ actor?: LogActor;
29
+ syncRecord?: LogSyncRecord;
30
+ }
31
+
32
+ export interface LogEntry extends LogMeta {
4
33
  level: LogLevel;
5
34
  scope: string;
6
35
  message: string;
@@ -15,11 +44,13 @@ export interface LogSink {
15
44
  write(entry: LogEntry): void;
16
45
  }
17
46
 
47
+ type LogMethod = (message: string, data?: Record<string, unknown>, meta?: LogMeta) => void;
48
+
18
49
  export interface Logger {
19
- debug(message: string, data?: Record<string, unknown>): void;
20
- info(message: string, data?: Record<string, unknown>): void;
21
- warn(message: string, data?: Record<string, unknown>): void;
22
- error(message: string, data?: Record<string, unknown>): void;
50
+ debug: LogMethod;
51
+ info: LogMethod;
52
+ warn: LogMethod;
53
+ error: LogMethod;
23
54
  createScope(name: string): Logger;
24
55
  addSink(sink: LogSink): void;
25
56
  removeSink(sinkId: string): void;
@@ -2,6 +2,7 @@ import type { OrderCreateEnvelope } from '@tallyui/core';
2
2
  import { deepEqual, type RxCollection, type RxDocumentData } from 'rxdb';
3
3
  import { BehaviorSubject, type Observable, type Subscription } from 'rxjs';
4
4
  import { outboxLogger } from './logger';
5
+ import type { LogSyncRecord, SyncRecordOutcome } from '../logging';
5
6
  import { toOrderCreateEnvelope, UnsupportedOrderVersionError, uuidv7, replacedOrderIds, type PosOrder, type PosOrderServerFailures } from '../pos-order';
6
7
  import { freezeSentForm } from '../pos-order/finalize';
7
8
  import { countFresh, readFresh } from '../rxdb';
@@ -23,6 +24,10 @@ export function isRequeueable(code: string | undefined): boolean {
23
24
  // The store's message in the refusal log is cut to this many characters, the cap connectors use for a foreign 426 message.
24
25
  const REFUSAL_LOG_MESSAGE_MAX = 200;
25
26
 
27
+ /** An order's sync record, keyed by its durable `id` (a resend gets a new commandId). */
28
+ const syncRecordOf = (orderId: string, outcome: SyncRecordOutcome): LogSyncRecord =>
29
+ ({ collection: 'pos_orders', recordId: orderId, outcome });
30
+
26
31
  // After this many consecutive failures the store answered (not offline) with the same head order and
27
32
  // no progress, the queue is probed one order at a time, so an order the store can't take holds up only
28
33
  // itself. With the default backoff the first probe goes after about 30 s: sales keep flowing within minutes.
@@ -100,7 +105,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
100
105
  // the orders whose probes failed are isolated and batching resumes. When no order is left to probe, the
101
106
  // store is down: nothing is isolated, and batching resumes with its backoff.
102
107
  let head: { id: string; count: number } | undefined;
103
- let walk: { failed: Map<string, string> } | undefined;
108
+ let walk: { failed: Map<string, { orderId: string; reason: string }> } | undefined;
104
109
  // Isolated orders are left out of batches and retried alone, each on its own backoff, while pending
105
110
  // under their commandId.
106
111
  const isolated = new Map<string, { backoff: number; nextAt: number; reason: string }>();
@@ -211,7 +216,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
211
216
  if (runProgressed && retryAfterMs === undefined && reason !== 'status_429') return undefined;
212
217
  return Math.max(retryAfterMs ?? 0, isolated.get(id)!.nextAt - now());
213
218
  }
214
- if (alone === 'probe') walk?.failed.set(id, reason);
219
+ if (alone === 'probe') walk?.failed.set(id, { orderId: orders[0].id, reason });
215
220
  else {
216
221
  head = { id, count: head?.id === id ? head.count + 1 : 1 };
217
222
  if (head.count >= isolateAfter) walk ??= { failed: new Map() };
@@ -402,8 +407,15 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
402
407
  }
403
408
  // Every refusal goes to the sync log once, with the store's code and message (the orders list shows the cashier
404
409
  // only the code's sentence, #269); unsupported_version stays an error.
405
- if (result.status === 'rejected') outboxLogger[error?.code === 'unsupported_version' ? 'error' : 'warn']('Order refused by the store',
406
- { orderId: order.id, code: error?.code, message: error?.message?.slice(0, REFUSAL_LOG_MESSAGE_MAX) });
410
+ // Each refusal and each apply also carries the order's sync record, so a Logs screen can tell which orders are
411
+ // stuck: the latest outcome per order rules (`deriveStuckRecords`, #656).
412
+ if (result.status === 'rejected') {
413
+ const message = error?.message?.slice(0, REFUSAL_LOG_MESSAGE_MAX);
414
+ outboxLogger[error?.code === 'unsupported_version' ? 'error' : 'warn']('Order refused by the store',
415
+ { orderId: order.id, code: error?.code, message },
416
+ { syncRecord: { ...syncRecordOf(order.id, 'failed'), ...(error?.code ? { code: error.code } : {}),
417
+ ...(message ? { reason: message } : {}) } });
418
+ }
407
419
  const updatedAt = new Date(now()).toISOString();
408
420
  // Progress removes the stored serverFailures in the write that marks the order applied or rejected.
409
421
  await current.incrementalModify((data) => {
@@ -413,6 +425,9 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
413
425
  : { syncStatus: 'applied' as const, serverRefs: result.serverRefs,
414
426
  ...(result.warnings ? { warnings: result.warnings } : {}), updatedAt });
415
427
  });
428
+ if (result.status !== 'rejected') {
429
+ outboxLogger.info('Order accepted by the store', { orderId: order.id }, { syncRecord: syncRecordOf(order.id, 'ok') });
430
+ }
416
431
  attempts.delete(order.commandId);
417
432
  isolated.delete(order.commandId);
418
433
  clocks.delete(order.commandId);
@@ -428,7 +443,12 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
428
443
  if (alone !== 'isolated') head = undefined;
429
444
  if (walk && alone === 'probe') {
430
445
  // The store took a probe, so it is up: the orders whose probes failed are isolated, and batching resumes.
431
- for (const [id, reason] of walk.failed) isolate(id, reason);
446
+ // Each is logged once, as pending: it stays queued and retries alone, so it is stuck but not refused (#656).
447
+ for (const [id, { orderId, reason }] of walk.failed) {
448
+ isolate(id, reason);
449
+ outboxLogger.warn('Order isolated: the store keeps failing it', { orderId, reason },
450
+ { syncRecord: { ...syncRecordOf(orderId, 'pending'), reason } });
451
+ }
432
452
  walk = undefined;
433
453
  }
434
454
  backoff = initialBackoff;
@@ -67,7 +67,9 @@ export function recordRegisterFact(fact: RegisterFact): void {
67
67
  type: string,
68
68
  context: Record<string, unknown> = {},
69
69
  level: 'info' | 'warn' = 'info',
70
- ) => registerFactsLogger[level](message, { actor: fact.actor, terminal, context: { type, ...pair, ...context } });
70
+ ) => registerFactsLogger[level](message, { actor: fact.actor, terminal, context: { type, ...pair, ...context } },
71
+ // The cashier also rides on the entry itself, so a Logs screen's Actions preset finds it (#656).
72
+ fact.actor ? { actor: fact.actor } : undefined);
71
73
  switch (fact.kind) {
72
74
  case 'session-opened':
73
75
  return emit('Register session opened', 'register.session-opened', { amount: fact.amount, variance: fact.variance });
@@ -1,26 +1,86 @@
1
1
  import type { ServerCapabilities } from '@tallyui/core';
2
- import { CLOSURE_HOLDING_REJECTIONS } from '../outbox/register-outbox';
2
+ import { CLOSURE_HOLDING_REJECTIONS, NON_BLOCKING_REJECTIONS } from '../outbox/register-outbox';
3
3
  import { readFresh } from '../rxdb';
4
4
  import { uuidv7 } from '../pos-order/uuidv7';
5
5
  import { countVariance, overThreshold } from './register-count.helpers';
6
- import { adoptStoreCounters, type RegisterHost } from './register-document';
6
+ import { adoptStoreCounters, renumberClosures, type RegisterHost } from './register-document';
7
7
  import { registerCommandsLogger, type RegisterCommand, type RegisterCommandCollection } from './register-commands';
8
8
  import type { Closure, RegisterSession } from './schemas';
9
- import { isKnownSessionStatus, RegisterSessionRequiredError, RegisterTakeOverError, type RegisterSessionCollection } from './session-store';
9
+ import { isKnownSessionStatus, RegisterSessionRequiredError, RegisterTakeOverError, type ClosureCollection,
10
+ type RegisterSessionCollection } from './session-store';
10
11
 
11
12
  const chains = new WeakMap<RegisterCommandCollection, Promise<void>>();
13
+ const figure = (value: unknown) => (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined);
14
+ type Counted = { number: number; sales: number; refunds: number };
15
+ const counted = (number: unknown, sales: unknown, refunds: unknown): Counted | undefined => {
16
+ const [n, s, r] = [figure(number), figure(sales), figure(refunds)];
17
+ return n === undefined || s === undefined || r === undefined ? undefined : { number: n, sales: s, refunds: r };
18
+ };
19
+
20
+ /**
21
+ * The store takes a closure only as its last number plus one; it refuses any other `register_closure_number_invalid`
22
+ * with its counters (ADR-068 d5). The register's first refused closure submit, past the outbox's non-blocking
23
+ * refusals, is the one: when the store refused it for its number, every unsent closure of this register and store
24
+ * (closed since, its submit missing, pending or refused for its number) is renumbered in one pass, in closed order,
25
+ * consecutively from the store's counter, the truth, with chained totals. Only the refused closure spends its retry
26
+ * (`number_retried`). The register document, the closure rows and the command rows are rewritten in that order, the
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.
29
+ */
30
+ async function renumberRefused(commands: RegisterCommandCollection, closures: ClosureCollection, host: RegisterHost,
31
+ storeKey: string, registerId: string) {
32
+ const [submits, local] = await Promise.all([
33
+ readFresh(commands, { selector: { registerId, type: 'register.closure.submit' }, sort: [{ seq: 'asc' }, { key: 'asc' }] }),
34
+ readFresh(closures, { selector: { register_id: registerId } }),
35
+ ]);
36
+ 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
+ if (refused?.error?.code !== 'register_closure_number_invalid' || !row) return;
39
+ const sent = new Map(submits.map((submit) => [submit.payload.closureId, submit]));
40
+ const unsent = (closure: Closure) => {
41
+ const submit = sent.get(closure.id);
42
+ return (closure.store_key ?? null) === storeKey && closure.closed_at >= row.closed_at && (!submit || submit.syncStatus === 'pending'
43
+ || (submit.syncStatus === 'rejected' && submit.error?.code === 'register_closure_number_invalid'));
44
+ };
45
+ let queued = local.filter(unsent).sort((a, b) => a.closed_at.localeCompare(b.closed_at) || a.id.localeCompare(b.id));
46
+ if (!row.number_retried) {
47
+ const store = (refused.error.data?.counters ?? {}) as Record<string, unknown>;
48
+ const base = counted(store.lastClosureNumber, store.perpetualSalesTotalMinor, store.perpetualRefundsTotalMinor);
49
+ if (!base) return;
50
+ let { number, sales, refunds } = base;
51
+ queued = queued.map((closure) => ({ ...closure, number: ++number, perpetual_sales_total_minor: sales += closure.period_sales_total_minor,
52
+ perpetual_refunds_total_minor: refunds += closure.period_refunds_total_minor, number_retried: closure.number_retried || closure.id === row.id }));
53
+ await renumberClosures(host, storeKey, registerId, queued);
54
+ } else if (refused.payload.number === row.number) return;
55
+ // The refused closure goes last, so a crash part way leaves it refused and unretried, or retried with a stale command.
56
+ for (const closure of [...queued.filter(({ id }) => id !== row.id), ...queued.filter(({ id }) => id === row.id)]) {
57
+ const { number, perpetual_sales_total_minor: sales, perpetual_refunds_total_minor: refunds, number_retried } = closure;
58
+ if (!row.number_retried) await (await closures.findOne(closure.id).exec(true)).incrementalPatch({ number,
59
+ perpetual_sales_total_minor: sales, perpetual_refunds_total_minor: refunds, number_retried });
60
+ const submit = sent.get(closure.id);
61
+ if (!submit || (submit.syncStatus === 'pending' && submit.payload.number === number
62
+ && submit.payload.perpetualSalesTotalMinor === sales && submit.payload.perpetualRefundsTotalMinor === refunds)) continue;
63
+ await (await commands.findOne(submit.key).exec())?.incrementalModify((doc) => {
64
+ if (doc.commandId !== submit.commandId || doc.syncStatus !== submit.syncStatus) return doc;
65
+ const { error: _refusal, ...rest } = doc;
66
+ return { ...rest, commandId: uuidv7(), syncStatus: 'pending', updatedAt: new Date().toISOString(), payload: { ...doc.payload,
67
+ number, perpetualSalesTotalMinor: sales, perpetualRefundsTotalMinor: refunds } };
68
+ });
69
+ }
70
+ }
12
71
  type SessionTarget = { commands: RegisterCommandCollection; sessions: RegisterSessionCollection; sessionId: string; now?: string };
13
72
 
14
73
  /**
15
74
  * Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
16
75
  * Superseded rejections make open/counting sessions terminal; a conflict session leaves only by an applied open or abandon (ADR-078 decision 9); terminal/unknown states stay untouched.
17
76
  * Applied conflict opens restore the latest transition's counting state, otherwise open; pending rows do nothing.
18
- * Given `host` and `storeKey`, applied rows also raise the register's counters to the store's (#651, `adoptStoreCounters`).
77
+ * Given `host` and `storeKey`, applied rows also raise the register's counters to the store's (#651, `adoptStoreCounters`),
78
+ * and given `closures` too, a closure refused for its number is renumbered once and requeued (#655, `renumberRefused`).
19
79
  * Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
20
80
  */
21
- export async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey }: {
81
+ export async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey, closures }: {
22
82
  commands: RegisterCommandCollection; sessions: RegisterSessionCollection; registerId: string;
23
- host?: RegisterHost; storeKey?: string;
83
+ host?: RegisterHost; storeKey?: string; closures?: ClosureCollection;
24
84
  }): Promise<void> {
25
85
  const run = (chains.get(commands) ?? Promise.resolve()).then(async () => {
26
86
  const [answers, transitions, rows] = await Promise.all([
@@ -59,6 +119,7 @@ export async function adoptRegisterResults({ commands, sessions, registerId, hos
59
119
  }
60
120
  const counters = answers.filter((answer) => answer.syncStatus === 'applied' && answer.result?.counters).map((answer) => answer.result?.counters);
61
121
  if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, counters);
122
+ if (host && storeKey && closures) await renumberRefused(commands, closures, host, storeKey, registerId);
62
123
  }).catch((error: unknown) => {
63
124
  registerCommandsLogger.error('Register result adoption failed', { context: { registerId, error: String(error) } });
64
125
  });
@@ -245,6 +245,28 @@ export function adoptStoreCounters(host: RegisterHost, storeKey: string, registe
245
245
  });
246
246
  }
247
247
 
248
+ /**
249
+ * Records the closures renumbered after a refusal (#655), in number order: the register's last number and totals are
250
+ * set outright to the last one's, the store's counter plus this till's unsent closures (no max: on a refusal the
251
+ * store's counter is the truth), and a reservation holding one of them takes its new row, keeping `applied`. Each
252
+ * field is set, not added, so a repeat changes nothing.
253
+ */
254
+ export function renumberClosures(host: RegisterHost, storeKey: string, registerId: string, rows: Closure[]) {
255
+ const last = rows[rows.length - 1];
256
+ return modifyStore(host, storeKey, (store) => {
257
+ const register = store?.registers?.[registerId] ?? {};
258
+ const reservation = register.closure_reservation;
259
+ const row = rows.find(({ id }) => id === reservation?.row.id);
260
+ return withRegister(store, registerId, {
261
+ ...register,
262
+ last_closure_number: last.number,
263
+ perpetual_sales_total_minor: last.perpetual_sales_total_minor,
264
+ perpetual_refunds_total_minor: last.perpetual_refunds_total_minor,
265
+ ...(reservation && row ? { closure_reservation: { ...reservation, row } } : {}),
266
+ });
267
+ });
268
+ }
269
+
248
270
  /**
249
271
  * Adds a closed period to the register's perpetual totals. With `closureId`, it applies that
250
272
  * reserved closure once: the totals become the reservation's, and a repeat does nothing.