@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.
package/dist/index.js CHANGED
@@ -6,39 +6,12 @@ var __export = (target, all) => {
6
6
 
7
7
  // src/logging/logger.ts
8
8
  function createLogger(scope = "root") {
9
- const sinks = /* @__PURE__ */ new Map();
10
- function log(level, message, data) {
11
- const entry = {
12
- level,
13
- scope,
14
- message,
15
- data,
16
- timestamp: Date.now()
17
- };
18
- for (const sink of sinks.values()) {
19
- if (!sink.levels.includes(level)) continue;
20
- if (sink.scopes && !sink.scopes.includes(scope)) continue;
21
- sink.write(entry);
22
- }
23
- }
24
- return {
25
- debug: (message, data) => log("debug", message, data),
26
- info: (message, data) => log("info", message, data),
27
- warn: (message, data) => log("warn", message, data),
28
- error: (message, data) => log("error", message, data),
29
- createScope(name) {
30
- return createChildLogger(sinks, name);
31
- },
32
- addSink(sink) {
33
- sinks.set(sink.id, sink);
34
- },
35
- removeSink(sinkId) {
36
- sinks.delete(sinkId);
37
- }
38
- };
9
+ return createChildLogger(/* @__PURE__ */ new Map(), scope);
39
10
  }
40
- function logWithSinks(sinks, level, scope, message, data) {
11
+ function logWithSinks(sinks, level, scope, message, data, meta) {
41
12
  const entry = { level, scope, message, data, timestamp: Date.now() };
13
+ if (meta?.actor) entry.actor = meta.actor;
14
+ if (meta?.syncRecord) entry.syncRecord = meta.syncRecord;
42
15
  for (const sink of sinks.values()) {
43
16
  if (!sink.levels.includes(level)) continue;
44
17
  if (sink.scopes && !sink.scopes.includes(scope)) continue;
@@ -47,13 +20,17 @@ function logWithSinks(sinks, level, scope, message, data) {
47
20
  }
48
21
  function createChildLogger(sinks, scope) {
49
22
  return {
50
- debug: (message, data) => logWithSinks(sinks, "debug", scope, message, data),
51
- info: (message, data) => logWithSinks(sinks, "info", scope, message, data),
52
- warn: (message, data) => logWithSinks(sinks, "warn", scope, message, data),
53
- error: (message, data) => logWithSinks(sinks, "error", scope, message, data),
23
+ debug: (message, data, meta) => logWithSinks(sinks, "debug", scope, message, data, meta),
24
+ info: (message, data, meta) => logWithSinks(sinks, "info", scope, message, data, meta),
25
+ warn: (message, data, meta) => logWithSinks(sinks, "warn", scope, message, data, meta),
26
+ error: (message, data, meta) => logWithSinks(sinks, "error", scope, message, data, meta),
54
27
  createScope: (childName) => createChildLogger(sinks, childName),
55
- addSink: (sink) => sinks.set(sink.id, sink),
56
- removeSink: (sinkId) => sinks.delete(sinkId)
28
+ addSink: (sink) => {
29
+ sinks.set(sink.id, sink);
30
+ },
31
+ removeSink: (sinkId) => {
32
+ sinks.delete(sinkId);
33
+ }
57
34
  };
58
35
  }
59
36
 
@@ -88,6 +65,49 @@ function callbackSink(options) {
88
65
  };
89
66
  }
90
67
 
68
+ // src/logging/logs-logic.ts
69
+ function presetFilters(preset, verbose) {
70
+ const level = verbose ? ["debug", "info", "warn", "error"] : ["info", "warn", "error"];
71
+ switch (preset) {
72
+ case "all":
73
+ return { level };
74
+ case "actions":
75
+ return { level, has_actor: true };
76
+ case "errors":
77
+ return { level: ["error"] };
78
+ }
79
+ }
80
+ function hasActor(entry) {
81
+ return !!(entry.actor?.id || entry.actor?.name);
82
+ }
83
+ function matchesPresetFilters(entry, filters) {
84
+ return filters.level.includes(entry.level) && (!filters.has_actor || hasActor(entry));
85
+ }
86
+ function deriveStuckRecords(entries) {
87
+ const latest = /* @__PURE__ */ new Map();
88
+ for (const entry of entries) {
89
+ if (!entry.syncRecord) continue;
90
+ const key = `${entry.syncRecord.collection}:${entry.syncRecord.recordId}`;
91
+ const seen = latest.get(key);
92
+ if (!seen || entry.timestamp >= seen.timestamp) latest.set(key, entry);
93
+ }
94
+ const stuck = [];
95
+ for (const [key, entry] of latest) {
96
+ const { collection, recordId, outcome, code, reason } = entry.syncRecord;
97
+ if (outcome === "ok") continue;
98
+ stuck.push({
99
+ key,
100
+ collection,
101
+ recordId,
102
+ outcome,
103
+ ...code ? { code } : {},
104
+ reason: reason || entry.message,
105
+ lastSeen: entry.timestamp
106
+ });
107
+ }
108
+ return stuck.sort((a, b) => b.lastSeen - a.lastSeen);
109
+ }
110
+
91
111
  // src/csv/csv.ts
92
112
  function csvCell(value) {
93
113
  const text2 = String(value ?? "");
@@ -4412,6 +4432,37 @@ async function mintClosureNumber(host, storeKey, registerId, closure) {
4412
4432
  });
4413
4433
  return number;
4414
4434
  }
4435
+ var STORE_COUNTERS = [
4436
+ ["last_closure_number", "lastClosureNumber"],
4437
+ ["perpetual_sales_total_minor", "perpetualSalesTotalMinor"],
4438
+ ["perpetual_refunds_total_minor", "perpetualRefundsTotalMinor"]
4439
+ ];
4440
+ function adoptStoreCounters(host, storeKey, registerId, counters) {
4441
+ return modifyStore(host, storeKey, (store) => {
4442
+ const register = store?.registers?.[registerId] ?? {};
4443
+ const raised = {};
4444
+ for (const [local, remote] of STORE_COUNTERS) for (const entry of counters) {
4445
+ const value = entry?.[remote];
4446
+ if (typeof value === "number" && Number.isSafeInteger(value) && value > (raised[local] ?? register[local] ?? 0)) raised[local] = value;
4447
+ }
4448
+ return Object.keys(raised).length ? withRegister(store, registerId, { ...register, ...raised }) : void 0;
4449
+ });
4450
+ }
4451
+ function renumberClosures(host, storeKey, registerId, rows) {
4452
+ const last = rows[rows.length - 1];
4453
+ return modifyStore(host, storeKey, (store) => {
4454
+ const register = store?.registers?.[registerId] ?? {};
4455
+ const reservation = register.closure_reservation;
4456
+ const row = rows.find(({ id: id2 }) => id2 === reservation?.row.id);
4457
+ return withRegister(store, registerId, {
4458
+ ...register,
4459
+ last_closure_number: last.number,
4460
+ perpetual_sales_total_minor: last.perpetual_sales_total_minor,
4461
+ perpetual_refunds_total_minor: last.perpetual_refunds_total_minor,
4462
+ ...reservation && row ? { closure_reservation: { ...reservation, row } } : {}
4463
+ });
4464
+ });
4465
+ }
4415
4466
  function advancePerpetual(host, storeKey, registerId, period) {
4416
4467
  return modifyStore(host, storeKey, (store) => {
4417
4468
  const register = store?.registers?.[registerId] ?? {};
@@ -4460,7 +4511,12 @@ function identity(fact) {
4460
4511
  function recordRegisterFact(fact) {
4461
4512
  const terminal = identity(fact);
4462
4513
  const pair = { sessionId: fact.sessionId, registerId: fact.registerId };
4463
- const emit = (message, type, context = {}, level = "info") => registerFactsLogger[level](message, { actor: fact.actor, terminal, context: { type, ...pair, ...context } });
4514
+ const emit = (message, type, context = {}, level = "info") => registerFactsLogger[level](
4515
+ message,
4516
+ { actor: fact.actor, terminal, context: { type, ...pair, ...context } },
4517
+ // The cashier also rides on the entry itself, so a Logs screen's Actions preset finds it (#656).
4518
+ fact.actor ? { actor: fact.actor } : void 0
4519
+ );
4464
4520
  switch (fact.kind) {
4465
4521
  case "session-opened":
4466
4522
  return emit("Register session opened", "register.session-opened", { amount: fact.amount, variance: fact.variance });
@@ -4546,7 +4602,7 @@ var validAmount = (value, exponent) => /^(?:\d+\.?\d*|\.\d+)$/.test(value) && Nu
4546
4602
  var countVariance = (countedMinor, expectedMinor) => countedMinor - expectedMinor;
4547
4603
  var overThreshold = (variance, thresholdMinor) => thresholdMinor != null && Math.abs(variance) > thresholdMinor;
4548
4604
  var closeNeedsApproval = (countedCashMinor, expectedCashMinor, thresholdMinor) => overThreshold(countVariance(countedCashMinor, expectedCashMinor), thresholdMinor);
4549
- var closureVariance = (counted, tillExpected) => Object.fromEntries(Object.entries(counted).map(([method, value]) => [method, countVariance(value, tillExpected[method] ?? 0)]));
4605
+ var closureVariance = (counted2, tillExpected) => Object.fromEntries(Object.entries(counted2).map(([method, value]) => [method, countVariance(value, tillExpected[method] ?? 0)]));
4550
4606
  var denominationTotal = (pieces) => Object.entries(pieces).reduce((sum2, [value, count]) => sum2 + Number(value) * count, 0);
4551
4607
  function varianceText(variance, exponent, format2, t) {
4552
4608
  if (!variance) return t("register.exact");
@@ -4753,16 +4809,16 @@ async function recordMovement(sessions, movements, closures, input) {
4753
4809
  created_by: input.actor,
4754
4810
  created_at_gmt: (/* @__PURE__ */ new Date()).toISOString()
4755
4811
  });
4756
- let counted;
4812
+ let counted2;
4757
4813
  try {
4758
4814
  const after = await readSession(sessions, input.sessionId);
4759
4815
  if (after?.status !== "closed") return row;
4760
- counted = (await closures.findOne(input.sessionId).exec())?.movement_ids;
4816
+ counted2 = (await closures.findOne(input.sessionId).exec())?.movement_ids;
4761
4817
  } catch {
4762
4818
  return row;
4763
4819
  }
4764
- if (!counted) throw new RegisterMovementStrandedError(row);
4765
- if (counted.includes(row.id)) return row;
4820
+ if (!counted2) throw new RegisterMovementStrandedError(row);
4821
+ if (counted2.includes(row.id)) return row;
4766
4822
  try {
4767
4823
  await row.remove();
4768
4824
  } catch {
@@ -4791,15 +4847,15 @@ async function voidMovement(sessions, movements, movementId, actor, closures) {
4791
4847
  created_at_gmt: (/* @__PURE__ */ new Date()).toISOString(),
4792
4848
  voids: row.id
4793
4849
  });
4794
- let counted;
4850
+ let counted2;
4795
4851
  try {
4796
4852
  const after = await readSession(sessions, row.session_id);
4797
4853
  if (after?.status !== "closed") return reversal;
4798
- counted = (await readClosure(closures, row.session_id))?.movement_ids;
4854
+ counted2 = (await readClosure(closures, row.session_id))?.movement_ids;
4799
4855
  } catch {
4800
4856
  return reversal;
4801
4857
  }
4802
- if (counted?.includes(reversal.id)) return reversal;
4858
+ if (counted2?.includes(reversal.id)) return reversal;
4803
4859
  throw new RegisterMovementStrandedError(reversal);
4804
4860
  }
4805
4861
  async function writeClosure({
@@ -4807,7 +4863,7 @@ async function writeClosure({
4807
4863
  register,
4808
4864
  storeKey,
4809
4865
  session,
4810
- counted,
4866
+ counted: counted2,
4811
4867
  otherTenders,
4812
4868
  movements,
4813
4869
  orders,
@@ -4847,7 +4903,7 @@ async function writeClosure({
4847
4903
  ledgerRowsBySession: rows,
4848
4904
  refunds
4849
4905
  });
4850
- const counts = { cash: counted, ...otherTenders };
4906
+ const counts = { cash: counted2, ...otherTenders };
4851
4907
  const sum2 = (values) => values.reduce((total, value) => total + value, 0);
4852
4908
  const payment_methods = {};
4853
4909
  for (const row2 of rows) {
@@ -5325,11 +5381,11 @@ function exportCsv(rows, exponent, t, names = {}, storeName = "") {
5325
5381
  ...tenders2.flatMap((method) => {
5326
5382
  const values = (row) => {
5327
5383
  const expected = at(row.expected, method);
5328
- const counted = at(row.counted, method) ?? (expected === void 0 ? void 0 : 0);
5329
- const value = at(row.variance, method) ?? (expected === void 0 ? void 0 : (counted ?? 0) - expected);
5384
+ const counted2 = at(row.counted, method) ?? (expected === void 0 ? void 0 : 0);
5385
+ const value = at(row.variance, method) ?? (expected === void 0 ? void 0 : (counted2 ?? 0) - expected);
5330
5386
  return [
5331
5387
  expected === void 0 ? "" : minorToDecimal(expected, exponent),
5332
- counted === void 0 ? "" : minorToDecimal(counted, exponent),
5388
+ counted2 === void 0 ? "" : minorToDecimal(counted2, exponent),
5333
5389
  value === void 0 ? "" : `${minorToDecimal(Math.abs(value), exponent)} ${t(value < 0 ? "register.short" : value > 0 ? "register.over" : "reports.exact")}`
5334
5390
  ];
5335
5391
  };
@@ -5486,10 +5542,10 @@ function envelope(row, context, xreport = false) {
5486
5542
  ([entryKey, value]) => money({ ...value, name: value.name ?? value.method ?? value.rate ?? entryKey }, fields)
5487
5543
  );
5488
5544
  const methods = breakdowns.payment_methods ?? {};
5489
- const counted = row.counted ?? {};
5545
+ const counted2 = row.counted ?? {};
5490
5546
  const expected = row.expected ?? {};
5491
5547
  const variances = row.variance ?? {};
5492
- const tenders2 = [.../* @__PURE__ */ new Set([...Object.keys(counted), ...Object.keys(expected)])].map((name) => {
5548
+ const tenders2 = [.../* @__PURE__ */ new Set([...Object.keys(counted2), ...Object.keys(expected)])].map((name) => {
5493
5549
  const variance = variances[name] ?? "";
5494
5550
  const method = Object.values(methods).find((m) => m.method === name) ?? methods[name];
5495
5551
  return money(
@@ -5497,7 +5553,7 @@ function envelope(row, context, xreport = false) {
5497
5553
  name,
5498
5554
  label: method?.name || name.charAt(0).toUpperCase() + name.slice(1),
5499
5555
  expected: expected[name] ?? "",
5500
- counted: counted[name] ?? "",
5556
+ counted: counted2[name] ?? "",
5501
5557
  variance,
5502
5558
  has_variance: Number(variance || 0) !== 0,
5503
5559
  variance_label: variance === "" ? "" : context.i18n[Number(variance) > 0 ? "over" : Number(variance) < 0 ? "short" : "exact"],
@@ -5571,7 +5627,7 @@ function buildClosureDocument(row, context) {
5571
5627
  store_key,
5572
5628
  till_expected,
5573
5629
  expected,
5574
- counted,
5630
+ counted: counted2,
5575
5631
  variance,
5576
5632
  period_sales_total_minor,
5577
5633
  period_refunds_total_minor,
@@ -5587,7 +5643,7 @@ function buildClosureDocument(row, context) {
5587
5643
  store_id: store_key,
5588
5644
  till_expected: decimalMap(till_expected, exponent),
5589
5645
  expected: decimalMap(expected, exponent),
5590
- counted: decimalMap(counted, exponent),
5646
+ counted: decimalMap(counted2, exponent),
5591
5647
  variance: decimalMap(variance, exponent),
5592
5648
  period_sales_total: dec(period_sales_total_minor),
5593
5649
  period_refunds_total: dec(period_refunds_total_minor),
@@ -5825,6 +5881,7 @@ function isRequeueable(code) {
5825
5881
  return !NOT_REQUEUEABLE.has(code ?? "");
5826
5882
  }
5827
5883
  var REFUSAL_LOG_MESSAGE_MAX = 200;
5884
+ var syncRecordOf = (orderId, outcome) => ({ collection: "pos_orders", recordId: orderId, outcome });
5828
5885
  var ISOLATE_AFTER_ATTEMPTS = 5;
5829
5886
  var STUCK_AFTER_MS = 15 * 6e4;
5830
5887
  var validMax = (max) => typeof max === "number" && Number.isSafeInteger(max) && max > 0 ? max : void 0;
@@ -5938,7 +5995,7 @@ function createOrderOutbox(options) {
5938
5995
  if (runProgressed && retryAfterMs === void 0 && reason !== "status_429") return void 0;
5939
5996
  return Math.max(retryAfterMs ?? 0, isolated.get(id2).nextAt - now());
5940
5997
  }
5941
- if (alone === "probe") walk?.failed.set(id2, reason);
5998
+ if (alone === "probe") walk?.failed.set(id2, { orderId: orders[0].id, reason });
5942
5999
  else {
5943
6000
  head = { id: id2, count: head?.id === id2 ? head.count + 1 : 1 };
5944
6001
  if (head.count >= isolateAfter) walk ??= { failed: /* @__PURE__ */ new Map() };
@@ -6147,10 +6204,18 @@ function createOrderOutbox(options) {
6147
6204
  }
6148
6205
  }
6149
6206
  }
6150
- if (result.status === "rejected") outboxLogger[error?.code === "unsupported_version" ? "error" : "warn"](
6151
- "Order refused by the store",
6152
- { orderId: order.id, code: error?.code, message: error?.message?.slice(0, REFUSAL_LOG_MESSAGE_MAX) }
6153
- );
6207
+ if (result.status === "rejected") {
6208
+ const message = error?.message?.slice(0, REFUSAL_LOG_MESSAGE_MAX);
6209
+ outboxLogger[error?.code === "unsupported_version" ? "error" : "warn"](
6210
+ "Order refused by the store",
6211
+ { orderId: order.id, code: error?.code, message },
6212
+ { syncRecord: {
6213
+ ...syncRecordOf(order.id, "failed"),
6214
+ ...error?.code ? { code: error.code } : {},
6215
+ ...message ? { reason: message } : {}
6216
+ } }
6217
+ );
6218
+ }
6154
6219
  const updatedAt = new Date(now()).toISOString();
6155
6220
  await current.incrementalModify((data) => {
6156
6221
  delete data.serverFailures;
@@ -6161,6 +6226,9 @@ function createOrderOutbox(options) {
6161
6226
  updatedAt
6162
6227
  });
6163
6228
  });
6229
+ if (result.status !== "rejected") {
6230
+ outboxLogger.info("Order accepted by the store", { orderId: order.id }, { syncRecord: syncRecordOf(order.id, "ok") });
6231
+ }
6164
6232
  attempts.delete(order.commandId);
6165
6233
  isolated.delete(order.commandId);
6166
6234
  clocks.delete(order.commandId);
@@ -6175,7 +6243,14 @@ function createOrderOutbox(options) {
6175
6243
  runProgressed = true;
6176
6244
  if (alone !== "isolated") head = void 0;
6177
6245
  if (walk && alone === "probe") {
6178
- for (const [id2, reason] of walk.failed) isolate(id2, reason);
6246
+ for (const [id2, { orderId, reason }] of walk.failed) {
6247
+ isolate(id2, reason);
6248
+ outboxLogger.warn(
6249
+ "Order isolated: the store keeps failing it",
6250
+ { orderId, reason },
6251
+ { syncRecord: { ...syncRecordOf(orderId, "pending"), reason } }
6252
+ );
6253
+ }
6179
6254
  walk = void 0;
6180
6255
  }
6181
6256
  backoff = initialBackoff;
@@ -6617,7 +6692,62 @@ function createRegisterOutbox(options) {
6617
6692
 
6618
6693
  // src/register/register-adoption.ts
6619
6694
  var chains2 = /* @__PURE__ */ new WeakMap();
6620
- async function adoptRegisterResults({ commands, sessions, registerId }) {
6695
+ var figure = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
6696
+ var counted = (number, sales, refunds) => {
6697
+ const [n, s, r] = [figure(number), figure(sales), figure(refunds)];
6698
+ return n === void 0 || s === void 0 || r === void 0 ? void 0 : { number: n, sales: s, refunds: r };
6699
+ };
6700
+ async function renumberRefused(commands, closures, host, storeKey, registerId) {
6701
+ const [submits, local] = await Promise.all([
6702
+ readFresh(commands, { selector: { registerId, type: "register.closure.submit" }, sort: [{ seq: "asc" }, { key: "asc" }] }),
6703
+ readFresh(closures, { selector: { register_id: registerId } })
6704
+ ]);
6705
+ const refused = submits.find((submit) => submit.syncStatus === "rejected" && !NON_BLOCKING_REJECTIONS.has(submit.error?.code ?? ""));
6706
+ const row = local.find(({ id: id2, store_key }) => id2 === refused?.payload.closureId && (store_key ?? null) === storeKey);
6707
+ if (refused?.error?.code !== "register_closure_number_invalid" || !row) return;
6708
+ const sent = new Map(submits.map((submit) => [submit.payload.closureId, submit]));
6709
+ const unsent = (closure) => {
6710
+ const submit = sent.get(closure.id);
6711
+ return (closure.store_key ?? null) === storeKey && closure.closed_at >= row.closed_at && (!submit || submit.syncStatus === "pending" || submit.syncStatus === "rejected" && submit.error?.code === "register_closure_number_invalid");
6712
+ };
6713
+ let queued = local.filter(unsent).sort((a, b) => a.closed_at.localeCompare(b.closed_at) || a.id.localeCompare(b.id));
6714
+ if (!row.number_retried) {
6715
+ const store = refused.error.data?.counters ?? {};
6716
+ const base = counted(store.lastClosureNumber, store.perpetualSalesTotalMinor, store.perpetualRefundsTotalMinor);
6717
+ if (!base) return;
6718
+ let { number, sales, refunds } = base;
6719
+ queued = queued.map((closure) => ({
6720
+ ...closure,
6721
+ number: ++number,
6722
+ perpetual_sales_total_minor: sales += closure.period_sales_total_minor,
6723
+ perpetual_refunds_total_minor: refunds += closure.period_refunds_total_minor,
6724
+ number_retried: closure.number_retried || closure.id === row.id
6725
+ }));
6726
+ await renumberClosures(host, storeKey, registerId, queued);
6727
+ } else if (refused.payload.number === row.number) return;
6728
+ for (const closure of [...queued.filter(({ id: id2 }) => id2 !== row.id), ...queued.filter(({ id: id2 }) => id2 === row.id)]) {
6729
+ const { number, perpetual_sales_total_minor: sales, perpetual_refunds_total_minor: refunds, number_retried } = closure;
6730
+ if (!row.number_retried) await (await closures.findOne(closure.id).exec(true)).incrementalPatch({
6731
+ number,
6732
+ perpetual_sales_total_minor: sales,
6733
+ perpetual_refunds_total_minor: refunds,
6734
+ number_retried
6735
+ });
6736
+ const submit = sent.get(closure.id);
6737
+ if (!submit || submit.syncStatus === "pending" && submit.payload.number === number && submit.payload.perpetualSalesTotalMinor === sales && submit.payload.perpetualRefundsTotalMinor === refunds) continue;
6738
+ await (await commands.findOne(submit.key).exec())?.incrementalModify((doc) => {
6739
+ if (doc.commandId !== submit.commandId || doc.syncStatus !== submit.syncStatus) return doc;
6740
+ const { error: _refusal, ...rest } = doc;
6741
+ return { ...rest, commandId: uuidv7(), syncStatus: "pending", updatedAt: (/* @__PURE__ */ new Date()).toISOString(), payload: {
6742
+ ...doc.payload,
6743
+ number,
6744
+ perpetualSalesTotalMinor: sales,
6745
+ perpetualRefundsTotalMinor: refunds
6746
+ } };
6747
+ });
6748
+ }
6749
+ }
6750
+ async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey, closures }) {
6621
6751
  const run = (chains2.get(commands) ?? Promise.resolve()).then(async () => {
6622
6752
  const [answers, transitions, rows] = await Promise.all([
6623
6753
  readFresh(commands, { selector: { registerId, syncStatus: { $in: ["applied", "rejected"] } }, sort: [{ seq: "asc" }, { key: "asc" }] }),
@@ -6650,6 +6780,9 @@ async function adoptRegisterResults({ commands, sessions, registerId }) {
6650
6780
  const row = await sessions.findOne(session.id).exec();
6651
6781
  if (row) await row.incrementalModify(modify);
6652
6782
  }
6783
+ const counters = answers.filter((answer) => answer.syncStatus === "applied" && answer.result?.counters).map((answer) => answer.result?.counters);
6784
+ if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, counters);
6785
+ if (host && storeKey && closures) await renumberRefused(commands, closures, host, storeKey, registerId);
6653
6786
  }).catch((error) => {
6654
6787
  registerCommandsLogger.error("Register result adoption failed", { context: { registerId, error: String(error) } });
6655
6788
  });
@@ -6779,17 +6912,17 @@ var subscribeClosing = (listener) => {
6779
6912
  };
6780
6913
  };
6781
6914
  var closedFacts = /* @__PURE__ */ new Set();
6782
- var isTenderMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((figure) => typeof figure === "number");
6915
+ var isTenderMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((figure2) => typeof figure2 === "number");
6783
6916
  function approvalNeededOf(commandRows, sessions) {
6784
6917
  const row = commandRows.filter((command) => command.type === "register.closure.submit" && command.syncStatus === "rejected" && CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? "")).sort((a, b) => a.seq - b.seq)[0];
6785
6918
  if (!row) return null;
6786
- const { closureId, sessionId, counted, tillExpected } = row.payload;
6919
+ const { closureId, sessionId, counted: counted2, tillExpected } = row.payload;
6787
6920
  const data = row.error?.data;
6788
6921
  return {
6789
6922
  closureId,
6790
6923
  sessionId,
6791
6924
  code: row.error.code,
6792
- variance: isTenderMap(data?.variance) ? data.variance : closureVariance(isTenderMap(counted) ? counted : {}, isTenderMap(tillExpected) ? tillExpected : {}),
6925
+ variance: isTenderMap(data?.variance) ? data.variance : closureVariance(isTenderMap(counted2) ? counted2 : {}, isTenderMap(tillExpected) ? tillExpected : {}),
6793
6926
  ...typeof data?.reason === "string" ? { reason: data.reason } : {},
6794
6927
  liveAtStore: isLiveAtStore(
6795
6928
  sessions.find((session) => session.id === sessionId),
@@ -6812,7 +6945,7 @@ function ledgerRows(orders, replaced = replacedOrderIds(orders)) {
6812
6945
  amountMinor: payment.amountMinor
6813
6946
  })));
6814
6947
  }
6815
- var closedCount = (counted) => ({ ...counted, cash: counted.cash ?? 0 });
6948
+ var closedCount = (counted2) => ({ ...counted2, cash: counted2.cash ?? 0 });
6816
6949
  var sameVariance = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.entries(b).every(([method, value]) => a[method] === value);
6817
6950
  function useRegisterSession(options) {
6818
6951
  const { sessions, movements, closures, orders, register, storeKey, registerId, enabled, actor, timezone, tenderInProgress, expectedCloseTime, labels } = options;
@@ -7169,10 +7302,10 @@ function useRegisterSession(options) {
7169
7302
  }
7170
7303
  },
7171
7304
  /** ADR-082 d3: the variance this count would close with, read as the gate reads it; the app sends it to its approval route and back as `approvedVariance`. */
7172
- closureVariance: async (counted) => {
7305
+ closureVariance: async (counted2) => {
7173
7306
  const stored = await readSession(live().sessions, current().id);
7174
7307
  if (!stored) throw new RegisterSessionRequiredError();
7175
- return closureVariance(closedCount(counted), await freshExpected(stored));
7308
+ return closureVariance(closedCount(counted2), await freshExpected(stored));
7176
7309
  },
7177
7310
  recordMovement: async (input) => {
7178
7311
  try {
@@ -7314,6 +7447,7 @@ var SALE_SAVING = "This sale is being saved. Retry to finish it.";
7314
7447
  var PAYMENT_IN_MOTION = "Finish or void the payment in progress before completing the sale";
7315
7448
  var SALE_PARTLY_PAID = "This sale is partly paid. Take the rest of the payment or void the paid legs first.";
7316
7449
  var SALE_IN_TENDER = "Finish or cancel the payment before switching sales";
7450
+ var REFERENCE_DROPPED = "The terminal's payment reference couldn't be kept";
7317
7451
  var HUNG_SAVE_CHECK_MS = 5e3;
7318
7452
  function useSale(settings, opts) {
7319
7453
  const taxContext = useTax();
@@ -7413,7 +7547,7 @@ function useSale(settings, opts) {
7413
7547
  const paymentId = builder.addPayment(kept);
7414
7548
  if (dropped) {
7415
7549
  droppedReferences.current.add(paymentId);
7416
- setError(`The terminal's payment reference couldn't be kept (${dropped}); the payment is recorded without it.`);
7550
+ setError(`${REFERENCE_DROPPED} (${dropped}); the payment is recorded without it.`);
7417
7551
  }
7418
7552
  try {
7419
7553
  if (dropped) saleLogger.warn("the terminal's payment reference was dropped", { reason: dropped, method: tender.method });
@@ -7429,6 +7563,9 @@ function useSale(settings, opts) {
7429
7563
  setError(null);
7430
7564
  if (tender) addOne(tender);
7431
7565
  }
7566
+ function clearStaleError() {
7567
+ setError((current) => current?.startsWith(REFERENCE_DROPPED) ? current : null);
7568
+ }
7432
7569
  function checkStored(completion) {
7433
7570
  const attempt2 = attempts.current;
7434
7571
  const isStored = opts.isStored;
@@ -7493,8 +7630,9 @@ function useSale(settings, opts) {
7493
7630
  saving,
7494
7631
  /** The failed save's order is confirmed stored (see `isStored`): the UI also offers Continue (`continueSale()`). */
7495
7632
  canContinue,
7633
+ /** Adds the entry, as a new line or one more on its line; returns that line's id, or the refusal `error` now shows. */
7496
7634
  add(entry, traits) {
7497
- if (locked()) return;
7635
+ if (locked()) return SALE_SAVING;
7498
7636
  const builder = builderNow.current;
7499
7637
  try {
7500
7638
  const known = new Set(builder.getSnapshot().lineItems.map((line2) => line2.id));
@@ -7513,12 +7651,15 @@ function useSale(settings, opts) {
7513
7651
  ].find((message) => message !== null);
7514
7652
  if (refused) {
7515
7653
  builder.removeItem(lineId);
7516
- return setError(refused);
7654
+ setError(refused);
7655
+ return refused;
7517
7656
  }
7518
7657
  setError(null);
7658
+ return { lineId };
7519
7659
  } catch (error2) {
7520
7660
  if (!(error2 instanceof CartError)) throw error2;
7521
7661
  setError(error2.message);
7662
+ return error2.message;
7522
7663
  }
7523
7664
  },
7524
7665
  setQuantity(lineId, quantity) {
@@ -7706,8 +7847,10 @@ function useSale(settings, opts) {
7706
7847
  const snapshot = builderNow.current.getSnapshot();
7707
7848
  const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
7708
7849
  if (due <= 0) return null;
7850
+ clearStaleError();
7709
7851
  return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) });
7710
7852
  }
7853
+ clearStaleError();
7711
7854
  return addOne(tender);
7712
7855
  },
7713
7856
  setTenderStatus(paymentId, status) {
@@ -7721,6 +7864,7 @@ function useSale(settings, opts) {
7721
7864
  if (!payment || payment.method !== "cash" && payment.method !== "external" || !canVoidLeg(payment, paymentMethodOf(payment.method))) return false;
7722
7865
  builderNow.current.setPaymentStatus(paymentId, "voided");
7723
7866
  droppedReferences.current.delete(paymentId);
7867
+ clearStaleError();
7724
7868
  return true;
7725
7869
  },
7726
7870
  /** ADR-072: remove one tender and its dropped-reference warning. An id not among the payments changes nothing. */
@@ -7729,6 +7873,7 @@ function useSale(settings, opts) {
7729
7873
  if (!builderNow.current.getSnapshot().payments.some((payment) => payment.id === paymentId)) return;
7730
7874
  builderNow.current.removePayment(paymentId);
7731
7875
  droppedReferences.current.delete(paymentId);
7876
+ clearStaleError();
7732
7877
  },
7733
7878
  cancelTender() {
7734
7879
  if (locked()) return;
@@ -8086,9 +8231,9 @@ function createSaleCouponSource(deps) {
8086
8231
  const data = doc.toJSON(true);
8087
8232
  if (!["percent", "fixed_cart", "fixed_product"].includes(data.discount_type) || !Number.isInteger(data.id) || typeof data.amount !== "string") return null;
8088
8233
  const orders = await deps.orders.find({ selector: { syncStatus: { $in: ["pending", "applied"] } } }).exec();
8089
- const counted = orders.filter((order) => order.coupons?.some((coupon) => coupon.code === code) && (order.syncStatus === "pending" || Date.parse(order.updatedAt) > data._meta.lwt && now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS));
8234
+ const counted2 = orders.filter((order) => order.coupons?.some((coupon) => coupon.code === code) && (order.syncStatus === "pending" || Date.parse(order.updatedAt) > data._meta.lwt && now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS));
8090
8235
  const usedBy = [...data.used_by ?? []];
8091
- for (const order of counted) {
8236
+ for (const order of counted2) {
8092
8237
  const id2 = Number(order.customer?.id);
8093
8238
  const email = order.customer?.email;
8094
8239
  if (Number.isSafeInteger(id2) && id2 > 0) usedBy.push(String(id2));
@@ -8115,7 +8260,7 @@ function createSaleCouponSource(deps) {
8115
8260
  amount: data.amount,
8116
8261
  id: data.id,
8117
8262
  code,
8118
- usage_count: (data.usage_count ?? 0) + counted.length,
8263
+ usage_count: (data.usage_count ?? 0) + counted2.length,
8119
8264
  used_by: usedBy
8120
8265
  };
8121
8266
  },
@@ -9291,6 +9436,7 @@ export {
9291
9436
  denominations,
9292
9437
  deriveExpected,
9293
9438
  deriveSettled,
9439
+ deriveStuckRecords,
9294
9440
  displayCart,
9295
9441
  displayReducer,
9296
9442
  driverForMethod,
@@ -9308,6 +9454,7 @@ export {
9308
9454
  getDeviceId,
9309
9455
  getProductStock,
9310
9456
  handoverSlip,
9457
+ hasActor,
9311
9458
  hasValidRetailCheckDigit,
9312
9459
  inCategory,
9313
9460
  inMotionMinor,
@@ -9328,6 +9475,7 @@ export {
9328
9475
  listCategories,
9329
9476
  makeEnvelope,
9330
9477
  marginOf,
9478
+ matchesPresetFilters,
9331
9479
  messageBytes,
9332
9480
  minorToDecimal,
9333
9481
  mintClosureNumber,
@@ -9356,6 +9504,7 @@ export {
9356
9504
  posOrdersLogger,
9357
9505
  posRefundCollection,
9358
9506
  posRefundSchema,
9507
+ presetFilters,
9359
9508
  presetRange,
9360
9509
  priceRefund,
9361
9510
  printerProfileCollection,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/pos",
3
- "version": "3.15.0",
3
+ "version": "3.17.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.15.0",
37
+ "@tallyui/core": "^3.17.0",
38
38
  "react": ">=18",
39
39
  "rxdb": "~17.5.0",
40
40
  "rxjs": ">=7"
41
41
  },
42
42
  "devDependencies": {
43
- "@tallyui/core": "3.15.0",
43
+ "@tallyui/core": "3.17.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.15.0",
49
- "@tallyui/connector-woocommerce": "3.15.0",
50
- "@tallyui/database": "3.15.0"
48
+ "@tallyui/connector-medusa": "3.17.0",
49
+ "@tallyui/connector-woocommerce": "3.17.0",
50
+ "@tallyui/database": "3.17.0"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsup",
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';
@@ -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';