@tallyui/pos 3.14.0 → 3.16.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/dist/index.d.ts CHANGED
@@ -3126,12 +3126,15 @@ type SessionTarget = {
3126
3126
  * Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
3127
3127
  * 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.
3128
3128
  * Applied conflict opens restore the latest transition's counting state, otherwise open; pending rows do nothing.
3129
+ * Given `host` and `storeKey`, applied rows also raise the register's counters to the store's (#651, `adoptStoreCounters`).
3129
3130
  * Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
3130
3131
  */
3131
- declare function adoptRegisterResults({ commands, sessions, registerId }: {
3132
+ declare function adoptRegisterResults({ commands, sessions, registerId, host, storeKey }: {
3132
3133
  commands: RegisterCommandCollection;
3133
3134
  sessions: RegisterSessionCollection;
3134
3135
  registerId: string;
3136
+ host?: RegisterHost;
3137
+ storeKey?: string;
3135
3138
  }): Promise<void>;
3136
3139
  declare function takeOverSession({ commands, sessions, sessionId, now, registerContract }: SessionTarget & {
3137
3140
  /** The store's register contract (`capabilities.register`); take over needs 2, and a missing value counts as below 2. */
package/dist/index.js CHANGED
@@ -4412,6 +4412,22 @@ async function mintClosureNumber(host, storeKey, registerId, closure) {
4412
4412
  });
4413
4413
  return number;
4414
4414
  }
4415
+ var STORE_COUNTERS = [
4416
+ ["last_closure_number", "lastClosureNumber"],
4417
+ ["perpetual_sales_total_minor", "perpetualSalesTotalMinor"],
4418
+ ["perpetual_refunds_total_minor", "perpetualRefundsTotalMinor"]
4419
+ ];
4420
+ function adoptStoreCounters(host, storeKey, registerId, counters) {
4421
+ return modifyStore(host, storeKey, (store) => {
4422
+ const register = store?.registers?.[registerId] ?? {};
4423
+ const raised = {};
4424
+ for (const [local, remote] of STORE_COUNTERS) for (const entry of counters) {
4425
+ const value = entry?.[remote];
4426
+ if (typeof value === "number" && Number.isSafeInteger(value) && value > (raised[local] ?? register[local] ?? 0)) raised[local] = value;
4427
+ }
4428
+ return Object.keys(raised).length ? withRegister(store, registerId, { ...register, ...raised }) : void 0;
4429
+ });
4430
+ }
4415
4431
  function advancePerpetual(host, storeKey, registerId, period) {
4416
4432
  return modifyStore(host, storeKey, (store) => {
4417
4433
  const register = store?.registers?.[registerId] ?? {};
@@ -6617,7 +6633,7 @@ function createRegisterOutbox(options) {
6617
6633
 
6618
6634
  // src/register/register-adoption.ts
6619
6635
  var chains2 = /* @__PURE__ */ new WeakMap();
6620
- async function adoptRegisterResults({ commands, sessions, registerId }) {
6636
+ async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey }) {
6621
6637
  const run = (chains2.get(commands) ?? Promise.resolve()).then(async () => {
6622
6638
  const [answers, transitions, rows] = await Promise.all([
6623
6639
  readFresh(commands, { selector: { registerId, syncStatus: { $in: ["applied", "rejected"] } }, sort: [{ seq: "asc" }, { key: "asc" }] }),
@@ -6650,6 +6666,8 @@ async function adoptRegisterResults({ commands, sessions, registerId }) {
6650
6666
  const row = await sessions.findOne(session.id).exec();
6651
6667
  if (row) await row.incrementalModify(modify);
6652
6668
  }
6669
+ const counters = answers.filter((answer) => answer.syncStatus === "applied" && answer.result?.counters).map((answer) => answer.result?.counters);
6670
+ if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, counters);
6653
6671
  }).catch((error) => {
6654
6672
  registerCommandsLogger.error("Register result adoption failed", { context: { registerId, error: String(error) } });
6655
6673
  });
@@ -7314,6 +7332,7 @@ var SALE_SAVING = "This sale is being saved. Retry to finish it.";
7314
7332
  var PAYMENT_IN_MOTION = "Finish or void the payment in progress before completing the sale";
7315
7333
  var SALE_PARTLY_PAID = "This sale is partly paid. Take the rest of the payment or void the paid legs first.";
7316
7334
  var SALE_IN_TENDER = "Finish or cancel the payment before switching sales";
7335
+ var REFERENCE_DROPPED = "The terminal's payment reference couldn't be kept";
7317
7336
  var HUNG_SAVE_CHECK_MS = 5e3;
7318
7337
  function useSale(settings, opts) {
7319
7338
  const taxContext = useTax();
@@ -7413,7 +7432,7 @@ function useSale(settings, opts) {
7413
7432
  const paymentId = builder.addPayment(kept);
7414
7433
  if (dropped) {
7415
7434
  droppedReferences.current.add(paymentId);
7416
- setError(`The terminal's payment reference couldn't be kept (${dropped}); the payment is recorded without it.`);
7435
+ setError(`${REFERENCE_DROPPED} (${dropped}); the payment is recorded without it.`);
7417
7436
  }
7418
7437
  try {
7419
7438
  if (dropped) saleLogger.warn("the terminal's payment reference was dropped", { reason: dropped, method: tender.method });
@@ -7429,6 +7448,9 @@ function useSale(settings, opts) {
7429
7448
  setError(null);
7430
7449
  if (tender) addOne(tender);
7431
7450
  }
7451
+ function clearStaleError() {
7452
+ setError((current) => current?.startsWith(REFERENCE_DROPPED) ? current : null);
7453
+ }
7432
7454
  function checkStored(completion) {
7433
7455
  const attempt2 = attempts.current;
7434
7456
  const isStored = opts.isStored;
@@ -7706,8 +7728,10 @@ function useSale(settings, opts) {
7706
7728
  const snapshot = builderNow.current.getSnapshot();
7707
7729
  const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
7708
7730
  if (due <= 0) return null;
7731
+ clearStaleError();
7709
7732
  return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) });
7710
7733
  }
7734
+ clearStaleError();
7711
7735
  return addOne(tender);
7712
7736
  },
7713
7737
  setTenderStatus(paymentId, status) {
@@ -7721,6 +7745,7 @@ function useSale(settings, opts) {
7721
7745
  if (!payment || payment.method !== "cash" && payment.method !== "external" || !canVoidLeg(payment, paymentMethodOf(payment.method))) return false;
7722
7746
  builderNow.current.setPaymentStatus(paymentId, "voided");
7723
7747
  droppedReferences.current.delete(paymentId);
7748
+ clearStaleError();
7724
7749
  return true;
7725
7750
  },
7726
7751
  /** ADR-072: remove one tender and its dropped-reference warning. An id not among the payments changes nothing. */
@@ -7729,6 +7754,7 @@ function useSale(settings, opts) {
7729
7754
  if (!builderNow.current.getSnapshot().payments.some((payment) => payment.id === paymentId)) return;
7730
7755
  builderNow.current.removePayment(paymentId);
7731
7756
  droppedReferences.current.delete(paymentId);
7757
+ clearStaleError();
7732
7758
  },
7733
7759
  cancelTender() {
7734
7760
  if (locked()) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/pos",
3
- "version": "3.14.0",
3
+ "version": "3.16.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.14.0",
37
+ "@tallyui/core": "^3.16.0",
38
38
  "react": ">=18",
39
39
  "rxdb": "~17.5.0",
40
40
  "rxjs": ">=7"
41
41
  },
42
42
  "devDependencies": {
43
- "@tallyui/core": "3.14.0",
43
+ "@tallyui/core": "3.16.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.14.0",
49
- "@tallyui/connector-woocommerce": "3.14.0",
50
- "@tallyui/database": "3.14.0"
48
+ "@tallyui/connector-medusa": "3.16.0",
49
+ "@tallyui/connector-woocommerce": "3.16.0",
50
+ "@tallyui/database": "3.16.0"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsup",
@@ -3,6 +3,7 @@ import { CLOSURE_HOLDING_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
7
  import { registerCommandsLogger, type RegisterCommand, type RegisterCommandCollection } from './register-commands';
7
8
  import type { Closure, RegisterSession } from './schemas';
8
9
  import { isKnownSessionStatus, RegisterSessionRequiredError, RegisterTakeOverError, type RegisterSessionCollection } from './session-store';
@@ -14,10 +15,12 @@ type SessionTarget = { commands: RegisterCommandCollection; sessions: RegisterSe
14
15
  * Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
15
16
  * 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
17
  * 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`).
17
19
  * Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
18
20
  */
19
- export async function adoptRegisterResults({ commands, sessions, registerId }: {
21
+ export async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey }: {
20
22
  commands: RegisterCommandCollection; sessions: RegisterSessionCollection; registerId: string;
23
+ host?: RegisterHost; storeKey?: string;
21
24
  }): Promise<void> {
22
25
  const run = (chains.get(commands) ?? Promise.resolve()).then(async () => {
23
26
  const [answers, transitions, rows] = await Promise.all([
@@ -54,6 +57,8 @@ export async function adoptRegisterResults({ commands, sessions, registerId }: {
54
57
  const row = await sessions.findOne(session.id).exec();
55
58
  if (row) await row.incrementalModify(modify);
56
59
  }
60
+ const counters = answers.filter((answer) => answer.syncStatus === 'applied' && answer.result?.counters).map((answer) => answer.result?.counters);
61
+ if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, counters);
57
62
  }).catch((error: unknown) => {
58
63
  registerCommandsLogger.error('Register result adoption failed', { context: { registerId, error: String(error) } });
59
64
  });
@@ -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,28 @@ 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
+
225
248
  /**
226
249
  * Adds a closed period to the register's perpetual totals. With `closureId`, it applies that
227
250
  * 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;
@@ -450,8 +457,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
450
457
  const snapshot = builderNow.current.getSnapshot();
451
458
  const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
452
459
  if (due <= 0) return null;
460
+ clearStaleError(); // before addOne, which sets its own message for a dropped reference
453
461
  return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) });
454
462
  }
463
+ clearStaleError();
455
464
  return addOne(tender);
456
465
  },
457
466
  setTenderStatus(paymentId: string, status: 'authorized' | 'captured' | 'failed'): boolean {
@@ -465,6 +474,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
465
474
  if (!payment || (payment.method !== 'cash' && payment.method !== 'external') || !canVoidLeg(payment, paymentMethodOf(payment.method))) return false;
466
475
  builderNow.current.setPaymentStatus(paymentId, 'voided');
467
476
  droppedReferences.current.delete(paymentId);
477
+ clearStaleError();
468
478
  return true;
469
479
  },
470
480
  /** ADR-072: remove one tender and its dropped-reference warning. An id not among the payments changes nothing. */
@@ -473,6 +483,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
473
483
  if (!builderNow.current.getSnapshot().payments.some((payment) => payment.id === paymentId)) return;
474
484
  builderNow.current.removePayment(paymentId);
475
485
  droppedReferences.current.delete(paymentId);
486
+ clearStaleError();
476
487
  },
477
488
  cancelTender() {
478
489
  if (locked()) return;