@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/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 ?? "");
@@ -106,10 +126,41 @@ function toCsv(rows, columns) {
106
126
  // src/currency/currency-provider.tsx
107
127
  import { createContext, useContext, useMemo, useCallback } from "react";
108
128
  import { formatMoney } from "@tallyui/core";
129
+
130
+ // src/currency/format-money-with.ts
131
+ import { minorUnitDigits } from "@tallyui/core";
132
+ function formatMoneyWith(money, format2, locale) {
133
+ if (money.currency === "XXX") return void 0;
134
+ const minor2 = minorUnitDigits(money.currency);
135
+ const decimals = format2.decimals ?? minor2;
136
+ const abs = Math.abs(money.amount);
137
+ const major = decimals >= minor2 ? abs / 10 ** minor2 : Math.round(abs / 10 ** (minor2 - decimals)) / 10 ** decimals;
138
+ let parts;
139
+ try {
140
+ parts = new Intl.NumberFormat(locale, {
141
+ style: "currency",
142
+ currency: money.currency,
143
+ minimumFractionDigits: decimals,
144
+ maximumFractionDigits: decimals
145
+ }).formatToParts(major);
146
+ } catch {
147
+ return void 0;
148
+ }
149
+ const text2 = (...types) => parts.filter((p) => types.includes(p.type)).map((p) => p.value).join("");
150
+ const { position, thousandSeparator, decimalSeparator } = format2;
151
+ const integer = thousandSeparator === void 0 ? text2("integer", "group") : text2("integer").replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
152
+ const number = integer + (decimals > 0 ? (decimalSeparator ?? text2("decimal")) + text2("fraction") : "");
153
+ const symbol = text2("currency");
154
+ const left = position ? position.startsWith("left") : parts.findIndex((p) => p.type === "currency") < parts.findIndex((p) => p.type === "integer");
155
+ const gap = position ? position.endsWith("_space") ? " " : "" : text2("literal");
156
+ return (money.amount < 0 && major > 0 ? "-" : "") + (left ? symbol + gap + number : number + gap + symbol);
157
+ }
158
+
159
+ // src/currency/currency-provider.tsx
109
160
  import { jsx } from "react/jsx-runtime";
110
161
  var CurrencyCtx = createContext(null);
111
- function CurrencyProvider({ currencyCode, locale, children }) {
112
- const value = useMemo(() => ({ currencyCode, locale }), [currencyCode, locale]);
162
+ function CurrencyProvider({ currencyCode, locale, format: format2, children }) {
163
+ const value = useMemo(() => ({ currencyCode, locale, format: format2 }), [currencyCode, locale, format2]);
113
164
  return /* @__PURE__ */ jsx(CurrencyCtx.Provider, { value, children });
114
165
  }
115
166
  function useCurrencyFormatter() {
@@ -117,9 +168,10 @@ function useCurrencyFormatter() {
117
168
  if (!ctx) {
118
169
  throw new Error("useCurrencyFormatter() must be used within a <CurrencyProvider>");
119
170
  }
171
+ const { locale, format: format2 } = ctx;
120
172
  return useCallback(
121
- (money) => formatMoney(money, ctx.locale) ?? `${money.amount} ${money.currency}`,
122
- [ctx.locale]
173
+ (money) => (format2 ? formatMoneyWith(money, format2, locale) : formatMoney(money, locale)) ?? `${money.amount} ${money.currency}`,
174
+ [locale, format2]
123
175
  );
124
176
  }
125
177
  function useCurrencyCode() {
@@ -131,9 +183,9 @@ function useCurrencyCode() {
131
183
  }
132
184
 
133
185
  // src/order/woocommerce-tax.ts
134
- import { minorUnitDigits, woocommerceTax, woocommerceCoupons } from "@tallyui/core";
186
+ import { minorUnitDigits as minorUnitDigits2, woocommerceTax, woocommerceCoupons } from "@tallyui/core";
135
187
  function woocommerceLine(amountMinor, rates, inclusive, currency, roundAtSubtotal, pricesIncludeTax = inclusive) {
136
- const dp = minorUnitDigits(currency), factor = 10 ** dp;
188
+ const dp = minorUnitDigits2(currency), factor = 10 ** dp;
137
189
  const precision = woocommerceTax.getRoundingPrecision(dp);
138
190
  const input = {
139
191
  amount: amountMinor / factor,
@@ -169,7 +221,7 @@ function lineAmounts(net, taxes, taxLines, dp, roundAtSubtotal, pricesIncludeTax
169
221
  };
170
222
  }
171
223
  function woocommerceCouponReplay(lines, codes, context, getTaxRates, currency, roundAtSubtotal, pricesIncludeTax) {
172
- const dp = minorUnitDigits(currency), factor = 10 ** dp;
224
+ const dp = minorUnitDigits2(currency), factor = 10 ** dp;
173
225
  const inputLines = lines.filter((line) => line.unitPriceMinor >= 0);
174
226
  const lineItems = inputLines.map((line) => {
175
227
  const productId = Number(line.productId), variationId = Number(line.variantId);
@@ -233,7 +285,7 @@ function woocommerceCouponReplay(lines, codes, context, getTaxRates, currency, r
233
285
  };
234
286
  }
235
287
  function woocommerceTotals(lines, fees, shipping, currency, roundAtSubtotal, inclusive) {
236
- const dp = minorUnitDigits(currency), factor = 10 ** dp;
288
+ const dp = minorUnitDigits2(currency), factor = 10 ** dp;
237
289
  const net = (line) => Number(line.netMicros) / (factor * 1e6);
238
290
  const productNet = lines.reduce((sum2, line) => sum2 + (roundAtSubtotal ? net(line) : woocommerceTax.roundHalfUp(net(line), dp)), 0);
239
291
  const amount = productNet + fees.reduce((sum2, line) => sum2 + net(line), 0) + shipping.reduce((sum2, line) => sum2 + woocommerceTax.roundHalfUp(net(line), dp), 0);
@@ -1803,7 +1855,7 @@ function buildReceiptData(order, config) {
1803
1855
  }
1804
1856
 
1805
1857
  // src/receipt/reprint.ts
1806
- import { minorUnitDigits as minorUnitDigits2, woocommerceTax as woocommerceTax4 } from "@tallyui/core";
1858
+ import { minorUnitDigits as minorUnitDigits3, woocommerceTax as woocommerceTax4 } from "@tallyui/core";
1807
1859
 
1808
1860
  // src/pos-order/note-delivery.ts
1809
1861
  function noteDelivery(order) {
@@ -1833,7 +1885,7 @@ var sum = (amounts) => amounts.reduce((total, amount) => total + amount, 0);
1833
1885
  function buildReceiptDataFromPosOrder(order, config) {
1834
1886
  const { header, ...blocks } = reprintBlocks(config, order.customer);
1835
1887
  const { display, taxRounding: rounding } = order;
1836
- const dp = minorUnitDigits2(order.currency), factor = 10 ** dp;
1888
+ const dp = minorUnitDigits3(order.currency), factor = 10 ** dp;
1837
1889
  const wooGrossMinor = (line, roundAtSubtotal) => {
1838
1890
  const tax = line.taxLines.reduce((sum2, row) => sum2 + (roundAtSubtotal ? Number(row.taxMicros) / (factor * 1e6) : woocommerceTax4.roundTaxTotal(Number(row.taxMicros) / (factor * 1e6), dp, order.pricesIncludeTax)), 0);
1839
1891
  return Math.round(woocommerceTax4.roundHalfUp(Number(line.netMicros) / (factor * 1e6) + tax, dp) * factor);
@@ -3535,7 +3587,7 @@ import { useEffect as useEffect8, useLayoutEffect, useRef as useRef4, useState a
3535
3587
  import { paymentMethodOf } from "@tallyui/core";
3536
3588
 
3537
3589
  // src/pos-order/finalize.ts
3538
- import { minorUnitDigits as minorUnitDigits3, ORDER_NOTE_MAX } from "@tallyui/core";
3590
+ import { minorUnitDigits as minorUnitDigits4, ORDER_NOTE_MAX } from "@tallyui/core";
3539
3591
 
3540
3592
  // src/outbox/logger.ts
3541
3593
  var outboxLogger = createLogger("outbox");
@@ -3742,7 +3794,7 @@ function finalizeOrder(order, options = {}) {
3742
3794
  }
3743
3795
  display = {
3744
3796
  currency: order.currency,
3745
- exponent: minorUnitDigits3(order.currency),
3797
+ exponent: minorUnitDigits4(order.currency),
3746
3798
  ...order.display,
3747
3799
  ...fees?.length ? { fees: order.display.fees.map((row, i) => ({ ...row, id: fees[i].id })) } : {},
3748
3800
  ...shipping?.length ? { shipping: order.display.shipping.map((row, i) => ({ ...row, id: shipping[i].id })) } : {},
@@ -4428,6 +4480,21 @@ function adoptStoreCounters(host, storeKey, registerId, counters) {
4428
4480
  return Object.keys(raised).length ? withRegister(store, registerId, { ...register, ...raised }) : void 0;
4429
4481
  });
4430
4482
  }
4483
+ function renumberClosures(host, storeKey, registerId, rows) {
4484
+ const last = rows[rows.length - 1];
4485
+ return modifyStore(host, storeKey, (store) => {
4486
+ const register = store?.registers?.[registerId] ?? {};
4487
+ const reservation = register.closure_reservation;
4488
+ const row = rows.find(({ id: id2 }) => id2 === reservation?.row.id);
4489
+ return withRegister(store, registerId, {
4490
+ ...register,
4491
+ last_closure_number: last.number,
4492
+ perpetual_sales_total_minor: last.perpetual_sales_total_minor,
4493
+ perpetual_refunds_total_minor: last.perpetual_refunds_total_minor,
4494
+ ...reservation && row ? { closure_reservation: { ...reservation, row } } : {}
4495
+ });
4496
+ });
4497
+ }
4431
4498
  function advancePerpetual(host, storeKey, registerId, period) {
4432
4499
  return modifyStore(host, storeKey, (store) => {
4433
4500
  const register = store?.registers?.[registerId] ?? {};
@@ -4476,7 +4543,12 @@ function identity(fact) {
4476
4543
  function recordRegisterFact(fact) {
4477
4544
  const terminal = identity(fact);
4478
4545
  const pair = { sessionId: fact.sessionId, registerId: fact.registerId };
4479
- const emit = (message, type, context = {}, level = "info") => registerFactsLogger[level](message, { actor: fact.actor, terminal, context: { type, ...pair, ...context } });
4546
+ const emit = (message, type, context = {}, level = "info") => registerFactsLogger[level](
4547
+ message,
4548
+ { actor: fact.actor, terminal, context: { type, ...pair, ...context } },
4549
+ // The cashier also rides on the entry itself, so a Logs screen's Actions preset finds it (#656).
4550
+ fact.actor ? { actor: fact.actor } : void 0
4551
+ );
4480
4552
  switch (fact.kind) {
4481
4553
  case "session-opened":
4482
4554
  return emit("Register session opened", "register.session-opened", { amount: fact.amount, variance: fact.variance });
@@ -4562,7 +4634,7 @@ var validAmount = (value, exponent) => /^(?:\d+\.?\d*|\.\d+)$/.test(value) && Nu
4562
4634
  var countVariance = (countedMinor, expectedMinor) => countedMinor - expectedMinor;
4563
4635
  var overThreshold = (variance, thresholdMinor) => thresholdMinor != null && Math.abs(variance) > thresholdMinor;
4564
4636
  var closeNeedsApproval = (countedCashMinor, expectedCashMinor, thresholdMinor) => overThreshold(countVariance(countedCashMinor, expectedCashMinor), thresholdMinor);
4565
- var closureVariance = (counted, tillExpected) => Object.fromEntries(Object.entries(counted).map(([method, value]) => [method, countVariance(value, tillExpected[method] ?? 0)]));
4637
+ var closureVariance = (counted2, tillExpected) => Object.fromEntries(Object.entries(counted2).map(([method, value]) => [method, countVariance(value, tillExpected[method] ?? 0)]));
4566
4638
  var denominationTotal = (pieces) => Object.entries(pieces).reduce((sum2, [value, count]) => sum2 + Number(value) * count, 0);
4567
4639
  function varianceText(variance, exponent, format2, t) {
4568
4640
  if (!variance) return t("register.exact");
@@ -4769,16 +4841,16 @@ async function recordMovement(sessions, movements, closures, input) {
4769
4841
  created_by: input.actor,
4770
4842
  created_at_gmt: (/* @__PURE__ */ new Date()).toISOString()
4771
4843
  });
4772
- let counted;
4844
+ let counted2;
4773
4845
  try {
4774
4846
  const after = await readSession(sessions, input.sessionId);
4775
4847
  if (after?.status !== "closed") return row;
4776
- counted = (await closures.findOne(input.sessionId).exec())?.movement_ids;
4848
+ counted2 = (await closures.findOne(input.sessionId).exec())?.movement_ids;
4777
4849
  } catch {
4778
4850
  return row;
4779
4851
  }
4780
- if (!counted) throw new RegisterMovementStrandedError(row);
4781
- if (counted.includes(row.id)) return row;
4852
+ if (!counted2) throw new RegisterMovementStrandedError(row);
4853
+ if (counted2.includes(row.id)) return row;
4782
4854
  try {
4783
4855
  await row.remove();
4784
4856
  } catch {
@@ -4807,15 +4879,15 @@ async function voidMovement(sessions, movements, movementId, actor, closures) {
4807
4879
  created_at_gmt: (/* @__PURE__ */ new Date()).toISOString(),
4808
4880
  voids: row.id
4809
4881
  });
4810
- let counted;
4882
+ let counted2;
4811
4883
  try {
4812
4884
  const after = await readSession(sessions, row.session_id);
4813
4885
  if (after?.status !== "closed") return reversal;
4814
- counted = (await readClosure(closures, row.session_id))?.movement_ids;
4886
+ counted2 = (await readClosure(closures, row.session_id))?.movement_ids;
4815
4887
  } catch {
4816
4888
  return reversal;
4817
4889
  }
4818
- if (counted?.includes(reversal.id)) return reversal;
4890
+ if (counted2?.includes(reversal.id)) return reversal;
4819
4891
  throw new RegisterMovementStrandedError(reversal);
4820
4892
  }
4821
4893
  async function writeClosure({
@@ -4823,7 +4895,7 @@ async function writeClosure({
4823
4895
  register,
4824
4896
  storeKey,
4825
4897
  session,
4826
- counted,
4898
+ counted: counted2,
4827
4899
  otherTenders,
4828
4900
  movements,
4829
4901
  orders,
@@ -4863,7 +4935,7 @@ async function writeClosure({
4863
4935
  ledgerRowsBySession: rows,
4864
4936
  refunds
4865
4937
  });
4866
- const counts = { cash: counted, ...otherTenders };
4938
+ const counts = { cash: counted2, ...otherTenders };
4867
4939
  const sum2 = (values) => values.reduce((total, value) => total + value, 0);
4868
4940
  const payment_methods = {};
4869
4941
  for (const row2 of rows) {
@@ -5341,11 +5413,11 @@ function exportCsv(rows, exponent, t, names = {}, storeName = "") {
5341
5413
  ...tenders2.flatMap((method) => {
5342
5414
  const values = (row) => {
5343
5415
  const expected = at(row.expected, method);
5344
- const counted = at(row.counted, method) ?? (expected === void 0 ? void 0 : 0);
5345
- const value = at(row.variance, method) ?? (expected === void 0 ? void 0 : (counted ?? 0) - expected);
5416
+ const counted2 = at(row.counted, method) ?? (expected === void 0 ? void 0 : 0);
5417
+ const value = at(row.variance, method) ?? (expected === void 0 ? void 0 : (counted2 ?? 0) - expected);
5346
5418
  return [
5347
5419
  expected === void 0 ? "" : minorToDecimal(expected, exponent),
5348
- counted === void 0 ? "" : minorToDecimal(counted, exponent),
5420
+ counted2 === void 0 ? "" : minorToDecimal(counted2, exponent),
5349
5421
  value === void 0 ? "" : `${minorToDecimal(Math.abs(value), exponent)} ${t(value < 0 ? "register.short" : value > 0 ? "register.over" : "reports.exact")}`
5350
5422
  ];
5351
5423
  };
@@ -5502,10 +5574,10 @@ function envelope(row, context, xreport = false) {
5502
5574
  ([entryKey, value]) => money({ ...value, name: value.name ?? value.method ?? value.rate ?? entryKey }, fields)
5503
5575
  );
5504
5576
  const methods = breakdowns.payment_methods ?? {};
5505
- const counted = row.counted ?? {};
5577
+ const counted2 = row.counted ?? {};
5506
5578
  const expected = row.expected ?? {};
5507
5579
  const variances = row.variance ?? {};
5508
- const tenders2 = [.../* @__PURE__ */ new Set([...Object.keys(counted), ...Object.keys(expected)])].map((name) => {
5580
+ const tenders2 = [.../* @__PURE__ */ new Set([...Object.keys(counted2), ...Object.keys(expected)])].map((name) => {
5509
5581
  const variance = variances[name] ?? "";
5510
5582
  const method = Object.values(methods).find((m) => m.method === name) ?? methods[name];
5511
5583
  return money(
@@ -5513,7 +5585,7 @@ function envelope(row, context, xreport = false) {
5513
5585
  name,
5514
5586
  label: method?.name || name.charAt(0).toUpperCase() + name.slice(1),
5515
5587
  expected: expected[name] ?? "",
5516
- counted: counted[name] ?? "",
5588
+ counted: counted2[name] ?? "",
5517
5589
  variance,
5518
5590
  has_variance: Number(variance || 0) !== 0,
5519
5591
  variance_label: variance === "" ? "" : context.i18n[Number(variance) > 0 ? "over" : Number(variance) < 0 ? "short" : "exact"],
@@ -5587,7 +5659,7 @@ function buildClosureDocument(row, context) {
5587
5659
  store_key,
5588
5660
  till_expected,
5589
5661
  expected,
5590
- counted,
5662
+ counted: counted2,
5591
5663
  variance,
5592
5664
  period_sales_total_minor,
5593
5665
  period_refunds_total_minor,
@@ -5603,7 +5675,7 @@ function buildClosureDocument(row, context) {
5603
5675
  store_id: store_key,
5604
5676
  till_expected: decimalMap(till_expected, exponent),
5605
5677
  expected: decimalMap(expected, exponent),
5606
- counted: decimalMap(counted, exponent),
5678
+ counted: decimalMap(counted2, exponent),
5607
5679
  variance: decimalMap(variance, exponent),
5608
5680
  period_sales_total: dec(period_sales_total_minor),
5609
5681
  period_refunds_total: dec(period_refunds_total_minor),
@@ -5841,6 +5913,7 @@ function isRequeueable(code) {
5841
5913
  return !NOT_REQUEUEABLE.has(code ?? "");
5842
5914
  }
5843
5915
  var REFUSAL_LOG_MESSAGE_MAX = 200;
5916
+ var syncRecordOf = (orderId, outcome) => ({ collection: "pos_orders", recordId: orderId, outcome });
5844
5917
  var ISOLATE_AFTER_ATTEMPTS = 5;
5845
5918
  var STUCK_AFTER_MS = 15 * 6e4;
5846
5919
  var validMax = (max) => typeof max === "number" && Number.isSafeInteger(max) && max > 0 ? max : void 0;
@@ -5954,7 +6027,7 @@ function createOrderOutbox(options) {
5954
6027
  if (runProgressed && retryAfterMs === void 0 && reason !== "status_429") return void 0;
5955
6028
  return Math.max(retryAfterMs ?? 0, isolated.get(id2).nextAt - now());
5956
6029
  }
5957
- if (alone === "probe") walk?.failed.set(id2, reason);
6030
+ if (alone === "probe") walk?.failed.set(id2, { orderId: orders[0].id, reason });
5958
6031
  else {
5959
6032
  head = { id: id2, count: head?.id === id2 ? head.count + 1 : 1 };
5960
6033
  if (head.count >= isolateAfter) walk ??= { failed: /* @__PURE__ */ new Map() };
@@ -6163,10 +6236,18 @@ function createOrderOutbox(options) {
6163
6236
  }
6164
6237
  }
6165
6238
  }
6166
- if (result.status === "rejected") outboxLogger[error?.code === "unsupported_version" ? "error" : "warn"](
6167
- "Order refused by the store",
6168
- { orderId: order.id, code: error?.code, message: error?.message?.slice(0, REFUSAL_LOG_MESSAGE_MAX) }
6169
- );
6239
+ if (result.status === "rejected") {
6240
+ const message = error?.message?.slice(0, REFUSAL_LOG_MESSAGE_MAX);
6241
+ outboxLogger[error?.code === "unsupported_version" ? "error" : "warn"](
6242
+ "Order refused by the store",
6243
+ { orderId: order.id, code: error?.code, message },
6244
+ { syncRecord: {
6245
+ ...syncRecordOf(order.id, "failed"),
6246
+ ...error?.code ? { code: error.code } : {},
6247
+ ...message ? { reason: message } : {}
6248
+ } }
6249
+ );
6250
+ }
6170
6251
  const updatedAt = new Date(now()).toISOString();
6171
6252
  await current.incrementalModify((data) => {
6172
6253
  delete data.serverFailures;
@@ -6177,6 +6258,9 @@ function createOrderOutbox(options) {
6177
6258
  updatedAt
6178
6259
  });
6179
6260
  });
6261
+ if (result.status !== "rejected") {
6262
+ outboxLogger.info("Order accepted by the store", { orderId: order.id }, { syncRecord: syncRecordOf(order.id, "ok") });
6263
+ }
6180
6264
  attempts.delete(order.commandId);
6181
6265
  isolated.delete(order.commandId);
6182
6266
  clocks.delete(order.commandId);
@@ -6191,7 +6275,14 @@ function createOrderOutbox(options) {
6191
6275
  runProgressed = true;
6192
6276
  if (alone !== "isolated") head = void 0;
6193
6277
  if (walk && alone === "probe") {
6194
- for (const [id2, reason] of walk.failed) isolate(id2, reason);
6278
+ for (const [id2, { orderId, reason }] of walk.failed) {
6279
+ isolate(id2, reason);
6280
+ outboxLogger.warn(
6281
+ "Order isolated: the store keeps failing it",
6282
+ { orderId, reason },
6283
+ { syncRecord: { ...syncRecordOf(orderId, "pending"), reason } }
6284
+ );
6285
+ }
6195
6286
  walk = void 0;
6196
6287
  }
6197
6288
  backoff = initialBackoff;
@@ -6633,7 +6724,62 @@ function createRegisterOutbox(options) {
6633
6724
 
6634
6725
  // src/register/register-adoption.ts
6635
6726
  var chains2 = /* @__PURE__ */ new WeakMap();
6636
- async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey }) {
6727
+ var figure = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
6728
+ var counted = (number, sales, refunds) => {
6729
+ const [n, s, r] = [figure(number), figure(sales), figure(refunds)];
6730
+ return n === void 0 || s === void 0 || r === void 0 ? void 0 : { number: n, sales: s, refunds: r };
6731
+ };
6732
+ async function renumberRefused(commands, closures, host, storeKey, registerId) {
6733
+ const [submits, local] = await Promise.all([
6734
+ readFresh(commands, { selector: { registerId, type: "register.closure.submit" }, sort: [{ seq: "asc" }, { key: "asc" }] }),
6735
+ readFresh(closures, { selector: { register_id: registerId } })
6736
+ ]);
6737
+ const refused = submits.find((submit) => submit.syncStatus === "rejected" && !NON_BLOCKING_REJECTIONS.has(submit.error?.code ?? ""));
6738
+ const row = local.find(({ id: id2, store_key }) => id2 === refused?.payload.closureId && (store_key ?? null) === storeKey);
6739
+ if (refused?.error?.code !== "register_closure_number_invalid" || !row) return;
6740
+ const sent = new Map(submits.map((submit) => [submit.payload.closureId, submit]));
6741
+ const unsent = (closure) => {
6742
+ const submit = sent.get(closure.id);
6743
+ 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");
6744
+ };
6745
+ let queued = local.filter(unsent).sort((a, b) => a.closed_at.localeCompare(b.closed_at) || a.id.localeCompare(b.id));
6746
+ if (!row.number_retried) {
6747
+ const store = refused.error.data?.counters ?? {};
6748
+ const base = counted(store.lastClosureNumber, store.perpetualSalesTotalMinor, store.perpetualRefundsTotalMinor);
6749
+ if (!base) return;
6750
+ let { number, sales, refunds } = base;
6751
+ queued = queued.map((closure) => ({
6752
+ ...closure,
6753
+ number: ++number,
6754
+ perpetual_sales_total_minor: sales += closure.period_sales_total_minor,
6755
+ perpetual_refunds_total_minor: refunds += closure.period_refunds_total_minor,
6756
+ number_retried: closure.number_retried || closure.id === row.id
6757
+ }));
6758
+ await renumberClosures(host, storeKey, registerId, queued);
6759
+ } else if (refused.payload.number === row.number) return;
6760
+ for (const closure of [...queued.filter(({ id: id2 }) => id2 !== row.id), ...queued.filter(({ id: id2 }) => id2 === row.id)]) {
6761
+ const { number, perpetual_sales_total_minor: sales, perpetual_refunds_total_minor: refunds, number_retried } = closure;
6762
+ if (!row.number_retried) await (await closures.findOne(closure.id).exec(true)).incrementalPatch({
6763
+ number,
6764
+ perpetual_sales_total_minor: sales,
6765
+ perpetual_refunds_total_minor: refunds,
6766
+ number_retried
6767
+ });
6768
+ const submit = sent.get(closure.id);
6769
+ if (!submit || submit.syncStatus === "pending" && submit.payload.number === number && submit.payload.perpetualSalesTotalMinor === sales && submit.payload.perpetualRefundsTotalMinor === refunds) continue;
6770
+ await (await commands.findOne(submit.key).exec())?.incrementalModify((doc) => {
6771
+ if (doc.commandId !== submit.commandId || doc.syncStatus !== submit.syncStatus) return doc;
6772
+ const { error: _refusal, ...rest } = doc;
6773
+ return { ...rest, commandId: uuidv7(), syncStatus: "pending", updatedAt: (/* @__PURE__ */ new Date()).toISOString(), payload: {
6774
+ ...doc.payload,
6775
+ number,
6776
+ perpetualSalesTotalMinor: sales,
6777
+ perpetualRefundsTotalMinor: refunds
6778
+ } };
6779
+ });
6780
+ }
6781
+ }
6782
+ async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey, closures }) {
6637
6783
  const run = (chains2.get(commands) ?? Promise.resolve()).then(async () => {
6638
6784
  const [answers, transitions, rows] = await Promise.all([
6639
6785
  readFresh(commands, { selector: { registerId, syncStatus: { $in: ["applied", "rejected"] } }, sort: [{ seq: "asc" }, { key: "asc" }] }),
@@ -6668,6 +6814,7 @@ async function adoptRegisterResults({ commands, sessions, registerId, host, stor
6668
6814
  }
6669
6815
  const counters = answers.filter((answer) => answer.syncStatus === "applied" && answer.result?.counters).map((answer) => answer.result?.counters);
6670
6816
  if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, counters);
6817
+ if (host && storeKey && closures) await renumberRefused(commands, closures, host, storeKey, registerId);
6671
6818
  }).catch((error) => {
6672
6819
  registerCommandsLogger.error("Register result adoption failed", { context: { registerId, error: String(error) } });
6673
6820
  });
@@ -6797,17 +6944,17 @@ var subscribeClosing = (listener) => {
6797
6944
  };
6798
6945
  };
6799
6946
  var closedFacts = /* @__PURE__ */ new Set();
6800
- var isTenderMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((figure) => typeof figure === "number");
6947
+ var isTenderMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((figure2) => typeof figure2 === "number");
6801
6948
  function approvalNeededOf(commandRows, sessions) {
6802
6949
  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];
6803
6950
  if (!row) return null;
6804
- const { closureId, sessionId, counted, tillExpected } = row.payload;
6951
+ const { closureId, sessionId, counted: counted2, tillExpected } = row.payload;
6805
6952
  const data = row.error?.data;
6806
6953
  return {
6807
6954
  closureId,
6808
6955
  sessionId,
6809
6956
  code: row.error.code,
6810
- variance: isTenderMap(data?.variance) ? data.variance : closureVariance(isTenderMap(counted) ? counted : {}, isTenderMap(tillExpected) ? tillExpected : {}),
6957
+ variance: isTenderMap(data?.variance) ? data.variance : closureVariance(isTenderMap(counted2) ? counted2 : {}, isTenderMap(tillExpected) ? tillExpected : {}),
6811
6958
  ...typeof data?.reason === "string" ? { reason: data.reason } : {},
6812
6959
  liveAtStore: isLiveAtStore(
6813
6960
  sessions.find((session) => session.id === sessionId),
@@ -6830,7 +6977,7 @@ function ledgerRows(orders, replaced = replacedOrderIds(orders)) {
6830
6977
  amountMinor: payment.amountMinor
6831
6978
  })));
6832
6979
  }
6833
- var closedCount = (counted) => ({ ...counted, cash: counted.cash ?? 0 });
6980
+ var closedCount = (counted2) => ({ ...counted2, cash: counted2.cash ?? 0 });
6834
6981
  var sameVariance = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.entries(b).every(([method, value]) => a[method] === value);
6835
6982
  function useRegisterSession(options) {
6836
6983
  const { sessions, movements, closures, orders, register, storeKey, registerId, enabled, actor, timezone, tenderInProgress, expectedCloseTime, labels } = options;
@@ -7187,10 +7334,10 @@ function useRegisterSession(options) {
7187
7334
  }
7188
7335
  },
7189
7336
  /** 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`. */
7190
- closureVariance: async (counted) => {
7337
+ closureVariance: async (counted2) => {
7191
7338
  const stored = await readSession(live().sessions, current().id);
7192
7339
  if (!stored) throw new RegisterSessionRequiredError();
7193
- return closureVariance(closedCount(counted), await freshExpected(stored));
7340
+ return closureVariance(closedCount(counted2), await freshExpected(stored));
7194
7341
  },
7195
7342
  recordMovement: async (input) => {
7196
7343
  try {
@@ -7337,7 +7484,18 @@ var HUNG_SAVE_CHECK_MS = 5e3;
7337
7484
  function useSale(settings, opts) {
7338
7485
  const taxContext = useTax();
7339
7486
  const madeWith = useRef4({ taxContext, currency: settings.currency });
7340
- const [rendered, setBuilder] = useState7(() => createOrderBuilder({ currency: settings.currency, taxContext }));
7487
+ function defaulted() {
7488
+ const customer = opts.defaultCustomer ?? null;
7489
+ return customer && !customerRefusal(customer) ? customer : null;
7490
+ }
7491
+ const defaultKey = opts.defaultCustomer ? JSON.stringify([opts.defaultCustomer.id, opts.defaultCustomer.name, opts.defaultCustomer.email]) : "";
7492
+ const defaultSeen = useRef4(defaultKey);
7493
+ const [rendered, setBuilder] = useState7(() => {
7494
+ const first = createOrderBuilder({ currency: settings.currency, taxContext });
7495
+ const customer = defaulted();
7496
+ if (customer) first.setCustomer(customer);
7497
+ return first;
7498
+ });
7341
7499
  const builderNow = useRef4(rendered);
7342
7500
  const applied = useRef4(/* @__PURE__ */ new Map());
7343
7501
  const appliedWith = useRef4(null);
@@ -7381,7 +7539,7 @@ function useSale(settings, opts) {
7381
7539
  if (active) setError(SALE_SAVING);
7382
7540
  return active;
7383
7541
  }
7384
- function resetSale(customer, restored) {
7542
+ function resetSale(customer = defaulted(), restored) {
7385
7543
  if (inFlight.current && !pending.current) return setError(SALE_SAVING);
7386
7544
  if (pending.current && confirmed.current !== pending.current) {
7387
7545
  if (inFlight.current) checkStored(pending.current);
@@ -7413,7 +7571,9 @@ function useSale(settings, opts) {
7413
7571
  useLayoutEffect(() => {
7414
7572
  const live = builderNow.current.getSnapshot();
7415
7573
  const liveIdle = stageNow.current.kind === "cart" && !live.lineItems.length && !live.fees?.length && !live.shipping?.length && !inFlight.current && !pending.current;
7416
- if (liveIdle && (madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency)) resetSale(live.customer ?? null);
7574
+ const newDefault = defaultSeen.current !== defaultKey;
7575
+ defaultSeen.current = defaultKey;
7576
+ if (liveIdle && (newDefault || madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency)) resetSale(newDefault ? void 0 : live.customer ?? null);
7417
7577
  });
7418
7578
  useEffect8(() => () => {
7419
7579
  clearHungSaveTimer();
@@ -7515,8 +7675,9 @@ function useSale(settings, opts) {
7515
7675
  saving,
7516
7676
  /** The failed save's order is confirmed stored (see `isStored`): the UI also offers Continue (`continueSale()`). */
7517
7677
  canContinue,
7678
+ /** Adds the entry, as a new line or one more on its line; returns that line's id, or the refusal `error` now shows. */
7518
7679
  add(entry, traits) {
7519
- if (locked()) return;
7680
+ if (locked()) return SALE_SAVING;
7520
7681
  const builder = builderNow.current;
7521
7682
  try {
7522
7683
  const known = new Set(builder.getSnapshot().lineItems.map((line2) => line2.id));
@@ -7535,12 +7696,15 @@ function useSale(settings, opts) {
7535
7696
  ].find((message) => message !== null);
7536
7697
  if (refused) {
7537
7698
  builder.removeItem(lineId);
7538
- return setError(refused);
7699
+ setError(refused);
7700
+ return refused;
7539
7701
  }
7540
7702
  setError(null);
7703
+ return { lineId };
7541
7704
  } catch (error2) {
7542
7705
  if (!(error2 instanceof CartError)) throw error2;
7543
7706
  setError(error2.message);
7707
+ return error2.message;
7544
7708
  }
7545
7709
  },
7546
7710
  setQuantity(lineId, quantity) {
@@ -7848,7 +8012,7 @@ function useSale(settings, opts) {
7848
8012
  * updates or requeues `pos_orders` itself.
7849
8013
  */
7850
8014
  newSale() {
7851
- resetSale(null);
8015
+ resetSale();
7852
8016
  },
7853
8017
  /** Parks the cart in `drafts`; resolves to a refusal message, or null once parked. */
7854
8018
  async park() {
@@ -7860,7 +8024,7 @@ function useSale(settings, opts) {
7860
8024
  if (!snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length) return "There is nothing to park";
7861
8025
  await writeOrderDraft(opts.drafts, snapshot);
7862
8026
  if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return "The sale changed while it was being parked; park it again";
7863
- resetSale(null);
8027
+ resetSale();
7864
8028
  return null;
7865
8029
  },
7866
8030
  /** Resumes a draft into an empty cart; resolves to a refusal message, or null once resumed. */
@@ -7943,7 +8107,7 @@ function useSale(settings, opts) {
7943
8107
  await writeOrderDraft(opts.drafts, snapshot);
7944
8108
  if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return "The sale changed while it was being parked; park it again";
7945
8109
  }
7946
- resetSale(null);
8110
+ resetSale();
7947
8111
  return draftId === null ? null : result.resume(draftId);
7948
8112
  },
7949
8113
  /** Discards the current sale (nothing is parked) and starts an empty one; refused while saving, once a leg of an unfinished sale took or holds money, or in the tender stage. */
@@ -7952,7 +8116,7 @@ function useSale(settings, opts) {
7952
8116
  const { payments } = builderNow.current.getSnapshot();
7953
8117
  if (stageNow.current.kind !== "receipt" && (capturedMinor(payments) > 0 || payments.some(isInMotion))) return SALE_PARTLY_PAID;
7954
8118
  if (stageNow.current.kind === "tender") return SALE_IN_TENDER;
7955
- resetSale(null);
8119
+ resetSale();
7956
8120
  return null;
7957
8121
  },
7958
8122
  /**
@@ -8008,10 +8172,10 @@ __export(woocommerce_exports, {
8008
8172
  });
8009
8173
 
8010
8174
  // src/sale/woocommerce/discount-codes.ts
8011
- import { minorUnitDigits as minorUnitDigits5, woocommerceCoupons as woocommerceCoupons3 } from "@tallyui/core";
8175
+ import { minorUnitDigits as minorUnitDigits6, woocommerceCoupons as woocommerceCoupons3 } from "@tallyui/core";
8012
8176
 
8013
8177
  // src/sale/woocommerce/coupons.ts
8014
- import { minorUnitDigits as minorUnitDigits4 } from "@tallyui/core";
8178
+ import { minorUnitDigits as minorUnitDigits5 } from "@tallyui/core";
8015
8179
  function couponRefusal(code, rejection) {
8016
8180
  switch (rejection.code) {
8017
8181
  case "already_applied":
@@ -8039,7 +8203,7 @@ function couponRefusal(code, rejection) {
8039
8203
  }
8040
8204
  }
8041
8205
  function couponLineItems(lines, currency, categories) {
8042
- const digits = minorUnitDigits4(currency), factor = 10 ** digits;
8206
+ const digits = minorUnitDigits5(currency), factor = 10 ** digits;
8043
8207
  return lines.flatMap((line, lineIndex) => {
8044
8208
  if (line.unitPriceMinor < 0) return [];
8045
8209
  const id2 = Number(line.productId), product_id = !line.custom && Number.isSafeInteger(id2) && id2 >= 0 ? id2 : 0;
@@ -8075,7 +8239,7 @@ function createDiscountCodes(source) {
8075
8239
  lineItems: couponLineItems(snapshot.lineItems, snapshot.currency, sale.categories),
8076
8240
  appliedCoupons: [...sale.accepted.keys()],
8077
8241
  appliedCouponsWithIndividualUse: [...sale.accepted].filter(([, value]) => value.individual_use).map(([key]) => key),
8078
- cartSubtotal: snapshot.display.subtotalMinor / 10 ** minorUnitDigits5(snapshot.currency),
8242
+ cartSubtotal: snapshot.display.subtotalMinor / 10 ** minorUnitDigits6(snapshot.currency),
8079
8243
  customerEmail: snapshot.customer?.email ?? "",
8080
8244
  customerId: wooCustomerId(snapshot.customer),
8081
8245
  now: Date.now()
@@ -8112,9 +8276,9 @@ function createSaleCouponSource(deps) {
8112
8276
  const data = doc.toJSON(true);
8113
8277
  if (!["percent", "fixed_cart", "fixed_product"].includes(data.discount_type) || !Number.isInteger(data.id) || typeof data.amount !== "string") return null;
8114
8278
  const orders = await deps.orders.find({ selector: { syncStatus: { $in: ["pending", "applied"] } } }).exec();
8115
- 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));
8279
+ 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));
8116
8280
  const usedBy = [...data.used_by ?? []];
8117
- for (const order of counted) {
8281
+ for (const order of counted2) {
8118
8282
  const id2 = Number(order.customer?.id);
8119
8283
  const email = order.customer?.email;
8120
8284
  if (Number.isSafeInteger(id2) && id2 > 0) usedBy.push(String(id2));
@@ -8141,7 +8305,7 @@ function createSaleCouponSource(deps) {
8141
8305
  amount: data.amount,
8142
8306
  id: data.id,
8143
8307
  code,
8144
- usage_count: (data.usage_count ?? 0) + counted.length,
8308
+ usage_count: (data.usage_count ?? 0) + counted2.length,
8145
8309
  used_by: usedBy
8146
8310
  };
8147
8311
  },
@@ -9317,6 +9481,7 @@ export {
9317
9481
  denominations,
9318
9482
  deriveExpected,
9319
9483
  deriveSettled,
9484
+ deriveStuckRecords,
9320
9485
  displayCart,
9321
9486
  displayReducer,
9322
9487
  driverForMethod,
@@ -9334,6 +9499,7 @@ export {
9334
9499
  getDeviceId,
9335
9500
  getProductStock,
9336
9501
  handoverSlip,
9502
+ hasActor,
9337
9503
  hasValidRetailCheckDigit,
9338
9504
  inCategory,
9339
9505
  inMotionMinor,
@@ -9354,6 +9520,7 @@ export {
9354
9520
  listCategories,
9355
9521
  makeEnvelope,
9356
9522
  marginOf,
9523
+ matchesPresetFilters,
9357
9524
  messageBytes,
9358
9525
  minorToDecimal,
9359
9526
  mintClosureNumber,
@@ -9382,6 +9549,7 @@ export {
9382
9549
  posOrdersLogger,
9383
9550
  posRefundCollection,
9384
9551
  posRefundSchema,
9552
+ presetFilters,
9385
9553
  presetRange,
9386
9554
  priceRefund,
9387
9555
  printerProfileCollection,