@tallyui/pos 3.15.0 → 3.17.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.
@@ -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,23 +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, renumberClosures, type RegisterHost } from './register-document';
6
7
  import { registerCommandsLogger, type RegisterCommand, type RegisterCommandCollection } from './register-commands';
7
8
  import type { Closure, RegisterSession } from './schemas';
8
- import { isKnownSessionStatus, RegisterSessionRequiredError, RegisterTakeOverError, type RegisterSessionCollection } from './session-store';
9
+ import { isKnownSessionStatus, RegisterSessionRequiredError, RegisterTakeOverError, type ClosureCollection,
10
+ type RegisterSessionCollection } from './session-store';
9
11
 
10
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
+ }
11
71
  type SessionTarget = { commands: RegisterCommandCollection; sessions: RegisterSessionCollection; sessionId: string; now?: string };
12
72
 
13
73
  /**
14
74
  * Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
15
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.
16
76
  * Applied conflict opens restore the latest transition's counting state, otherwise open; pending rows do nothing.
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`).
17
79
  * Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
18
80
  */
19
- export async function adoptRegisterResults({ commands, sessions, registerId }: {
81
+ export async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey, closures }: {
20
82
  commands: RegisterCommandCollection; sessions: RegisterSessionCollection; registerId: string;
83
+ host?: RegisterHost; storeKey?: string; closures?: ClosureCollection;
21
84
  }): Promise<void> {
22
85
  const run = (chains.get(commands) ?? Promise.resolve()).then(async () => {
23
86
  const [answers, transitions, rows] = await Promise.all([
@@ -54,6 +117,9 @@ export async function adoptRegisterResults({ commands, sessions, registerId }: {
54
117
  const row = await sessions.findOne(session.id).exec();
55
118
  if (row) await row.incrementalModify(modify);
56
119
  }
120
+ const counters = answers.filter((answer) => answer.syncStatus === 'applied' && answer.result?.counters).map((answer) => answer.result?.counters);
121
+ if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, counters);
122
+ if (host && storeKey && closures) await renumberRefused(commands, closures, host, storeKey, registerId);
57
123
  }).catch((error: unknown) => {
58
124
  registerCommandsLogger.error('Register result adoption failed', { context: { registerId, error: String(error) } });
59
125
  });
@@ -9,6 +9,7 @@
9
9
  * module-level snapshots (`getRegisterSnapshot`, `getRegisterId`, `getCurrentBoundRegisterId`)
10
10
  * are not ported: callers pass the host and read the document explicitly.
11
11
  */
12
+ import type { RegisterCommandResult } from '@tallyui/core';
12
13
  import type { RxLocalDocumentMutation } from 'rxdb';
13
14
  import { map } from 'rxjs';
14
15
  import type { Closure } from './schemas';
@@ -222,6 +223,50 @@ export async function mintClosureNumber(
222
223
  return number;
223
224
  }
224
225
 
226
+ export type StoreCounters = NonNullable<RegisterCommandResult['counters']>;
227
+ const STORE_COUNTERS = [['last_closure_number', 'lastClosureNumber'], ['perpetual_sales_total_minor', 'perpetualSalesTotalMinor'],
228
+ ['perpetual_refunds_total_minor', 'perpetualRefundsTotalMinor']] as const;
229
+
230
+ /**
231
+ * Raises the register's counters to the store's (`RegisterCommandResult.counters`, #651), each field on its own: the
232
+ * store's figure is a floor, so a counter only rises, and one the till is ahead on (closures not yet sent) stays. A field
233
+ * that isn't a safe non-negative integer is ignored. A reserved closure keeps its number and totals.
234
+ */
235
+ export function adoptStoreCounters(host: RegisterHost, storeKey: string, registerId: string,
236
+ counters: ReadonlyArray<Partial<StoreCounters> | undefined>) {
237
+ return modifyStore(host, storeKey, (store) => {
238
+ const register = store?.registers?.[registerId] ?? {};
239
+ const raised: Partial<RegisterCounters> = {};
240
+ for (const [local, remote] of STORE_COUNTERS) for (const entry of counters) {
241
+ const value: unknown = entry?.[remote];
242
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value > (raised[local] ?? register[local] ?? 0)) raised[local] = value;
243
+ }
244
+ return Object.keys(raised).length ? withRegister(store, registerId, { ...register, ...raised }) : undefined;
245
+ });
246
+ }
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
+
225
270
  /**
226
271
  * Adds a closed period to the register's perpetual totals. With `closureId`, it applies that
227
272
  * reserved closure once: the totals become the reservation's, and a repeat does nothing.
@@ -32,6 +32,8 @@ export const PAYMENT_IN_MOTION = 'Finish or void the payment in progress before
32
32
  */
33
33
  export const SALE_PARTLY_PAID = 'This sale is partly paid. Take the rest of the payment or void the paid legs first.';
34
34
  export const SALE_IN_TENDER = 'Finish or cancel the payment before switching sales';
35
+ // The start of the message addOne sets when a terminal reference is dropped; a later tender change keeps it.
36
+ const REFERENCE_DROPPED = "The terminal's payment reference couldn't be kept";
35
37
  /**
36
38
  * How often a hung save re-asks `isStored`, while the order is built and its save is still in flight
37
39
  * and unconfirmed: an app whose tender has no New sale control while saving (the Front desk,
@@ -193,7 +195,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
193
195
  const paymentId = builder.addPayment(kept);
194
196
  if (dropped) {
195
197
  droppedReferences.current.add(paymentId);
196
- setError(`The terminal's payment reference couldn't be kept (${dropped}); the payment is recorded without it.`);
198
+ setError(`${REFERENCE_DROPPED} (${dropped}); the payment is recorded without it.`);
197
199
  }
198
200
  try {
199
201
  if (dropped) saleLogger.warn("the terminal's payment reference was dropped", { reason: dropped, method: tender.method });
@@ -210,6 +212,11 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
210
212
  if (tender) addOne(tender);
211
213
  }
212
214
 
215
+ /** addTender, voidTender and removeTender changed the tenders: a stale error goes, a dropped-reference message stays. */
216
+ function clearStaleError() {
217
+ setError((current) => current?.startsWith(REFERENCE_DROPPED) ? current : null);
218
+ }
219
+
213
220
  /** Asks `isStored`; Continue is offered only once it confirms, for this attempt, with the completion still pending. */
214
221
  function checkStored(completion: { order: Order; posOrder: PosOrder }) {
215
222
  const attempt = attempts.current;
@@ -284,8 +291,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
284
291
  saving,
285
292
  /** The failed save's order is confirmed stored (see `isStored`): the UI also offers Continue (`continueSale()`). */
286
293
  canContinue,
287
- add(entry: CatalogueEntry<any>, traits: ProductTraits<any>) {
288
- if (locked()) return;
294
+ /** Adds the entry, as a new line or one more on its line; returns that line's id, or the refusal `error` now shows. */
295
+ add(entry: CatalogueEntry<any>, traits: ProductTraits<any>): { lineId: string } | string {
296
+ if (locked()) return SALE_SAVING;
289
297
  const builder = builderNow.current;
290
298
  try {
291
299
  const known = new Set(builder.getSnapshot().lineItems.map((line) => line.id));
@@ -303,11 +311,13 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
303
311
  const refused = line && [line.variantId !== undefined ? referenceError(`${name}: the variant id`, line.variantId)
304
312
  : referenceError(`${name}: the product id`, line.productId),
305
313
  ...taxLines.map((tax) => referenceError(`${name}: the tax code`, tax.code))].find((message) => message !== null);
306
- if (refused) { builder.removeItem(lineId); return setError(refused); }
314
+ if (refused) { builder.removeItem(lineId); setError(refused); return refused; }
307
315
  setError(null);
316
+ return { lineId };
308
317
  } catch (error) {
309
318
  if (!(error instanceof CartError)) throw error;
310
319
  setError(error.message);
320
+ return error.message;
311
321
  }
312
322
  },
313
323
  setQuantity(lineId: string, quantity: number) { if (!locked()) builderNow.current.updateQuantity(lineId, quantity); },
@@ -450,8 +460,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
450
460
  const snapshot = builderNow.current.getSnapshot();
451
461
  const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
452
462
  if (due <= 0) return null;
463
+ clearStaleError(); // before addOne, which sets its own message for a dropped reference
453
464
  return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) });
454
465
  }
466
+ clearStaleError();
455
467
  return addOne(tender);
456
468
  },
457
469
  setTenderStatus(paymentId: string, status: 'authorized' | 'captured' | 'failed'): boolean {
@@ -465,6 +477,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
465
477
  if (!payment || (payment.method !== 'cash' && payment.method !== 'external') || !canVoidLeg(payment, paymentMethodOf(payment.method))) return false;
466
478
  builderNow.current.setPaymentStatus(paymentId, 'voided');
467
479
  droppedReferences.current.delete(paymentId);
480
+ clearStaleError();
468
481
  return true;
469
482
  },
470
483
  /** ADR-072: remove one tender and its dropped-reference warning. An id not among the payments changes nothing. */
@@ -473,6 +486,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
473
486
  if (!builderNow.current.getSnapshot().payments.some((payment) => payment.id === paymentId)) return;
474
487
  builderNow.current.removePayment(paymentId);
475
488
  droppedReferences.current.delete(paymentId);
489
+ clearStaleError();
476
490
  },
477
491
  cancelTender() {
478
492
  if (locked()) return;