@tallyui/pos 4.1.0 → 5.0.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.
Files changed (64) hide show
  1. package/dist/index.d.ts +584 -161
  2. package/dist/index.js +1908 -1077
  3. package/package.json +7 -6
  4. package/src/index.ts +17 -10
  5. package/src/order/index.ts +1 -0
  6. package/src/order/order-builder.ts +65 -21
  7. package/src/order/order-drafts.ts +78 -24
  8. package/src/order/taken-at.ts +5 -0
  9. package/src/order/types.ts +11 -2
  10. package/src/order/woocommerce-tax.ts +9 -12
  11. package/src/outbox/http-transport.ts +16 -1
  12. package/src/outbox/index.ts +2 -1
  13. package/src/outbox/needs-admin-reason.ts +10 -0
  14. package/src/outbox/order-outbox.ts +14 -5
  15. package/src/outbox/register-outbox.ts +4 -3
  16. package/src/outbox/types.ts +3 -1
  17. package/src/outbox/use-order-outbox.ts +7 -3
  18. package/src/pos-order/command.ts +3 -0
  19. package/src/pos-order/finalize.ts +11 -0
  20. package/src/pos-order/reopen.ts +11 -2
  21. package/src/pos-order/schema.ts +7 -2
  22. package/src/pos-order/types.ts +7 -1
  23. package/src/print/escpos/bluetooth-sink.ts +114 -0
  24. package/src/print/escpos/index.ts +4 -0
  25. package/src/print/escpos/transport.ts +3 -2
  26. package/src/print/escpos/usb-sink.ts +84 -0
  27. package/src/print/index.ts +2 -2
  28. package/src/receipt/build-receipt-data.ts +8 -1
  29. package/src/receipt/reprint.ts +2 -0
  30. package/src/receipt/types.ts +2 -0
  31. package/src/receipt-template/template-data.ts +1 -1
  32. package/src/receipt-template/wcpos/from-orders.ts +5 -1
  33. package/src/refund/index.ts +1 -0
  34. package/src/refund/needs-admin-line.ts +6 -0
  35. package/src/refund/refundable-lines.ts +2 -91
  36. package/src/refund/send-order-refund.ts +6 -1
  37. package/src/refund/submit-order-refund.ts +33 -1
  38. package/src/register/closing.ts +15 -0
  39. package/src/register/closure-document.ts +13 -5
  40. package/src/register/closure-figures.ts +83 -0
  41. package/src/register/document-labels.ts +5 -3
  42. package/src/register/expected.ts +30 -9
  43. package/src/register/index.ts +3 -1
  44. package/src/register/register-adoption.ts +42 -4
  45. package/src/register/register-document.ts +17 -0
  46. package/src/register/session-store.ts +48 -12
  47. package/src/register/use-register-session.ts +53 -20
  48. package/src/reports/adapters.ts +5 -1
  49. package/src/reports/index.ts +1 -1
  50. package/src/reports/sales-figures.ts +33 -6
  51. package/src/reports/types.ts +3 -1
  52. package/src/sale/index.ts +1 -1
  53. package/src/sale/use-sale.ts +321 -135
  54. package/src/store-orders/index.ts +5 -0
  55. package/src/store-orders/sales-range-query.ts +18 -0
  56. package/src/store-orders/use-store-orders-in-range.ts +127 -0
  57. package/src/store-orders/use-store-refunds-in-range.ts +179 -0
  58. package/src/tax/exact.ts +2 -10
  59. package/src/tax/index.ts +1 -0
  60. package/src/tender/cash-rounding.ts +49 -6
  61. package/src/tender/index.ts +1 -1
  62. package/src/tender/payment-legs.ts +5 -0
  63. package/src/tender/tender-figures.ts +3 -1
  64. package/src/outbox/types.test-d.ts +0 -27
package/dist/index.js CHANGED
@@ -83,9 +83,9 @@ function hasActor(entry) {
83
83
  function matchesPresetFilters(entry, filters) {
84
84
  return filters.level.includes(entry.level) && (!filters.has_actor || hasActor(entry));
85
85
  }
86
- function deriveStuckRecords(entries) {
86
+ function deriveStuckRecords(entries2) {
87
87
  const latest = /* @__PURE__ */ new Map();
88
- for (const entry of entries) {
88
+ for (const entry of entries2) {
89
89
  if (!entry.syncRecord) continue;
90
90
  const key = `${entry.syncRecord.collection}:${entry.syncRecord.recordId}`;
91
91
  const seen = latest.get(key);
@@ -110,8 +110,8 @@ function deriveStuckRecords(entries) {
110
110
 
111
111
  // src/csv/csv.ts
112
112
  function csvCell(value) {
113
- const text2 = String(value ?? "");
114
- return `"${(/^(?:[\t\r\n]|[\s\x00-\x1f\x7f-\x9f]*[=+\-@])/.test(text2) ? "'" + text2 : text2).replace(/"/g, '""')}"`;
113
+ const text3 = String(value ?? "");
114
+ return `"${(/^(?:[\t\r\n]|[\s\x00-\x1f\x7f-\x9f]*[=+\-@])/.test(text3) ? "'" + text3 : text3).replace(/"/g, '""')}"`;
115
115
  }
116
116
  function csvFromCells(lines) {
117
117
  return lines.map((line) => line.map(csvCell).join(",")).join("\r\n");
@@ -151,6 +151,9 @@ function useCurrencyCode() {
151
151
  return ctx.currencyCode;
152
152
  }
153
153
 
154
+ // src/tax/exact.ts
155
+ import { roundRatio } from "@tallyui/core";
156
+
154
157
  // src/order/woocommerce-tax.ts
155
158
  import { minorUnitDigits, woocommerceTax, woocommerceCoupons } from "@tallyui/core";
156
159
  function woocommerceLine(amountMinor, rates, inclusive, currency, roundAtSubtotal, pricesIncludeTax = inclusive) {
@@ -189,10 +192,10 @@ function lineAmounts(net, taxes, taxLines, dp, roundAtSubtotal, pricesIncludeTax
189
192
  taxMicros: taxLines.reduce((sum4, rate) => sum4 + BigInt(rate.taxMicros), 0n).toString()
190
193
  };
191
194
  }
192
- function woocommerceCouponReplay(lines, codes2, context, getTaxRates, currency, roundAtSubtotal, pricesIncludeTax) {
195
+ function woocommerceCouponReplay(lines, codes2, context, ratesFor, currency, roundAtSubtotal, pricesIncludeTax) {
193
196
  const dp = minorUnitDigits(currency), factor = 10 ** dp;
194
197
  const inputLines = lines.filter((line) => line.unitPriceMinor >= 0);
195
- const lineItems = inputLines.map((line) => {
198
+ const lineItems = inputLines.map((line, index2) => {
196
199
  const productId = Number(line.productId), variationId = Number(line.variantId);
197
200
  const net = (Number(line.netMicros) / (factor * 1e6)).toFixed(6);
198
201
  const taxes = line.taxLines.map((tax2) => {
@@ -204,7 +207,7 @@ function woocommerceCouponReplay(lines, codes2, context, getTaxRates, currency,
204
207
  product_id: !line.custom && Number.isSafeInteger(productId) && productId >= 0 ? productId : 0,
205
208
  ...Number.isSafeInteger(variationId) && variationId >= 0 ? { variation_id: variationId } : {},
206
209
  quantity: line.quantity,
207
- tax_class: line.taxClass ?? "",
210
+ tax_class: `line-${index2}`,
208
211
  ...line.taxStatus === "none" ? { tax_status: "none" } : {},
209
212
  subtotal: net,
210
213
  total: net,
@@ -213,18 +216,14 @@ function woocommerceCouponReplay(lines, codes2, context, getTaxRates, currency,
213
216
  total_tax: tax
214
217
  };
215
218
  });
216
- const taxRates = /* @__PURE__ */ new Map();
217
- for (const line of inputLines) for (const rate of getTaxRates(line.taxClass)) {
218
- const taxClass = woocommerceTax.normalizeTaxClass(line.taxClass);
219
- taxRates.set(JSON.stringify([rate.id, taxClass]), {
220
- id: rate.id,
221
- rate: rate.rate,
222
- compound: rate.compound,
223
- order: rate.priority,
224
- priority: rate.priority,
225
- class: taxClass
226
- });
227
- }
219
+ const taxRates = inputLines.flatMap((line, index2) => ratesFor(line).map((rate) => ({
220
+ id: rate.id,
221
+ rate: rate.rate,
222
+ compound: rate.compound,
223
+ order: rate.priority,
224
+ priority: rate.priority,
225
+ class: `line-${index2}`
226
+ })));
228
227
  const result = woocommerceCoupons.recalculateCoupons({
229
228
  lineItems,
230
229
  couponLines: codes2.map((code) => ({ code })),
@@ -232,7 +231,7 @@ function woocommerceCouponReplay(lines, codes2, context, getTaxRates, currency,
232
231
  pricesIncludeTax,
233
232
  calcDiscountsSequentially: context.calcDiscountsSequentially,
234
233
  productCategories: new Map(context.productCategories),
235
- taxRates: [...taxRates.values()],
234
+ taxRates,
236
235
  taxRoundAtSubtotal: roundAtSubtotal,
237
236
  dp
238
237
  });
@@ -303,6 +302,7 @@ function woocommerceTaxByRate(lines, roundAtSubtotal, taxLabels, orderTaxMinor)
303
302
 
304
303
  // src/tax/exact.ts
305
304
  import { ratePpmFromPercent } from "@tallyui/core";
305
+ import { roundRatio as roundRatio2 } from "@tallyui/core";
306
306
  var MICROS_PER_MINOR = 1000000n;
307
307
  var DEFAULT_TAX_ROUNDING = { granularity: "per_order", mode: "half_away_from_zero" };
308
308
  function taxMicros(amountMinor, ratePpm, pricesIncludeTax) {
@@ -316,11 +316,6 @@ function taxMicros(amountMinor, ratePpm, pricesIncludeTax) {
316
316
  const sign = numerator < 0n ? -1n : 1n;
317
317
  return sign * ((sign * numerator + denominator / 2n) / denominator);
318
318
  }
319
- function roundRatio(n, d, mode = "half_away_from_zero") {
320
- if (mode === "half_away_from_zero" && n < 0n) return -roundRatio(-n, d, mode);
321
- const a = 2n * n + d, b = 2n * d;
322
- return a / b - (a < 0n && a % b !== 0n ? 1n : 0n);
323
- }
324
319
  function roundMicrosToMinor(micros, mode) {
325
320
  const minor2 = roundRatio(micros, MICROS_PER_MINOR, mode);
326
321
  if (minor2 < -BigInt(Number.MAX_SAFE_INTEGER) || minor2 > BigInt(Number.MAX_SAFE_INTEGER)) {
@@ -544,8 +539,8 @@ function customerRefusal(customer) {
544
539
  return customer.email !== void 0 && customer.email !== "" && !sendable(customer.email, 254) ? CUSTOMER_REFUSALS[0] : customer.id !== void 0 && customer.id !== "" && !sendable(customer.id, 64) ? CUSTOMER_REFUSALS[1] : null;
545
540
  }
546
541
  var CUSTOMER_REFUSALS = ["email", "id"].map((field) => `This customer's ${field} can't be sent to the store, so they weren't added to the sale.`);
547
- function cutText(text2, max) {
548
- const clean2 = text2.replaceAll("\0", "");
542
+ function cutText(text3, max) {
543
+ const clean2 = text3.replaceAll("\0", "");
549
544
  if (clean2.length <= max) return clean2;
550
545
  const high = clean2.charCodeAt(max - 2);
551
546
  return `${clean2.slice(0, high >= 55296 && high <= 56319 ? max - 2 : max - 1)}\u2026`;
@@ -695,6 +690,8 @@ function createEnvelope(order, deviceId, attempt2, options, floor) {
695
690
  ...discountMinor > 0 ? { discountMinor } : {},
696
691
  taxMinor: order.taxMinor,
697
692
  totalMinor: order.totalMinor,
693
+ // ADR-094: a rounded sale's entries ride at its content version; finalize refuses them unless the store declares cashRounding.
694
+ ...order.cashRoundings?.length ? { cashRoundings: order.cashRoundings.map(({ paymentId, minor: minor2 }) => ({ paymentId, minor: minor2 })) } : {},
698
695
  ...base >= 3 ? {
699
696
  display: {
700
697
  ...storedDisplay,
@@ -898,6 +895,18 @@ function taxDerivation(settings, taxLocation) {
898
895
  };
899
896
  }
900
897
 
898
+ // src/tax/taxed-lines.ts
899
+ function taxedLinesFor(lines, charges, pricesIncludeTax, rounding) {
900
+ return [
901
+ ...lines.map((line) => ({ ...line, taxInclusive: rounding?.granularity === "woocommerce" && line.netMicros !== void 0 ? pricesIncludeTax : line.taxInclusive ?? pricesIncludeTax })),
902
+ ...charges.map((charge) => ({ ...charge, taxInclusive: rounding?.granularity === "woocommerce" ? pricesIncludeTax : charge.amountIncludesTax ?? pricesIncludeTax }))
903
+ ];
904
+ }
905
+ function recordedTaxByRate(order) {
906
+ if (order.taxRounding?.granularity === "woocommerce" && order.lines.some((line) => line.netMicros !== void 0 && line.taxInclusive !== void 0)) return void 0;
907
+ return order.taxByRate;
908
+ }
909
+
901
910
  // src/store-settings/resolve-store-settings.ts
902
911
  import { StoreSettingsError } from "@tallyui/core";
903
912
  function narrowInitial(tried, choices) {
@@ -961,7 +970,7 @@ function useStoreSettings(options) {
961
970
  const retryTimerRef = useRef(void 0);
962
971
  const retryDelayRef = useRef(INITIAL_RETRY_MS);
963
972
  const [state, setState] = useState(LOADING);
964
- const resolve = useCallback2((choice, from, known, previous) => {
973
+ const resolve = useCallback2((choice, from, known2, previous) => {
965
974
  if (from !== void 0 && from !== requestRef.current) return;
966
975
  clearTimeout(retryTimerRef.current);
967
976
  const request = ++requestRef.current;
@@ -974,7 +983,7 @@ function useStoreSettings(options) {
974
983
  const { refreshError: _error, ...refreshing } = previous;
975
984
  setState({ ...refreshing, refreshing: true });
976
985
  } else setState(LOADING);
977
- const rounding = known ?? readTaxRounding(optionsRef.current);
986
+ const rounding = known2 ?? readTaxRounding(optionsRef.current);
978
987
  Promise.all([resolveStoreSettings(optionsRef.current, choice), rounding]).then(
979
988
  ([result, taxRounding]) => {
980
989
  if (!current()) return;
@@ -1118,8 +1127,8 @@ function parseCartColumns(value) {
1118
1127
  parsed[id2] = Object.fromEntries(CART_COLUMN_FIELDS[id2].filter((field) => typeof column[field] === "boolean").map((field) => [field, column[field]]));
1119
1128
  }
1120
1129
  if (Array.isArray(value.order)) {
1121
- const known = value.order.filter((id2) => CART_COLUMN_IDS.includes(id2));
1122
- parsed.order = [...new Set(known)];
1130
+ const known2 = value.order.filter((id2) => CART_COLUMN_IDS.includes(id2));
1131
+ parsed.order = [...new Set(known2)];
1123
1132
  }
1124
1133
  return parsed;
1125
1134
  }
@@ -1314,6 +1323,9 @@ function canMoveLeg(from, to) {
1314
1323
  function canVoidLeg(leg, method) {
1315
1324
  return method.capabilities.void && (isInMotion(leg) || legStatus(leg) === "captured" && method.capture.mode === "manual");
1316
1325
  }
1326
+ function takenLeg(leg) {
1327
+ return (legStatus(leg) === "captured" || legStatus(leg) === "voided") && leg.takenAt !== void 0;
1328
+ }
1317
1329
 
1318
1330
  // src/order/apportion.ts
1319
1331
  function apportionLargestRemainders(weights, totalMinor, fallbackIndex) {
@@ -1429,10 +1441,25 @@ function createOrderBuilder(options) {
1429
1441
  const currency = options.currency.toUpperCase();
1430
1442
  const orderId = options.id ?? uid();
1431
1443
  const woo = taxContext.rounding?.granularity === "woocommerce" && taxContext.getTaxRates ? taxContext.rounding : void 0;
1432
- const wooLine = (amount, taxClass, inclusive, untaxed = false, shipping2 = false) => woocommerceLine(amount, untaxed ? [] : taxContext.getTaxRates(taxClass, { shipping: shipping2 }), inclusive, currency, woo.roundAtSubtotal, taxContext.pricesIncludeTax);
1444
+ const heldFor = (id2) => {
1445
+ const held = options.heldRates;
1446
+ return held?.taxLines.has(id2) && payments.some((p) => held.legIds.includes(p.id) && (countsTowardPaid(p) || isInMotion(p))) ? held.taxLines.get(id2) : void 0;
1447
+ };
1448
+ const toWooRates = (held) => held.map((t, i) => ({ id: t.rateId, code: t.code ?? "", label: "", rate: (t.ratePpm / 1e4).toFixed(4), priority: i, compound: t.compound ?? false, shipping: true }));
1449
+ const wooLine = (amount, taxClass, inclusive, untaxed = false, shipping2 = false, id2) => {
1450
+ const held = id2 !== void 0 ? heldFor(id2) : void 0;
1451
+ return woocommerceLine(
1452
+ amount,
1453
+ untaxed ? [] : held ? toWooRates(held) : taxContext.getTaxRates(taxClass, { shipping: shipping2 }),
1454
+ inclusive,
1455
+ currency,
1456
+ woo.roundAtSubtotal,
1457
+ taxContext.pricesIncludeTax
1458
+ );
1459
+ };
1433
1460
  const displayAmount = (line, amount) => {
1434
1461
  if (!woo || line.taxInclusive === taxContext.pricesIncludeTax) return toDisplayMode(line, amount, taxContext.pricesIncludeTax);
1435
- const item = wooLine(amount, line.taxClass, line.taxInclusive, line.taxStatus === "none");
1462
+ const item = wooLine(amount, line.taxClass, line.taxInclusive, line.taxStatus === "none", false, line.id);
1436
1463
  return taxContext.pricesIncludeTax ? item.totalMinor : item.netMinor;
1437
1464
  };
1438
1465
  const storeModeMinor = (li) => woo ? taxContext.pricesIncludeTax ? li.totalMinor : li.netMinor : toDisplayMode(li, li.netMinor, taxContext.pricesIncludeTax);
@@ -1441,6 +1468,7 @@ function createOrderBuilder(options) {
1441
1468
  let shipping = [];
1442
1469
  let orderDiscounts = [];
1443
1470
  let payments = [];
1471
+ let cashRoundings = [];
1444
1472
  let customer = null;
1445
1473
  let note = "";
1446
1474
  let meta = [];
@@ -1463,7 +1491,7 @@ function createOrderBuilder(options) {
1463
1491
  discounts: recalcedDiscounts,
1464
1492
  discountMinor,
1465
1493
  orderDiscountMinor,
1466
- ...wooLine(netMinor, line.taxClass, line.taxInclusive, line.taxStatus === "none")
1494
+ ...wooLine(netMinor, line.taxClass, line.taxInclusive, line.taxStatus === "none", false, line.id)
1467
1495
  };
1468
1496
  const combinedRate = line.taxLines.reduce((sum4, tax) => sum4 + tax.ratePpm, 0);
1469
1497
  const inclusiveTax = line.taxInclusive ? taxMicros(netMinor, combinedRate, true) : 0n;
@@ -1510,7 +1538,10 @@ function createOrderBuilder(options) {
1510
1538
  displaySourceLines,
1511
1539
  couponCodes,
1512
1540
  couponContext,
1513
- taxContext.getTaxRates,
1541
+ (line) => {
1542
+ const held = heldFor(line.id);
1543
+ return held ? toWooRates(held) : taxContext.getTaxRates(line.taxClass);
1544
+ },
1514
1545
  currency,
1515
1546
  woo.roundAtSubtotal,
1516
1547
  taxContext.pricesIncludeTax
@@ -1538,7 +1569,8 @@ function createOrderBuilder(options) {
1538
1569
  amountMinor: Number((basis * BigInt(Math.round(fee.percent * 1e4)) + 500000n) / 1000000n)
1539
1570
  }));
1540
1571
  }
1541
- if (woo) shipping = shipping.map((charge) => ({ ...charge, ...recalculateCharge(charge.id, charge, true) }));
1572
+ if (options.heldRates) fees = fees.map((fee) => fee.percent !== void 0 ? fee : { ...fee, ...recalculateCharge(fee.id, fee) });
1573
+ if (woo || options.heldRates) shipping = shipping.map((charge) => ({ ...charge, ...recalculateCharge(charge.id, charge, true) }));
1542
1574
  const charges = [...fees, ...shipping];
1543
1575
  const taxedCharges = charges.map((charge) => ({
1544
1576
  ...charge,
@@ -1666,12 +1698,14 @@ function createOrderBuilder(options) {
1666
1698
  throw new Error(`Display line ${line.lineId} shows ${line.amountMinor}, less than its rows ${rows} and share ${shareMinor} (ADR-063)`);
1667
1699
  }
1668
1700
  }
1701
+ const live = cashRoundings.filter((e) => payments.some((p) => p.id === e.paymentId && countsTowardPaid(p)));
1702
+ const total = totalMinor + live.reduce((sum4, e) => sum4 + e.minor, 0);
1669
1703
  const display = {
1670
1704
  taxInclusive,
1671
1705
  subtotalMinor: displaySubtotal,
1672
1706
  discountMinor: displayDiscount,
1673
1707
  taxMinor,
1674
- totalMinor,
1708
+ totalMinor: total,
1675
1709
  lines: displayLines,
1676
1710
  orderDiscountMinor: orderDiscountDisplay,
1677
1711
  ...displayCoupons ? { coupons: displayCoupons } : {},
@@ -1679,8 +1713,8 @@ function createOrderBuilder(options) {
1679
1713
  ...shipping.length ? { shipping: displayShipping } : {}
1680
1714
  };
1681
1715
  const paidMinor = capturedMinor(payments);
1682
- const balanceDueMinor = Math.max(0, totalMinor - paidMinor);
1683
- const changeDueMinor = Math.max(0, paidMinor - totalMinor);
1716
+ const balanceDueMinor = Math.max(0, total - paidMinor);
1717
+ const changeDueMinor = Math.max(0, paidMinor - total);
1684
1718
  const order = {
1685
1719
  id: orderId,
1686
1720
  ...storeOrder !== void 0 ? { storeOrder } : {},
@@ -1692,13 +1726,14 @@ function createOrderBuilder(options) {
1692
1726
  ...shipping.length ? { shipping: [...shipping] } : {},
1693
1727
  discounts: recalcedOrderDiscounts,
1694
1728
  payments: [...payments],
1729
+ ...live.length ? { cashRoundings: live.map((e) => ({ ...e })) } : {},
1695
1730
  customer,
1696
1731
  note,
1697
1732
  ...meta.length ? { meta: meta.map((m) => ({ ...m })) } : {},
1698
1733
  subtotalMinor,
1699
1734
  discountMinor,
1700
1735
  taxMinor,
1701
- totalMinor,
1736
+ totalMinor: total,
1702
1737
  display,
1703
1738
  paidMinor,
1704
1739
  balanceDueMinor,
@@ -1740,7 +1775,8 @@ function createOrderBuilder(options) {
1740
1775
  taxClass === woocommerceTax6.NO_SHIPPING_TAX || shipping2 && untaxed ? void 0 : taxClass,
1741
1776
  inclusive,
1742
1777
  untaxed,
1743
- shipping2
1778
+ shipping2,
1779
+ id2
1744
1780
  );
1745
1781
  return {
1746
1782
  id: id2,
@@ -1753,7 +1789,7 @@ function createOrderBuilder(options) {
1753
1789
  ...line2
1754
1790
  };
1755
1791
  }
1756
- const code = taxContext.getTaxRateCode?.(input.taxClass);
1792
+ const code = taxContext.getTaxRateCode?.(input.taxClass), held = heldFor(id2);
1757
1793
  const line = recalculateLine({
1758
1794
  id: id2,
1759
1795
  productId: id2,
@@ -1761,7 +1797,7 @@ function createOrderBuilder(options) {
1761
1797
  sku: "",
1762
1798
  unitPriceMinor: input.amountMinor,
1763
1799
  quantity: 1,
1764
- taxLines: [{
1800
+ taxLines: held ? held.map(({ code: code2, ratePpm }) => ({ ...code2 !== void 0 ? { code: code2 } : {}, ratePpm, taxMicros: "0" })) : [{
1765
1801
  ...code !== void 0 ? { code } : {},
1766
1802
  ratePpm: taxStatus === "none" ? 0 : taxContext.getTaxRatePpm(input.taxClass),
1767
1803
  taxMicros: "0"
@@ -1795,7 +1831,7 @@ function createOrderBuilder(options) {
1795
1831
  if (input.regularUnitPriceMinor !== void 0 && (!Number.isInteger(input.regularUnitPriceMinor) || input.regularUnitPriceMinor < 0))
1796
1832
  throw new RangeError("Regular price must be integer minor units >= 0");
1797
1833
  const code = woo || input.taxRates ? void 0 : taxContext.getTaxRateCode?.(input.taxClass);
1798
- const taxRates = woo ? wooLine(unitPrice.amount * quantity, input.taxClass, unitPrice.taxInclusive ?? taxContext.pricesIncludeTax, input.taxStatus === "none").taxLines : input.taxStatus === "none" ? [{ ...code !== void 0 ? { code } : {}, ratePpm: 0 }] : input.taxRates ?? [{ ...code !== void 0 ? { code } : {}, ratePpm: taxContext.getTaxRatePpm(input.taxClass) }];
1834
+ const taxRates = woo ? wooLine(unitPrice.amount * quantity, input.taxClass, unitPrice.taxInclusive ?? taxContext.pricesIncludeTax, input.taxStatus === "none", false, input.id).taxLines : input.taxStatus === "none" ? [{ ...code !== void 0 ? { code } : {}, ratePpm: 0 }] : input.taxRates ?? [{ ...code !== void 0 ? { code } : {}, ratePpm: taxContext.getTaxRatePpm(input.taxClass) }];
1799
1835
  const taxInclusive = unitPrice.taxInclusive ?? taxContext.pricesIncludeTax;
1800
1836
  const fromClass = !woo && input.taxRates === void 0;
1801
1837
  const existing = lineItems.find(
@@ -1964,9 +2000,9 @@ function createOrderBuilder(options) {
1964
2000
  },
1965
2001
  restoreItem(kind, item, index) {
1966
2002
  for (const { id: id2 } of kind === "line" ? [item, ...item.discounts] : [item]) idFor(id2);
1967
- const at2 = (list, entry) => {
1968
- const i = Math.min(index, list.length);
1969
- return [...list.slice(0, i), entry, ...list.slice(i)];
2003
+ const at2 = (list2, entry) => {
2004
+ const i = Math.min(index, list2.length);
2005
+ return [...list2.slice(0, i), entry, ...list2.slice(i)];
1970
2006
  };
1971
2007
  if (kind === "line") lineItems = at2(lineItems, recalculateLine(item));
1972
2008
  else {
@@ -2009,16 +2045,27 @@ function createOrderBuilder(options) {
2009
2045
  });
2010
2046
  emit();
2011
2047
  },
2012
- addPayment(payment) {
2048
+ addPayment(payment, rounding) {
2013
2049
  const id2 = idFor(payment.id);
2014
2050
  payments = [...payments, { ...payment, id: id2 }];
2051
+ if (rounding && rounding.minor !== 0) cashRoundings = [...cashRoundings, { paymentId: id2, minor: rounding.minor }];
2015
2052
  emit();
2016
2053
  return id2;
2017
2054
  },
2018
- setPaymentStatus(paymentId, status) {
2055
+ addCashRounding(entry) {
2056
+ const prior = cashRoundings.find((e) => e.paymentId === entry.paymentId);
2057
+ if (!prior) cashRoundings = [...cashRoundings, { paymentId: entry.paymentId, minor: entry.minor }];
2058
+ else {
2059
+ const minor2 = prior.minor + entry.minor;
2060
+ cashRoundings = minor2 === 0 ? cashRoundings.filter((e) => e !== prior) : cashRoundings.map((e) => e === prior ? { ...e, minor: minor2 } : e);
2061
+ }
2062
+ emit();
2063
+ },
2064
+ setPaymentStatus(paymentId, status, takenAt, sessionId) {
2019
2065
  const payment = payments.find((p) => p.id === paymentId);
2020
2066
  if (!payment || payment.locked || !canMoveLeg(legStatus(payment), status)) return false;
2021
- payments = payments.map((p) => p.id === paymentId ? { ...p, status } : p);
2067
+ const stamp2 = status === "captured" && takenAt !== void 0 ? { takenAt, ...sessionId !== void 0 && payment.sessionId === void 0 ? { sessionId } : {} } : {};
2068
+ payments = payments.map((p) => p.id === paymentId ? { ...p, status, ...stamp2 } : p);
2022
2069
  emit();
2023
2070
  return true;
2024
2071
  },
@@ -2077,6 +2124,7 @@ function createOrderBuilder(options) {
2077
2124
  shipping = [];
2078
2125
  orderDiscounts = [];
2079
2126
  payments = [];
2127
+ cashRoundings = [];
2080
2128
  customer = null;
2081
2129
  note = "";
2082
2130
  meta = [];
@@ -2113,6 +2161,18 @@ import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
2113
2161
 
2114
2162
  // src/order/order-drafts.ts
2115
2163
  import { map as map3 } from "rxjs";
2164
+
2165
+ // src/pos-order/till-payments.ts
2166
+ function tillPayments(payments) {
2167
+ return payments.filter((payment) => payment.storePaymentId === void 0);
2168
+ }
2169
+
2170
+ // src/order/taken-at.ts
2171
+ function isTakenAt(value) {
2172
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
2173
+ }
2174
+
2175
+ // src/order/order-drafts.ts
2116
2176
  var orderDraftSchema = {
2117
2177
  version: 0,
2118
2178
  primaryKey: "id",
@@ -2127,14 +2187,36 @@ var orderDraftSchema = {
2127
2187
  },
2128
2188
  required: ["id", "data"]
2129
2189
  };
2190
+ var savedDraft = (data) => JSON.parse(String(data));
2130
2191
  function draftExtras(data) {
2131
2192
  try {
2132
- const saved = JSON.parse(String(data));
2193
+ const saved = savedDraft(data);
2133
2194
  return { paidMinor: capturedMinor(saved.payments ?? []), balanceDueMinor: saved.balanceDueMinor, firstItem: saved.lineItems?.[0]?.name };
2134
2195
  } catch {
2135
2196
  return {};
2136
2197
  }
2137
2198
  }
2199
+ function sessionTakenLegs(payments, counted2 = () => false) {
2200
+ return tillPayments(payments).filter((leg) => countsTowardPaid(leg) && !leg.reopened && !counted2(leg) && typeof leg.sessionId === "string");
2201
+ }
2202
+ function parkedTakenLegs(data) {
2203
+ try {
2204
+ const payments = savedDraft(data).payments;
2205
+ return Array.isArray(payments) ? sessionTakenLegs(payments) : [];
2206
+ } catch {
2207
+ return [];
2208
+ }
2209
+ }
2210
+ function parkedCashRoundings(data) {
2211
+ try {
2212
+ const entries2 = savedDraft(data).cashRoundings;
2213
+ if (!Array.isArray(entries2)) return [];
2214
+ const taken = new Set(parkedTakenLegs(data).map((leg) => leg.id));
2215
+ return entries2.filter((entry) => typeof entry?.paymentId === "string" && Number.isFinite(entry?.minor) && taken.has(entry.paymentId));
2216
+ } catch {
2217
+ return [];
2218
+ }
2219
+ }
2138
2220
  async function writeOrderDraft(drafts, snapshot) {
2139
2221
  await drafts.upsert({
2140
2222
  id: snapshot.id,
@@ -2148,9 +2230,16 @@ async function writeOrderDraft(drafts, snapshot) {
2148
2230
  }
2149
2231
  function restoreOrderDraft(saved, options) {
2150
2232
  const { currency, taxContext } = options;
2233
+ const wooNow = taxContext.rounding?.granularity === "woocommerce" && !!taxContext.getTaxRates;
2234
+ const items = [...saved.lineItems, ...saved.fees ?? [], ...saved.shipping ?? []];
2235
+ const heldRates = options.keepTaxRates && wooNow === (saved.taxRounding?.granularity === "woocommerce") ? {
2236
+ legIds: (saved.payments ?? []).filter((p) => countsTowardPaid(p) || isInMotion(p)).map((p) => p.id),
2237
+ taxLines: new Map(items.filter((i) => !wooNow || i.taxLines.every((t) => t.rateId !== void 0)).map((i) => [i.id, i.taxLines]))
2238
+ } : void 0;
2151
2239
  const builder = createOrderBuilder({
2152
2240
  currency,
2153
2241
  taxContext,
2242
+ ...heldRates ? { heldRates } : {},
2154
2243
  id: saved.id,
2155
2244
  ...saved.createdAt ? { createdAt: saved.createdAt } : {},
2156
2245
  // #742: with every id below (fees and shipping replay whole)
@@ -2164,6 +2253,25 @@ function restoreOrderDraft(saved, options) {
2164
2253
  builder.setNote(saved.note);
2165
2254
  }
2166
2255
  if (saved.meta?.length) builder.setMeta(saved.meta);
2256
+ for (const payment of saved.payments) {
2257
+ builder.addPayment({
2258
+ id: payment.id,
2259
+ method: payment.method,
2260
+ amountMinor: payment.amountMinor,
2261
+ tenderedMinor: payment.tenderedMinor,
2262
+ changeMinor: payment.changeMinor,
2263
+ reference: payment.reference,
2264
+ ...payment.status !== void 0 ? { status: payment.status } : {},
2265
+ ...payment.storePaymentId !== void 0 ? { storePaymentId: payment.storePaymentId } : {},
2266
+ ...payment.locked !== void 0 ? { locked: payment.locked } : {},
2267
+ ...payment.reopened !== void 0 ? { reopened: payment.reopened } : {},
2268
+ ...payment.methodId !== void 0 ? { methodId: payment.methodId } : {},
2269
+ ...payment.units !== void 0 ? { units: payment.units } : {},
2270
+ ...isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {},
2271
+ ...typeof payment.sessionId === "string" ? { sessionId: payment.sessionId } : {}
2272
+ });
2273
+ }
2274
+ for (const entry of saved.cashRoundings ?? []) builder.addCashRounding(entry);
2167
2275
  for (const line of saved.lineItems) {
2168
2276
  const rederive = line.taxFromClass === true && !options.keepTaxRates;
2169
2277
  const lineId = builder.addLine({
@@ -2207,22 +2315,6 @@ function restoreOrderDraft(saved, options) {
2207
2315
  couponCode: discount.couponCode
2208
2316
  });
2209
2317
  }
2210
- for (const payment of saved.payments) {
2211
- builder.addPayment({
2212
- id: payment.id,
2213
- method: payment.method,
2214
- amountMinor: payment.amountMinor,
2215
- tenderedMinor: payment.tenderedMinor,
2216
- changeMinor: payment.changeMinor,
2217
- reference: payment.reference,
2218
- ...payment.status !== void 0 ? { status: payment.status } : {},
2219
- ...payment.storePaymentId !== void 0 ? { storePaymentId: payment.storePaymentId } : {},
2220
- ...payment.locked !== void 0 ? { locked: payment.locked } : {},
2221
- ...payment.reopened !== void 0 ? { reopened: payment.reopened } : {},
2222
- ...payment.methodId !== void 0 ? { methodId: payment.methodId } : {},
2223
- ...payment.units !== void 0 ? { units: payment.units } : {}
2224
- });
2225
- }
2226
2318
  if (saved.coupons?.some((c) => c.carried) && !saved.coupons.every((c) => c.carried)) throw new Error("restoreOrderDraft: a draft cannot mix carried and redeemable coupons");
2227
2319
  if (saved.coupons?.length && saved.coupons.every((coupon) => coupon.carried)) {
2228
2320
  builder.setCoupons(saved.coupons.map((c) => c.code), {
@@ -2238,12 +2330,14 @@ function restoreOrderDraft(saved, options) {
2238
2330
  }
2239
2331
  if (options.keepCoupons && saved.coupons?.length && saved.display.coupons?.length === saved.coupons.length) {
2240
2332
  const restored = builder.getSnapshot();
2333
+ const parkedRates = new Map(saved.lineItems.map((li) => [li.id, li.taxLines]));
2334
+ const keptBasis = couponPricingBasis({ ...restored, lineItems: restored.lineItems.map((li) => ({ ...li, taxLines: parkedRates.get(li.id) ?? li.taxLines })) });
2241
2335
  builder.setCoupons(saved.coupons.map((coupon) => coupon.code), {
2242
2336
  kind: "kept",
2243
2337
  coupons: saved.coupons,
2244
2338
  displayRows: saved.display.coupons.map((row) => row.amountMinor),
2245
2339
  lines: new Map(saved.lineItems.map((li) => [li.id, li])),
2246
- basis: saved.couponPricesStale ? "" : couponPricingBasis(restored),
2340
+ basis: saved.couponPricesStale ? "" : keptBasis,
2247
2341
  linesBasis: couponPricingBasis({ ...restored, customer: null }),
2248
2342
  legIds: saved.payments.filter(isLiveLeg).map((p) => p.id)
2249
2343
  });
@@ -2330,6 +2424,215 @@ function useParkedSales(drafts) {
2330
2424
  return { parked, discard };
2331
2425
  }
2332
2426
 
2427
+ // src/store-orders/sales-range-query.ts
2428
+ function salesRangeQuery(range, orderFilters) {
2429
+ return orderFilters?.includes("modifiedAfter") ? { modifiedAfter: range.after, dateRange: { before: range.before } } : { dateRange: { after: range.after, before: range.before } };
2430
+ }
2431
+
2432
+ // src/store-orders/use-store-orders-in-range.ts
2433
+ import { useEffect as useEffect5, useMemo as useMemo4, useState as useState5 } from "react";
2434
+ var PER_PAGE = 100;
2435
+ var STALLED = "listOrders answered hasMore: true with a page that added no new order";
2436
+ var IDLE = { orders: [], progress: null, unreadable: 0, error: null, complete: false };
2437
+ var STARTING = {
2438
+ orders: [],
2439
+ progress: { downloaded: 0, total: null },
2440
+ unreadable: 0,
2441
+ error: null,
2442
+ complete: false
2443
+ };
2444
+ async function readPages(connector, context, query, live, onPage) {
2445
+ for (let page = 1; ; page++) {
2446
+ await Promise.resolve();
2447
+ if (!live()) return;
2448
+ const result = await connector.listOrders(context, { ...query, page, perPage: PER_PAGE });
2449
+ if (!live()) return;
2450
+ onPage(result, page === 1);
2451
+ if (!result.hasMore) return;
2452
+ }
2453
+ }
2454
+ function useStoreOrdersInRange(connector, context, query) {
2455
+ const key = query ? JSON.stringify(query) : null;
2456
+ const [read, setRead] = useState5(null);
2457
+ useEffect5(() => {
2458
+ if (!connector?.listOrders || !context || key === null) return;
2459
+ let live = true;
2460
+ const seen = /* @__PURE__ */ new Set();
2461
+ let current = { connector, context, key, orders: [], unreadable: 0, total: null, status: "reading" };
2462
+ const publish = (next) => {
2463
+ current = next;
2464
+ setRead(next);
2465
+ };
2466
+ readPages(connector, context, JSON.parse(key), () => live, (page, first) => {
2467
+ const fresh = page.orders.filter((order) => {
2468
+ if (seen.has(order.id)) return false;
2469
+ seen.add(order.id);
2470
+ return true;
2471
+ });
2472
+ if (page.hasMore && fresh.length === 0) throw new Error(STALLED);
2473
+ publish({
2474
+ ...current,
2475
+ orders: [...current.orders, ...fresh],
2476
+ unreadable: current.unreadable + (first || fresh.length > 0 ? page.unreadable ?? 0 : 0),
2477
+ total: first ? page.total ?? null : current.total,
2478
+ status: page.hasMore ? "reading" : "complete"
2479
+ });
2480
+ }).catch((error) => {
2481
+ if (live) publish({ ...current, status: "error", error });
2482
+ });
2483
+ return () => {
2484
+ live = false;
2485
+ setRead(null);
2486
+ };
2487
+ }, [connector, context, key]);
2488
+ return useMemo4(() => {
2489
+ if (!connector?.listOrders || !context || key === null) return IDLE;
2490
+ if (!read || read.connector !== connector || read.context !== context || read.key !== key) return STARTING;
2491
+ const { orders, unreadable, total } = read;
2492
+ const progress = read.status === "reading" ? { downloaded: orders.length + unreadable, total } : null;
2493
+ return { orders, progress, unreadable, error: read.status === "error" ? read.error : null, complete: read.status === "complete" };
2494
+ }, [connector, context, key, read]);
2495
+ }
2496
+
2497
+ // src/store-orders/use-store-refunds-in-range.ts
2498
+ import { useEffect as useEffect6, useMemo as useMemo5, useState as useState6 } from "react";
2499
+ import { StoreRefundsUnsupportedError } from "@tallyui/core";
2500
+
2501
+ // src/sale/order-filters-query.ts
2502
+ var COPIED = ["status", "customerId", "cashierId", "registerId", "paymentMethod", "storeId", "createdVia"];
2503
+ var DAY_MS = 864e5;
2504
+ function offsetMs(at2, timezone) {
2505
+ const format2 = new Intl.DateTimeFormat("en-US", {
2506
+ timeZone: timezone,
2507
+ hourCycle: "h23",
2508
+ year: "numeric",
2509
+ month: "numeric",
2510
+ day: "numeric",
2511
+ hour: "numeric",
2512
+ minute: "numeric",
2513
+ second: "numeric"
2514
+ });
2515
+ const part = Object.fromEntries(format2.formatToParts(new Date(at2)).map(({ type, value }) => [type, Number(value)]));
2516
+ const wall = Date.UTC(part.year, part.month - 1, part.day, part.hour, part.minute, part.second);
2517
+ return wall - Math.floor(at2 / 1e3) * 1e3;
2518
+ }
2519
+ function dayStart(day, timezone) {
2520
+ const [year, month, date] = day.split("-").map(Number);
2521
+ if (timezone === "device") return new Date(year, month - 1, date).toISOString();
2522
+ const wall = Date.UTC(year, month - 1, date);
2523
+ const guess = wall - offsetMs(wall, timezone);
2524
+ return new Date(wall - offsetMs(guess, timezone)).toISOString();
2525
+ }
2526
+ var nextDay = (day) => {
2527
+ const [year, month, date] = day.split("-").map(Number);
2528
+ return new Date(Date.UTC(year, month - 1, date) + DAY_MS).toISOString().slice(0, 10);
2529
+ };
2530
+ function orderFiltersQuery(value, timezone) {
2531
+ const query = {};
2532
+ for (const field of COPIED) {
2533
+ if (value[field] !== void 0) query[field] = value[field];
2534
+ }
2535
+ if (value.dateRange) {
2536
+ query.dateRange = { after: dayStart(value.dateRange.from, timezone), before: dayStart(nextDay(value.dateRange.to), timezone) };
2537
+ }
2538
+ return query;
2539
+ }
2540
+
2541
+ // src/store-orders/use-store-refunds-in-range.ts
2542
+ var PER_PAGE2 = 100;
2543
+ var STALLED2 = "listRefunds answered hasMore: true with a page that added no new refund";
2544
+ var SCOPE_FIELDS = ["storeId", "cashierId", "registerId"];
2545
+ var EMPTY = { orphans: [], unscoped: [], otherCurrency: [], unreadable: 0 };
2546
+ var IDLE2 = { ...EMPTY, refunds: void 0, progress: null, error: null, complete: false };
2547
+ var NO_DATED = { ...IDLE2, complete: true };
2548
+ var STARTING2 = { ...EMPTY, refunds: [], progress: { downloaded: 0, total: null }, error: null, complete: false };
2549
+ async function readPages2(connector, context, dateRange, live, onPage) {
2550
+ for (let page = 1; ; page++) {
2551
+ await Promise.resolve();
2552
+ if (!live()) return;
2553
+ const result = await connector.listRefunds(context, { page, perPage: PER_PAGE2, dateRange });
2554
+ if (!live()) return;
2555
+ await onPage(result, page === 1);
2556
+ if (!live() || !result.hasMore) return;
2557
+ }
2558
+ }
2559
+ function useStoreRefundsInRange(connector, context, query) {
2560
+ const key = query ? JSON.stringify(query) : null;
2561
+ const [read, setRead] = useState6(null);
2562
+ useEffect6(() => {
2563
+ if (!connector?.listRefunds || !context || key === null) return;
2564
+ const q = JSON.parse(key);
2565
+ const scope = SCOPE_FIELDS.filter((field) => q.scope?.[field] !== void 0);
2566
+ let live = true;
2567
+ const seen = /* @__PURE__ */ new Set();
2568
+ const asked = /* @__PURE__ */ new Set();
2569
+ const orders = /* @__PURE__ */ new Map();
2570
+ let current = { connector, context, key, ...EMPTY, refunds: [], seen: 0, total: null, status: "reading" };
2571
+ const take = (row) => !seen.has(row.id) && seen.add(row.id).has(row.id);
2572
+ const dateRange = orderFiltersQuery({ dateRange: q.range }, q.timezone).dateRange;
2573
+ readPages2(connector, context, dateRange, () => live, async (page, first) => {
2574
+ const fresh = page.refunds.filter(take);
2575
+ const orphans = page.orphans.filter(take);
2576
+ if (page.hasMore && fresh.length + orphans.length === 0) throw new Error(STALLED2);
2577
+ if (scope.length && connector.getOrders) {
2578
+ const ids = [...new Set(fresh.map((refund) => refund.orderId))].filter((id2) => !asked.has(id2));
2579
+ ids.forEach((id2) => asked.add(id2));
2580
+ if (ids.length) for (const order of await connector.getOrders(context, ids)) orders.set(order.id, order);
2581
+ if (!live) return;
2582
+ }
2583
+ const refunds = [...current.refunds];
2584
+ const unscoped = [...current.unscoped];
2585
+ const other = new Map(current.otherCurrency.map((row) => [row.currency, row]));
2586
+ for (const refund of fresh) {
2587
+ const order = orders.get(refund.orderId);
2588
+ if (scope.length) {
2589
+ if (order && scope.some((field) => order[field] !== void 0 && order[field] !== q.scope[field])) continue;
2590
+ if (!order || scope.some((field) => order[field] === void 0)) {
2591
+ unscoped.push(refund);
2592
+ continue;
2593
+ }
2594
+ }
2595
+ if (refund.currency === q.currency) {
2596
+ refunds.push({ id: refund.id, orderId: refund.orderId, at: refund.refundedAt, amountMinor: refund.amountMinor });
2597
+ continue;
2598
+ }
2599
+ const row = other.get(refund.currency) ?? { currency: refund.currency, count: 0, amountMinor: 0 };
2600
+ other.set(refund.currency, { ...row, count: row.count + 1, amountMinor: row.amountMinor + refund.amountMinor });
2601
+ }
2602
+ current = {
2603
+ ...current,
2604
+ refunds,
2605
+ unscoped,
2606
+ orphans: [...current.orphans, ...orphans],
2607
+ otherCurrency: [...other.values()].sort((a, b) => a.currency < b.currency ? -1 : a.currency > b.currency ? 1 : 0),
2608
+ unreadable: current.unreadable + (first || fresh.length + orphans.length > 0 ? page.unreadable ?? 0 : 0),
2609
+ seen: seen.size,
2610
+ total: first ? page.total ?? null : current.total,
2611
+ status: page.hasMore ? "reading" : "complete"
2612
+ };
2613
+ setRead(current);
2614
+ }).catch((error) => {
2615
+ if (!live) return;
2616
+ current = error instanceof StoreRefundsUnsupportedError ? { ...current, status: "unsupported" } : { ...current, status: "error", error };
2617
+ setRead(current);
2618
+ });
2619
+ return () => {
2620
+ live = false;
2621
+ setRead(null);
2622
+ };
2623
+ }, [connector, context, key]);
2624
+ return useMemo5(() => {
2625
+ if (!connector || !context || key === null) return IDLE2;
2626
+ if (!connector.listRefunds) return NO_DATED;
2627
+ if (!read || read.connector !== connector || read.context !== context || read.key !== key) return STARTING2;
2628
+ if (read.status === "unsupported") return NO_DATED;
2629
+ const { refunds, orphans, unreadable, unscoped, otherCurrency, seen, total } = read;
2630
+ const progress = read.status === "reading" ? { downloaded: seen + unreadable, total } : null;
2631
+ const error = read.status === "error" ? read.error : null;
2632
+ return { refunds, orphans, unreadable, unscoped, otherCurrency, progress, error, complete: read.status === "complete" };
2633
+ }, [connector, context, key, read]);
2634
+ }
2635
+
2333
2636
  // src/pos-order/refund-due.ts
2334
2637
  var sum = (amounts) => amounts.reduce((total, amount) => total + amount, 0);
2335
2638
  function refundDueOf(order) {
@@ -2345,18 +2648,6 @@ function tillLegsTheStoreRefuses(order) {
2345
2648
  return lockedMinor >= order.totalMinor ? captured.filter((payment) => !payment.locked).map((payment) => payment.id) : [];
2346
2649
  }
2347
2650
 
2348
- // src/tax/taxed-lines.ts
2349
- function taxedLinesFor(lines, charges, pricesIncludeTax, rounding) {
2350
- return [
2351
- ...lines.map((line) => ({ ...line, taxInclusive: rounding?.granularity === "woocommerce" && line.netMicros !== void 0 ? pricesIncludeTax : line.taxInclusive ?? pricesIncludeTax })),
2352
- ...charges.map((charge) => ({ ...charge, taxInclusive: rounding?.granularity === "woocommerce" ? pricesIncludeTax : charge.amountIncludesTax ?? pricesIncludeTax }))
2353
- ];
2354
- }
2355
- function recordedTaxByRate(order) {
2356
- if (order.taxRounding?.granularity === "woocommerce" && order.lines.some((line) => line.netMicros !== void 0 && line.taxInclusive !== void 0)) return void 0;
2357
- return order.taxByRate;
2358
- }
2359
-
2360
2651
  // src/receipt/carried-rows.ts
2361
2652
  var carriedCouponLabel = (code) => `coupon ${code} not accepted at send`;
2362
2653
  var isCarriedCouponLabel = (label) => label.startsWith("coupon ") && label.endsWith(" not accepted at send");
@@ -2378,6 +2669,10 @@ function carriedRows(coupons, lineId, inclusiveOf, displayInclusive, displayRows
2378
2669
  var RECEIPT_SCHEMA_VERSION = "1.4.0";
2379
2670
 
2380
2671
  // src/receipt/build-receipt-data.ts
2672
+ function receiptRounding(order) {
2673
+ const amountMinor = (order.cashRoundings ?? []).reduce((sum4, entry) => sum4 + entry.minor, 0);
2674
+ return amountMinor !== 0 ? { rounding: { name: "Rounding", amountMinor } } : {};
2675
+ }
2381
2676
  function buildReceiptData(order, config) {
2382
2677
  const taxedLines = taxedLinesFor(order.lineItems, [...order.fees ?? [], ...order.shipping ?? []], order.pricesIncludeTax, order.taxRounding);
2383
2678
  const taxLines = taxLinesByRate(taxedLines, order.taxMinor, config.taxLabels, order.taxRounding).map(
@@ -2451,6 +2746,7 @@ function buildReceiptData(order, config) {
2451
2746
  })),
2452
2747
  fees: (order.display.fees ?? []).map(({ name, amountMinor }) => ({ name, amountMinor })),
2453
2748
  shipping: (order.display.shipping ?? []).map(({ name, amountMinor }) => ({ name, amountMinor })),
2749
+ ...receiptRounding(order),
2454
2750
  orderDiscountMinor: order.display.orderDiscountMinor,
2455
2751
  totals: {
2456
2752
  taxInclusive: order.display.taxInclusive,
@@ -2566,6 +2862,7 @@ function buildReceiptDataFromPosOrder(order, config) {
2566
2862
  discounts: display && display.orderDiscountMinor > 0 ? [{ label: "Order discount", amountMinor: display.orderDiscountMinor }] : [],
2567
2863
  fees: charges(display ? display.fees : order.fees),
2568
2864
  shipping: charges(display ? display.shipping : order.shipping),
2865
+ ...receiptRounding(order),
2569
2866
  orderDiscountMinor: display ? display.orderDiscountMinor : 0,
2570
2867
  totals: display ? {
2571
2868
  taxInclusive: display.taxInclusive,
@@ -2647,8 +2944,8 @@ function parseChildren(parent) {
2647
2944
  const nodes = [];
2648
2945
  for (const child of Array.from(parent.childNodes)) {
2649
2946
  if (child.nodeType === 3) {
2650
- const text2 = child.textContent ?? "";
2651
- if (/\S/.test(text2)) nodes.push({ type: "raw-text", value: text2 });
2947
+ const text3 = child.textContent ?? "";
2948
+ if (/\S/.test(text3)) nodes.push({ type: "raw-text", value: text3 });
2652
2949
  continue;
2653
2950
  }
2654
2951
  if (child.nodeType !== 1) continue;
@@ -2854,10 +3151,10 @@ function renderNode(node, widthChars) {
2854
3151
  }
2855
3152
  }
2856
3153
  function pendingCode(kind, value) {
2857
- const text2 = value.trim();
2858
- if (!text2) return "";
3154
+ const text3 = value.trim();
3155
+ if (!text3) return "";
2859
3156
  const safeKind = kind === "qrcode" ? "qrcode" : "barcode";
2860
- return `<div data-barcode-kind="${safeKind}" data-barcode-value="${escapeHtml(text2)}" data-barcode-pending="true" style="text-align: center; padding: 8px 0"><code>${escapeHtml(text2)}</code></div>`;
3157
+ return `<div data-barcode-kind="${safeKind}" data-barcode-value="${escapeHtml(text3)}" data-barcode-pending="true" style="text-align: center; padding: 8px 0"><code>${escapeHtml(text3)}</code></div>`;
2861
3158
  }
2862
3159
  function renderRow(node, widthChars) {
2863
3160
  const cols = node.children.map((col) => renderCol(col, widthChars)).join("");
@@ -3069,7 +3366,7 @@ function receiptTemplateData(receipt, options = {}) {
3069
3366
  subtotal: money(totals.subtotalMinor),
3070
3367
  lineDiscount: lineDiscountMinor > 0 ? `\u2212${money(lineDiscountMinor)}` : "",
3071
3368
  orderDiscount: receipt.orderDiscountMinor > 0 ? `\u2212${money(receipt.orderDiscountMinor)}` : "",
3072
- charges: [...receipt.fees, ...receipt.shipping].map((charge) => ({
3369
+ charges: [...receipt.fees, ...receipt.shipping, ...receipt.rounding ? [receipt.rounding] : []].map((charge) => ({
3073
3370
  label: charge.name,
3074
3371
  amount: money(charge.amountMinor)
3075
3372
  })),
@@ -3241,8 +3538,8 @@ function metaText(value) {
3241
3538
  if (value === null || value === void 0) return "";
3242
3539
  return typeof value === "object" ? JSON.stringify(value) : String(value);
3243
3540
  }
3244
- function taxIdsKey(list) {
3245
- const kept = (list ?? []).filter((id2) => id2.type && id2.value).map((id2) => ({
3541
+ function taxIdsKey(list2) {
3542
+ const kept = (list2 ?? []).filter((id2) => id2.type && id2.value).map((id2) => ({
3246
3543
  type: id2.type,
3247
3544
  value: id2.value,
3248
3545
  ...id2.country ? { country: id2.country } : {},
@@ -3589,7 +3886,7 @@ var WCPOS_TAX_ID_LABELS = {
3589
3886
  ch_uid: "UID"
3590
3887
  };
3591
3888
  var tri = (key) => [key, `${key}_incl`, `${key}_excl`];
3592
- var own = (record, key) => Object.hasOwn(record, key) ? record[key] : void 0;
3889
+ var own = (record2, key) => Object.hasOwn(record2, key) ? record2[key] : void 0;
3593
3890
  var definedOnly = (values) => Object.fromEntries(Object.entries(values).filter((entry) => entry[1] !== void 0));
3594
3891
  function displays(source, keys, format2) {
3595
3892
  const out = {};
@@ -3714,8 +4011,8 @@ function formatWcposReceiptData(data, options = {}) {
3714
4011
  import { paymentMethodOf } from "@tallyui/core";
3715
4012
  function rateKeyOf(rates) {
3716
4013
  const codes2 = new Map(rates.map((rate) => [JSON.stringify([rate.code ?? "", rate.ratePpm]), rate.code ?? ""]));
3717
- const list = [...codes2.values()];
3718
- const plain = list.every((code) => code !== "") && new Set(list).size === list.length;
4014
+ const list2 = [...codes2.values()];
4015
+ const plain = list2.every((code) => code !== "") && new Set(list2).size === list2.length;
3719
4016
  return (rate) => plain ? rate.code : JSON.stringify([rate.code ?? "", rate.ratePpm]);
3720
4017
  }
3721
4018
  var sumTax = (rates) => roundMicrosToMinor(rates.reduce((total, rate) => total + BigInt(rate.taxMicros), 0n));
@@ -3780,7 +4077,11 @@ function tillSource(order, receipt, lines) {
3780
4077
  pricesIncludeTax: order.pricesIncludeTax,
3781
4078
  customer: order.customer && { id: order.customer.id, firstName: order.customer.name, email: order.customer.email },
3782
4079
  lines: lines.map((line) => tillLine(line, key)),
3783
- fees: (order.fees ?? []).map((fee) => ({ name: fee.name, ...tillCharge(fee, context, key) })),
4080
+ fees: [
4081
+ ...(order.fees ?? []).map((fee) => ({ name: fee.name, ...tillCharge(fee, context, key) })),
4082
+ // ADR-094 detail 5: the rounding prints as WooCommerce carries it, a tax-free fee row named 'Rounding'.
4083
+ ...receipt.rounding ? [{ name: receipt.rounding.name, totalMinor: receipt.rounding.amountMinor, totalTaxMinor: 0 }] : []
4084
+ ],
3784
4085
  shipping: (order.shipping ?? []).map((row) => ({
3785
4086
  methodTitle: row.name,
3786
4087
  ...row.methodId !== void 0 ? { methodId: row.methodId } : {},
@@ -4027,11 +4328,11 @@ var PAYLOAD_CHECKS = {
4027
4328
  "display.hello": (p) => isTemplate(p.template),
4028
4329
  "display.config": (p) => p.contract === "1.0" && isObj(p.display) && isStr(p.display.id) && isStr(p.display.name) && isObj(p.store) && isStr(p.store.id) && isStr(p.store.name) && isStr(p.store.currency) && isStr(p.store.locale) && isObj(p.presentation_hints) && isObj(p.i18n) && (p.template === void 0 || isTemplate(p.template)) && isObj(p.idle) && isNum(p.idle.afterCompleteMs)
4029
4330
  };
4030
- function decode(text2) {
4031
- if (!isStr(text2)) return { ok: false, refusal: "malformed" };
4331
+ function decode(text3) {
4332
+ if (!isStr(text3)) return { ok: false, refusal: "malformed" };
4032
4333
  let message;
4033
4334
  try {
4034
- message = JSON.parse(text2);
4335
+ message = JSON.parse(text3);
4035
4336
  } catch {
4036
4337
  return { ok: false, refusal: "malformed" };
4037
4338
  }
@@ -4048,14 +4349,14 @@ var MAX_MESSAGE_BYTES = 200 * 1024;
4048
4349
  var MAX_NOTE_BYTES = 1024;
4049
4350
  var MAX_LINE_ATTRIBUTES = 8;
4050
4351
  var encoder = new TextEncoder();
4051
- function messageBytes(text2) {
4052
- return encoder.encode(text2).byteLength;
4352
+ function messageBytes(text3) {
4353
+ return encoder.encode(text3).byteLength;
4053
4354
  }
4054
- function truncateUtf8(text2, limit) {
4055
- if (messageBytes(text2) <= limit) return text2;
4355
+ function truncateUtf8(text3, limit) {
4356
+ if (messageBytes(text3) <= limit) return text3;
4056
4357
  let bytes = 0;
4057
4358
  let result = "";
4058
- for (const character of text2) {
4359
+ for (const character of text3) {
4059
4360
  bytes += messageBytes(character);
4060
4361
  if (bytes > limit) break;
4061
4362
  result += character;
@@ -4078,10 +4379,10 @@ function trimCart(cart, size) {
4078
4379
  while (size() > MAX_MESSAGE_BYTES && receipt.lineItems.length > 0) receipt.lineItems.shift();
4079
4380
  }
4080
4381
  function encode(envelope2) {
4081
- let text2 = JSON.stringify(envelope2);
4082
- if (messageBytes(text2) <= MAX_MESSAGE_BYTES) return text2;
4083
- const copy = JSON.parse(text2);
4084
- const size = () => messageBytes(text2 = JSON.stringify(copy));
4382
+ let text3 = JSON.stringify(envelope2);
4383
+ if (messageBytes(text3) <= MAX_MESSAGE_BYTES) return text3;
4384
+ const copy = JSON.parse(text3);
4385
+ const size = () => messageBytes(text3 = JSON.stringify(copy));
4085
4386
  if (copy.action === "cart.updated" || copy.action === "payment.state") trimCart(copy.payload, size);
4086
4387
  else if (copy.action === "display.config") {
4087
4388
  copy.payload.i18n = {};
@@ -4090,7 +4391,7 @@ function encode(envelope2) {
4090
4391
  size();
4091
4392
  }
4092
4393
  }
4093
- return text2;
4394
+ return text3;
4094
4395
  }
4095
4396
 
4096
4397
  // src/customer-display/display-state.ts
@@ -4166,7 +4467,7 @@ var quietly = (run) => {
4166
4467
  function createSnapshotSender({ post: post2, clock, onError }) {
4167
4468
  let state = null;
4168
4469
  let stopped = false;
4169
- let inFlight2 = false;
4470
+ let inFlight3 = false;
4170
4471
  let timer = null;
4171
4472
  let timerFor = null;
4172
4473
  let last = null;
@@ -4197,7 +4498,7 @@ function createSnapshotSender({ post: post2, clock, onError }) {
4197
4498
  return state?.active || next.idle && clearing ? next : null;
4198
4499
  };
4199
4500
  const schedule = () => {
4200
- if (stopped || inFlight2) return;
4501
+ if (stopped || inFlight3) return;
4201
4502
  const next = wanted();
4202
4503
  if (!next) return clear();
4203
4504
  if (last?.key === next.key) {
@@ -4215,11 +4516,11 @@ function createSnapshotSender({ post: post2, clock, onError }) {
4215
4516
  };
4216
4517
  function fire() {
4217
4518
  timer = timerFor = null;
4218
- if (stopped || inFlight2) return;
4519
+ if (stopped || inFlight3) return;
4219
4520
  const next = wanted();
4220
4521
  if (!next) return;
4221
4522
  if (last?.key === next.key && clock.now() < last.at + SNAPSHOT_RESEND_MS) return schedule();
4222
- inFlight2 = true;
4523
+ inFlight3 = true;
4223
4524
  void new Promise((resolve) => resolve(post2(next.body))).then(() => {
4224
4525
  last = { key: next.key, at: clock.now(), ok: true };
4225
4526
  cartPostedAt = next.idle ? null : clock.now();
@@ -4229,7 +4530,7 @@ function createSnapshotSender({ post: post2, clock, onError }) {
4229
4530
  if (!retryable(error)) refused = next.key;
4230
4531
  last = { key: next.key, at: clock.now(), ok: false };
4231
4532
  }).finally(() => {
4232
- inFlight2 = false;
4533
+ inFlight3 = false;
4233
4534
  schedule();
4234
4535
  });
4235
4536
  }
@@ -4301,12 +4602,12 @@ function createDisplayLink(transport, options) {
4301
4602
  }
4302
4603
 
4303
4604
  // src/customer-display/use-customer-display.ts
4304
- import { useEffect as useEffect5, useState as useState5 } from "react";
4605
+ import { useEffect as useEffect7, useState as useState7 } from "react";
4305
4606
  var DISPLAY_TEMPLATE = { id: "default", version: 1 };
4306
4607
  var HELLO_RETRY_MS = 2e3;
4307
4608
  function useCustomerDisplay(transport) {
4308
- const [state, setState] = useState5(initialDisplayState);
4309
- useEffect5(() => {
4609
+ const [state, setState] = useState7(initialDisplayState);
4610
+ useEffect7(() => {
4310
4611
  if (!transport) return;
4311
4612
  const hello = makeEnvelope("display.hello", { template: DISPLAY_TEMPLATE });
4312
4613
  let configured = false;
@@ -4409,14 +4710,14 @@ function createSaleDisplayPublisher(link, options = {}) {
4409
4710
  }
4410
4711
 
4411
4712
  // src/customer-display/use-sale-display.ts
4412
- import { useEffect as useEffect6, useRef as useRef2 } from "react";
4713
+ import { useEffect as useEffect8, useRef as useRef2 } from "react";
4413
4714
  function useSaleDisplay(link, sale, options) {
4414
4715
  const latest = useRef2(options);
4415
- useEffect6(() => {
4716
+ useEffect8(() => {
4416
4717
  latest.current = options;
4417
4718
  });
4418
4719
  const held = useRef2(null);
4419
- useEffect6(() => {
4720
+ useEffect8(() => {
4420
4721
  if (!link) return;
4421
4722
  if (held.current?.link !== link) {
4422
4723
  const live = {
@@ -4434,7 +4735,7 @@ function useSaleDisplay(link, sale, options) {
4434
4735
  }
4435
4736
  held.current.publisher.update({ order: sale.order, stage: sale.stage });
4436
4737
  }, [link, sale.order, sale.stage]);
4437
- useEffect6(() => () => {
4738
+ useEffect8(() => () => {
4438
4739
  held.current?.publisher.close();
4439
4740
  held.current = null;
4440
4741
  }, [link]);
@@ -4844,7 +5145,7 @@ function createDisplayClient(options) {
4844
5145
 
4845
5146
  // src/customer-display/use-display-client.ts
4846
5147
  import { useCallback as useCallback3, useSyncExternalStore } from "react";
4847
- var STARTING = { phase: { phase: "starting" }, state: initialDisplayState };
5148
+ var STARTING3 = { phase: { phase: "starting" }, state: initialDisplayState };
4848
5149
  var views = /* @__PURE__ */ new WeakMap();
4849
5150
  var noSubscription = () => () => {
4850
5151
  };
@@ -4857,7 +5158,7 @@ function viewOf(client) {
4857
5158
  }
4858
5159
  function useDisplayClient(client) {
4859
5160
  const subscribe = useCallback3((listener) => client ? client.onChange(listener) : noSubscription(), [client]);
4860
- const getSnapshot = useCallback3(() => client ? viewOf(client) : STARTING, [client]);
5161
+ const getSnapshot = useCallback3(() => client ? viewOf(client) : STARTING3, [client]);
4861
5162
  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
4862
5163
  }
4863
5164
 
@@ -4918,7 +5219,7 @@ function createTillDisplayService(options) {
4918
5219
  let forbidden = false;
4919
5220
  let pauseReason = null;
4920
5221
  let latest = null;
4921
- let entries = [];
5222
+ let entries2 = [];
4922
5223
  const timers = { list: null, signal: null };
4923
5224
  let signalBusy = false;
4924
5225
  let listGeneration = 0;
@@ -4928,7 +5229,7 @@ function createTillDisplayService(options) {
4928
5229
  timers[which] = null;
4929
5230
  };
4930
5231
  const emit = () => {
4931
- entries = [...slots.values()].map((slot) => ({ display: slot.record, link: slot.link?.state ?? "closed" }));
5232
+ entries2 = [...slots.values()].map((slot) => ({ display: slot.record, link: slot.link?.state ?? "closed" }));
4932
5233
  listeners.forEach(quietly);
4933
5234
  };
4934
5235
  const push = (slot) => slot.sender.update({
@@ -5040,8 +5341,8 @@ function createTillDisplayService(options) {
5040
5341
  if (latest) callDisplay(slot.view, latest);
5041
5342
  ensureSignalPoll();
5042
5343
  };
5043
- const addSlot = (record) => {
5044
- const id2 = record.displayId;
5344
+ const addSlot = (record2) => {
5345
+ const id2 = record2.displayId;
5045
5346
  const sender = createSnapshotSender({
5046
5347
  clock,
5047
5348
  onError: (error) => void (error !== NOT_SENT && report(error)),
@@ -5056,8 +5357,8 @@ function createTillDisplayService(options) {
5056
5357
  });
5057
5358
  const slot = {
5058
5359
  id: id2,
5059
- record,
5060
- config: configFor(record),
5360
+ record: record2,
5361
+ config: configFor(record2),
5061
5362
  seq: clock.now() - 1,
5062
5363
  link: null,
5063
5364
  view: null,
@@ -5070,12 +5371,12 @@ function createTillDisplayService(options) {
5070
5371
  return slot;
5071
5372
  };
5072
5373
  const reconcile = (records) => {
5073
- const listed = new Set(records.map((record) => record.displayId));
5374
+ const listed = new Set(records.map((record2) => record2.displayId));
5074
5375
  for (const id2 of [...slots.keys()]) if (!listed.has(id2)) remove(id2);
5075
- for (const record of records) {
5076
- let slot = slots.get(record.displayId);
5077
- if (slot) Object.assign(slot, { record, config: configFor(record) });
5078
- else slot = addSlot(record);
5376
+ for (const record2 of records) {
5377
+ let slot = slots.get(record2.displayId);
5378
+ if (slot) Object.assign(slot, { record: record2, config: configFor(record2) });
5379
+ else slot = addSlot(record2);
5079
5380
  connect(slot);
5080
5381
  push(slot);
5081
5382
  }
@@ -5112,7 +5413,7 @@ function createTillDisplayService(options) {
5112
5413
  return pauseReason;
5113
5414
  },
5114
5415
  get displays() {
5115
- return entries;
5416
+ return entries2;
5116
5417
  },
5117
5418
  onChange(listener) {
5118
5419
  listeners.add(listener);
@@ -5685,7 +5986,7 @@ function createScanSession(options) {
5685
5986
  }
5686
5987
 
5687
5988
  // src/scanner/use-barcode-scanner.ts
5688
- import { useEffect as useEffect8, useRef as useRef5 } from "react";
5989
+ import { useEffect as useEffect10, useRef as useRef5 } from "react";
5689
5990
  import { merge, Subject as Subject2 } from "rxjs";
5690
5991
 
5691
5992
  // src/scanner/scan-dedup.ts
@@ -5717,7 +6018,7 @@ function scanTimeOf(event) {
5717
6018
  }
5718
6019
 
5719
6020
  // src/scanner/scan-hub-context.tsx
5720
- import { createContext as createContext3, useCallback as useCallback5, useContext as useContext3, useEffect as useEffect7, useMemo as useMemo4, useRef as useRef4, useState as useState6, useSyncExternalStore as useSyncExternalStore3 } from "react";
6021
+ import { createContext as createContext3, useCallback as useCallback5, useContext as useContext3, useEffect as useEffect9, useMemo as useMemo6, useRef as useRef4, useState as useState8, useSyncExternalStore as useSyncExternalStore3 } from "react";
5721
6022
 
5722
6023
  // src/scanner/chooser-cancel.ts
5723
6024
  function isChooserCancel(error) {
@@ -6007,9 +6308,9 @@ function createHidScanner(options) {
6007
6308
  }
6008
6309
 
6009
6310
  // src/scanner/scan-events.ts
6010
- import { EMPTY, Subject } from "rxjs";
6311
+ import { EMPTY as EMPTY2, Subject } from "rxjs";
6011
6312
  var inertScanHub = {
6012
- events$: EMPTY,
6313
+ events$: EMPTY2,
6013
6314
  registerSource: () => () => void 0,
6014
6315
  emit: () => void 0
6015
6316
  };
@@ -6225,7 +6526,7 @@ function useDeviceScanControl(scanner) {
6225
6526
  );
6226
6527
  const getState = useCallback5(() => scanner ? scanner.getState() : DISCONNECTED, [scanner]);
6227
6528
  const state = useSyncExternalStore3(subscribe, getState, getState);
6228
- return useMemo4(
6529
+ return useMemo6(
6229
6530
  () => scanner ? {
6230
6531
  available: scanner.available,
6231
6532
  connect: scanner.connect,
@@ -6239,9 +6540,9 @@ function useDeviceScanControl(scanner) {
6239
6540
  function ScanHubProvider({ children, ...props }) {
6240
6541
  const latest = useRef4(props);
6241
6542
  latest.current = props;
6242
- const [hub] = useState6(() => createScanHub());
6243
- const [controllers, setControllers] = useState6(null);
6244
- useEffect7(() => {
6543
+ const [hub] = useState8(() => createScanHub());
6544
+ const [controllers, setControllers] = useState8(null);
6545
+ useEffect9(() => {
6245
6546
  const nav2 = browserNavigator();
6246
6547
  const shared = {
6247
6548
  profiles: {
@@ -6266,7 +6567,7 @@ function ScanHubProvider({ children, ...props }) {
6266
6567
  }, [hub]);
6267
6568
  const serial = useDeviceScanControl(controllers?.serial ?? null);
6268
6569
  const hid = useDeviceScanControl(controllers?.hid ?? null);
6269
- const controls = useMemo4(() => ({ serial, hid }), [serial, hid]);
6570
+ const controls = useMemo6(() => ({ serial, hid }), [serial, hid]);
6270
6571
  return /* @__PURE__ */ jsx3(ScanHubContext.Provider, { value: hub, children: /* @__PURE__ */ jsx3(DeviceScanControlsContext.Provider, { value: controls, children }) });
6271
6572
  }
6272
6573
  function useScanHub() {
@@ -6282,7 +6583,7 @@ function useBarcodeScanner(options) {
6282
6583
  latest.current = options;
6283
6584
  const enabled = options.enabled ?? true;
6284
6585
  const hub = useScanHub();
6285
- useEffect8(() => {
6586
+ useEffect10(() => {
6286
6587
  if (!enabled) return;
6287
6588
  const wedge$ = new Subject2();
6288
6589
  const subscription = merge(wedge$, hub.events$).pipe(dedupeScans(SCAN_DEDUP_WINDOW_MS, scanTimeOf)).subscribe((event) => {
@@ -6485,15 +6786,15 @@ var CAMERA_CONSTRAINTS = {
6485
6786
  };
6486
6787
 
6487
6788
  // src/scanner/use-camera-scan.ts
6488
- import { useMemo as useMemo5, useRef as useRef6, useState as useState7 } from "react";
6789
+ import { useMemo as useMemo7, useRef as useRef6, useState as useState9 } from "react";
6489
6790
  function useCameraScan(options = {}) {
6490
6791
  const latest = useRef6(options);
6491
6792
  latest.current = options;
6492
6793
  const hub = useScanHub();
6493
6794
  const hubRef = useRef6(hub);
6494
6795
  hubRef.current = hub;
6495
- const [scanCount, setScanCount] = useState7(0);
6496
- const [session] = useState7(() => createScanSession({
6796
+ const [scanCount, setScanCount] = useState9(0);
6797
+ const [session] = useState9(() => createScanSession({
6497
6798
  continuous: true,
6498
6799
  now: () => (latest.current.now ?? Date.now)(),
6499
6800
  onAccept: (code, symbology) => {
@@ -6501,7 +6802,7 @@ function useCameraScan(options = {}) {
6501
6802
  setScanCount((count) => count + 1);
6502
6803
  }
6503
6804
  }));
6504
- return useMemo5(() => ({
6805
+ return useMemo7(() => ({
6505
6806
  offer: (code, symbology) => {
6506
6807
  const { active = true, minChars = DEFAULT_MIN_SCAN_CHARS, onTooShort } = latest.current;
6507
6808
  if (!active) return;
@@ -6852,8 +7153,8 @@ function resolveCodePage(name) {
6852
7153
  return ESCPOS_CODE_PAGES[name] ?? ESCPOS_CODE_PAGES.cp437;
6853
7154
  }
6854
7155
  var PRINTABLE_ASCII = /^[\x20-\x7E]$/;
6855
- function foldText(text2, page) {
6856
- const normalized = text2.replace(/[\u2010-\u2014\u2212]/g, "-").replace(/[\u2018\u2019]/g, "'").replace(/[\u201C\u201D]/g, '"').replace(/[\u00A0\u202F\u2009\u2007]/g, " ");
7156
+ function foldText(text3, page) {
7157
+ const normalized = text3.replace(/[\u2010-\u2014\u2212]/g, "-").replace(/[\u2018\u2019]/g, "'").replace(/[\u201C\u201D]/g, '"').replace(/[\u00A0\u202F\u2009\u2007]/g, " ");
6857
7158
  return Array.from(normalized, (char) => {
6858
7159
  if (char === "\n" || PRINTABLE_ASCII.test(char) || page.high.includes(char)) return char;
6859
7160
  if (char === "\xD7") return "x";
@@ -6971,10 +7272,10 @@ function escpos(page = resolveCodePage()) {
6971
7272
 
6972
7273
  // src/print/escpos/encode.ts
6973
7274
  import { formatMoney as formatMoney3, moneyToMajor } from "@tallyui/core";
6974
- function wrapText(text2, width) {
7275
+ function wrapText(text3, width) {
6975
7276
  const lines = [];
6976
7277
  let line = "";
6977
- for (let word of text2.split(" ").filter(Boolean)) {
7278
+ for (let word of text3.split(" ").filter(Boolean)) {
6978
7279
  while (word.length > width) {
6979
7280
  if (line) lines.push(line);
6980
7281
  line = "";
@@ -6994,7 +7295,7 @@ function wrapText(text2, width) {
6994
7295
  function encodeEscPos(receipt, options) {
6995
7296
  const { columns, cut = true, openDrawer = false, drawerConnector = "pin2" } = options;
6996
7297
  const page = resolveCodePage(options.codePage);
6997
- const fold = (text2) => foldText(text2, page);
7298
+ const fold = (text3) => foldText(text3, page);
6998
7299
  const money = options.formatMoney ?? ((minor2, currency) => {
6999
7300
  const formatted = formatMoney3({ amount: minor2, currency }) ?? "";
7000
7301
  if (!fold(formatted).includes("?")) return formatted;
@@ -7006,7 +7307,7 @@ function encodeEscPos(receipt, options) {
7006
7307
  for (const line of lines) out.text(`${line}
7007
7308
  `);
7008
7309
  };
7009
- const block = (text2, indent = "") => fold(text2).split("\n").flatMap((part) => wrapText(part, columns - indent.length).map((line) => indent + line));
7310
+ const block = (text3, indent = "") => fold(text3).split("\n").flatMap((part) => wrapText(part, columns - indent.length).map((line) => indent + line));
7010
7311
  const pair = (left, right, indent = "") => {
7011
7312
  const amount = fold(right);
7012
7313
  const space = columns - amount.length - 1;
@@ -7088,7 +7389,7 @@ function createEscPosTransport({ sink, profile, format: format2 }) {
7088
7389
  try {
7089
7390
  await sink.write(bytes);
7090
7391
  } catch (error) {
7091
- throw new PrintError("failed", error instanceof Error ? error.message : String(error), { cause: error });
7392
+ throw toPrintError(error);
7092
7393
  }
7093
7394
  }
7094
7395
  };
@@ -7184,6 +7485,104 @@ function networkSinkFor(profile, options = {}) {
7184
7485
  return null;
7185
7486
  }
7186
7487
 
7488
+ // src/print/escpos/usb-sink.ts
7489
+ var USB_CHUNK_SIZE = 4096;
7490
+ var USB_PRINTER_CLASS = 7;
7491
+ function bulkOut(device) {
7492
+ const candidates = (device.configuration?.interfaces ?? []).flatMap((usbInterface) => {
7493
+ const endpoint = usbInterface.alternate.endpoints.find(({ direction, type }) => direction === "out" && type === "bulk");
7494
+ return endpoint ? [{ usbInterface, endpointNumber: endpoint.endpointNumber }] : [];
7495
+ });
7496
+ return candidates.find(({ usbInterface }) => usbInterface.alternate.interfaceClass === USB_PRINTER_CLASS) ?? candidates[0] ?? null;
7497
+ }
7498
+ function createWebUsbSink({ device, chunkSize = USB_CHUNK_SIZE }) {
7499
+ if (!Number.isInteger(chunkSize) || chunkSize < 1) throw new RangeError(`chunkSize must be a positive integer, not ${chunkSize}`);
7500
+ const name = () => device.productName || "USB printer";
7501
+ async function step(label, run) {
7502
+ try {
7503
+ return await run();
7504
+ } catch (error) {
7505
+ throw new PrintError("failed", `${name()}: ${label} failed: ${error instanceof Error ? error.message : error}`, { cause: error });
7506
+ }
7507
+ }
7508
+ return {
7509
+ async write(bytes) {
7510
+ if (!device.opened) await step("open", () => device.open());
7511
+ if (device.configuration == null) await step("selectConfiguration(1)", () => device.selectConfiguration(1));
7512
+ const target = bulkOut(device);
7513
+ if (!target) throw new PrintError("unsupported", `${name()} has no bulk OUT endpoint to print to`);
7514
+ const { usbInterface: { interfaceNumber, claimed }, endpointNumber } = target;
7515
+ if (!claimed) await step(`claimInterface(${interfaceNumber})`, () => device.claimInterface(interfaceNumber));
7516
+ for (let i = 0; i < bytes.length; i += chunkSize) {
7517
+ const chunk = bytes.slice(i, i + chunkSize);
7518
+ const result = await step(`transferOut(${endpointNumber})`, () => device.transferOut(endpointNumber, chunk));
7519
+ if (result.status === "ok") continue;
7520
+ if (result.status === "stall") await device.clearHalt("out", endpointNumber).catch(() => void 0);
7521
+ throw new PrintError("failed", `${name()}: transferOut(${endpointNumber}) ended with status ${result.status}`);
7522
+ }
7523
+ }
7524
+ };
7525
+ }
7526
+
7527
+ // src/print/escpos/bluetooth-sink.ts
7528
+ var PRINT_PROFILES = [
7529
+ ["000018f0-0000-1000-8000-00805f9b34fb", "00002af1-0000-1000-8000-00805f9b34fb"],
7530
+ ["0000ff00-0000-1000-8000-00805f9b34fb", "0000ff02-0000-1000-8000-00805f9b34fb"],
7531
+ ["49535343-fe7d-4ae5-8fa9-9fafd205e455", "49535343-8841-43f4-a8d4-ecbe34729bb3"],
7532
+ ["e7810a71-73ae-499d-8c15-faa9aef0c3f2", "bef8d6c9-9c21-4c9e-b632-bd58c1009f9f"]
7533
+ ];
7534
+ var BLUETOOTH_PRINT_SERVICES = PRINT_PROFILES.map(([service]) => service);
7535
+ var BLE_CHUNK_SIZE = 20;
7536
+ var BLE_CHUNK_PAUSE_MS = 20;
7537
+ var BLE_SETTLE_MS = 300;
7538
+ var pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
7539
+ async function printCharacteristic(gatt) {
7540
+ for (const [service, characteristic] of PRINT_PROFILES) {
7541
+ try {
7542
+ const found = await (await gatt.getPrimaryService(service)).getCharacteristic(characteristic);
7543
+ if (found.properties.write) return found;
7544
+ } catch {
7545
+ }
7546
+ }
7547
+ return null;
7548
+ }
7549
+ function createWebBluetoothSink({ device, chunkSize = BLE_CHUNK_SIZE }) {
7550
+ if (!Number.isInteger(chunkSize) || chunkSize < 1) throw new RangeError(`chunkSize must be a positive integer, not ${chunkSize}`);
7551
+ const name = () => device.name || "Bluetooth printer";
7552
+ async function step(label, run) {
7553
+ try {
7554
+ return await run();
7555
+ } catch (error) {
7556
+ throw new PrintError("failed", `${name()}: ${label} failed: ${error instanceof Error ? error.message : error}`, { cause: error });
7557
+ }
7558
+ }
7559
+ return {
7560
+ async write(bytes) {
7561
+ const { gatt } = device;
7562
+ if (!gatt) throw new PrintError("unsupported", `${name()} has no GATT server to print to`);
7563
+ if (!gatt.connected) await step("connect", () => gatt.connect());
7564
+ const target = await printCharacteristic(gatt);
7565
+ if (!target && !gatt.connected) {
7566
+ throw new PrintError("failed", `${name()}: the link dropped while finding the print service; nothing was written`);
7567
+ }
7568
+ if (!target) {
7569
+ throw new PrintError("unsupported", `${name()}: no known print service was found; nothing was written; is BLUETOOTH_PRINT_SERVICES in optionalServices?`);
7570
+ }
7571
+ for (let i = 0; i < bytes.length; i += chunkSize) {
7572
+ const chunk = bytes.slice(i, i + chunkSize);
7573
+ const last = i + chunkSize >= bytes.length;
7574
+ const chunkLabel = `chunk ${i / chunkSize + 1}`;
7575
+ if (last || !target.properties.writeWithoutResponse) {
7576
+ await step(`writeValueWithResponse (${chunkLabel})`, () => target.writeValueWithResponse(chunk));
7577
+ } else {
7578
+ await step(`writeValueWithoutResponse (${chunkLabel})`, () => target.writeValueWithoutResponse(chunk));
7579
+ }
7580
+ await pause(last ? BLE_SETTLE_MS : BLE_CHUNK_PAUSE_MS);
7581
+ }
7582
+ }
7583
+ };
7584
+ }
7585
+
7187
7586
  // src/print/escpos/drawer.ts
7188
7587
  function canOpenDrawer(profile) {
7189
7588
  if (!profile || profile.connectionType === "system") return false;
@@ -7200,7 +7599,7 @@ function openDrawerJob(profile, id2) {
7200
7599
  var PLAIN = { bold: false, underline: false, invert: false, width: 1, height: 1 };
7201
7600
  var TRAILING = /* @__PURE__ */ new Set(["cut", "feed", "drawer"]);
7202
7601
  var BREAK = /\r\n|\r|\n/;
7203
- var leading = (text2) => text2.length - text2.replace(/^ +/, "").length;
7602
+ var leading = (text3) => text3.length - text3.replace(/^ +/, "").length;
7204
7603
  function renderEscpos(ast, options = {}) {
7205
7604
  const page = resolveCodePage(options.codePage);
7206
7605
  const columns = options.columns ?? ast.paperWidth;
@@ -7216,14 +7615,14 @@ function renderEscpos(ast, options = {}) {
7216
7615
  if (next.invert !== printed.invert) out.invert(next.invert);
7217
7616
  printed = next;
7218
7617
  };
7219
- const emit = (text2, styles, mode, scale) => {
7220
- const room = columns - text2.length * scale;
7618
+ const emit = (text3, styles, mode, scale) => {
7619
+ const room = columns - text3.length * scale;
7221
7620
  const pad = Math.floor((mode === "center" ? Math.floor(room / 2) : mode === "right" ? room : 0) / scale);
7222
- if (text2 && pad > 0) {
7621
+ if (text3 && pad > 0) {
7223
7622
  sync({ ...styles[0], underline: false, invert: false });
7224
7623
  out.text(" ".repeat(pad));
7225
7624
  }
7226
- Array.from(text2).forEach((char, i) => {
7625
+ Array.from(text3).forEach((char, i) => {
7227
7626
  sync(styles[i]);
7228
7627
  out.text(char);
7229
7628
  });
@@ -7231,15 +7630,15 @@ function renderEscpos(ast, options = {}) {
7231
7630
  };
7232
7631
  const endLine = (force) => {
7233
7632
  if (!force && !line.length) return;
7234
- const text2 = line.map((run) => run.text).join("");
7633
+ const text3 = line.map((run) => run.text).join("");
7235
7634
  const styles = line.flatMap((run) => Array.from(run.text, () => run.style));
7236
7635
  const scale = Math.max(1, ...line.map((run) => run.style.width));
7237
- const indent = leading(text2);
7636
+ const indent = leading(text3);
7238
7637
  line = [];
7239
7638
  let cursor = indent;
7240
- for (const part of wrapText(text2.slice(indent), Math.max(1, Math.floor(columns / scale) - indent))) {
7639
+ for (const part of wrapText(text3.slice(indent), Math.max(1, Math.floor(columns / scale) - indent))) {
7241
7640
  const partStyles = Array.from(part, (char) => {
7242
- while (text2[cursor] !== char) cursor++;
7641
+ while (text3[cursor] !== char) cursor++;
7243
7642
  return styles[cursor++];
7244
7643
  });
7245
7644
  emit(" ".repeat(indent) + part, [...styles.slice(0, indent), ...partStyles], align, scale);
@@ -7248,9 +7647,9 @@ function renderEscpos(ast, options = {}) {
7248
7647
  const row = (cols) => {
7249
7648
  const widths = rowWidths(cols, Math.floor(columns / style.width));
7250
7649
  const cells = cols.map((col, i) => {
7251
- const text2 = foldText(extractText(col.children).split(BREAK).join(" "), page);
7252
- const indent = col.align === "left" ? Math.min(leading(text2), widths[i] - 1) : 0;
7253
- return wrapText(text2.slice(leading(text2)), widths[i] - indent).map((cell) => col.align === "left" ? (" ".repeat(indent) + cell).padEnd(widths[i]) : cell.padStart(widths[i]));
7650
+ const text3 = foldText(extractText(col.children).split(BREAK).join(" "), page);
7651
+ const indent = col.align === "left" ? Math.min(leading(text3), widths[i] - 1) : 0;
7652
+ return wrapText(text3.slice(leading(text3)), widths[i] - indent).map((cell) => col.align === "left" ? (" ".repeat(indent) + cell).padEnd(widths[i]) : cell.padStart(widths[i]));
7254
7653
  });
7255
7654
  const height = Math.max(0, ...cells.map((cell) => cell.length));
7256
7655
  for (let r = 0; r < height; r++) {
@@ -7353,7 +7752,7 @@ var extractText = (nodes) => nodes.map((node) => node.type === "raw-text" ? node
7353
7752
  var hasDrawer = (nodes) => nodes.some((node) => node.type === "drawer" || "children" in node && hasDrawer(node.children));
7354
7753
 
7355
7754
  // src/sale/use-sale.ts
7356
- import { useEffect as useEffect10, useLayoutEffect, useMemo as useMemo7, useRef as useRef8, useState as useState9 } from "react";
7755
+ import { useEffect as useEffect12, useLayoutEffect, useMemo as useMemo9, useRef as useRef8, useState as useState11 } from "react";
7357
7756
  import { ORDER_META_KEY_MAX as ORDER_META_KEY_MAX3, ORDER_META_MAX as ORDER_META_MAX2, paymentMethodOf as paymentMethodOf2 } from "@tallyui/core";
7358
7757
 
7359
7758
  // src/tender/split-units.ts
@@ -7530,11 +7929,11 @@ function orderBuilderFromStoreOrder(read, options) {
7530
7929
  import { ORDER_TAX_ID_TYPE_MAX as ORDER_TAX_ID_TYPE_MAX2, ORDER_TAX_ID_VALUE_MAX as ORDER_TAX_ID_VALUE_MAX2, ORDER_TAX_IDS_MAX as ORDER_TAX_IDS_MAX2 } from "@tallyui/core";
7531
7930
  var TAX_IDS_INVALID = "Each tax id needs a type of at most 32 characters and a number of at most 64, no two the same; a country is a two-letter code, and a sale takes at most 10.";
7532
7931
  var TAX_ID_LABEL_MAX = 255;
7533
- function cleanTaxIds(list) {
7534
- if (list.length > ORDER_TAX_IDS_MAX2) return null;
7932
+ function cleanTaxIds(list2) {
7933
+ if (list2.length > ORDER_TAX_IDS_MAX2) return null;
7535
7934
  const seen = /* @__PURE__ */ new Set();
7536
7935
  const cleaned = [];
7537
- for (const taxId of list) {
7936
+ for (const taxId of list2) {
7538
7937
  const type = taxId.type.trim(), value = taxId.value.trim(), country = taxId.country?.trim().toUpperCase(), label = taxId.label?.trim();
7539
7938
  const key = JSON.stringify([type, value]);
7540
7939
  if (!type || !value || type.length > ORDER_TAX_ID_TYPE_MAX2 || value.length > ORDER_TAX_ID_VALUE_MAX2 || seen.has(key) || [type, value, country, label].some((field) => field?.includes("\0")) || country && !/^[A-Z]{2}$/.test(country) || label && label.length > TAX_ID_LABEL_MAX) return null;
@@ -7560,8 +7959,8 @@ var outboxLogger = createLogger("outbox");
7560
7959
  // src/pos-order/finalize.ts
7561
7960
  var ORDER_ADDRESS_KEYS = ["firstName", "lastName", "company", "address1", "address2", "city", "state", "postcode", "country", "phone"];
7562
7961
  function orderAddress(address) {
7563
- const entries = ORDER_ADDRESS_KEYS.flatMap((key) => typeof address?.[key] === "string" && address[key] ? [[key, address[key]]] : []);
7564
- return entries.length ? Object.fromEntries(entries) : void 0;
7962
+ const entries2 = ORDER_ADDRESS_KEYS.flatMap((key) => typeof address?.[key] === "string" && address[key] ? [[key, address[key]]] : []);
7963
+ return entries2.length ? Object.fromEntries(entries2) : void 0;
7565
7964
  }
7566
7965
  var AFTER_CLOSE_PAYMENTS_CHANGED = "This sale was counted in a closed register. Its payments must stay as that closure counted them.";
7567
7966
  var sameTaxes = (a, b) => a.taxLines.length === b.taxLines.length && a.taxLines.every((tax, i) => tax.code === b.taxLines[i].code && tax.ratePpm === b.taxLines[i].ratePpm && tax.taxMicros === b.taxLines[i].taxMicros);
@@ -7712,6 +8111,9 @@ function finalizeOrder(order, options = {}) {
7712
8111
  if (order.lineItems.some((line) => line.anyAttributes?.length) && (options.capabilities?.orderCreate ?? 1) < 6) {
7713
8112
  throw new Error("finalize: picked options need the store to accept order.create version 6; update the store's TallyUI plugin");
7714
8113
  }
8114
+ if (order.cashRoundings?.length && options.capabilities?.cashRounding !== true) {
8115
+ throw new Error("finalize: cash rounding needs a store whose connector declares the cashRounding capability");
8116
+ }
7715
8117
  if (!order.lineItems.length) throw new Error("finalize: no lines");
7716
8118
  if (order.discountMinor < 0 || order.lineItems.some((line) => line.discountMinor < 0) || order.discounts.some((d) => d.amountMinor < 0)) {
7717
8119
  throw new Error("finalize: negative discount");
@@ -7807,7 +8209,9 @@ function finalizeOrder(order, options = {}) {
7807
8209
  amountMinor: payment.amountMinor,
7808
8210
  ...payment.tenderedMinor !== void 0 ? { tenderedMinor: payment.tenderedMinor } : {},
7809
8211
  ...payment.changeMinor !== void 0 ? { changeMinor: payment.changeMinor } : {},
7810
- ...payment.reference !== void 0 ? { reference: payment.reference } : {}
8212
+ ...payment.reference !== void 0 ? { reference: payment.reference } : {},
8213
+ ...isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {},
8214
+ ...payment.sessionId !== void 0 ? { sessionId: payment.sessionId } : {}
7811
8215
  }));
7812
8216
  const localWarnings = options.localWarnings?.flatMap((warning) => {
7813
8217
  if (warning.code !== "payment_reference_dropped") return [{ ...warning }];
@@ -7889,6 +8293,11 @@ function finalizeOrder(order, options = {}) {
7889
8293
  pricesIncludeTax: order.pricesIncludeTax,
7890
8294
  lines,
7891
8295
  payments,
8296
+ ...order.cashRoundings?.length ? { cashRoundings: order.cashRoundings.map((entry) => {
8297
+ const index = order.payments.findIndex((payment) => payment.id === entry.paymentId);
8298
+ if (index === -1) throw new Error("finalize: a cash rounding names no payment on the order");
8299
+ return { paymentId: payments[index].id, minor: entry.minor };
8300
+ }) } : {},
7892
8301
  ...fees?.length ? { fees } : {},
7893
8302
  ...shipping?.length ? { shipping } : {},
7894
8303
  subtotalMinor: order.subtotalMinor,
@@ -7944,7 +8353,7 @@ var orderAddressSchema = { type: "object", additionalProperties: false, properti
7944
8353
  phone: { type: "string" }
7945
8354
  } };
7946
8355
  var posOrderSchema = {
7947
- version: 19,
8356
+ version: 21,
7948
8357
  primaryKey: "id",
7949
8358
  type: "object",
7950
8359
  additionalProperties: false,
@@ -8070,10 +8479,15 @@ var posOrderSchema = {
8070
8479
  amountMinor: { type: "integer" },
8071
8480
  tenderedMinor: { type: "integer" },
8072
8481
  changeMinor: { type: "integer" },
8073
- reference: { type: "string" }
8482
+ reference: { type: "string" },
8483
+ takenAt: { type: "string", maxLength: 40 }
8074
8484
  },
8075
8485
  required: ["id", "method", "amountMinor"]
8076
8486
  } },
8487
+ cashRoundings: { type: "array", items: { type: "object", additionalProperties: false, properties: {
8488
+ paymentId: { type: "string", maxLength: 36 },
8489
+ minor: { type: "integer" }
8490
+ }, required: ["paymentId", "minor"] } },
8077
8491
  customer: { type: ["object", "null"], properties: {
8078
8492
  id: { type: "string" },
8079
8493
  name: { type: "string" },
@@ -8204,7 +8618,7 @@ function posOrderCollection() {
8204
8618
  };
8205
8619
  return {
8206
8620
  schema: posOrderSchema,
8207
- migrationStrategies: { 1: identity2, 2: identity2, 3: identity2, 4: identity2, 5: recordSent, 6: recordRounding, 7: identity2, 8: identity2, 9: identity2, 10: identity2, 11: identity2, 12: identity2, 13: identity2, 14: identity2, 15: identity2, 16: identity2, 17: identity2, 18: identity2, 19: identity2 }
8621
+ migrationStrategies: { 1: identity2, 2: identity2, 3: identity2, 4: identity2, 5: recordSent, 6: recordRounding, 7: identity2, 8: identity2, 9: identity2, 10: identity2, 11: identity2, 12: identity2, 13: identity2, 14: identity2, 15: identity2, 16: identity2, 17: identity2, 18: identity2, 19: identity2, 20: identity2, 21: identity2 }
8208
8622
  };
8209
8623
  }
8210
8624
 
@@ -8301,13 +8715,13 @@ async function openCollection(db, opener, previous) {
8301
8715
  await (closing() ? checkpoint.close() : checkpoint.remove());
8302
8716
  stopIfClosing();
8303
8717
  const settled = new Subject3();
8304
- let inFlight2 = 0;
8718
+ let inFlight3 = 0;
8305
8719
  let drained;
8306
8720
  const track = (result) => {
8307
8721
  if (!(result instanceof Promise)) return result;
8308
- inFlight2++;
8722
+ inFlight3++;
8309
8723
  return result.finally(() => {
8310
- if (--inFlight2 === 0) drained?.();
8724
+ if (--inFlight3 === 0) drained?.();
8311
8725
  });
8312
8726
  };
8313
8727
  const gate = (target, closed) => new Proxy(target, { get: (t, key) => {
@@ -8343,7 +8757,7 @@ async function openCollection(db, opener, previous) {
8343
8757
  state.cancel = () => {
8344
8758
  if (running) {
8345
8759
  cancelled = true;
8346
- if (inFlight2 === 0) onCancel();
8760
+ if (inFlight3 === 0) onCancel();
8347
8761
  else drained = onCancel;
8348
8762
  }
8349
8763
  return cancel();
@@ -8452,11 +8866,6 @@ function moneyDivergence(order) {
8452
8866
  return orderFields.length === 0 && lineIds.length === 0 ? null : { orderFields, lineIds };
8453
8867
  }
8454
8868
 
8455
- // src/pos-order/till-payments.ts
8456
- function tillPayments(payments) {
8457
- return payments.filter((payment) => payment.storePaymentId === void 0);
8458
- }
8459
-
8460
8869
  // src/register/expected.ts
8461
8870
  import { legMethodId } from "@tallyui/core";
8462
8871
  function refundAmounts(refund) {
@@ -8468,13 +8877,19 @@ function refundAmounts(refund) {
8468
8877
  }
8469
8878
  function paymentLedgerRows(orders) {
8470
8879
  return orders.flatMap((order) => tillPayments(order.payments).map((payment) => ({
8471
- session_id: order.sessionId,
8880
+ session_id: payment.sessionId ?? order.sessionId,
8472
8881
  kind: payment.method === "cash" ? "cash" : "other",
8473
8882
  method_id: payment.method,
8474
8883
  status: "captured",
8475
8884
  amountMinor: payment.amountMinor
8476
8885
  })));
8477
8886
  }
8887
+ function liveLedgerRows(legs) {
8888
+ return paymentLedgerRows([{ payments: legs }]);
8889
+ }
8890
+ function parkedLedgerRows(drafts) {
8891
+ return liveLedgerRows(drafts.flatMap((draft) => parkedTakenLegs(draft.data)));
8892
+ }
8478
8893
  function deriveExpected({
8479
8894
  session,
8480
8895
  movements,
@@ -8545,11 +8960,11 @@ function deriveDrawerTerms(input) {
8545
8960
  expected: deriveExpected(input)
8546
8961
  };
8547
8962
  }
8548
- function takingsByMethod(orders, sessionId) {
8963
+ function takingsByMethod(orders, sessionId, extra = []) {
8549
8964
  const takings = /* @__PURE__ */ Object.create(null);
8550
- for (const order of orders) {
8551
- if (order.sessionId !== sessionId) continue;
8965
+ for (const order of [...orders, { payments: extra }]) {
8552
8966
  for (const payment of tillPayments(order.payments)) {
8967
+ if ((payment.sessionId ?? order.sessionId) !== sessionId) continue;
8553
8968
  const term = takings[legMethodId(payment)] ??= { amountMinor: 0, count: 0 };
8554
8969
  term.amountMinor += payment.amountMinor;
8555
8970
  term.count += 1;
@@ -8715,6 +9130,13 @@ function renumberClosures(host, storeKey, registerId, rows) {
8715
9130
  });
8716
9131
  });
8717
9132
  }
9133
+ function settleStoreRefunds(host, storeKey, registerId, { lastClosureNumber, perpetualRefundsTotalMinor }) {
9134
+ return modifyStore(host, storeKey, (store) => {
9135
+ const register = store?.registers?.[registerId] ?? {};
9136
+ if (register.last_closure_number !== lastClosureNumber || register.closure_reservation?.applied === false || register.perpetual_refunds_total_minor === perpetualRefundsTotalMinor) return void 0;
9137
+ return withRegister(store, registerId, { ...register, perpetual_refunds_total_minor: perpetualRefundsTotalMinor });
9138
+ });
9139
+ }
8718
9140
  function advancePerpetual(host, storeKey, registerId, period) {
8719
9141
  return modifyStore(host, storeKey, (store) => {
8720
9142
  const register = store?.registers?.[registerId] ?? {};
@@ -8845,8 +9267,8 @@ function movementFieldError(input) {
8845
9267
  }
8846
9268
 
8847
9269
  // src/register/register-count.helpers.ts
8848
- function parseMinor(text2, exponent) {
8849
- const [whole, fraction = ""] = text2.trim().split(".");
9270
+ function parseMinor(text3, exponent) {
9271
+ const [whole, fraction = ""] = text3.trim().split(".");
8850
9272
  if (fraction.length > exponent) return NaN;
8851
9273
  return Number(whole || "0") * 10 ** exponent + Number(fraction.padEnd(exponent, "0") || "0");
8852
9274
  }
@@ -9133,6 +9555,9 @@ async function writeClosure({
9133
9555
  otherTenders,
9134
9556
  movements,
9135
9557
  orders,
9558
+ drafts,
9559
+ liveLegs,
9560
+ liveRoundings,
9136
9561
  refunds,
9137
9562
  tillExpected,
9138
9563
  labels,
@@ -9153,11 +9578,11 @@ async function writeClosure({
9153
9578
  const replaced = replacedOrderIds(orders);
9154
9579
  const bound = orders.filter((order) => order.sessionId === session.id && !replaced.has(order.id));
9155
9580
  const countedRefunds = (refunds ?? []).filter((refund) => refund.status === "applied" && refund.sessionId === session.id);
9156
- const rows = paymentLedgerRows(bound);
9157
- const entries = movements.filter((row2) => row2.session_id === session.id);
9581
+ const rows = [...paymentLedgerRows(bound), ...parkedLedgerRows(drafts ?? []), ...liveLedgerRows(liveLegs ?? [])].filter((row2) => row2.session_id === session.id);
9582
+ const entries2 = movements.filter((row2) => row2.session_id === session.id);
9158
9583
  const till_expected = tillExpected ?? deriveExpected({
9159
9584
  session: { id: session.id, countedFloatMinor: session.counted_float_minor },
9160
- movements: entries,
9585
+ movements: entries2,
9161
9586
  ledgerRowsBySession: rows,
9162
9587
  refunds
9163
9588
  });
@@ -9174,6 +9599,7 @@ async function writeClosure({
9174
9599
  }
9175
9600
  }
9176
9601
  const payment_methods = Object.fromEntries(methodTotals);
9602
+ const taxRateKey = (code, ratePpm) => `${ratePpm}:${(code ?? "").replace(/[%.[\]\\]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`;
9177
9603
  const taxRates = /* @__PURE__ */ new Map();
9178
9604
  const roundings = /* @__PURE__ */ new Set();
9179
9605
  for (const order of bound) {
@@ -9181,16 +9607,27 @@ async function writeClosure({
9181
9607
  const rounding = recorded.granularity === "custom" ? DEFAULT_TAX_ROUNDING : recorded;
9182
9608
  roundings.add(rounding.granularity === "woocommerce" ? `woocommerce ${rounding.roundAtSubtotal}` : `${rounding.granularity} ${rounding.mode}`);
9183
9609
  const taxedLines = taxedLinesFor(order.lines, [...order.fees ?? [], ...order.shipping ?? []], order.pricesIncludeTax, order.taxRounding);
9184
- for (const { ratePpm, netMinor, amountMinor } of taxLinesByRate(taxedLines, order.taxMinor, void 0, order.taxRounding)) {
9185
- const existing2 = taxRates.get(String(ratePpm));
9186
- taxRates.set(String(ratePpm), {
9610
+ for (const { ratePpm, code, netMinor, amountMinor } of taxLinesByRate(taxedLines, order.taxMinor, void 0, order.taxRounding)) {
9611
+ const existing2 = taxRates.get(taxRateKey(code, ratePpm));
9612
+ taxRates.set(taxRateKey(code, ratePpm), {
9187
9613
  ratePpm,
9614
+ code,
9188
9615
  net_minor: (existing2?.net_minor ?? 0) + netMinor,
9189
9616
  tax_minor: (existing2?.tax_minor ?? 0) + amountMinor
9190
9617
  });
9191
9618
  }
9192
9619
  }
9193
9620
  const unsynced = bound.filter((order) => order.syncStatus === "pending");
9621
+ const cashRoundingMinor = sum4(bound.flatMap((order) => {
9622
+ const legs = new Map(tillPayments(order.payments).map((payment) => [payment.id, payment]));
9623
+ return (order.cashRoundings ?? []).filter((entry) => {
9624
+ const leg = legs.get(entry.paymentId);
9625
+ return leg !== void 0 && (leg.sessionId ?? order.sessionId) === session.id;
9626
+ }).map((entry) => entry.minor);
9627
+ })) + sum4([
9628
+ ...(drafts ?? []).map((row2) => ({ legs: parkedTakenLegs(row2.data), entries: parkedCashRoundings(row2.data) })),
9629
+ { legs: liveLegs ?? [], entries: liveRoundings ?? [] }
9630
+ ].flatMap(({ legs, entries: entries3 }) => entries3.filter((entry) => legs.some((leg) => leg.id === entry.paymentId && leg.sessionId === session.id)).map((entry) => entry.minor)));
9194
9631
  const draft = {
9195
9632
  id: session.id,
9196
9633
  session_id: session.id,
@@ -9224,21 +9661,24 @@ async function writeClosure({
9224
9661
  ...session.count_note?.trim() ? { variance_note: session.count_note } : {},
9225
9662
  payment_methods,
9226
9663
  tax_rates: Object.fromEntries(
9227
- [...taxRates.values()].map(({ ratePpm, net_minor, tax_minor }) => [
9228
- ratePpm,
9229
- { name: `Tax ${ratePpm / 1e4}%`, net_minor, tax_minor, gross_minor: net_minor + tax_minor }
9664
+ [...taxRates.values()].sort((a, b) => a.ratePpm - b.ratePpm || ((a.code ?? "") < (b.code ?? "") ? -1 : (a.code ?? "") > (b.code ?? "") ? 1 : 0)).map(({ ratePpm, code, net_minor, tax_minor }) => [
9665
+ // Numeric keys sorted automatically; identity keys need an explicit sort.
9666
+ taxRateKey(code, ratePpm),
9667
+ { name: `Tax ${ratePpm / 1e4}%${[...taxRates.values()].filter((row2) => row2.ratePpm === ratePpm).length > 1 && code ? ` (${code})` : ""}`, rate_ppm: ratePpm, ...code ? { code } : {}, net_minor, tax_minor, gross_minor: net_minor + tax_minor }
9230
9668
  ])
9231
9669
  ),
9232
9670
  // The session's sales used more than one tax rounding (#287): the Z report says so.
9233
9671
  ...roundings.size > 1 ? { tax_rounding_mixed: true } : {},
9234
9672
  // A reopened sale's tax rates are its whole order's, including tax on what was paid earlier in the store (ADR-090 ruling 38).
9235
9673
  ...bound.some((order) => tillPayments(order.payments).length < order.payments.length) ? { tax_includes_store_paid: true } : {},
9674
+ // ADR-094: in period_sales_total_minor, in no tax_rates row.
9675
+ ...cashRoundingMinor !== 0 ? { cash_rounding_minor: cashRoundingMinor } : {},
9236
9676
  opening_float: {
9237
9677
  expected_minor: session.expected_float_minor ?? null,
9238
9678
  counted_minor: session.counted_float_minor,
9239
9679
  variance_minor: session.opening_variance_minor ?? null
9240
9680
  },
9241
- movements: entries.map(({ id: id2, type, amountMinor, reason, voids, voided_by, created_at_gmt, created_by }) => ({
9681
+ movements: entries2.map(({ id: id2, type, amountMinor, reason, voids, voided_by, created_at_gmt, created_by }) => ({
9242
9682
  id: id2,
9243
9683
  type,
9244
9684
  amountMinor,
@@ -9260,7 +9700,7 @@ async function writeClosure({
9260
9700
  }))
9261
9701
  },
9262
9702
  order_ids: bound.map((order) => order.id),
9263
- movement_ids: entries.map((row2) => row2.id)
9703
+ movement_ids: entries2.map((row2) => row2.id)
9264
9704
  };
9265
9705
  await mintClosureNumber(register, storeKey, session.register_id, draft);
9266
9706
  const reserved = (await readRegister(register)).stores[storeKey].registers[session.register_id].closure_reservation.row;
@@ -9375,15 +9815,22 @@ async function reopenRefusedOrder(orderId, deps, options) {
9375
9815
  ...shipping.taxStatus !== void 0 ? { taxStatus: shipping.taxStatus } : {},
9376
9816
  ...shipping.methodId !== void 0 ? { methodId: shipping.methodId } : {}
9377
9817
  });
9378
- for (const payment of order.payments) builder.addPayment({
9818
+ const legIds = /* @__PURE__ */ new Map();
9819
+ for (const payment of order.payments) legIds.set(payment.id, builder.addPayment({
9379
9820
  // After close each leg keeps the refused order's id, so finalize knows it for the leg that closure counted.
9380
9821
  ...afterClose ? { id: payment.id } : {},
9381
9822
  method: payment.method,
9382
9823
  amountMinor: payment.amountMinor,
9383
9824
  reopened: true,
9384
9825
  ...payment.reference !== void 0 ? { reference: payment.reference } : {},
9385
- ...payment.methodId !== void 0 ? { methodId: payment.methodId } : {}
9386
- });
9826
+ ...payment.methodId !== void 0 ? { methodId: payment.methodId } : {},
9827
+ ...isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {},
9828
+ ...payment.sessionId !== void 0 ? { sessionId: payment.sessionId } : {}
9829
+ }));
9830
+ for (const entry of order.cashRoundings ?? []) {
9831
+ const paymentId = legIds.get(entry.paymentId);
9832
+ if (paymentId) builder.addCashRounding({ paymentId, minor: entry.minor });
9833
+ }
9387
9834
  if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
9388
9835
  builder.setCustomer({
9389
9836
  id: order.customer.id,
@@ -9459,29 +9906,329 @@ var OrderContentMismatchError = class extends Error {
9459
9906
  }
9460
9907
  };
9461
9908
 
9462
- // src/register/register-count.denominations.ts
9463
- var coinsMinor = [200, 100, 50, 20, 10, 5, 2, 1];
9464
- var denominations = {
9465
- GBP: [5e3, 2e3, 1e3, 500, ...coinsMinor],
9466
- EUR: [5e4, 2e4, 1e4, 5e3, 2e3, 1e3, 500, ...coinsMinor],
9467
- USD: [1e4, 5e3, 2e3, 1e3, 500, 100, 25, 10, 5, 1],
9468
- default: [1e4, 5e3, 2e3, 1e3, 500, 200, 100, 50, 25, 10, 5, 1]
9469
- };
9909
+ // src/tender/cash-rounding.ts
9910
+ import { wireMethodOf } from "@tallyui/core";
9470
9911
 
9471
- // src/register/schemas.ts
9472
- import { addRxPlugin as addRxPlugin2 } from "rxdb";
9473
- import { RxDBLocalDocumentsPlugin } from "rxdb/plugins/local-documents";
9474
- import { RxDBMigrationSchemaPlugin as RxDBMigrationSchemaPlugin2 } from "rxdb/plugins/migration-schema";
9475
- var id = { type: "string", maxLength: 36 };
9476
- var text = { type: "string" };
9477
- var nullableText = { type: ["string", "null"] };
9478
- var minor = { type: "integer" };
9479
- var nullableMinor = { type: ["integer", "null"] };
9480
- var tenders = { type: "object", additionalProperties: minor };
9481
- var registerSessionSchema = {
9482
- title: "Register sessions",
9483
- version: 2,
9484
- primaryKey: "id",
9912
+ // src/tender/tender-state.ts
9913
+ var MAX_TENDER_MINOR = 999999999;
9914
+ var initialTenderState = {
9915
+ view: "select",
9916
+ methodId: null,
9917
+ readerId: null,
9918
+ transport: null,
9919
+ entryMinor: 0,
9920
+ entryDirty: false,
9921
+ entryMode: "money",
9922
+ plan: null,
9923
+ splitView: false,
9924
+ splitTab: "even",
9925
+ pickedLineIds: [],
9926
+ linesPaidBy: {},
9927
+ pickedUnits: {},
9928
+ unitAllocations: {}
9929
+ };
9930
+ function initTenderState({
9931
+ methodId,
9932
+ balanceMinor,
9933
+ payments
9934
+ }) {
9935
+ const state = payments ? { ...initialTenderState, unitAllocations: unitAllocationsFromLegs(payments ?? []) } : initialTenderState;
9936
+ if (!methodId) return state;
9937
+ return { ...state, view: "amount", methodId, entryMinor: balanceMinor };
9938
+ }
9939
+ function tenderReducer(state, action) {
9940
+ switch (action.type) {
9941
+ case "pick-method":
9942
+ return {
9943
+ ...state,
9944
+ view: "amount",
9945
+ methodId: action.methodId,
9946
+ readerId: action.readerId,
9947
+ transport: action.transport ?? null,
9948
+ entryMinor: state.entryDirty ? state.entryMinor : action.prefillMinor,
9949
+ entryDirty: state.entryDirty
9950
+ };
9951
+ case "pick-transport":
9952
+ return { ...state, transport: action.transport };
9953
+ case "pick-reader":
9954
+ return { ...state, readerId: action.readerId };
9955
+ case "key": {
9956
+ if (state.view !== "amount") {
9957
+ return state;
9958
+ }
9959
+ if (action.key === "backspace") {
9960
+ return { ...state, entryMinor: Math.floor(state.entryMinor / 10), entryDirty: true };
9961
+ }
9962
+ if (action.key === "clear") {
9963
+ return { ...state, entryMinor: 0, entryDirty: true };
9964
+ }
9965
+ const digit = Number(action.key);
9966
+ if (!state.entryDirty) {
9967
+ return { ...state, entryMinor: digit, entryDirty: true };
9968
+ }
9969
+ const entryMinor = state.entryMinor * 10 + digit;
9970
+ return entryMinor > MAX_TENDER_MINOR ? state : { ...state, entryMinor };
9971
+ }
9972
+ case "set-entry":
9973
+ return {
9974
+ ...state,
9975
+ entryMinor: Math.max(0, Math.min(action.minor, MAX_TENDER_MINOR)),
9976
+ entryDirty: true
9977
+ };
9978
+ case "set-entry-mode":
9979
+ return { ...state, entryMode: action.mode, entryMinor: 0, entryDirty: false };
9980
+ case "tender-started": {
9981
+ const leg = action.units ?? state.pickedUnits;
9982
+ const freeze = action.paymentId !== void 0 && Object.keys(leg).length > 0;
9983
+ const clear = action.paymentId !== void 0 && Object.keys(state.pickedUnits).length > 0;
9984
+ const units = {
9985
+ ...freeze ? { unitAllocations: { ...state.unitAllocations, [String(action.paymentId)]: leg } } : {},
9986
+ ...clear ? { pickedUnits: {} } : {}
9987
+ };
9988
+ return { ...state, entryMinor: 0, entryDirty: false, entryMode: "money", splitView: false, ...units };
9989
+ }
9990
+ case "back":
9991
+ return {
9992
+ ...state,
9993
+ view: "select",
9994
+ methodId: null,
9995
+ readerId: null,
9996
+ transport: null,
9997
+ entryMinor: 0,
9998
+ entryDirty: false,
9999
+ entryMode: "money"
10000
+ };
10001
+ case "tender-recorded": {
10002
+ const linesPaidBy = { ...state.linesPaidBy };
10003
+ if (state.plan?.kind === "items" && action.rowsSinceFrom.reduce((sum4, row) => sum4 + row.amountMinor, 0) >= state.plan.firstMinor) {
10004
+ for (const id2 of state.plan.lineIds) {
10005
+ linesPaidBy[id2] ??= [...new Set(action.rowsSinceFrom.map((row) => row.title))];
10006
+ }
10007
+ } else if (state.plan?.kind === "items") {
10008
+ for (const id2 of state.plan.lineIds) {
10009
+ delete linesPaidBy[id2];
10010
+ }
10011
+ }
10012
+ const rows = action.rowsSinceFrom.map((row) => ({
10013
+ minor: row.amountMinor,
10014
+ title: row.title
10015
+ }));
10016
+ const plan = activePlan(state.plan, rows.length, action.balanceMinor);
10017
+ const entryMinor = plan ? planLegs(plan, rows, action.balanceMinor).thisPaymentMinor : action.balanceMinor;
10018
+ return {
10019
+ ...state,
10020
+ view: state.methodId ? "amount" : "select",
10021
+ entryMinor,
10022
+ entryDirty: false,
10023
+ entryMode: "money",
10024
+ // Split closed means no picks: while units are picked (a leg recorded or settled elsewhere), Split stays open.
10025
+ splitView: Object.keys(state.pickedUnits).length > 0 ? state.splitView : false,
10026
+ pickedLineIds: [],
10027
+ linesPaidBy
10028
+ };
10029
+ }
10030
+ case "open-split":
10031
+ return {
10032
+ ...state,
10033
+ splitView: true,
10034
+ pickedLineIds: state.plan?.kind === "items" ? state.plan.lineIds.filter((id2) => !state.linesPaidBy[id2]) : state.pickedLineIds
10035
+ };
10036
+ // Split closed means no picks: every action that closes Split clears pickedUnits, except tender-recorded (above) and tender-started without a payment id (S5); allocations stay.
10037
+ case "close-split":
10038
+ return { ...state, splitView: false, pickedUnits: {} };
10039
+ case "set-split-tab":
10040
+ return { ...state, splitTab: action.tab };
10041
+ case "toggle-split-line":
10042
+ if (state.linesPaidBy[action.lineId]) return state;
10043
+ return {
10044
+ ...state,
10045
+ pickedLineIds: state.pickedLineIds.includes(action.lineId) ? state.pickedLineIds.filter((id2) => id2 !== action.lineId) : [...state.pickedLineIds, action.lineId]
10046
+ };
10047
+ case "set-split-units": {
10048
+ if (!Number.isInteger(action.units) || action.units < 0) return state;
10049
+ if (!Number.isInteger(action.unpaidUnits) || action.unpaidUnits < 0) return state;
10050
+ if (state.plan && action.units > 0) return state;
10051
+ const units = Math.min(action.units, action.unpaidUnits);
10052
+ const next = { ...state.pickedUnits, [String(action.lineId)]: units };
10053
+ return { ...state, pickedUnits: Object.fromEntries(Object.entries(next).filter(([, n]) => n > 0)) };
10054
+ }
10055
+ case "set-plan":
10056
+ return {
10057
+ ...state,
10058
+ plan: action.plan,
10059
+ splitView: false,
10060
+ pickedUnits: {},
10061
+ pickedLineIds: [],
10062
+ entryMinor: state.view === "amount" ? planLegs(action.plan, [], action.balanceMinor).thisPaymentMinor : state.entryMinor,
10063
+ entryDirty: state.view !== "amount" && state.entryDirty,
10064
+ entryMode: "money"
10065
+ };
10066
+ case "clear-plan":
10067
+ case "arm-custom":
10068
+ return {
10069
+ ...state,
10070
+ plan: null,
10071
+ splitView: false,
10072
+ pickedUnits: {},
10073
+ view: action.type === "arm-custom" ? "amount" : state.view,
10074
+ entryMinor: action.type === "clear-plan" ? action.balanceMinor : 0,
10075
+ entryDirty: false,
10076
+ entryMode: "money"
10077
+ };
10078
+ case "request-cancel":
10079
+ return { ...state, view: "cancel", splitView: false, pickedUnits: {} };
10080
+ case "reset":
10081
+ return initialTenderState;
10082
+ }
10083
+ }
10084
+ function appliedMinor(entryMinor, balanceMinor) {
10085
+ return Math.max(0, Math.min(entryMinor, balanceMinor));
10086
+ }
10087
+ function changeMinor(entryMinor, appliedAmountMinor, givesChange) {
10088
+ return givesChange ? Math.max(0, entryMinor - appliedAmountMinor) : 0;
10089
+ }
10090
+ function quickTenderedAmounts(balanceMinor, stepsMinor) {
10091
+ if (balanceMinor === 0) {
10092
+ return [];
10093
+ }
10094
+ const amounts = /* @__PURE__ */ new Set([balanceMinor]);
10095
+ for (const stepMinor of stepsMinor) {
10096
+ if (stepMinor <= 0) continue;
10097
+ const remainder = balanceMinor % stepMinor;
10098
+ amounts.add(remainder === 0 ? balanceMinor : balanceMinor + stepMinor - remainder);
10099
+ }
10100
+ return [...amounts].sort((left, right) => left - right);
10101
+ }
10102
+ function evenSplitShareMinor(balanceMinor, ways) {
10103
+ if (ways < 2) {
10104
+ return balanceMinor;
10105
+ }
10106
+ const wholeShare = Math.floor(balanceMinor / ways);
10107
+ const remainder = balanceMinor % ways;
10108
+ return wholeShare + (remainder * 2 >= ways ? 1 : 0);
10109
+ }
10110
+ function percentOfMinor(balanceMinor, percent) {
10111
+ return Math.max(0, Math.min(balanceMinor, Math.round(balanceMinor * percent / 100)));
10112
+ }
10113
+ function activePlan(plan, taken, balanceMinor) {
10114
+ if (!plan || balanceMinor === 0) return null;
10115
+ if (plan.kind !== "items" && taken >= (plan.kind === "even" ? plan.ways : 1 + (plan.thenWays ?? 1)))
10116
+ return null;
10117
+ return plan;
10118
+ }
10119
+ function planLegs(plan, rowsSinceFrom, balanceMinor) {
10120
+ const taken = rowsSinceFrom.length;
10121
+ const legs = rowsSinceFrom.map((row) => ({ ...row, state: "done" }));
10122
+ const groupPaid = rowsSinceFrom.reduce((sum4, row) => sum4 + row.minor, 0);
10123
+ const groupLeft = plan.kind === "items" ? Math.min(balanceMinor, Math.max(0, plan.firstMinor - groupPaid)) : balanceMinor;
10124
+ const rest = plan.kind === "items" && groupLeft === 0;
10125
+ const ways = plan.kind === "fixed" ? 1 + (plan.thenWays ?? 1) : Math.max(plan.ways, taken + 1);
10126
+ const firstFixed = plan.kind === "fixed" && taken === 0;
10127
+ const left = firstFixed || rest ? 1 : Math.max(1, ways - taken);
10128
+ const amount = rest ? balanceMinor : groupLeft;
10129
+ const each = plan.kind === "fixed" && taken === 0 ? Math.min(plan.firstMinor, balanceMinor) : evenSplitShareMinor(amount, left);
10130
+ let remaining = amount;
10131
+ for (let i = 0; i < left; i++) {
10132
+ const minor2 = Math.min(remaining, i === left - 1 && !firstFixed ? remaining : each);
10133
+ legs.push({ minor: minor2, state: i === 0 ? "now" : "todo" });
10134
+ remaining -= minor2;
10135
+ }
10136
+ if (firstFixed && remaining > 0) {
10137
+ const thenWays = plan.thenWays ?? 1;
10138
+ const share = evenSplitShareMinor(remaining, thenWays);
10139
+ for (let i = 0; i < thenWays; i++) {
10140
+ const minor2 = Math.min(remaining, i === thenWays - 1 ? remaining : share);
10141
+ legs.push({ minor: minor2, state: "todo" });
10142
+ remaining -= minor2;
10143
+ }
10144
+ }
10145
+ if (plan.kind === "items" && !rest && balanceMinor > groupLeft)
10146
+ legs.push({ minor: balanceMinor - groupLeft, state: "rest" });
10147
+ const title = plan.kind === "fixed" && taken === 0 ? plan.title : null;
10148
+ return { legs, thisPaymentMinor: each, label: { n: taken + 1, ways, rest, title } };
10149
+ }
10150
+
10151
+ // src/tender/cash-rounding.ts
10152
+ function roundToIncrement(minor2, incrementMinor, mode) {
10153
+ if (!Number.isInteger(incrementMinor) || incrementMinor <= 1) return minor2;
10154
+ const remainder = minor2 % incrementMinor;
10155
+ if (remainder === 0) return minor2;
10156
+ const down = minor2 - remainder;
10157
+ if (mode === "down") return down;
10158
+ if (mode === "up") return down + incrementMinor;
10159
+ return remainder * 2 >= incrementMinor ? down + incrementMinor : down;
10160
+ }
10161
+ function nearestPayableCash(amountMinor, incrementMinor) {
10162
+ if (!Number.isInteger(incrementMinor) || incrementMinor <= 1 || amountMinor % incrementMinor === 0) return null;
10163
+ const belowMinor = Math.floor(amountMinor / incrementMinor) * incrementMinor;
10164
+ return { belowMinor, aboveMinor: belowMinor + incrementMinor };
10165
+ }
10166
+ function roundedRemainder(balanceMinor, entriesMinor, rounding) {
10167
+ if (balanceMinor <= 0) return balanceMinor;
10168
+ const unrounded = balanceMinor - entriesMinor;
10169
+ return unrounded <= 0 ? 0 : roundToIncrement(unrounded, rounding.incrementMinor, rounding.mode);
10170
+ }
10171
+ function roundedPickTarget(targetMinor, rounding) {
10172
+ return rounding ? roundToIncrement(targetMinor, rounding.incrementMinor, rounding.mode) : targetMinor;
10173
+ }
10174
+ function remainderEntriesMinor(order) {
10175
+ return (order.cashRoundings ?? []).reduce((sum4, entry) => {
10176
+ const units = order.payments.find((leg) => leg.id === entry.paymentId)?.units;
10177
+ return !units || Object.keys(units).length === 0 ? sum4 + entry.minor : sum4;
10178
+ }, 0);
10179
+ }
10180
+ function cashVoidRefusal(order, paymentId) {
10181
+ const carries = (id2) => (order.cashRoundings ?? []).some((entry) => entry.paymentId === id2 && entry.minor !== 0);
10182
+ const at2 = order.payments.findIndex((leg) => leg.id === paymentId);
10183
+ if (at2 < 0 || !carries(paymentId)) return void 0;
10184
+ return order.payments.slice(at2 + 1).some((leg) => leg.method === "cash" && countsTowardPaid(leg) && carries(leg.id)) ? "later_cash_rounding" : void 0;
10185
+ }
10186
+ function roundedDue(balanceMinor, method, entriesMinor = 0) {
10187
+ const rounding = method?.capture.mode === "manual" && wireMethodOf(method) === "cash" ? method.defaults.rounding : null;
10188
+ if (!rounding) return { dueMinor: balanceMinor, roundingMinor: 0 };
10189
+ const dueMinor = roundedRemainder(balanceMinor, entriesMinor, rounding);
10190
+ return { dueMinor, roundingMinor: dueMinor - balanceMinor };
10191
+ }
10192
+ function settlesAtRoundedDue(facts) {
10193
+ const { amountMinor, tenderedMinor, balanceMinor, dueMinor } = facts;
10194
+ return amountMinor >= Math.min(balanceMinor, dueMinor) && tenderedMinor >= dueMinor;
10195
+ }
10196
+ function tenderRounding(state, balanceMinor, method, entriesMinor = 0) {
10197
+ const roundedDueMinor = roundedDue(balanceMinor, method, entriesMinor).dueMinor;
10198
+ const entryMinor = !state.entryDirty && state.entryMinor === balanceMinor ? roundedDueMinor : state.entryMinor;
10199
+ const legMinor = appliedMinor(entryMinor, balanceMinor);
10200
+ const roundingMinor = settlesAtRoundedDue({
10201
+ amountMinor: legMinor,
10202
+ tenderedMinor: entryMinor,
10203
+ balanceMinor,
10204
+ dueMinor: roundedDueMinor
10205
+ }) ? roundedDueMinor - balanceMinor : 0;
10206
+ return { roundedDueMinor, roundingMinor, entryMinor, appliedMinor: roundingMinor !== 0 ? roundedDueMinor : legMinor };
10207
+ }
10208
+
10209
+ // src/register/register-count.denominations.ts
10210
+ var coinsMinor = [200, 100, 50, 20, 10, 5, 2, 1];
10211
+ var denominations = {
10212
+ GBP: [5e3, 2e3, 1e3, 500, ...coinsMinor],
10213
+ EUR: [5e4, 2e4, 1e4, 5e3, 2e3, 1e3, 500, ...coinsMinor],
10214
+ USD: [1e4, 5e3, 2e3, 1e3, 500, 100, 25, 10, 5, 1],
10215
+ default: [1e4, 5e3, 2e3, 1e3, 500, 200, 100, 50, 25, 10, 5, 1]
10216
+ };
10217
+
10218
+ // src/register/schemas.ts
10219
+ import { addRxPlugin as addRxPlugin2 } from "rxdb";
10220
+ import { RxDBLocalDocumentsPlugin } from "rxdb/plugins/local-documents";
10221
+ import { RxDBMigrationSchemaPlugin as RxDBMigrationSchemaPlugin2 } from "rxdb/plugins/migration-schema";
10222
+ var id = { type: "string", maxLength: 36 };
10223
+ var text = { type: "string" };
10224
+ var nullableText = { type: ["string", "null"] };
10225
+ var minor = { type: "integer" };
10226
+ var nullableMinor = { type: ["integer", "null"] };
10227
+ var tenders = { type: "object", additionalProperties: minor };
10228
+ var registerSessionSchema = {
10229
+ title: "Register sessions",
10230
+ version: 2,
10231
+ primaryKey: "id",
9485
10232
  type: "object",
9486
10233
  additionalProperties: false,
9487
10234
  properties: {
@@ -9681,6 +10428,67 @@ function deriveSettled(recorded, corrections) {
9681
10428
  return { settled, touched };
9682
10429
  }
9683
10430
 
10431
+ // src/register/closure-figures.ts
10432
+ var integer = (value) => typeof value === "number" && Number.isInteger(value) ? value : void 0;
10433
+ var text2 = (value) => typeof value === "string" ? value : void 0;
10434
+ var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
10435
+ var list = (value) => Array.isArray(value) ? value : [];
10436
+ var entries = (value) => Object.entries(record(value) ?? {}).flatMap(([key, entry]) => {
10437
+ const values = record(entry);
10438
+ return values ? [[key, values]] : [];
10439
+ });
10440
+ var known = (values) => Object.fromEntries(Object.entries(values).filter(([, value]) => value !== void 0));
10441
+ function closureFigures(closure) {
10442
+ const b = closure.breakdowns;
10443
+ const float = record(b.opening_float) ?? {};
10444
+ const paymentMethods = entries(b.payment_methods).flatMap(([id2, entry]) => {
10445
+ const salesMinor = integer(entry.sales_minor);
10446
+ const refundsMinor = integer(entry.refunds_minor);
10447
+ if (salesMinor === void 0 || refundsMinor === void 0) return [];
10448
+ return [{ id: id2, ...known({ name: text2(entry.name) }), salesMinor, refundsMinor }];
10449
+ });
10450
+ const taxRates = entries(b.tax_rates).flatMap(([key, entry]) => {
10451
+ const [netMinor, taxMinor, grossMinor] = [integer(entry.net_minor), integer(entry.tax_minor), integer(entry.gross_minor)];
10452
+ if (netMinor === void 0 || taxMinor === void 0 || grossMinor === void 0) return [];
10453
+ return [{ key, ...known({ name: text2(entry.name) }), netMinor, taxMinor, grossMinor }];
10454
+ });
10455
+ const movements = list(b.movements).flatMap((value) => {
10456
+ const m = record(value);
10457
+ const id2 = text2(m?.id);
10458
+ const amountMinor = integer(m?.amountMinor);
10459
+ if (!m || id2 === void 0 || amountMinor === void 0) return [];
10460
+ return [{
10461
+ id: id2,
10462
+ type: text2(m.type) ?? "",
10463
+ amountMinor,
10464
+ reason: text2(m.reason) ?? "",
10465
+ voided: !!m.voided_by,
10466
+ ...known({ createdAtGmt: text2(m.created_at_gmt), createdBy: text2(m.created_by) })
10467
+ }];
10468
+ });
10469
+ const cashiers = list(b.cashiers).flatMap((value) => {
10470
+ if (typeof value === "string") return [{ id: value, name: value }];
10471
+ const c = record(value) ?? {};
10472
+ const id2 = text2(c.id) ?? (Number.isFinite(c.id) ? String(c.id) : void 0);
10473
+ return id2 === void 0 ? [] : [{ id: id2, name: text2(c.name) || id2 }];
10474
+ });
10475
+ return {
10476
+ openingFloat: known({
10477
+ expectedMinor: integer(float.expected_minor),
10478
+ countedMinor: integer(float.counted_minor),
10479
+ varianceMinor: integer(float.variance_minor)
10480
+ }),
10481
+ paymentMethods,
10482
+ taxRates,
10483
+ movements,
10484
+ ...known({ transactionCount: integer(b.transaction_count), refundCount: integer(b.refund_count) }),
10485
+ cashiers,
10486
+ taxRoundingMixed: b.tax_rounding_mixed === true,
10487
+ taxIncludesStorePaid: b.tax_includes_store_paid === true,
10488
+ ...known({ varianceNote: text2(b.variance_note) })
10489
+ };
10490
+ }
10491
+
9684
10492
  // src/register/float-suggestion.ts
9685
10493
  function suggestFloat({ register, lastCountedCashMinor }) {
9686
10494
  if (register?.defaultFloatMinor != null) return { amountMinor: register.defaultFloatMinor, source: "default" };
@@ -9805,7 +10613,9 @@ var labelKeys = {
9805
10613
  paid_out: "register.paid_out",
9806
10614
  no_sale: "register.no_sale",
9807
10615
  void: "register.void",
9808
- copy: "reports.document.copy"
10616
+ copy: "reports.document.copy",
10617
+ // TallyUI's own key (ADR-094); the WCPOS server template has none.
10618
+ cash_rounding: "reports.document.cash_rounding"
9809
10619
  };
9810
10620
  var ENGLISH_CLOSURE_LABELS = {
9811
10621
  x_report: "X report",
@@ -9848,7 +10658,8 @@ var ENGLISH_CLOSURE_LABELS = {
9848
10658
  paid_out: "Paid out",
9849
10659
  no_sale: "No sale",
9850
10660
  void: "Void",
9851
- copy: "Copy"
10661
+ copy: "Copy",
10662
+ cash_rounding: "Rounding"
9852
10663
  };
9853
10664
 
9854
10665
  // src/register/closure-rows.ts
@@ -9905,20 +10716,24 @@ function decimalizeBreakdowns(breakdowns, exponent) {
9905
10716
  ])
9906
10717
  );
9907
10718
  };
9908
- const openingFloat = breakdowns.opening_float;
10719
+ const float = closureFigures({ breakdowns }).openingFloat;
10720
+ const decOrNull = (m) => m === void 0 ? null : minorToDecimal(m, exponent);
9909
10721
  return {
9910
10722
  ...breakdowns,
9911
10723
  ...breakdowns.payment_methods ? { payment_methods: group("payment_methods", [["sales_minor", "sales"], ["refunds_minor", "refunds"]]) } : {},
9912
10724
  ...breakdowns.tax_rates ? { tax_rates: group("tax_rates", [["net_minor", "net"], ["tax_minor", "tax"], ["gross_minor", "gross"]]) } : {},
9913
- ...openingFloat ? {
10725
+ ...breakdowns.opening_float ? {
9914
10726
  opening_float: {
9915
- ...openingFloat,
9916
- expected: dec(openingFloat.expected_minor),
9917
- counted: dec(openingFloat.counted_minor),
9918
- variance: dec(openingFloat.variance_minor)
10727
+ expected_minor: float.expectedMinor ?? null,
10728
+ counted_minor: float.countedMinor ?? null,
10729
+ variance_minor: float.varianceMinor ?? null,
10730
+ expected: decOrNull(float.expectedMinor),
10731
+ counted: decOrNull(float.countedMinor),
10732
+ variance: decOrNull(float.varianceMinor)
9919
10733
  }
9920
10734
  } : {},
9921
- ...breakdowns.movements ? { movements: breakdowns.movements.map((m) => ({ ...m, amount: dec(m.amountMinor) })) } : {}
10735
+ ...breakdowns.movements ? { movements: breakdowns.movements.map((m) => ({ ...m, amount: dec(m.amountMinor) })) } : {},
10736
+ ...breakdowns.cash_rounding_minor !== void 0 ? { cash_rounding: dec(breakdowns.cash_rounding_minor) } : {}
9922
10737
  };
9923
10738
  }
9924
10739
  function formatClosureDate(value, context) {
@@ -9995,9 +10810,11 @@ function envelope(row, context, xreport = false) {
9995
10810
  ...Object.fromEntries(
9996
10811
  ["payment_methods", "tax_rates", "movements"].map((key) => [`has_${key}`, Object.keys(breakdowns[key] ?? {}).length > 0])
9997
10812
  ),
10813
+ has_cash_rounding: breakdowns.cash_rounding !== void 0,
9998
10814
  ...breakdowns.tax_rounding_mixed === true ? { tax_rounding_note: TAX_ROUNDING_MIXED_NOTE } : {},
9999
10815
  ...breakdowns.tax_includes_store_paid === true ? { tax_store_paid_note: TAX_STORE_PAID_NOTE } : {},
10000
10816
  ...money(row, ["period_sales_total", "period_refunds_total", "perpetual_sales_total", "perpetual_refunds_total", "unsynced_total"]),
10817
+ ...breakdowns.cash_rounding !== void 0 ? { cash_rounding: money({ name: context.i18n.cash_rounding, amount: breakdowns.cash_rounding }, ["amount"]) } : {},
10001
10818
  opened_at_gmt: row.opened_at,
10002
10819
  opened_by: breakdowns.opened_by ?? null,
10003
10820
  closed_by: row.closed_by ?? null,
@@ -10018,7 +10835,7 @@ function envelope(row, context, xreport = false) {
10018
10835
  type_label: context.i18n[String(m.type)] ?? m.type,
10019
10836
  voided: !!m.voided_by
10020
10837
  })),
10021
- cashiers: (breakdowns.cashiers ?? []).map((c) => typeof c === "string" ? { id: c, name: c } : c)
10838
+ cashiers: closureFigures({ breakdowns }).cashiers
10022
10839
  }
10023
10840
  },
10024
10841
  store: context.store,
@@ -10113,7 +10930,7 @@ function buildXReportDocument(session, context) {
10113
10930
  }
10114
10931
 
10115
10932
  // src/register/use-register-session.ts
10116
- import { useEffect as useEffect9, useMemo as useMemo6, useRef as useRef7, useState as useState8, useSyncExternalStore as useSyncExternalStore4 } from "react";
10933
+ import { useEffect as useEffect11, useMemo as useMemo8, useRef as useRef7, useState as useState10, useSyncExternalStore as useSyncExternalStore4 } from "react";
10117
10934
  import { combineLatest, map as map7, of, switchMap } from "rxjs";
10118
10935
 
10119
10936
  // src/outbox/register-outbox.ts
@@ -10240,14 +11057,14 @@ function reconcileRegisterCommands({ commands, sessions, movements, closures, ho
10240
11057
  const rows = await readFresh(sessions, { selector: { register_id: registerId } });
10241
11058
  const complete = new Set((await commands.storageInstance.findDocumentsById(rows.flatMap((session) => [`session.open:${session.id}`, ...session.status === "closed" && session.closure_id ? [`closure.submit:${session.closure_id}`] : []]), false)).map(({ key }) => key));
10242
11059
  const facts = await Promise.all(rows.filter((session) => session.status !== "abandoned" && (session.status !== "closed" || (session.status_at == null || session.status_at >= since || complete.has(`session.open:${session.id}`)) && !complete.has(`closure.submit:${session.closure_id}`))).map(async (session) => {
10243
- const [entries, closureRows] = await Promise.all([
11060
+ const [entries2, closureRows] = await Promise.all([
10244
11061
  readFresh(movements, { selector: { session_id: session.id } }),
10245
11062
  session.closure_id ? closures.storageInstance.findDocumentsById([session.closure_id], false) : Promise.resolve([])
10246
11063
  ]);
10247
11064
  const events = (observed ?? []).filter((row) => row.id === session.id && !transitioned.has(session.id) && row.status !== session.status && row.status !== "closed").flatMap((row) => row.status_at == null || !sentStatus(row) ? [] : [sessionTransitionCommand({ ...row, status_at: row.status_at })]);
10248
11065
  events.push(
10249
- ...entries.filter((entry) => entry.type !== "void").map(movementCommand),
10250
- ...entries.filter((entry) => entry.type === "void").map(movementCommand)
11066
+ ...entries2.filter((entry) => entry.type !== "void").map(movementCommand),
11067
+ ...entries2.filter((entry) => entry.type === "void").map(movementCommand)
10251
11068
  );
10252
11069
  if (session.status_at != null && sentStatus(session)) events.push(sessionTransitionCommand({ ...session, status_at: session.status_at }));
10253
11070
  return { session, number: closureRows[0]?.number, built: [
@@ -10324,6 +11141,8 @@ var syncRecordOf = (orderId, outcome) => ({ collection: "pos_orders", recordId:
10324
11141
  var ISOLATE_AFTER_ATTEMPTS = 5;
10325
11142
  var STUCK_AFTER_MS = 15 * 6e4;
10326
11143
  var validMax = (max) => typeof max === "number" && Number.isSafeInteger(max) && max > 0 ? max : void 0;
11144
+ var stateRefreshers = /* @__PURE__ */ new WeakMap();
11145
+ var refreshOutboxState = (outbox) => stateRefreshers.get(outbox)?.() ?? Promise.resolve();
10327
11146
  function createOrderOutbox(options) {
10328
11147
  const { collection, transport, deviceId } = options;
10329
11148
  const toEnvelope = (order, attempt2, maxVersion) => order.storeOrderId !== void 0 ? toOrderUpdateEnvelope(order, deviceId, attempt2, { maxVersion }) : toOrderCreateEnvelope(order, deviceId, attempt2, { maxVersion });
@@ -10426,16 +11245,23 @@ function createOrderOutbox(options) {
10426
11245
  const delay = retryDelay(entry.backoff, retryAfterMs, maxBackoff, random);
10427
11246
  isolated.set(id2, { reason, backoff: Math.min(entry.backoff * 2, maxBackoff), nextAt: now() + delay });
10428
11247
  }
10429
- function serverFailed(orders, alone, reason, retryAfterMs) {
11248
+ function serverFailed(orders, alone, reason, retryAfterMs, needsAdminId) {
10430
11249
  const at2 = now();
10431
- for (const { commandId } of orders) clocks.set(commandId, { ...clocks.get(commandId) ?? { since: at2, firstFailedAt: at2 }, seq: ++failureSeq, reason });
11250
+ for (const { commandId } of orders) clocks.set(commandId, {
11251
+ ...clocks.get(commandId) ?? { since: at2, firstFailedAt: at2 },
11252
+ seq: ++failureSeq,
11253
+ reason: needsAdminId === void 0 || commandId === needsAdminId ? reason : "status_409"
11254
+ });
10432
11255
  const id2 = orders[0].commandId;
10433
11256
  if (alone === "isolated") {
10434
11257
  isolate(id2, reason, retryAfterMs);
10435
11258
  if (runProgressed && retryAfterMs === void 0 && reason !== "status_429") return void 0;
10436
11259
  return Math.max(retryAfterMs ?? 0, isolated.get(id2).nextAt - now());
10437
11260
  }
10438
- if (alone === "probe") walk?.failed.set(id2, { orderId: orders[0].id, reason });
11261
+ if (alone === "probe") walk?.failed.set(id2, {
11262
+ orderId: orders[0].id,
11263
+ reason: needsAdminId === void 0 || id2 === needsAdminId ? reason : "status_409"
11264
+ });
10439
11265
  else {
10440
11266
  head = { id: id2, count: head?.id === id2 ? head.count + 1 : 1 };
10441
11267
  if (head.count >= isolateAfter) walk ??= { failed: /* @__PURE__ */ new Map() };
@@ -10589,7 +11415,7 @@ function createOrderOutbox(options) {
10589
11415
  if (outcome.reason === "network") {
10590
11416
  for (const clock of clocks.values()) clock.pausedAt ??= now();
10591
11417
  walk = void 0;
10592
- } else if ((floor = serverFailed(orders, alone, outcome.reason, outcome.retryAfterMs)) === void 0) continue;
11418
+ } else if ((floor = serverFailed(orders, alone, outcome.reason, outcome.retryAfterMs, outcome.needsAdmin?.id)) === void 0) continue;
10593
11419
  return scheduleRetry(outcome.reason, floor);
10594
11420
  }
10595
11421
  if (outcome.kind === "unauthorized") {
@@ -10766,7 +11592,7 @@ function createOrderOutbox(options) {
10766
11592
  }
10767
11593
  updateState().catch(() => {
10768
11594
  });
10769
- return {
11595
+ const outbox = {
10770
11596
  state$,
10771
11597
  flush,
10772
11598
  async requeue(orderIds) {
@@ -10848,6 +11674,8 @@ function createOrderOutbox(options) {
10848
11674
  state$.next({ ...state$.value, nextAttemptAt: void 0 });
10849
11675
  }
10850
11676
  };
11677
+ stateRefreshers.set(outbox, () => updateState());
11678
+ return outbox;
10851
11679
  }
10852
11680
 
10853
11681
  // src/outbox/safe-error.ts
@@ -10944,9 +11772,13 @@ function createRegisterOutbox(options) {
10944
11772
  orders: stuck.map(([commandId, { since, firstFailedAt, reason }]) => ({ commandId, since, firstFailedAt, reason }))
10945
11773
  };
10946
11774
  }
10947
- function serverFailed(commands, reason) {
11775
+ function serverFailed(commands, reason, needsAdminId) {
10948
11776
  const at2 = now();
10949
- for (const { commandId } of commands) clocks.set(commandId, { ...clocks.get(commandId) ?? { since: at2, firstFailedAt: at2 }, seq: ++failureSeq, reason });
11777
+ for (const { commandId } of commands) clocks.set(commandId, {
11778
+ ...clocks.get(commandId) ?? { since: at2, firstFailedAt: at2 },
11779
+ seq: ++failureSeq,
11780
+ reason: needsAdminId === void 0 || commandId === needsAdminId ? reason : "status_409"
11781
+ });
10950
11782
  }
10951
11783
  function isNonBlocking(command, abandoned) {
10952
11784
  return NON_BLOCKING_REJECTIONS.has(command.error?.code ?? "") || CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? "") || command.error?.code === "register_session_already_open" && typeof command.payload.sessionId === "string" && abandoned.has(command.payload.sessionId);
@@ -11040,7 +11872,7 @@ function createRegisterOutbox(options) {
11040
11872
  clock.pausedAt = void 0;
11041
11873
  }
11042
11874
  if (outcome.kind === "retry") {
11043
- if (outcome.reason !== "network") serverFailed(commands, outcome.reason);
11875
+ if (outcome.reason !== "network") serverFailed(commands, outcome.reason, outcome.needsAdmin?.id);
11044
11876
  return scheduleRetry(outcome.reason, outcome.retryAfterMs);
11045
11877
  }
11046
11878
  if (outcome.kind === "unauthorized") {
@@ -11191,6 +12023,20 @@ function createRegisterOutbox(options) {
11191
12023
  };
11192
12024
  }
11193
12025
 
12026
+ // src/register/closing.ts
12027
+ var closingByRegister = /* @__PURE__ */ new Map();
12028
+ var closingListeners = /* @__PURE__ */ new Set();
12029
+ var notifyClosing = () => closingListeners.forEach((listener) => listener());
12030
+ var subscribeClosing = (listener) => {
12031
+ closingListeners.add(listener);
12032
+ return () => {
12033
+ closingListeners.delete(listener);
12034
+ };
12035
+ };
12036
+ function isRegisterClosing(registerId) {
12037
+ return closingByRegister.has(registerId);
12038
+ }
12039
+
11194
12040
  // src/register/register-adoption.ts
11195
12041
  var chains2 = /* @__PURE__ */ new WeakMap();
11196
12042
  var figure = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
@@ -11248,6 +12094,29 @@ async function renumberRefused(commands, closures, host, storeKey, registerId) {
11248
12094
  });
11249
12095
  }
11250
12096
  }
12097
+ async function settleRefunds(answers, commands, closures, host, storeKey, registerId) {
12098
+ const [submits, local] = await Promise.all([
12099
+ readFresh(commands, { selector: { registerId, type: "register.closure.submit" } }),
12100
+ readFresh(closures, { selector: { register_id: registerId } })
12101
+ ]);
12102
+ const own2 = new Set(local.filter(({ store_key }) => (store_key ?? storeKey) === storeKey).map(({ id: id2 }) => id2));
12103
+ const store = answers.flatMap(({ type, syncStatus, result, payload }) => {
12104
+ const [number, refunds] = [figure(result?.counters?.lastClosureNumber), figure(result?.counters?.perpetualRefundsTotalMinor)];
12105
+ return syncStatus === "applied" && number !== void 0 && refunds !== void 0 ? [{
12106
+ number,
12107
+ refunds,
12108
+ anchor: type === "register.closure.submit" && result?.closure?.number === number && own2.has(payload.closureId)
12109
+ }] : [];
12110
+ });
12111
+ const n = Math.max(-1, ...store.filter(({ anchor }) => anchor).map(({ number }) => number));
12112
+ if (n < 0 || store.some(({ number }) => number > n)) return;
12113
+ const blocks = (code = "") => code === "register_closure_number_invalid" || CLOSURE_HOLDING_REJECTIONS.has(code) || isRegisterRequeueable(code);
12114
+ if (local.some(({ number, store_key }) => (store_key ?? storeKey) === storeKey && number > n) || submits.some(({ syncStatus, error }) => syncStatus === "pending" || syncStatus === "rejected" && blocks(error?.code))) return;
12115
+ await settleStoreRefunds(host, storeKey, registerId, {
12116
+ lastClosureNumber: n,
12117
+ perpetualRefundsTotalMinor: Math.max(...store.filter(({ number }) => number === n).map(({ refunds }) => refunds))
12118
+ });
12119
+ }
11251
12120
  async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey, closures }) {
11252
12121
  const run = (chains2.get(commands) ?? Promise.resolve()).then(async () => {
11253
12122
  const [answers, transitions, rows] = await Promise.all([
@@ -11282,7 +12151,14 @@ async function adoptRegisterResults({ commands, sessions, registerId, host, stor
11282
12151
  if (row) await row.incrementalModify(modify);
11283
12152
  }
11284
12153
  const counters = answers.filter((answer) => answer.syncStatus === "applied" && answer.result?.counters).map((answer) => answer.result?.counters);
11285
- if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, counters);
12154
+ const top = Math.max(-1, ...counters.map((entry) => figure(entry?.lastClosureNumber) ?? -1));
12155
+ const raising = counters.map((entry) => {
12156
+ if (!entry || figure(entry.lastClosureNumber) === top) return entry;
12157
+ const { perpetualRefundsTotalMinor: _older, ...rest } = entry;
12158
+ return rest;
12159
+ });
12160
+ if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, raising);
12161
+ if (host && storeKey && closures) await settleRefunds(answers, commands, closures, host, storeKey, registerId);
11286
12162
  if (host && storeKey && closures) await renumberRefused(commands, closures, host, storeKey, registerId);
11287
12163
  }).catch((error) => {
11288
12164
  registerCommandsLogger.error("Register result adoption failed", { context: { registerId, error: String(error) } });
@@ -11384,6 +12260,12 @@ var RegisterTenderInProgressError = class extends Error {
11384
12260
  this.name = "RegisterTenderInProgressError";
11385
12261
  }
11386
12262
  };
12263
+ var RegisterSaleSavingError = class extends Error {
12264
+ constructor() {
12265
+ super("A sale is still being saved. Wait for it to finish, or retry it if it failed, then close the register.");
12266
+ this.name = "RegisterSaleSavingError";
12267
+ }
12268
+ };
11387
12269
  var RegisterSessionAlreadyOpenError = class extends Error {
11388
12270
  constructor() {
11389
12271
  super("This register already has an open session.");
@@ -11403,15 +12285,6 @@ var RegisterApprovalRequiredError = class extends Error {
11403
12285
  }
11404
12286
  };
11405
12287
  var openingByRegister = /* @__PURE__ */ new Map();
11406
- var closingByRegister = /* @__PURE__ */ new Map();
11407
- var closingListeners = /* @__PURE__ */ new Set();
11408
- var notifyClosing = () => closingListeners.forEach((listener) => listener());
11409
- var subscribeClosing = (listener) => {
11410
- closingListeners.add(listener);
11411
- return () => {
11412
- closingListeners.delete(listener);
11413
- };
11414
- };
11415
12288
  var closedFacts = /* @__PURE__ */ new Set();
11416
12289
  var isTenderMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((figure2) => typeof figure2 === "number");
11417
12290
  function approvalNeededOf(commandRows, sessions) {
@@ -11437,17 +12310,17 @@ function currentSession(rows, closureRows, reservation) {
11437
12310
  if (rows.some((row) => !isKnownSessionStatus(row.status))) return null;
11438
12311
  return (reservation && !reservation.applied ? rows.find((row) => row.id === reservation.row.session_id) : void 0) ?? rows.find((row) => row.status === "open" || row.status === "counting") ?? rows.find((row) => row.status === "conflict") ?? rows.find((row) => unwritten(row, closureRows)) ?? null;
11439
12312
  }
11440
- function ledgerRows(orders, replaced = replacedOrderIds(orders)) {
11441
- return paymentLedgerRows(orders.filter((order) => !replaced.has(order.id)));
12313
+ function ledgerRows(orders, extra, replaced = replacedOrderIds(orders)) {
12314
+ return [...paymentLedgerRows(orders.filter((order) => !replaced.has(order.id))), ...extra];
11442
12315
  }
11443
12316
  var closedCount = (counted2) => ({ ...counted2, cash: counted2.cash ?? 0 });
11444
12317
  var sameVariance = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.entries(b).every(([method, value]) => a[method] === value);
11445
12318
  function useRegisterSession(options) {
11446
12319
  const { sessions, movements, closures, orders, register, storeKey, registerId, enabled, actor, timezone, tenderInProgress, expectedCloseTime, labels } = options;
11447
- const { commands, refunds } = options;
12320
+ const { commands, refunds, drafts } = options;
11448
12321
  const varianceThreshold = options.capabilities?.registerApproval?.thresholdMinor ?? options.varianceThreshold;
11449
12322
  const commandEnabled = (options.capabilities?.register ?? 0) >= 1;
11450
- const commandTarget = useMemo6(
12323
+ const commandTarget = useMemo8(
11451
12324
  () => enabled && commandEnabled && commands && sessions && movements && closures && register && registerId ? { commands, sessions, movements, closures, host: register, storeKey, registerId, registerContract: options.capabilities?.register, deviceName: options.deviceName } : null,
11452
12325
  [enabled, commandEnabled, commands, sessions, movements, closures, register, storeKey, registerId, options.capabilities?.register, options.deviceName]
11453
12326
  );
@@ -11463,15 +12336,15 @@ function useRegisterSession(options) {
11463
12336
  }
11464
12337
  });
11465
12338
  };
11466
- useEffect9(reconcile, [commandTarget]);
11467
- useEffect9(() => {
12339
+ useEffect11(reconcile, [commandTarget]);
12340
+ useEffect11(() => {
11468
12341
  if (!commandTarget) return;
11469
12342
  const subscription = commandTarget.commands.find({ selector: { registerId: commandTarget.registerId } }).$.subscribe(() => {
11470
12343
  void adoptRegisterResults(commandTarget);
11471
12344
  });
11472
12345
  return () => subscription.unsubscribe();
11473
12346
  }, [commandTarget]);
11474
- const source = useMemo6(() => {
12347
+ const source = useMemo8(() => {
11475
12348
  if (!enabled || !sessions || !movements || !closures || !orders || !registerId || !register || refunds === null) return null;
11476
12349
  return combineLatest([
11477
12350
  watchFresh(sessions, { selector: { register_id: registerId } }),
@@ -11483,25 +12356,26 @@ function useRegisterSession(options) {
11483
12356
  } }) : of([])
11484
12357
  ]).pipe(switchMap(([rows, closureRows, reservation, commandRows2]) => {
11485
12358
  const current2 = currentSession(rows, closureRows, reservation);
11486
- if (!current2) return of({ rows, closureRows, reservation, entries: [], sales: [], refundRows: [], commandRows: commandRows2 });
12359
+ if (!current2) return of({ rows, closureRows, reservation, entries: [], sales: [], refundRows: [], parked: [], commandRows: commandRows2 });
11487
12360
  return combineLatest([
11488
12361
  watchFresh(movements, { selector: { session_id: current2.id } }),
11489
12362
  watchFresh(orders, { selector: { sessionId: current2.id } }),
11490
- refunds ? watchFresh(refunds, { selector: { sessionId: current2.id } }) : of([])
11491
- ]).pipe(map7(([entries2, sales2, refundRows]) => ({ rows, closureRows, reservation, entries: entries2, sales: sales2, refundRows, commandRows: commandRows2 })));
12363
+ refunds ? watchFresh(refunds, { selector: { sessionId: current2.id } }) : of([]),
12364
+ drafts ? watchFresh(drafts, { selector: {} }) : of([])
12365
+ ]).pipe(map7(([entries3, sales2, refundRows, parked2]) => ({ rows, closureRows, reservation, entries: entries3, sales: sales2, refundRows, parked: parked2, commandRows: commandRows2 })));
11492
12366
  }));
11493
- }, [enabled, sessions, movements, closures, orders, register, storeKey, registerId, commandTarget, refunds]);
12367
+ }, [enabled, sessions, movements, closures, orders, register, storeKey, registerId, commandTarget, refunds, drafts]);
11494
12368
  const tender = useRef7(tenderInProgress);
11495
12369
  tender.current = tenderInProgress;
11496
12370
  const closing = useSyncExternalStore4(subscribeClosing, () => closingByRegister.has(registerId ?? ""));
11497
- const [observed, setObserved] = useState8(null);
11498
- useEffect9(() => {
12371
+ const [observed, setObserved] = useState10(null);
12372
+ useEffect11(() => {
11499
12373
  if (!source) return;
11500
12374
  const subscription = source.subscribe((snapshot) => setObserved({ source, snapshot }));
11501
12375
  return () => subscription.unsubscribe();
11502
12376
  }, [source]);
11503
- const [, setMinute] = useState8(0);
11504
- useEffect9(() => {
12377
+ const [, setMinute] = useState10(0);
12378
+ useEffect11(() => {
11505
12379
  if (!enabled || !expectedCloseTime) return;
11506
12380
  const timer = setInterval(() => setMinute((value) => value + 1), 6e4);
11507
12381
  return () => clearInterval(timer);
@@ -11533,7 +12407,7 @@ function useRegisterSession(options) {
11533
12407
  return state.running = run;
11534
12408
  };
11535
12409
  const seen = useRef7(null);
11536
- useEffect9(() => {
12410
+ useEffect11(() => {
11537
12411
  if (!data) return;
11538
12412
  const ids = data.closureRows.map((row) => row.id);
11539
12413
  if (seen.current?.source !== source) {
@@ -11549,10 +12423,13 @@ function useRegisterSession(options) {
11549
12423
  const open = session ? commandRows.find((row) => row.key === `session.open:${session.id}`) : void 0;
11550
12424
  const refusal = open?.error?.data;
11551
12425
  const conflict = session?.status !== "conflict" || !commandTarget ? void 0 : open?.syncStatus === "pending" && typeof open.payload.supersedes === "string" ? { sessionId: open.payload.supersedes, takingOver: true } : open?.syncStatus === "rejected" && refusal ? { sessionId: refusal.sessionId, openedAt: refusal.openedAt, openedBy: refusal.openedBy, deviceName: refusal.deviceName, takingOver: false } : void 0;
11552
- const entries = data?.entries ?? [];
12426
+ const entries2 = data?.entries ?? [];
11553
12427
  const sales = data?.sales ?? [];
11554
12428
  const replaced = replacedOrderIds(sales);
11555
- const terms = session ? deriveDrawerTerms({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries, ledgerRowsBySession: ledgerRows(sales, replaced), refunds: data?.refundRows ?? [] }) : null;
12429
+ const parked = data?.parked;
12430
+ const parkedRows = useMemo8(() => parkedLedgerRows(parked ?? []), [parked]);
12431
+ const sale = options.liveSale?.();
12432
+ const terms = session ? deriveDrawerTerms({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries2, ledgerRowsBySession: ledgerRows(sales, [...parkedRows, ...liveLedgerRows(sale?.saving ? [] : sale?.takenLegs ?? [])], replaced), refunds: data?.refundRows ?? [] }) : null;
11556
12433
  const expected = terms ? terms.expected : {};
11557
12434
  const now = /* @__PURE__ */ new Date();
11558
12435
  const [hour, minute] = String(expectedCloseTime ?? "").split(":").map(Number);
@@ -11575,23 +12452,36 @@ function useRegisterSession(options) {
11575
12452
  };
11576
12453
  const live = () => {
11577
12454
  if (!enabled || !sessions || !movements || !closures || !orders || !registerId || !register || refunds === null) throw new RegisterSessionRequiredError();
11578
- return { sessions, movements, closures, orders, registerId, register, refunds };
12455
+ return { sessions, movements, closures, orders, registerId, register, refunds, drafts, liveSale: options.liveSale };
11579
12456
  };
11580
12457
  const current = () => {
11581
12458
  if (!session) throw new RegisterSessionRequiredError();
11582
12459
  return session;
11583
12460
  };
12461
+ const parkedFresh = async () => {
12462
+ const { drafts: drafts2 } = live();
12463
+ return drafts2 ? readFresh(drafts2, { selector: {} }) : [];
12464
+ };
12465
+ const liveTaken = () => {
12466
+ const sale2 = live().liveSale?.();
12467
+ return sale2?.saving ? { liveLegs: [], liveRoundings: [] } : { liveLegs: sale2?.takenLegs ?? [], liveRoundings: sale2?.cashRoundings ?? [] };
12468
+ };
12469
+ const liveLegs = () => liveTaken().liveLegs;
11584
12470
  const freshExpected = async (row) => {
11585
12471
  const { movements: movements2, orders: orders2, refunds: refunds2 } = live();
11586
12472
  return deriveExpected({
11587
12473
  session: { id: row.id, countedFloatMinor: row.counted_float_minor },
11588
12474
  movements: await readFresh(movements2, { selector: { session_id: row.id } }),
11589
- ledgerRowsBySession: ledgerRows(await readFresh(orders2, { selector: { sessionId: row.id } })),
12475
+ ledgerRowsBySession: ledgerRows(
12476
+ await readFresh(orders2, { selector: { sessionId: row.id } }),
12477
+ [...parkedLedgerRows(await parkedFresh()), ...liveLedgerRows(liveLegs())]
12478
+ ),
11590
12479
  refunds: refunds2 ? await readFresh(refunds2, { selector: { sessionId: row.id } }) : void 0
11591
12480
  });
11592
12481
  };
11593
12482
  const refuseDuringTender = () => {
11594
12483
  if (tender.current) throw new RegisterTenderInProgressError();
12484
+ if (live().liveSale?.().saving) throw new RegisterSaleSavingError();
11595
12485
  };
11596
12486
  const nameOf2 = (id2) => !id2 ? "" : id2 === actor.id ? actor.name : labels?.resolveCashierName?.(id2) ?? "";
11597
12487
  return {
@@ -11600,7 +12490,7 @@ function useRegisterSession(options) {
11600
12490
  conflict,
11601
12491
  /** Any unknown session status in the current snapshot means the register needs upgrade. */
11602
12492
  needsUpgrade: data?.rows.some((row) => !isKnownSessionStatus(row.status)) ?? false,
11603
- movements: entries,
12493
+ movements: entries2,
11604
12494
  expected,
11605
12495
  /** `expected`'s drawer ledger, term by term with row counts (`deriveDrawerTerms`); `null` without a session. */
11606
12496
  terms,
@@ -11760,6 +12650,8 @@ function useRegisterSession(options) {
11760
12650
  softwareVersion: options.softwareVersion,
11761
12651
  movements: await readFresh(movements2, { selector: { session_id: closed.id } }),
11762
12652
  orders: await readFresh(orders2, { selector: { sessionId: closed.id } }),
12653
+ drafts: await parkedFresh(),
12654
+ ...liveTaken(),
11763
12655
  refunds: refunds2 ? await readFresh(refunds2, { selector: { sessionId: closed.id } }) : void 0,
11764
12656
  resolveCashierName: labels?.resolveCashierName,
11765
12657
  labels: {
@@ -11942,10 +12834,21 @@ var COUPONS_NEED_CONNECTION = "Coupons need a connection to the store";
11942
12834
  var saleLogger = createLogger("sale");
11943
12835
  var DISCOUNTS_UNSUPPORTED = "finalize: discounts are not supported by the server yet (order.create v2)";
11944
12836
  var SALE_SAVING = "This sale is being saved. Retry to finish it.";
12837
+ var REGISTER_CLOSING = "The register is closing. Wait for the close to finish, then try again.";
11945
12838
  var PAYMENT_IN_MOTION = "Finish or void the payment in progress before completing the sale";
11946
12839
  var SALE_PARTLY_PAID = "This sale is partly paid. Take the rest of the payment or void the paid legs first.";
12840
+ var SALE_CARD_IN_PROGRESS = "A card payment is still in progress. Finish or cancel it before starting a new sale.";
11947
12841
  var SALE_IN_TENDER = "Finish or cancel the payment before switching sales";
11948
12842
  var SALE_HAS_PAYMENT = "A payment was taken on this sale. Cancel the payment before changing the sale.";
12843
+ var PAYMENT_TAKEN = "This payment was taken. Void it instead of removing it.";
12844
+ var NOTHING_DUE = "Nothing is left to pay: the payments on this sale already cover the total.";
12845
+ var NOTHING_TO_ROUND_AGAINST = "This sale rounds to nothing in cash: take it by another method.";
12846
+ var CASH_NOT_PAYABLE = "Cash cannot pay that amount: take a whole number of the smallest cash step.";
12847
+ var CASH_WAITS_FOR_PAYMENT = "Cash cannot pay that amount while another payment is in progress: finish that payment first.";
12848
+ var CASH_PICK_ENTRIES_MAX = 15;
12849
+ var CASH_PICK_LIMIT = "Too many rounded cash payments on this sale: take the rest as one payment.";
12850
+ var CASH_SETTLE_LIMIT = "Too many rounded cash payments on this sale: take the rest by another method.";
12851
+ var VOID_LATER_CASH_FIRST = "Void the later cash payment first.";
11949
12852
  var SALE_FINISHED = "This sale is finished. Start a new sale to change it.";
11950
12853
  var COUPONS_REPRICING = "Coupon prices are being checked; try again in a moment";
11951
12854
  var COUPON_CARRIED = "The store refused this sale's coupon, so it is carried at the amount charged. Coupons can't be added or removed on this sale.";
@@ -11962,6 +12865,7 @@ var RESTORE_STALE = "This item can no longer be put back. Add it again.";
11962
12865
  var REFERENCE_DROPPED = "The terminal's payment reference couldn't be kept";
11963
12866
  var KEPT = /* @__PURE__ */ Symbol("kept coupon");
11964
12867
  var HUNG_SAVE_CHECK_MS = 5e3;
12868
+ var SAVE_TIMEOUT_MS = 6e4;
11965
12869
  function refusalOf(run) {
11966
12870
  try {
11967
12871
  return run();
@@ -11983,7 +12887,8 @@ function useSale(settings, opts) {
11983
12887
  }
11984
12888
  const defaultKey = opts.defaultCustomer ? JSON.stringify([opts.defaultCustomer.id, opts.defaultCustomer.name, opts.defaultCustomer.email]) : "";
11985
12889
  const defaultSeen = useRef8(defaultKey);
11986
- const [rendered, setBuilder] = useState9(() => {
12890
+ const resetRefused = useRef8(false);
12891
+ const [rendered, setBuilder] = useState11(() => {
11987
12892
  const customer = defaulted();
11988
12893
  taxNow.current = contextFor(customer);
11989
12894
  const first = createOrderBuilder({ currency: settings.currency, taxContext: taxNow.current.taxContext });
@@ -12000,18 +12905,18 @@ function useSale(settings, opts) {
12000
12905
  function codesFor() {
12001
12906
  return opts.capabilities?.coupons === true && (opts.capabilities?.orderCreate ?? 1) >= 6 && opts.discountCodes && opts.discountCodes.supports({ capabilities: opts.capabilities, rounding: taxContext.rounding }) ? opts.discountCodes : null;
12002
12907
  }
12003
- const [order, setOrder] = useState9(() => rendered.getSnapshot());
12004
- const [stage, setStage] = useState9({ kind: "cart" });
12005
- const [saleError, setError] = useState9(null);
12908
+ const [order, setOrder] = useState11(() => rendered.getSnapshot());
12909
+ const [stage, setStage] = useState11({ kind: "cart" });
12910
+ const [saleError, setError] = useState11(null);
12006
12911
  const configError = referenceError("cashierRef", opts.cashierRef) ?? referenceError("registerId", opts.registerId);
12007
12912
  const pending = useRef8(null);
12008
- const [saving, setSaving] = useState9(false);
12913
+ const [saving, setSaving] = useState11(false);
12009
12914
  const error = saving && saleError ? saleError : configError ?? saleError;
12010
12915
  const tenderSession = useRef8(null);
12011
12916
  const tenderGatePending = useRef8(false);
12012
12917
  const droppedReferences = useRef8(/* @__PURE__ */ new Set());
12013
12918
  const confirmed = useRef8(null);
12014
- const [canContinue, setCanContinue] = useState9(false);
12919
+ const [canContinue, setCanContinue] = useState11(false);
12015
12920
  const attempts = useRef8(0);
12016
12921
  const hungSaveTimer = useRef8(null);
12017
12922
  const checking = useRef8(null);
@@ -12026,7 +12931,8 @@ function useSale(settings, opts) {
12026
12931
  setCanContinue(!!completion);
12027
12932
  clearHungSaveTimer();
12028
12933
  }
12029
- const inFlight2 = useRef8(null);
12934
+ const inFlight3 = useRef8(null);
12935
+ const moving = useRef8(0);
12030
12936
  const stageNow = useRef8(stage);
12031
12937
  stageNow.current = stage;
12032
12938
  function locked() {
@@ -12035,7 +12941,7 @@ function useSale(settings, opts) {
12035
12941
  return active;
12036
12942
  }
12037
12943
  function busy() {
12038
- return !!(inFlight2.current || pending.current);
12944
+ return !!(inFlight3.current || pending.current);
12039
12945
  }
12040
12946
  function editRefusal() {
12041
12947
  const refusal = busy() ? SALE_SAVING : stageNow.current.kind === "receipt" ? SALE_FINISHED : liveLeg() ? SALE_HAS_PAYMENT : null;
@@ -12049,17 +12955,25 @@ function useSale(settings, opts) {
12049
12955
  return [...applied.current.values()].includes(KEPT);
12050
12956
  }
12051
12957
  const repricing = useRef8(null);
12052
- const [couponsRepricing, setCouponsRepricing] = useState9(false);
12958
+ const [couponsRepricing, setCouponsRepricing] = useState11(false);
12053
12959
  const generation = useRef8(0);
12054
- const saleEpoch = useRef8(0);
12960
+ const removalEpoch = useRef8(0);
12055
12961
  const stopped = useRef8(null);
12056
12962
  const keptCoupons = useRef8(void 0);
12057
12963
  const keptLegIds = useRef8([]);
12964
+ const resumedLegIds = useRef8([]);
12965
+ const resumedTakenIds = useRef8([]);
12058
12966
  function countedLeg(p) {
12059
12967
  return !!builderNow.current.getSnapshot().afterClose?.payments.some((leg) => leg.id === p.id);
12060
12968
  }
12061
12969
  function heldLeg(p) {
12062
- return !!p.locked || !!p.reopened || countedLeg(p) || keptCodes() && isLiveLeg(p) && keptLegIds.current.includes(p.id);
12970
+ return !!p.locked || !!p.reopened || countedLeg(p) || keptCodes() && isLiveLeg(p) && keptLegIds.current.includes(p.id) || isLiveLeg(p) && resumedLegIds.current.includes(p.id) || taken(p) || isInMotion(p);
12971
+ }
12972
+ function taken(p) {
12973
+ return takenLeg(p) || resumedTakenIds.current.includes(p.id);
12974
+ }
12975
+ function holdsTakenPayment() {
12976
+ return builderNow.current.getSnapshot().payments.some((p) => !p.locked && legStatus(p) === "captured" && taken(p));
12063
12977
  }
12064
12978
  function reprice() {
12065
12979
  if (repricing.current) return repricing.current;
@@ -12109,14 +13023,14 @@ function useSale(settings, opts) {
12109
13023
  return builderNow.current.getSnapshot().coupons?.some((coupon) => coupon.carried);
12110
13024
  }
12111
13025
  function resetSale(customer = defaulted(), restored, restoredTax) {
12112
- if (inFlight2.current && !pending.current) return setError(SALE_SAVING);
13026
+ if (inFlight3.current && !pending.current) return setError(SALE_SAVING);
12113
13027
  if (pending.current && confirmed.current !== pending.current) {
12114
- if (inFlight2.current) checkStored(pending.current);
13028
+ if (inFlight3.current) checkStored(pending.current);
12115
13029
  return setError(SALE_SAVING);
12116
13030
  }
12117
13031
  confirm(null);
12118
13032
  pending.current = null;
12119
- inFlight2.current = null;
13033
+ inFlight3.current = null;
12120
13034
  tenderSession.current = null;
12121
13035
  droppedReferences.current.clear();
12122
13036
  setSaving(false);
@@ -12129,20 +13043,22 @@ function useSale(settings, opts) {
12129
13043
  applied.current.clear();
12130
13044
  keptCoupons.current = void 0;
12131
13045
  keptLegIds.current = [];
13046
+ resumedLegIds.current = [];
13047
+ resumedTakenIds.current = [];
12132
13048
  appliedWith.current = null;
12133
13049
  generation.current++;
12134
- saleEpoch.current++;
13050
+ removalEpoch.current++;
12135
13051
  setBuilder(next);
12136
13052
  setOrder(next.getSnapshot());
12137
13053
  stageNow.current = { kind: "cart" };
12138
13054
  setStage(stageNow.current);
12139
13055
  setError(null);
12140
13056
  }
12141
- useEffect10(() => {
13057
+ useEffect12(() => {
12142
13058
  const subscription = rendered.order$.subscribe(setOrder);
12143
13059
  return () => subscription.unsubscribe();
12144
13060
  }, [rendered]);
12145
- useEffect10(() => {
13061
+ useEffect12(() => {
12146
13062
  if (order.couponPricesStale && applied.current.size > 0 && !repricing.current && stageNow.current.kind !== "receipt" && !busy() && !liveLeg() && stopped.current?.order !== order) void (appliedWith.current ? reprice() : dropKept());
12147
13063
  });
12148
13064
  function dropKept() {
@@ -12153,12 +13069,21 @@ function useSale(settings, opts) {
12153
13069
  setError(COUPONS_UNSUPPORTED);
12154
13070
  }
12155
13071
  const idle3 = stage.kind === "cart" && !order.lineItems.length && !order.fees?.length && !order.shipping?.length;
13072
+ function refuseIdleReset() {
13073
+ if (!resetRefused.current) setError(SALE_PARTLY_PAID);
13074
+ resetRefused.current = true;
13075
+ }
12156
13076
  useLayoutEffect(() => {
12157
13077
  const live = builderNow.current.getSnapshot();
12158
- const liveIdle = stageNow.current.kind === "cart" && !live.lineItems.length && !live.fees?.length && !live.shipping?.length && !inFlight2.current && !pending.current;
13078
+ const liveIdle = stageNow.current.kind === "cart" && !live.lineItems.length && !live.fees?.length && !live.shipping?.length && !inFlight3.current && !pending.current;
12159
13079
  const newDefault = defaultSeen.current !== defaultKey;
12160
13080
  defaultSeen.current = defaultKey;
12161
- if (liveIdle && (newDefault || madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency || madeWith.current.taxContextFor !== opts.taxContextFor)) resetSale(newDefault ? void 0 : live.customer ?? null);
13081
+ const due = liveIdle && (newDefault || madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency || madeWith.current.taxContextFor !== opts.taxContextFor);
13082
+ if (due && holdsTakenPayment()) refuseIdleReset();
13083
+ else {
13084
+ resetRefused.current = false;
13085
+ if (due) resetSale(newDefault ? void 0 : live.customer ?? null);
13086
+ }
12162
13087
  });
12163
13088
  function retax(customer, next) {
12164
13089
  const snapshot = { ...builderNow.current.getSnapshot(), customer, ...carriedCoupon() ? { couponPricesStale: true } : {} };
@@ -12177,31 +13102,34 @@ function useSale(settings, opts) {
12177
13102
  return true;
12178
13103
  }
12179
13104
  const liveCustomer = order.customer, taxContextFor = opts.taxContextFor;
12180
- const taxLocation = useMemo7(() => taxContextFor ? { ...taxContextFor(liveCustomer).location, hasCustomer: liveCustomer !== null } : void 0, [liveCustomer, taxContextFor]);
12181
- useEffect10(() => () => {
13105
+ const taxLocation = useMemo9(() => taxContextFor ? { ...taxContextFor(liveCustomer).location, hasCustomer: liveCustomer !== null } : void 0, [liveCustomer, taxContextFor]);
13106
+ useEffect12(() => () => {
12182
13107
  clearHungSaveTimer();
12183
- if (pending.current || inFlight2.current) {
13108
+ if (pending.current || inFlight3.current) {
12184
13109
  saleLogger.error(
12185
13110
  "useSale unmounted with a save pending or in flight",
12186
13111
  { orderId: pending.current?.posOrder.id, stage: stageNow.current.kind }
12187
13112
  );
12188
13113
  }
12189
13114
  }, []);
12190
- function addOne(tender) {
13115
+ function addOne(tender, stamp2, rounding) {
12191
13116
  const reason = referenceReason(tender.reference);
12192
13117
  const dropped = reason && (reason === "nul" ? "it contains a NUL character" : `it is over ${PAYLOAD_STRING_MAX} characters`);
13118
+ const captured = stamp2 && legStatus({ status: tender.status }) === "captured", sessionId = captured ? legSessionId() : void 0;
13119
+ const takenAt = { ...captured ? { takenAt: (/* @__PURE__ */ new Date()).toISOString() } : {}, ...sessionId !== void 0 ? { sessionId } : {} };
12193
13120
  const kept = dropped ? {
12194
13121
  method: tender.method,
12195
13122
  amountMinor: tender.amountMinor,
13123
+ ...takenAt,
12196
13124
  ...tender.tenderedMinor !== void 0 ? { tenderedMinor: tender.tenderedMinor } : {},
12197
13125
  ...tender.changeMinor !== void 0 ? { changeMinor: tender.changeMinor } : {},
12198
13126
  ...tender.units !== void 0 ? { units: tender.units } : {},
12199
13127
  ...tender.methodId !== void 0 ? { methodId: tender.methodId } : {},
12200
13128
  ...tender.status !== void 0 ? { status: tender.status } : {}
12201
- } : tender;
13129
+ } : { ...tender, ...takenAt };
12202
13130
  const builder = builderNow.current;
12203
13131
  const { units, ...payment } = kept;
12204
- const paymentId = builder.addPayment({ ...payment, ...units && Object.keys(units).length ? { units } : {} });
13132
+ const paymentId = builder.addPayment({ ...payment, ...units && Object.keys(units).length ? { units } : {} }, rounding);
12205
13133
  if (dropped) {
12206
13134
  droppedReferences.current.add(paymentId);
12207
13135
  setError(`${REFERENCE_DROPPED} (${dropped}); the payment is recorded without it.`);
@@ -12223,10 +13151,12 @@ function useSale(settings, opts) {
12223
13151
  if (taxIdsRefused) return setError(taxIdsRefused);
12224
13152
  if (tender && builderNow.current.getSnapshot().afterClose) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
12225
13153
  const builder = builderNow.current;
12226
- for (const payment of builder.getSnapshot().payments) if (!heldLeg(payment)) builder.removePayment(payment.id);
12227
- droppedReferences.current.clear();
13154
+ for (const payment of builder.getSnapshot().payments) if (!heldLeg(payment)) {
13155
+ builder.removePayment(payment.id);
13156
+ droppedReferences.current.delete(payment.id);
13157
+ }
12228
13158
  setError(null);
12229
- if (tender) addOne(tender);
13159
+ if (tender) addOne(tender, false);
12230
13160
  }
12231
13161
  function clearStaleError() {
12232
13162
  setError((current) => current?.startsWith(REFERENCE_DROPPED) ? current : null);
@@ -12246,12 +13176,27 @@ function useSale(settings, opts) {
12246
13176
  clearHungSaveTimer();
12247
13177
  const timer = opts.isStored ? setInterval(() => {
12248
13178
  if (checking.current === completion) return;
12249
- if (pending.current === completion && inFlight2.current && confirmed.current !== completion) checkStored(completion);
13179
+ if (pending.current === completion && inFlight3.current && confirmed.current !== completion) checkStored(completion);
12250
13180
  else if (hungSaveTimer.current === timer) clearHungSaveTimer();
12251
13181
  }, opts.hungSaveCheckMs ?? HUNG_SAVE_CHECK_MS) : null;
12252
13182
  hungSaveTimer.current = timer;
13183
+ let timeout;
13184
+ let timedOut = false;
12253
13185
  try {
12254
- await opts.onSaleCompleted?.(completion.posOrder);
13186
+ await Promise.race([
13187
+ Promise.resolve(opts.onSaleCompleted?.(completion.posOrder)).then(() => {
13188
+ if (timedOut && pending.current === completion && inFlight3.current === null) finish();
13189
+ }, (error2) => {
13190
+ if (timedOut && confirmed.current !== completion) saleLogger.error("onSaleCompleted failed", { orderId: completion.posOrder.id, error: error2 instanceof Error ? error2.message : String(error2) });
13191
+ throw error2;
13192
+ }),
13193
+ new Promise((_resolve, reject) => {
13194
+ timeout = setTimeout(() => {
13195
+ timedOut = true;
13196
+ reject(new Error("the save took too long"));
13197
+ }, opts.saveTimeoutMs ?? SAVE_TIMEOUT_MS);
13198
+ })
13199
+ ]);
12255
13200
  } catch (error2) {
12256
13201
  if (hungSaveTimer.current === timer) clearHungSaveTimer();
12257
13202
  const message = error2 instanceof Error ? error2.message : String(error2);
@@ -12263,26 +13208,32 @@ function useSale(settings, opts) {
12263
13208
  checkStored(completion);
12264
13209
  }
12265
13210
  return;
13211
+ } finally {
13212
+ clearTimeout(timeout);
13213
+ }
13214
+ finish();
13215
+ function finish() {
13216
+ if (hungSaveTimer.current === timer) clearHungSaveTimer();
13217
+ if (pending.current !== completion) return;
13218
+ pending.current = null;
13219
+ droppedReferences.current.clear();
13220
+ confirm(null);
13221
+ setSaving(false);
13222
+ setError(null);
13223
+ stageNow.current = { kind: "receipt", order: withSentForm(completion.order, completion.posOrder), posOrder: completion.posOrder };
13224
+ setStage(stageNow.current);
12266
13225
  }
12267
- if (hungSaveTimer.current === timer) clearHungSaveTimer();
12268
- if (pending.current !== completion) return;
12269
- pending.current = null;
12270
- droppedReferences.current.clear();
12271
- confirm(null);
12272
- setSaving(false);
12273
- setError(null);
12274
- stageNow.current = { kind: "receipt", order: withSentForm(completion.order, completion.posOrder), posOrder: completion.posOrder };
12275
- setStage(stageNow.current);
12276
13226
  }
12277
13227
  function once(attempt2) {
12278
- if (!inFlight2.current && stageNow.current.kind !== "receipt") {
13228
+ if (!inFlight3.current && stageNow.current.kind !== "receipt") {
12279
13229
  const mine = attempt2().finally(() => {
12280
- if (inFlight2.current === mine) inFlight2.current = null;
13230
+ if (inFlight3.current === mine) inFlight3.current = null;
12281
13231
  });
12282
- inFlight2.current = mine;
13232
+ inFlight3.current = mine;
12283
13233
  }
12284
- return inFlight2.current ?? Promise.resolve();
13234
+ return inFlight3.current ?? Promise.resolve();
12285
13235
  }
13236
+ const legSessionId = () => (tenderSession.current?.session ?? opts.session)?.id;
12286
13237
  function begin(method, options) {
12287
13238
  if (stageNow.current.kind === "receipt") return setError(SALE_FINISHED);
12288
13239
  if (locked()) return;
@@ -12291,7 +13242,7 @@ function useSale(settings, opts) {
12291
13242
  if (couponsUnpriced()) return setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING);
12292
13243
  if (afterCloseChanged(current)) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
12293
13244
  tenderSession.current ??= { session: options?.session ?? opts.session };
12294
- const heldMinor = current.payments.reduce((sum4, payment) => sum4 + (heldLeg(payment) ? payment.amountMinor : 0), 0);
13245
+ const heldMinor = current.payments.reduce((sum4, payment) => sum4 + (heldLeg(payment) && legStatus(payment) !== "voided" ? payment.amountMinor : 0), 0);
12295
13246
  if (current.afterClose) setTender(null);
12296
13247
  else if (heldMinor === 0) setTender(method === "external" ? { method, amountMinor: current.totalMinor } : null);
12297
13248
  else setTender(method === "external" && current.totalMinor - heldMinor > 0 ? { method, amountMinor: current.totalMinor - heldMinor } : null);
@@ -12327,14 +13278,14 @@ function useSale(settings, opts) {
12327
13278
  if (held) return held;
12328
13279
  const builder = builderNow.current;
12329
13280
  try {
12330
- const known = new Set(builder.getSnapshot().lineItems.map((line2) => line2.id));
13281
+ const known2 = new Set(builder.getSnapshot().lineItems.map((line2) => line2.id));
12331
13282
  const productId = Number(traits.getId(entry.product));
12332
13283
  if (Number.isSafeInteger(productId) && productId >= 0) {
12333
13284
  const ids = productCategories(entry.product, traits).map(({ id: id2 }) => ({ id: Number(id2) })).filter(({ id: id2 }) => Number.isSafeInteger(id2));
12334
13285
  if (ids.length) categories.current.set(productId, ids);
12335
13286
  }
12336
13287
  const lineId = addEntryToCart(builder, entry, traits, madeWith.current.currency);
12337
- const line = builder.getSnapshot().lineItems.find((item) => item.id === lineId && !known.has(item.id));
13288
+ const line = builder.getSnapshot().lineItems.find((item) => item.id === lineId && !known2.has(item.id));
12338
13289
  const name = line && `"${cutText(line.name, MESSAGE_NAME_MAX)}"`;
12339
13290
  const taxLines = line && (opts.capabilities?.orderCreate ?? 1) >= 3 ? line.taxLines : [];
12340
13291
  const refused = line && [
@@ -12465,21 +13416,19 @@ function useSale(settings, opts) {
12465
13416
  /** #1095: the line, fee or shipping line `id` as it is now, taken before a remove for `restore()`; null when it is not there. */
12466
13417
  removal(kind, id2) {
12467
13418
  const order2 = builderNow.current.getSnapshot();
12468
- const list = kind === "line" ? order2.lineItems : kind === "fee" ? order2.fees ?? [] : order2.shipping ?? [];
12469
- const index = list.findIndex((item) => item.id === id2);
12470
- return index < 0 ? null : { kind, id: id2, item: list[index], index, orderId: order2.id, taxContext: taxNow.current.taxContext, epoch: saleEpoch.current };
13419
+ const list2 = kind === "line" ? order2.lineItems : kind === "fee" ? order2.fees ?? [] : order2.shipping ?? [];
13420
+ const index = list2.findIndex((item) => item.id === id2);
13421
+ return index < 0 ? null : { kind, id: id2, item: list2[index], index, orderId: order2.id, taxContext: taxNow.current.taxContext, epoch: removalEpoch.current };
12471
13422
  },
12472
- /** #1095, v2's Undo: puts a removal back at its old index (clamped), re-taxed when the sale's rates moved since; returns a refusal or null. */
13423
+ /** #1095, v2's Undo: puts a removal back at its old index (clamped); returns a refusal or null. Any customer change, a re-tax, a reset (park, resume, new sale) or the receipt voids it (RESTORE_STALE). */
12473
13424
  restore(removal) {
12474
13425
  const held = editRefusal();
12475
13426
  if (held) return held;
12476
- const order2 = builderNow.current.getSnapshot(), moved = removal.taxContext !== taxNow.current.taxContext;
12477
- if (stageNow.current.kind !== "cart" || removal.orderId !== order2.id || removal.epoch !== saleEpoch.current) return RESTORE_STALE;
13427
+ const order2 = builderNow.current.getSnapshot();
13428
+ if (stageNow.current.kind !== "cart" || removal.orderId !== order2.id || removal.epoch !== removalEpoch.current || removal.taxContext !== taxNow.current.taxContext) return RESTORE_STALE;
12478
13429
  const ids = [removal.item, ...removal.kind === "line" ? removal.item.discounts : []].map((entry) => entry.id);
12479
13430
  if ([...order2.lineItems.flatMap((li) => [li, ...li.discounts]), ...order2.fees ?? [], ...order2.shipping ?? [], ...order2.discounts, ...order2.payments].some((entry) => ids.includes(entry.id))) return RESTORE_STALE;
12480
- if (moved && (capturedMinor(order2.payments) !== 0 || order2.payments.some(isInMotion) || keptCodes())) return RESTORE_STALE;
12481
13431
  builderNow.current.restoreItem(removal.kind, removal.item, removal.index);
12482
- if (moved) retax(builderNow.current.getSnapshot().customer, taxNow.current);
12483
13432
  return null;
12484
13433
  },
12485
13434
  /** A line's discount, or the order's without a line; returns the refusal to show, or null once applied. */
@@ -12575,6 +13524,7 @@ function useSale(settings, opts) {
12575
13524
  if (same2) taxNow.current = same2;
12576
13525
  builderNow.current.setCustomer(customer);
12577
13526
  }
13527
+ removalEpoch.current++;
12578
13528
  setError((current) => current !== null && (CUSTOMER_REFUSALS.includes(current) || current === CUSTOMER_RETAX_REFUSED || current === TAX_IDS_INVALID) ? null : current);
12579
13529
  },
12580
13530
  /**
@@ -12600,6 +13550,7 @@ function useSale(settings, opts) {
12600
13550
  if (same2) taxNow.current = same2;
12601
13551
  builderNow.current.setCustomer(next);
12602
13552
  }
13553
+ removalEpoch.current++;
12603
13554
  setError((current) => current === ADDRESS_CHANGE_REFUSED ? null : current);
12604
13555
  return true;
12605
13556
  },
@@ -12621,6 +13572,7 @@ function useSale(settings, opts) {
12621
13572
  }
12622
13573
  const { taxIds: _taxIds, ...rest } = customer;
12623
13574
  builderNow.current.setCustomer(cleaned.length ? { ...rest, taxIds: cleaned } : rest);
13575
+ removalEpoch.current++;
12624
13576
  setError((current) => current === TAX_IDS_CHANGE_REFUSED || current === TAX_IDS_INVALID ? null : current);
12625
13577
  return true;
12626
13578
  },
@@ -12637,12 +13589,12 @@ function useSale(settings, opts) {
12637
13589
  return false;
12638
13590
  }
12639
13591
  const name = key.trim();
12640
- const known = meta.some((m) => m.key === name);
12641
- if (!name || name.length > ORDER_META_KEY_MAX3 || name.startsWith("_") || value !== null && !known && meta.length >= ORDER_META_MAX2) {
13592
+ const known2 = meta.some((m) => m.key === name);
13593
+ if (!name || name.length > ORDER_META_KEY_MAX3 || name.startsWith("_") || value !== null && !known2 && meta.length >= ORDER_META_MAX2) {
12642
13594
  setError(META_INVALID);
12643
13595
  return false;
12644
13596
  }
12645
- const next = value === null ? meta.filter((m) => m.key !== name) : known ? meta.map((m) => m.key === name ? { key: name, value } : m) : [...meta, { key: name, value }];
13597
+ const next = value === null ? meta.filter((m) => m.key !== name) : known2 ? meta.map((m) => m.key === name ? { key: name, value } : m) : [...meta, { key: name, value }];
12646
13598
  builderNow.current.setMeta(next);
12647
13599
  setError((current) => current === META_CHANGE_REFUSED || current === META_INVALID ? null : current);
12648
13600
  return true;
@@ -12673,13 +13625,17 @@ function useSale(settings, opts) {
12673
13625
  });
12674
13626
  },
12675
13627
  setTender,
12676
- /** ADR-072: external is capped at the balance due; change comes only from cash. A leg is captured unless a status says otherwise; a leg in motion is held against the external cap. Units are checked against the units legs hold (`heldUnitsByLine`), but a leg's amount is not tied to its units' money here; the pane enforces that (#1133). */
12677
- addTender(tender) {
13628
+ /** ADR-072: external is capped at the balance due; change comes only from cash. A cash leg records the amount applied, the amount handed over (`tenderedMinor`) and the change (`changeMinor`). A leg is captured unless a status says otherwise; a leg in motion is held against the external cap. Units are checked against the units legs hold (`heldUnitsByLine`), but a leg's amount is not tied to its units' money here; the pane enforces that (#1133). A cash part pick rounds its own target on a cashRounding store (ADR-094). */
13629
+ addTender(input) {
13630
+ const { rounding, ...tender } = input;
12678
13631
  if (stageNow.current.kind === "receipt") {
12679
13632
  setError(SALE_FINISHED);
12680
13633
  return null;
12681
13634
  }
12682
- if (locked() || !Number.isInteger(tender.amountMinor) || tender.amountMinor <= 0) return null;
13635
+ if (rounding && tender.method !== "cash") return null;
13636
+ const rule = rounding && tender.tenderedMinor === void 0 && opts.capabilities?.cashRounding === true && inMotionMinor(builderNow.current.getSnapshot().payments) === 0 ? rounding : null;
13637
+ const pickRule = rounding && tender.method === "cash" && opts.capabilities?.cashRounding === true && inMotionMinor(builderNow.current.getSnapshot().payments) === 0 ? rounding : null;
13638
+ if (locked() || !Number.isInteger(tender.amountMinor) || tender.amountMinor < 0 || tender.amountMinor === 0 && !rule) return null;
12683
13639
  if (builderNow.current.getSnapshot().afterClose) {
12684
13640
  setError(AFTER_CLOSE_PAYMENTS_CHANGED);
12685
13641
  return null;
@@ -12695,20 +13651,74 @@ function useSale(settings, opts) {
12695
13651
  const unpaid = unpaidUnitsByLine(lineItems.map(({ id: id2, quantity }) => ({ id: id2, quantity, totalMinor: 0 })), heldUnitsByLine(payments));
12696
13652
  if (Object.entries(tender.units).some(([id2, units]) => !id2 || !Number.isInteger(units) || units <= 0 || !Object.hasOwn(unpaid, id2) || units > unpaid[id2])) return null;
12697
13653
  }
12698
- if (tender.tenderedMinor !== void 0 && (tender.method !== "cash" || !tender.units || !Object.keys(tender.units).length || !Number.isInteger(tender.tenderedMinor) || tender.tenderedMinor < tender.amountMinor)) return null;
13654
+ const pickMinor = pickRule && tender.tenderedMinor !== void 0 ? roundedPickTarget(tender.amountMinor, pickRule) : tender.amountMinor;
13655
+ if (tender.tenderedMinor !== void 0 && pickMinor === 0) return null;
13656
+ if (tender.tenderedMinor !== void 0 && (tender.method !== "cash" || !tender.units || !Object.keys(tender.units).length || !Number.isInteger(tender.tenderedMinor) || tender.tenderedMinor < pickMinor)) return null;
12699
13657
  if (tender.tenderedMinor !== void 0) {
12700
13658
  const snapshot = builderNow.current.getSnapshot();
12701
13659
  if (tender.amountMinor > snapshot.balanceDueMinor - inMotionMinor(snapshot.payments)) return null;
13660
+ if (pickMinor !== tender.amountMinor && (snapshot.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX) {
13661
+ setError(CASH_PICK_LIMIT);
13662
+ return null;
13663
+ }
13664
+ if (rounding && opts.capabilities?.cashRounding === true && tender.method === "cash" && inMotionMinor(snapshot.payments) > 0 && nearestPayableCash(tender.amountMinor, rounding.incrementMinor) !== null) {
13665
+ setError(CASH_WAITS_FOR_PAYMENT);
13666
+ return null;
13667
+ }
12702
13668
  }
12703
13669
  if (tender.method === "external") {
12704
13670
  const snapshot = builderNow.current.getSnapshot();
12705
13671
  const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
12706
13672
  if (due <= 0) return null;
12707
13673
  clearStaleError();
12708
- return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) });
13674
+ return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) }, true);
13675
+ }
13676
+ if (tender.tenderedMinor === void 0) {
13677
+ const snapshot = builderNow.current.getSnapshot();
13678
+ const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
13679
+ if (due <= 0) {
13680
+ setError(NOTHING_DUE);
13681
+ return null;
13682
+ }
13683
+ const entries2 = remainderEntriesMinor(snapshot);
13684
+ const dueMinor = rule ? roundedRemainder(due, entries2, rule) : due;
13685
+ if (rule && settlesAtRoundedDue({ amountMinor: Math.min(tender.amountMinor, due), tenderedMinor: tender.amountMinor, balanceMinor: due, dueMinor })) {
13686
+ const against = snapshot.payments.filter(countsTowardPaid).at(-1);
13687
+ const roundings = snapshot.cashRoundings ?? [];
13688
+ if (roundings.length >= CASH_PICK_ENTRIES_MAX + 1 && (dueMinor > 0 ? dueMinor !== due : against !== void 0 && !roundings.some((entry) => entry.paymentId === against.id))) {
13689
+ setError(CASH_SETTLE_LIMIT);
13690
+ return null;
13691
+ }
13692
+ clearStaleError();
13693
+ if (dueMinor > 0) {
13694
+ return addOne({ ...tender, amountMinor: dueMinor, tenderedMinor: tender.amountMinor, changeMinor: tender.amountMinor - dueMinor }, true, { minor: dueMinor - due });
13695
+ }
13696
+ if (!against) {
13697
+ setError(NOTHING_TO_ROUND_AGAINST);
13698
+ return null;
13699
+ }
13700
+ builderNow.current.addCashRounding({ paymentId: against.id, minor: -due });
13701
+ return against.id;
13702
+ }
13703
+ if (tender.amountMinor === 0) return null;
13704
+ if (rule && nearestPayableCash(tender.amountMinor, rule.incrementMinor)) {
13705
+ setError(CASH_NOT_PAYABLE);
13706
+ return null;
13707
+ }
13708
+ const amountMinor = Math.min(tender.amountMinor, due);
13709
+ if (rounding && tender.tenderedMinor === void 0 && opts.capabilities?.cashRounding === true && inMotionMinor(snapshot.payments) > 0 && nearestPayableCash(amountMinor, rounding.incrementMinor) !== null) {
13710
+ setError(CASH_WAITS_FOR_PAYMENT);
13711
+ return null;
13712
+ }
13713
+ clearStaleError();
13714
+ return addOne({ ...tender, amountMinor, tenderedMinor: tender.amountMinor, changeMinor: tender.amountMinor - amountMinor }, true);
12709
13715
  }
12710
13716
  clearStaleError();
12711
- return addOne({ ...tender, ...tender.tenderedMinor !== void 0 ? { changeMinor: tender.tenderedMinor - tender.amountMinor } : {} });
13717
+ return addOne(
13718
+ { ...tender, amountMinor: pickMinor, changeMinor: tender.tenderedMinor - pickMinor },
13719
+ true,
13720
+ pickMinor !== tender.amountMinor ? { minor: pickMinor - tender.amountMinor } : void 0
13721
+ );
12712
13722
  },
12713
13723
  setTenderStatus(paymentId, status) {
12714
13724
  if (stageNow.current.kind === "receipt") {
@@ -12721,11 +13731,12 @@ function useSale(settings, opts) {
12721
13731
  setError(AFTER_CLOSE_PAYMENTS_CHANGED);
12722
13732
  return false;
12723
13733
  }
12724
- const changed = builderNow.current.setPaymentStatus(paymentId, status);
13734
+ const changed = status === "captured" ? builderNow.current.setPaymentStatus(paymentId, status, (/* @__PURE__ */ new Date()).toISOString(), legSessionId()) : builderNow.current.setPaymentStatus(paymentId, status);
12725
13735
  if (changed && status === "failed" && !liveLeg()) setError((current) => current === SALE_HAS_PAYMENT ? null : current);
13736
+ if (changed) setError((current) => current === NOTHING_DUE ? null : current);
12726
13737
  return changed;
12727
13738
  },
12728
- /** The leg stays in order.payments as voided and counts nothing; removeTender still removes a leg outright. Refused on the receipt. */
13739
+ /** The leg stays in order.payments as voided and counts nothing; removeTender removes only a leg that took no money. Refused on the receipt. */
12729
13740
  voidTender(paymentId) {
12730
13741
  if (stageNow.current.kind === "receipt") {
12731
13742
  setError(SALE_FINISHED);
@@ -12739,6 +13750,10 @@ function useSale(settings, opts) {
12739
13750
  if (payment?.locked) return false;
12740
13751
  if (locked()) return false;
12741
13752
  if (!payment || payment.method !== "cash" && payment.method !== "external" || !canVoidLeg(payment, paymentMethodOf2(payment.method))) return false;
13753
+ if (cashVoidRefusal(builderNow.current.getSnapshot(), paymentId)) {
13754
+ setError(VOID_LATER_CASH_FIRST);
13755
+ return false;
13756
+ }
12742
13757
  builderNow.current.setPaymentStatus(paymentId, "voided");
12743
13758
  droppedReferences.current.delete(paymentId);
12744
13759
  clearStaleError();
@@ -12752,10 +13767,16 @@ function useSale(settings, opts) {
12752
13767
  if (payment?.locked) return;
12753
13768
  if (locked()) return;
12754
13769
  if (!payment) return;
13770
+ if (taken(payment)) return setError(PAYMENT_TAKEN);
12755
13771
  builderNow.current.removePayment(paymentId);
12756
13772
  droppedReferences.current.delete(paymentId);
12757
13773
  clearStaleError();
12758
13774
  },
13775
+ /** True when setTender keeps this payment; false for one it replaces and for an id not among the payments. Changes nothing. */
13776
+ tenderHeld(paymentId) {
13777
+ const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
13778
+ return !!payment && heldLeg(payment);
13779
+ },
12759
13780
  cancelTender() {
12760
13781
  if (stageNow.current.kind === "receipt") return setError(SALE_FINISHED);
12761
13782
  if (locked()) return;
@@ -12779,8 +13800,9 @@ function useSale(settings, opts) {
12779
13800
  * another is in flight returns that call's promise, and a call on the receipt does nothing. While
12780
13801
  * `cashierRef` or `registerId` is out of bounds (shown as `error`), a call does nothing either,
12781
13802
  * unless it's the Retry of a pending completion, which was built with the options as they were.
13803
+ * Refused with `REGISTER_CLOSING`, changing nothing, while a close for this register is in flight (#1275).
12782
13804
  */
12783
- complete: () => configError && !pending.current && !inFlight2.current ? Promise.resolve() : once(async () => {
13805
+ complete: () => configError && !pending.current && !inFlight3.current ? Promise.resolve() : isRegisterClosing(opts.registerId) ? (setError(REGISTER_CLOSING), Promise.resolve()) : once(async () => {
12784
13806
  attempts.current++;
12785
13807
  confirm(null);
12786
13808
  if (pending.current) return deliver(pending.current);
@@ -12796,7 +13818,8 @@ function useSale(settings, opts) {
12796
13818
  setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING);
12797
13819
  return;
12798
13820
  }
12799
- const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid) };
13821
+ const completedAt = (/* @__PURE__ */ new Date()).toISOString(), sessionId = legSessionId();
13822
+ const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid).map((payment) => payment.takenAt === void 0 && !payment.locked && !payment.reopened && !resumedTakenIds.current.includes(payment.id) ? { ...payment, takenAt: completedAt, ...sessionId !== void 0 && payment.sessionId === void 0 ? { sessionId } : {} } : payment) };
12800
13823
  const localWarnings = current.payments.filter((payment) => droppedReferences.current.has(payment.id)).map((payment) => ({ code: "payment_reference_dropped", paymentId: payment.id }));
12801
13824
  let posOrder;
12802
13825
  try {
@@ -12855,24 +13878,56 @@ function useSale(settings, opts) {
12855
13878
  * save still in flight carries on in the background, a throw logged at error) and starts the new
12856
13879
  * sale outright — from the receipt, or an idle cart, there's nothing pending to abandon. Abandoning
12857
13880
  * clears the screen, never the record (the Front desk, 2026-09-25). `newSale()` never deletes,
12858
- * updates or requeues `pos_orders` itself.
13881
+ * updates or requeues `pos_orders` itself. An unfinished sale that still holds a taken payment is refused
13882
+ * with SALE_PARTLY_PAID, changing nothing, as `closeSale` refuses it; the receipt and a confirmed stored
13883
+ * pending completion are unchanged.
13884
+ * An unfinished sale with an unlocked leg in motion refuses with SALE_CARD_IN_PROGRESS, changing nothing.
12859
13885
  */
12860
13886
  newSale() {
13887
+ if (stageNow.current.kind !== "receipt" && !inFlight3.current && !pending.current && builderNow.current.getSnapshot().payments.some((p) => !p.locked && isInMotion(p))) return setError(SALE_CARD_IN_PROGRESS);
13888
+ if (stageNow.current.kind !== "receipt" && !inFlight3.current && !pending.current && holdsTakenPayment()) return setError(SALE_PARTLY_PAID);
12861
13889
  resetSale();
12862
13890
  },
12863
- /** Parks the cart in `drafts`; resolves to a refusal message, or null once parked. */
13891
+ /**
13892
+ * S3: the live sale's legs its session counts now and no stored order counts yet, for `useRegisterSession`'s
13893
+ * `liveSale`: captured till legs stamped with a session, not reopened and not counted by an after-close sale's closure
13894
+ * (`sessionTakenLegs`, the rule a parked draft's legs follow). `[]` on the receipt, whose stored order counts them.
13895
+ * `cashRoundings` are the sale's cash rounding entries on those legs, copied, counted on the Z with them (#1281).
13896
+ * `saving` is true while a completion is in flight or pending, including after a failed save, and while a
13897
+ * `park()` or `resume()` is in flight.
13898
+ */
13899
+ registerView() {
13900
+ const snapshot = builderNow.current.getSnapshot();
13901
+ const takenLegs = stageNow.current.kind === "receipt" ? [] : sessionTakenLegs(snapshot.payments, countedLeg);
13902
+ const taken2 = new Set(takenLegs.map((leg) => leg.id));
13903
+ return {
13904
+ takenLegs,
13905
+ saving: inFlight3.current !== null || pending.current !== null || moving.current > 0,
13906
+ cashRoundings: (snapshot.cashRoundings ?? []).filter((entry) => taken2.has(entry.paymentId)).map((entry) => ({ ...entry }))
13907
+ };
13908
+ },
13909
+ /**
13910
+ * Parks the cart in `drafts`; resolves to a refusal message, or null once parked.
13911
+ * Refused with `REGISTER_CLOSING` while a close for this register is in flight (#1275).
13912
+ */
12864
13913
  async park() {
12865
13914
  if (locked()) return SALE_SAVING;
12866
- if (!opts.drafts) throw new Error("useSale: park() needs the drafts option");
12867
- if (stageNow.current.kind !== "cart") return "Finish or cancel the payment before parking the sale";
12868
- const builder = builderNow.current;
12869
- const snapshot = builder.getSnapshot();
12870
- if (!snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length) return "There is nothing to park";
12871
- const refused = await writeParked(opts.drafts, snapshot);
12872
- if (refused) return refused;
12873
- if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return "The sale changed while it was being parked; park it again";
12874
- resetSale();
12875
- return null;
13915
+ if (isRegisterClosing(opts.registerId)) return REGISTER_CLOSING;
13916
+ moving.current++;
13917
+ try {
13918
+ if (!opts.drafts) throw new Error("useSale: park() needs the drafts option");
13919
+ if (stageNow.current.kind !== "cart") return "Finish or cancel the payment before parking the sale";
13920
+ const builder = builderNow.current;
13921
+ const snapshot = builder.getSnapshot();
13922
+ if (!snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length) return "There is nothing to park";
13923
+ const refused = await writeParked(opts.drafts, snapshot);
13924
+ if (refused) return refused;
13925
+ if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return "The sale changed while it was being parked; park it again";
13926
+ resetSale();
13927
+ return null;
13928
+ } finally {
13929
+ moving.current--;
13930
+ }
12876
13931
  },
12877
13932
  /** Whether the live sale or a parked draft holds this store order; unreadable drafts do not count. */
12878
13933
  async holdsStoreOrder(orderId) {
@@ -12888,12 +13943,13 @@ function useSale(settings, opts) {
12888
13943
  }
12889
13944
  });
12890
13945
  },
12891
- /** Loads a reopened store order (from reopenStoreOrder) into an empty sale, or returns why not. */
13946
+ /** Loads a reopened store order (from reopenStoreOrder) into an empty sale, or returns why not; refused with SALE_PARTLY_PAID while the live sale holds a taken payment. */
12892
13947
  openStoreOrder(order2) {
12893
13948
  if (locked()) return SALE_SAVING;
12894
13949
  if (!order2.storeOrder) throw new Error("useSale: openStoreOrder() takes a reopened store order");
12895
13950
  const liveSnapshot = builderNow.current.getSnapshot();
12896
13951
  if (stageNow.current.kind !== "cart" || liveSnapshot.lineItems.length || liveSnapshot.fees?.length || liveSnapshot.shipping?.length) return "Park or clear the current sale first";
13952
+ if (holdsTakenPayment()) return SALE_PARTLY_PAID;
12897
13953
  if (order2.currency.toUpperCase() !== settings.currency.toUpperCase()) return "That order is in another currency";
12898
13954
  const restoredTax = contextFor(order2.customer && !customerRefusal(order2.customer) ? order2.customer : null);
12899
13955
  const builder = restoreOrderDraft(order2, { currency: settings.currency, taxContext: restoredTax.taxContext });
@@ -12902,103 +13958,123 @@ function useSale(settings, opts) {
12902
13958
  resetSale(null, builder, restoredTax);
12903
13959
  return null;
12904
13960
  },
12905
- /** Resumes a draft into an empty cart; resolves to a refusal message, or null once resumed. */
13961
+ /**
13962
+ * Resumes a draft into an empty cart; resolves to a refusal message, or null once resumed; refused with SALE_PARTLY_PAID while the live sale holds a taken payment.
13963
+ * Refused with `REGISTER_CLOSING` while a close for this register is in flight (#1275).
13964
+ */
12906
13965
  async resume(draftId, options) {
12907
13966
  if (locked()) return SALE_SAVING;
12908
- if (!opts.drafts) throw new Error("useSale: resume() needs the drafts option");
12909
- const live = builderNow.current;
12910
- const liveSnapshot = live.getSnapshot();
12911
- if (stageNow.current.kind !== "cart" || liveSnapshot.lineItems.length || liveSnapshot.fees?.length || liveSnapshot.shipping?.length) return "Park or clear the current sale first";
12912
- const doc = await opts.drafts.findOne(draftId).exec();
12913
- if (!doc) return "That parked sale is no longer there";
12914
- const saved = JSON.parse(doc.toJSON().data);
12915
- if (saved.currency.toUpperCase() !== settings.currency.toUpperCase()) return "That parked sale is in another currency";
12916
- const restoredTax = contextFor(saved.customer && !customerRefusal(saved.customer) ? saved.customer : null);
12917
- const carriedDraft = !!saved.coupons?.length && saved.coupons.every((coupon) => coupon.carried);
12918
- const keep = !carriedDraft && !!saved.coupons?.length && saved.display.coupons?.length === saved.coupons.length && (saved.payments ?? []).some(isLiveLeg);
12919
- const builder = restoreOrderDraft(saved, {
12920
- currency: settings.currency,
12921
- taxContext: restoredTax.taxContext,
12922
- keepTaxRates: keep || capturedMinor(saved.payments ?? []) !== 0,
12923
- keepCoupons: keep
12924
- });
12925
- let n = 0;
12926
- if (opts.currentPrice && !options?.keepParkedPrices && !carriedDraft && !keep && capturedMinor(saved.payments ?? []) === 0 && !saved.storeOrder) {
12927
- for (const line of builder.getSnapshot().lineItems) {
12928
- if (!line.variantId) continue;
12929
- const price = opts.currentPrice(line.variantId);
12930
- if (price !== void 0 && Number.isInteger(price) && price >= 0 && price !== line.unitPriceMinor) {
12931
- builder.setUnitPrice(line.id, price);
12932
- n++;
13967
+ if (isRegisterClosing(opts.registerId)) return REGISTER_CLOSING;
13968
+ moving.current++;
13969
+ try {
13970
+ if (!opts.drafts) throw new Error("useSale: resume() needs the drafts option");
13971
+ const live = builderNow.current;
13972
+ const liveSnapshot = live.getSnapshot();
13973
+ if (stageNow.current.kind !== "cart" || liveSnapshot.lineItems.length || liveSnapshot.fees?.length || liveSnapshot.shipping?.length) return "Park or clear the current sale first";
13974
+ if (holdsTakenPayment()) return SALE_PARTLY_PAID;
13975
+ const doc = await opts.drafts.findOne(draftId).exec();
13976
+ if (!doc) return "That parked sale is no longer there";
13977
+ const saved = JSON.parse(doc.toJSON().data);
13978
+ if (saved.currency.toUpperCase() !== settings.currency.toUpperCase()) return "That parked sale is in another currency";
13979
+ const restoredTax = contextFor(saved.customer && !customerRefusal(saved.customer) ? saved.customer : null);
13980
+ const carriedDraft = !!saved.coupons?.length && saved.coupons.every((coupon) => coupon.carried);
13981
+ const keep = !carriedDraft && !!saved.coupons?.length && saved.display.coupons?.length === saved.coupons.length && (saved.payments ?? []).some(isLiveLeg);
13982
+ const builder = restoreOrderDraft(saved, {
13983
+ currency: settings.currency,
13984
+ taxContext: restoredTax.taxContext,
13985
+ keepTaxRates: keep || capturedMinor(saved.payments ?? []) !== 0,
13986
+ keepCoupons: keep
13987
+ });
13988
+ let n = 0;
13989
+ if (opts.currentPrice && !options?.keepParkedPrices && !carriedDraft && !keep && capturedMinor(saved.payments ?? []) === 0 && !saved.storeOrder) {
13990
+ for (const line of builder.getSnapshot().lineItems) {
13991
+ if (!line.variantId) continue;
13992
+ const price = opts.currentPrice(line.variantId);
13993
+ if (price !== void 0 && Number.isInteger(price) && price >= 0 && price !== line.unitPriceMinor) {
13994
+ builder.setUnitPrice(line.id, price);
13995
+ n++;
13996
+ }
12933
13997
  }
12934
13998
  }
12935
- }
12936
- const kept = /* @__PURE__ */ new Map(), messages = [];
12937
- const codes2 = !carriedDraft && saved.coupons?.length ? codesFor() : null;
12938
- if (n > 0) messages.push(`Prices changed since this sale was parked: ${n} ${n === 1 ? "line" : "lines"} updated to today's price.`);
12939
- if (!carriedDraft && saved.coupons?.length) {
12940
- const supported = codes2 !== null;
12941
- if (supported) await codes2.beforeResume?.(discountState(builder.getSnapshot(), /* @__PURE__ */ new Map()));
12942
- if (keep) for (const { code } of saved.coupons) kept.set(code, KEPT);
12943
- else for (const { code } of saved.coupons) {
12944
- let reason = supported ? null : COUPONS_UNSUPPORTED;
12945
- if (supported) {
12946
- const result2 = await codes2.find(code, discountState(builder.getSnapshot(), kept));
12947
- if ("refusal" in result2) reason = result2.refusal;
12948
- else {
12949
- reason = codes2.check(code, result2.found, discountState(builder.getSnapshot(), kept));
12950
- if (reason === null) try {
12951
- codes2.apply(builder, discountState(builder.getSnapshot(), new Map([...kept, [code, result2.found]])));
12952
- kept.set(code, result2.found);
12953
- } catch (error2) {
12954
- if (error2 instanceof Error) reason = error2.message;
12955
- else throw error2;
13999
+ const kept = /* @__PURE__ */ new Map(), messages = [];
14000
+ const codes2 = !carriedDraft && saved.coupons?.length ? codesFor() : null;
14001
+ if (n > 0) messages.push(`Prices changed since this sale was parked: ${n} ${n === 1 ? "line" : "lines"} updated to today's price.`);
14002
+ if (!carriedDraft && saved.coupons?.length) {
14003
+ const supported = codes2 !== null;
14004
+ if (supported) await codes2.beforeResume?.(discountState(builder.getSnapshot(), /* @__PURE__ */ new Map()));
14005
+ if (keep) for (const { code } of saved.coupons) kept.set(code, KEPT);
14006
+ else for (const { code } of saved.coupons) {
14007
+ let reason = supported ? null : COUPONS_UNSUPPORTED;
14008
+ if (supported) {
14009
+ const result2 = await codes2.find(code, discountState(builder.getSnapshot(), kept));
14010
+ if ("refusal" in result2) reason = result2.refusal;
14011
+ else {
14012
+ reason = codes2.check(code, result2.found, discountState(builder.getSnapshot(), kept));
14013
+ if (reason === null) try {
14014
+ codes2.apply(builder, discountState(builder.getSnapshot(), new Map([...kept, [code, result2.found]])));
14015
+ kept.set(code, result2.found);
14016
+ } catch (error2) {
14017
+ if (error2 instanceof Error) reason = error2.message;
14018
+ else throw error2;
14019
+ }
12956
14020
  }
12957
14021
  }
14022
+ if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
12958
14023
  }
12959
- if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
12960
14024
  }
12961
- }
12962
- await doc.remove();
12963
- if (builderNow.current !== live || live.getSnapshot() !== liveSnapshot) {
12964
- await writeOrderDraft(opts.drafts, saved);
12965
- return "The sale changed while it was being resumed; resume it again";
12966
- }
12967
- resetSale(null, builder, restoredTax);
12968
- if (builderNow.current === builder) {
12969
- applied.current = kept;
12970
- if (keep) {
12971
- keptCoupons.current = saved.coupons;
12972
- keptLegIds.current = saved.payments.filter(isLiveLeg).map((p) => p.id);
14025
+ await doc.remove();
14026
+ if (builderNow.current !== live || live.getSnapshot() !== liveSnapshot) {
14027
+ await writeOrderDraft(opts.drafts, saved);
14028
+ return "The sale changed while it was being resumed; resume it again";
14029
+ }
14030
+ resetSale(null, builder, restoredTax);
14031
+ if (builderNow.current === builder) {
14032
+ applied.current = kept;
14033
+ resumedLegIds.current = (saved.payments ?? []).filter(isLiveLeg).map((p) => p.id);
14034
+ resumedTakenIds.current = builder.getSnapshot().payments.filter((p) => !p.locked && legStatus(p) === "captured" && p.takenAt === void 0).map((p) => p.id);
14035
+ if (keep) {
14036
+ keptCoupons.current = saved.coupons;
14037
+ keptLegIds.current = saved.payments.filter(isLiveLeg).map((p) => p.id);
14038
+ }
14039
+ appliedWith.current = kept.size ? codes2 : null;
14040
+ generation.current++;
12973
14041
  }
12974
- appliedWith.current = kept.size ? codes2 : null;
12975
- generation.current++;
14042
+ if (messages.length) setError(messages.join(" "));
14043
+ return null;
14044
+ } finally {
14045
+ moving.current--;
12976
14046
  }
12977
- if (messages.length) setError(messages.join(" "));
12978
- return null;
12979
14047
  },
12980
14048
  /**
12981
14049
  * Opens the parked draft `draftId`, or an empty sale for null (New), as a tab switch (u19, v2 cart/tabs.tsx):
12982
14050
  * parks the current sale first when it has lines, fees or shipping (a receipt is done and is not parked).
12983
- * Refused, changing nothing, while saving, for a partly paid sale (SALE_PARTLY_PAID), a payment in motion or
14051
+ * Refused, changing nothing, while saving, for a partly paid sale or an empty sale holding a taken payment (SALE_PARTLY_PAID), a payment in motion or
12984
14052
  * the tender stage. Resolves to a refusal (park's, or `resume`'s for the chosen draft), or null.
14053
+ * Refused with `REGISTER_CLOSING` while a close for this register is in flight (#1275).
12985
14054
  */
12986
14055
  async switchSale(draftId) {
12987
14056
  if (locked()) return SALE_SAVING;
12988
- if (!opts.drafts) throw new Error("useSale: switchSale() needs the drafts option");
12989
- const builder = builderNow.current;
12990
- const snapshot = builder.getSnapshot();
12991
- if (draftId === snapshot.id) return null;
12992
- if (capturedMinor(snapshot.payments.filter((payment) => !payment.locked)) > 0 && snapshot.balanceDueMinor > 0) return SALE_PARTLY_PAID;
12993
- if (snapshot.payments.some(isInMotion)) return PAYMENT_IN_MOTION;
12994
- if (stageNow.current.kind === "tender") return SALE_IN_TENDER;
12995
- if (stageNow.current.kind !== "receipt" && (snapshot.lineItems.length || snapshot.fees?.length || snapshot.shipping?.length)) {
12996
- const refused = await writeParked(opts.drafts, snapshot);
12997
- if (refused) return refused;
12998
- if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return "The sale changed while it was being parked; park it again";
14057
+ if (isRegisterClosing(opts.registerId)) return REGISTER_CLOSING;
14058
+ moving.current++;
14059
+ try {
14060
+ if (!opts.drafts) throw new Error("useSale: switchSale() needs the drafts option");
14061
+ const builder = builderNow.current;
14062
+ const snapshot = builder.getSnapshot();
14063
+ if (draftId === snapshot.id) return null;
14064
+ if (capturedMinor(snapshot.payments.filter((payment) => !payment.locked)) > 0 && snapshot.balanceDueMinor > 0) return SALE_PARTLY_PAID;
14065
+ if (snapshot.payments.some(isInMotion)) return PAYMENT_IN_MOTION;
14066
+ if (stageNow.current.kind === "tender") return SALE_IN_TENDER;
14067
+ if (stageNow.current.kind !== "receipt" && !snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length && holdsTakenPayment()) return SALE_PARTLY_PAID;
14068
+ if (stageNow.current.kind !== "receipt" && (snapshot.lineItems.length || snapshot.fees?.length || snapshot.shipping?.length)) {
14069
+ const refused = await writeParked(opts.drafts, snapshot);
14070
+ if (refused) return refused;
14071
+ if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return "The sale changed while it was being parked; park it again";
14072
+ }
14073
+ resetSale();
14074
+ return draftId === null ? null : await result.resume(draftId);
14075
+ } finally {
14076
+ moving.current--;
12999
14077
  }
13000
- resetSale();
13001
- return draftId === null ? null : result.resume(draftId);
13002
14078
  },
13003
14079
  /** 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.
13004
14080
  * A reopened sale's locked store legs do not stop it closing; the store order stays reopened, as in v2. */
@@ -13291,9 +14367,9 @@ function catalogueEntries(products, traits, context) {
13291
14367
  return variants.map((variant) => ({ product, variant }));
13292
14368
  });
13293
14369
  }
13294
- function findEntryByCode(entries, code) {
13295
- const variant = findVariantByCode(entries.map((entry) => entry.variant), code);
13296
- return variant ? entries.find((entry) => entry.variant === variant) : void 0;
14370
+ function findEntryByCode(entries2, code) {
14371
+ const variant = findVariantByCode(entries2.map((entry) => entry.variant), code);
14372
+ return variant ? entries2.find((entry) => entry.variant === variant) : void 0;
13297
14373
  }
13298
14374
  function variantPriceLabel(variant, currency, locale) {
13299
14375
  const price = resolvePrice4(variant.prices, currency);
@@ -13323,66 +14399,37 @@ function matchVariant(variants, groups, picks) {
13323
14399
  }
13324
14400
  function disabledOptions(variants, groups, picks) {
13325
14401
  const disabled = {};
13326
- for (const { name, values } of groups) {
13327
- const others = Object.fromEntries(Object.entries(picks).filter(([group]) => group !== name));
13328
- const fitting = variants.filter((variant) => variantFits(variant, others));
13329
- disabled[name] = new Set(values.filter((value) => !fitting.some((variant) => variantFits(variant, { [name]: value }))));
13330
- }
13331
- return disabled;
13332
- }
13333
-
13334
- // src/sale/in-cart.ts
13335
- function cartQuantities(lines) {
13336
- const quantities = /* @__PURE__ */ new Map();
13337
- for (const line of lines) {
13338
- if (line.custom) continue;
13339
- quantities.set(line.productId, (quantities.get(line.productId) ?? 0) + line.quantity);
13340
- }
13341
- return quantities;
13342
- }
13343
-
13344
- // src/sale/order-filters-query.ts
13345
- var COPIED = ["status", "customerId", "cashierId", "registerId", "paymentMethod", "storeId", "createdVia"];
13346
- var DAY_MS = 864e5;
13347
- function offsetMs(at2, timezone) {
13348
- const format2 = new Intl.DateTimeFormat("en-US", {
13349
- timeZone: timezone,
13350
- hourCycle: "h23",
13351
- year: "numeric",
13352
- month: "numeric",
13353
- day: "numeric",
13354
- hour: "numeric",
13355
- minute: "numeric",
13356
- second: "numeric"
13357
- });
13358
- const part = Object.fromEntries(format2.formatToParts(new Date(at2)).map(({ type, value }) => [type, Number(value)]));
13359
- const wall = Date.UTC(part.year, part.month - 1, part.day, part.hour, part.minute, part.second);
13360
- return wall - Math.floor(at2 / 1e3) * 1e3;
13361
- }
13362
- function dayStart(day, timezone) {
13363
- const [year, month, date] = day.split("-").map(Number);
13364
- if (timezone === "device") return new Date(year, month - 1, date).toISOString();
13365
- const wall = Date.UTC(year, month - 1, date);
13366
- const guess = wall - offsetMs(wall, timezone);
13367
- return new Date(wall - offsetMs(guess, timezone)).toISOString();
13368
- }
13369
- var nextDay = (day) => {
13370
- const [year, month, date] = day.split("-").map(Number);
13371
- return new Date(Date.UTC(year, month - 1, date) + DAY_MS).toISOString().slice(0, 10);
13372
- };
13373
- function orderFiltersQuery(value, timezone) {
13374
- const query = {};
13375
- for (const field of COPIED) {
13376
- if (value[field] !== void 0) query[field] = value[field];
14402
+ for (const { name, values } of groups) {
14403
+ const others = Object.fromEntries(Object.entries(picks).filter(([group]) => group !== name));
14404
+ const fitting = variants.filter((variant) => variantFits(variant, others));
14405
+ disabled[name] = new Set(values.filter((value) => !fitting.some((variant) => variantFits(variant, { [name]: value }))));
13377
14406
  }
13378
- if (value.dateRange) {
13379
- query.dateRange = { after: dayStart(value.dateRange.from, timezone), before: dayStart(nextDay(value.dateRange.to), timezone) };
14407
+ return disabled;
14408
+ }
14409
+
14410
+ // src/sale/in-cart.ts
14411
+ function cartQuantities(lines) {
14412
+ const quantities = /* @__PURE__ */ new Map();
14413
+ for (const line of lines) {
14414
+ if (line.custom) continue;
14415
+ quantities.set(line.productId, (quantities.get(line.productId) ?? 0) + line.quantity);
13380
14416
  }
13381
- return query;
14417
+ return quantities;
14418
+ }
14419
+
14420
+ // src/outbox/http-transport.ts
14421
+ import { COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, NEEDS_ADMIN_MESSAGE_MAX, isCommandBatchResponse } from "@tallyui/core";
14422
+
14423
+ // src/outbox/needs-admin-reason.ts
14424
+ var NEEDS_ADMIN_RETRY_PREFIX = "needs_admin:";
14425
+ var NEEDS_ADMIN_REASON = /^[a-z][a-z0-9_]{0,39}$/;
14426
+ function needsAdminReasonOf(retryReason) {
14427
+ if (!retryReason.startsWith(NEEDS_ADMIN_RETRY_PREFIX)) return void 0;
14428
+ const reason = retryReason.slice(NEEDS_ADMIN_RETRY_PREFIX.length);
14429
+ return NEEDS_ADMIN_REASON.test(reason) ? reason : void 0;
13382
14430
  }
13383
14431
 
13384
14432
  // src/outbox/http-transport.ts
13385
- import { COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, isCommandBatchResponse } from "@tallyui/core";
13386
14433
  var PERMANENT_STATUSES = /* @__PURE__ */ new Set([400, 403, 413, 415, 422]);
13387
14434
  function createHttpCommandTransport(options) {
13388
14435
  const fetch = options.fetch ?? globalThis.fetch;
@@ -13424,6 +14471,20 @@ function createHttpCommandTransport(options) {
13424
14471
  }
13425
14472
  return { kind: "refused", status: response.status, reason };
13426
14473
  }
14474
+ if (response.status === 409) {
14475
+ try {
14476
+ const body2 = await response.json();
14477
+ if (typeof body2 === "object" && body2 !== null && body2.code === "needs_admin" && typeof body2.id === "string" && batch.some((command) => command.id === body2.id) && typeof body2.reason === "string" && NEEDS_ADMIN_REASON.test(body2.reason) && typeof body2.message === "string") {
14478
+ return { ...retry(`${NEEDS_ADMIN_RETRY_PREFIX}${body2.reason}`), needsAdmin: {
14479
+ id: body2.id,
14480
+ reason: body2.reason,
14481
+ message: body2.message.slice(0, NEEDS_ADMIN_MESSAGE_MAX)
14482
+ } };
14483
+ }
14484
+ } catch {
14485
+ }
14486
+ return retry("status_409");
14487
+ }
13427
14488
  if (response.status !== 200) return retry(`status_${response.status}`);
13428
14489
  let body;
13429
14490
  try {
@@ -13442,15 +14503,15 @@ function createHttpCommandTransport(options) {
13442
14503
  }
13443
14504
 
13444
14505
  // src/outbox/use-register-outbox.ts
13445
- import { useEffect as useEffect11, useRef as useRef9, useState as useState10 } from "react";
14506
+ import { useEffect as useEffect13, useRef as useRef9, useState as useState12 } from "react";
13446
14507
  var idle = { pending: 0, sending: false };
13447
14508
  function useRegisterOutbox(options) {
13448
14509
  const { commands, sessions, deviceId } = options;
13449
14510
  const latest = useRef9(options);
13450
14511
  latest.current = options;
13451
14512
  const current = useRef9(null);
13452
- const [state, setState] = useState10(idle);
13453
- useEffect11(() => {
14513
+ const [state, setState] = useState12(idle);
14514
+ useEffect13(() => {
13454
14515
  setState(idle);
13455
14516
  if (!commands) return;
13456
14517
  const outbox = createRegisterOutbox({
@@ -13489,7 +14550,7 @@ function useRegisterOutbox(options) {
13489
14550
  }
13490
14551
 
13491
14552
  // src/outbox/use-order-outbox.ts
13492
- import { useEffect as useEffect12, useMemo as useMemo8, useRef as useRef10, useState as useState11 } from "react";
14553
+ import { useEffect as useEffect14, useMemo as useMemo10, useRef as useRef10, useState as useState13 } from "react";
13493
14554
  var idle2 = { pending: 0, sending: false };
13494
14555
  var noneStuck = [];
13495
14556
  function useOrderOutbox(options) {
@@ -13499,12 +14560,12 @@ function useOrderOutbox(options) {
13499
14560
  const current = useRef10(null);
13500
14561
  const openingError = useRef10(null);
13501
14562
  const loggedMismatches = useRef10(/* @__PURE__ */ new Set());
13502
- const [orders, setOrders] = useState11(null);
13503
- const [state, setState] = useState11(idle2);
13504
- const [recent, setRecent] = useState11([]);
14563
+ const [orders, setOrders] = useState13(null);
14564
+ const [state, setState] = useState13(idle2);
14565
+ const [recent, setRecent] = useState13([]);
13505
14566
  const savesInFlight = useRef10(0);
13506
- const [savesInFlightCount, setSavesInFlightCount] = useState11(0);
13507
- useEffect12(() => {
14567
+ const [savesInFlightCount, setSavesInFlightCount] = useState13(0);
14568
+ useEffect14(() => {
13508
14569
  let active = true;
13509
14570
  let dispose;
13510
14571
  openingError.current = null;
@@ -13547,13 +14608,13 @@ function useOrderOutbox(options) {
13547
14608
  dispose?.();
13548
14609
  };
13549
14610
  }, [storeKey, deviceId]);
13550
- useEffect12(() => {
14611
+ useEffect14(() => {
13551
14612
  latest.current.onBusy?.(state.sending);
13552
14613
  return () => latest.current.onBusy?.(false);
13553
14614
  }, [state.sending]);
13554
14615
  const ready = current.current?.storeKey === storeKey && !!storeKey;
13555
14616
  const stuckKey = ready ? state.stuck?.commandIds.join(",") ?? "" : "";
13556
- const stuckCommandIds = useMemo8(() => stuckKey ? stuckKey.split(",") : noneStuck, [stuckKey]);
14617
+ const stuckCommandIds = useMemo10(() => stuckKey ? stuckKey.split(",") : noneStuck, [stuckKey]);
13557
14618
  return {
13558
14619
  orders: ready ? orders : null,
13559
14620
  state: ready ? state : idle2,
@@ -13593,7 +14654,14 @@ function useOrderOutbox(options) {
13593
14654
  });
13594
14655
  }
13595
14656
  }
13596
- if (current.current === opened) void opened.outbox.flush();
14657
+ if (current.current === opened) {
14658
+ try {
14659
+ await refreshOutboxState(opened.outbox);
14660
+ } catch (cause) {
14661
+ outboxLogger.warn("Failed to refresh the outbox state", { cause });
14662
+ }
14663
+ if (current.current === opened) void opened.outbox.flush();
14664
+ }
13597
14665
  } finally {
13598
14666
  savesInFlight.current--;
13599
14667
  setSavesInFlightCount(savesInFlight.current);
@@ -13634,10 +14702,10 @@ function watchOutboxHealth(sales$, tillUpdates$) {
13634
14702
  }
13635
14703
 
13636
14704
  // src/outbox/use-outbox-health.ts
13637
- import { useMemo as useMemo9 } from "react";
14705
+ import { useMemo as useMemo11 } from "react";
13638
14706
  function useOutboxHealth(options) {
13639
14707
  const { sales, tillUpdates } = options;
13640
- const health = useMemo9(() => summarizeOutboxHealth(sales.state, tillUpdates.state), [sales.state, tillUpdates.state]);
14708
+ const health = useMemo11(() => summarizeOutboxHealth(sales.state, tillUpdates.state), [sales.state, tillUpdates.state]);
13641
14709
  return { health, async flush() {
13642
14710
  await Promise.all([sales.flush(), tillUpdates.flush()]);
13643
14711
  } };
@@ -13649,594 +14717,318 @@ async function sendOrderRefund(transport, envelope2) {
13649
14717
  let outcome;
13650
14718
  try {
13651
14719
  outcome = await transport.send([envelope2]);
13652
- } catch {
13653
- return { kind: "unknown", reason: "transport_error" };
13654
- }
13655
- if (outcome.kind === "retry") {
13656
- return {
13657
- kind: "unknown",
13658
- reason: outcome.reason,
13659
- ...outcome.retryAfterMs !== void 0 ? { retryAfterMs: outcome.retryAfterMs } : {}
13660
- };
13661
- }
13662
- if (outcome.kind === "refused" || outcome.kind === "unauthorized") return outcome;
13663
- const matches = outcome.results.filter((result2) => result2.id === envelope2.id);
13664
- if (matches.length !== 1) return { kind: "unknown", reason: "missing_result" };
13665
- let result;
13666
- try {
13667
- result = parseCommandResult(matches[0]);
13668
- } catch {
13669
- return { kind: "unknown", reason: "bad_result" };
13670
- }
13671
- if (result.status === "applied" || result.status === "duplicate") {
13672
- if (!result.refund) return { kind: "unknown", reason: "bad_result" };
13673
- return { kind: "applied", refund: result.refund, duplicate: result.status === "duplicate" };
13674
- }
13675
- return { kind: "rejected", error: result.error };
13676
- }
13677
-
13678
- // src/refund/pos-refund.ts
13679
- var posRefundSchema = {
13680
- title: "POS refunds",
13681
- version: 0,
13682
- primaryKey: "id",
13683
- type: "object",
13684
- additionalProperties: false,
13685
- properties: {
13686
- id: { type: "string", maxLength: 64 },
13687
- commandId: { type: "string", maxLength: 64 },
13688
- orderId: { type: "string", maxLength: 64 },
13689
- sessionId: { type: "string", maxLength: 64 },
13690
- registerId: { type: "string", maxLength: 64 },
13691
- envelope: { type: "object", additionalProperties: true },
13692
- status: { type: "string", enum: ["pending", "applied", "rejected", "unsent"], maxLength: 10 },
13693
- result: { type: "object", additionalProperties: true },
13694
- duplicate: { type: "boolean" },
13695
- error: { type: "object", properties: {
13696
- code: { type: "string" },
13697
- message: { type: "string" },
13698
- data: { type: "object", additionalProperties: true }
13699
- }, required: ["code", "message"], additionalProperties: false },
13700
- createdAt: { type: "string" },
13701
- updatedAt: { type: "string" }
13702
- },
13703
- required: ["id", "commandId", "orderId", "sessionId", "registerId", "envelope", "status", "createdAt", "updatedAt"],
13704
- indexes: [["sessionId"]]
13705
- };
13706
- var posRefundCollection = () => ({ schema: posRefundSchema });
13707
-
13708
- // src/refund/submit-order-refund.ts
13709
- import { RxError } from "rxdb";
13710
- var RefundAnswerPendingError = class extends Error {
13711
- constructor(record) {
13712
- super("This refund's answer is still unknown. Send it again before trying a new refund attempt.");
13713
- this.record = record;
13714
- this.name = "RefundAnswerPendingError";
13715
- }
13716
- code = "REFUND_ANSWER_PENDING";
13717
- };
13718
- async function submitOrderRefund({ refunds, transport, envelope: envelope2, now = () => (/* @__PURE__ */ new Date()).toISOString() }) {
13719
- const id2 = envelope2.payload.clientRefundId;
13720
- let doc = await refunds.findOne(id2).exec();
13721
- if (!doc) {
13722
- const at2 = now();
13723
- const { orderId, sessionId, registerId } = envelope2.payload;
13724
- try {
13725
- doc = await refunds.insert({
13726
- id: id2,
13727
- commandId: envelope2.id,
13728
- orderId,
13729
- sessionId,
13730
- registerId,
13731
- envelope: envelope2,
13732
- status: "pending",
13733
- createdAt: at2,
13734
- updatedAt: at2
13735
- });
13736
- } catch (error) {
13737
- if (!(error instanceof RxError) || error.code !== "CONFLICT") throw error;
13738
- doc = await refunds.findOne(id2).exec();
13739
- }
13740
- }
13741
- let record = doc.toJSON();
13742
- for (let pass = 0; ; pass++) {
13743
- if (pass === 2) throw new RefundAnswerPendingError(record);
13744
- if (record.status === "applied") {
13745
- return { outcome: { kind: "applied", refund: record.result, duplicate: true }, record };
13746
- }
13747
- if (record.status === "pending") {
13748
- if (record.commandId !== envelope2.id) throw new RefundAnswerPendingError(record);
13749
- break;
13750
- }
13751
- if (record.status === "rejected" && record.commandId === envelope2.id) {
13752
- return { outcome: { kind: "rejected", error: record.error }, record };
13753
- }
13754
- if (record.status === "unsent" && record.commandId === envelope2.id) {
13755
- doc = await doc.incrementalModify((stored) => {
13756
- if (stored.status !== "unsent" || stored.commandId !== envelope2.id) return stored;
13757
- const { error, ...rest } = stored;
13758
- return { ...rest, status: "pending", updatedAt: now() };
13759
- });
13760
- record = doc.toJSON();
13761
- continue;
13762
- }
13763
- doc = await doc.incrementalModify((stored) => {
13764
- if (stored.status !== "rejected" && stored.status !== "unsent") return stored;
13765
- const { result, duplicate, error, ...rest } = stored;
13766
- return { ...rest, commandId: envelope2.id, envelope: envelope2, status: "pending", updatedAt: now() };
13767
- });
13768
- record = doc.toJSON();
13769
- if (record.commandId === envelope2.id) break;
13770
- }
13771
- const outcome = await sendOrderRefund(transport, envelope2);
13772
- if (outcome.kind !== "unknown") {
13773
- doc = await doc.incrementalModify((stored) => {
13774
- if (stored.status !== "pending" || stored.commandId !== envelope2.id) return stored;
13775
- const updatedAt = now();
13776
- if (outcome.kind === "applied") {
13777
- const { error: error2, ...rest } = stored;
13778
- return { ...rest, status: "applied", result: outcome.refund, duplicate: outcome.duplicate, updatedAt };
13779
- }
13780
- if (outcome.kind === "rejected") return { ...stored, status: "rejected", error: outcome.error, updatedAt };
13781
- const error = outcome.kind === "refused" ? { code: "refused", message: outcome.reason, data: { status: outcome.status } } : { code: "unauthorized", message: "unauthorized" };
13782
- return { ...stored, status: "unsent", error, updatedAt };
13783
- });
13784
- }
13785
- return { outcome, record: doc.getLatest().toJSON() };
13786
- }
13787
-
13788
- // src/refund/refundable-lines.ts
13789
- function refundableLines(lines, refunds) {
13790
- const earlier = refunds.flatMap((refund) => refund.lines);
13791
- for (const refund of earlier) {
13792
- if (!Number.isSafeInteger(refund.quantity)) throw new RangeError("Earlier refund quantity must be a safe integer");
13793
- }
13794
- return lines.map((line) => {
13795
- if (!Number.isSafeInteger(line.quantity) || line.quantity < 0 || !Number.isSafeInteger(line.totalMinor) || !Number.isSafeInteger(line.taxMinor)) {
13796
- throw new RangeError("Order line values must be safe integers and quantity non-negative");
13797
- }
13798
- const refundedQuantity = earlier.reduce((sum4, refund) => refund.orderLineId === line.id ? Math.min(line.quantity, sum4 + Math.abs(refund.quantity)) : sum4, 0);
13799
- const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) => line.quantity === 0 ? 0 : total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), "half_up")));
13800
- return {
13801
- orderLineId: line.id,
13802
- refundedQuantity,
13803
- refundableQuantity: line.quantity - refundedQuantity,
13804
- netMinor,
13805
- taxMinor
13806
- };
13807
- });
13808
- }
13809
- function priceRefund(lines, refunds, request) {
13810
- const available = refundableLines(lines, refunds);
13811
- const seen = /* @__PURE__ */ new Set();
13812
- const result = { lines: [], priced: [], clamped: [], netMinor: 0, taxMinor: 0, totalMinor: 0 };
13813
- for (const { orderLineId, quantity: requestedQuantity, restock } of request) {
13814
- if (!Number.isSafeInteger(requestedQuantity) || requestedQuantity < 0 || seen.has(orderLineId)) {
13815
- throw new RangeError("Request quantities must be non-negative safe integers and line ids unique");
13816
- }
13817
- seen.add(orderLineId);
13818
- const index = lines.findIndex((line2) => line2.id === orderLineId);
13819
- const quantity = Math.min(requestedQuantity, available[index]?.refundableQuantity ?? 0);
13820
- if (quantity < requestedQuantity) result.clamped.push({ orderLineId, requestedQuantity, quantity });
13821
- if (quantity < 1) continue;
13822
- const line = lines[index];
13823
- const refundedQuantity = available[index].refundedQuantity;
13824
- const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) => Number(roundRatio(BigInt(refundedQuantity + quantity) * BigInt(total), BigInt(line.quantity), "half_up")) - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), "half_up")));
13825
- const totalMinor = netMinor + taxMinor;
13826
- result.lines.push({ orderLineId, quantity, restock });
13827
- result.priced.push({ orderLineId, quantity, netMinor, taxMinor, totalMinor });
13828
- result.netMinor += netMinor;
13829
- result.taxMinor += taxMinor;
13830
- result.totalMinor += totalMinor;
13831
- }
13832
- return result;
13833
- }
13834
-
13835
- // src/reopen/send-order-reopen.ts
13836
- import { parseCommandResult as parseCommandResult2 } from "@tallyui/core";
13837
- var inFlight = /* @__PURE__ */ new Set();
13838
- async function sendOrderReopen(transport, envelope2) {
13839
- const orderId = envelope2.payload.orderId;
13840
- if (inFlight.has(orderId)) return { kind: "in_flight" };
13841
- inFlight.add(orderId);
13842
- try {
13843
- let outcome;
13844
- try {
13845
- outcome = await transport.send([envelope2]);
13846
- } catch {
13847
- return { kind: "unknown", reason: "transport_error" };
13848
- }
13849
- if (outcome.kind === "retry") {
13850
- return {
13851
- kind: "unknown",
13852
- reason: outcome.reason,
13853
- ...outcome.retryAfterMs !== void 0 ? { retryAfterMs: outcome.retryAfterMs } : {}
13854
- };
13855
- }
13856
- if (outcome.kind === "refused" || outcome.kind === "unauthorized") return outcome;
13857
- const matches = outcome.results.filter((result2) => result2.id === envelope2.id);
13858
- if (matches.length !== 1) return { kind: "unknown", reason: "missing_result" };
13859
- let result;
13860
- try {
13861
- result = parseCommandResult2(matches[0]);
13862
- } catch {
13863
- return { kind: "unknown", reason: "bad_result" };
13864
- }
13865
- if (result.status === "applied" || result.status === "duplicate") {
13866
- if (!result.reopen) return { kind: "unknown", reason: "bad_result" };
13867
- return { kind: "applied", reopen: result.reopen, duplicate: result.status === "duplicate" };
13868
- }
13869
- return { kind: "rejected", error: result.error };
13870
- } finally {
13871
- inFlight.delete(orderId);
13872
- }
13873
- }
13874
- function isOrderReopenInFlight(orderId) {
13875
- return inFlight.has(orderId);
13876
- }
13877
- function isReopenOffered(input) {
13878
- return (input.orderReopen ?? 0) >= 1 && (input.orderCreate ?? 0) >= 5 && input.online && !input.storageDegraded && !isOrderReopenInFlight(input.orderId);
13879
- }
13880
-
13881
- // src/reopen/reopen-entry.ts
13882
- var REOPEN_REFUSED_STATUSES = ["cancelled", "failed", "trash"];
13883
- var ReopenEntryError = class extends Error {
13884
- constructor(reason, message) {
13885
- super(message);
13886
- this.reason = reason;
13887
- this.name = "ReopenEntryError";
13888
- }
13889
- };
13890
- function storeOrderForReopen(read, options) {
13891
- if (REOPEN_REFUSED_STATUSES.includes(read.status.toLowerCase())) {
13892
- throw new ReopenEntryError("status", `An order that is ${read.status.toLowerCase()} cannot be reopened`);
13893
- }
13894
- const lineTaxes = /* @__PURE__ */ new Map();
13895
- for (const line of read.lines) {
13896
- if (!line.productId) continue;
13897
- const tax = options.catalogue(line);
13898
- if (tax === null) throw new ReopenEntryError("catalogue", `"${line.name}" is no longer in the till's catalogue`);
13899
- lineTaxes.set(line, tax);
13900
- }
13901
- let builder;
13902
- try {
13903
- builder = orderBuilderFromStoreOrder(read, {
13904
- currency: options.currency,
13905
- taxContext: options.taxContext,
13906
- lineTax: (line) => lineTaxes.get(line)
13907
- });
13908
- } catch (error) {
13909
- if (error instanceof StoreOrderRebuildError) throw new ReopenEntryError(error.reason, error.message);
13910
- throw error;
13911
- }
13912
- if (read.payments.reduce((sum4, payment) => sum4 + payment.amountMinor, 0) > read.totalMinor) {
13913
- throw new ReopenEntryError("overpaid", "This order is paid more than its total");
13914
- }
13915
- return builder;
13916
- }
13917
-
13918
- // src/reopen/reopen-store-order.ts
13919
- var REOPENED_NOT_LOADED = "The store has reopened this order, but the till could not load it. Check the order in the store before trying again.";
13920
- var STORE_ORDER_OPEN_HERE = "This order is already open on this till. Find it in the current sale or the parked sales.";
13921
- async function reopenStoreOrder(read, deps) {
13922
- const options = { currency: deps.currency, taxContext: deps.taxContext, catalogue: deps.catalogue };
13923
- try {
13924
- storeOrderForReopen(read, { ...options, taxContext: deps.taxContextFor ? deps.taxContextFor(storeOrderCustomer(read)).taxContext : deps.taxContext });
13925
- } catch (error) {
13926
- if (error instanceof ReopenEntryError) return { kind: "refused", reason: error.reason, message: error.message };
13927
- throw error;
14720
+ } catch {
14721
+ return { kind: "unknown", reason: "transport_error" };
13928
14722
  }
13929
- if (await deps.openHere(read.id)) return { kind: "refused", reason: "open_here", message: STORE_ORDER_OPEN_HERE };
13930
- if (deps.resend && deps.resend.payload.orderId !== read.id) throw new Error("reopenStoreOrder: resend is for another order");
13931
- const at2 = deps.resend ? 0 : (deps.now ?? Date.now)(), createdAt = new Date(at2).toISOString();
13932
- const { cashierRef, registerId, storeId, deviceId } = deps.identity;
13933
- const envelope2 = deps.resend ? { ...deps.resend, attempt: deps.resend.attempt + 1 } : {
13934
- id: uuidv7(at2),
13935
- type: "order.reopen",
13936
- version: 1,
13937
- createdAt,
13938
- deviceId,
13939
- attempt: 1,
13940
- payload: {
13941
- orderId: read.id,
13942
- ...read.clientOrderId !== void 0 ? { clientOrderId: read.clientOrderId } : {},
13943
- baseRevision: read.revision,
13944
- cashierRef,
13945
- registerId,
13946
- ...storeId !== void 0 ? { storeId } : {},
13947
- createdAt
14723
+ if (outcome.kind === "retry") {
14724
+ const { needsAdmin } = outcome;
14725
+ if (needsAdmin?.id === envelope2.id) {
14726
+ return { kind: "needs_admin", reason: needsAdmin.reason, message: needsAdmin.message };
13948
14727
  }
13949
- };
13950
- const outcome = await sendOrderReopen(deps.transport, envelope2);
13951
- if (outcome.kind !== "applied") return { kind: "not_reopened", outcome, envelope: envelope2 };
13952
- let reread;
14728
+ return {
14729
+ kind: "unknown",
14730
+ reason: outcome.reason,
14731
+ ...outcome.retryAfterMs !== void 0 ? { retryAfterMs: outcome.retryAfterMs } : {}
14732
+ };
14733
+ }
14734
+ if (outcome.kind === "refused" || outcome.kind === "unauthorized") return outcome;
14735
+ const matches = outcome.results.filter((result2) => result2.id === envelope2.id);
14736
+ if (matches.length !== 1) return { kind: "unknown", reason: "missing_result" };
14737
+ let result;
13953
14738
  try {
13954
- reread = (await deps.getOrders([read.id])).find((order) => order.id === read.id);
14739
+ result = parseCommandResult(matches[0]);
13955
14740
  } catch {
13956
- return { kind: "reopened_unloadable", reason: "reread", message: `${REOPENED_NOT_LOADED} The order could not be read again.` };
14741
+ return { kind: "unknown", reason: "bad_result" };
13957
14742
  }
13958
- if (!reread) return { kind: "reopened_unloadable", reason: "reread", message: `${REOPENED_NOT_LOADED} The order could not be read again.` };
13959
- if (outcome.reopen.revision !== void 0 && reread.revision !== outcome.reopen.revision)
13960
- return { kind: "reopened_unloadable", reason: "reread", message: `${REOPENED_NOT_LOADED} The order read back does not match the reopen.` };
13961
- try {
13962
- const builder = storeOrderForReopen(reread, { ...options, taxContext: deps.taxContextFor ? deps.taxContextFor(storeOrderCustomer(reread)).taxContext : deps.taxContext });
13963
- return { kind: "reopened", order: builder.getSnapshot(), duplicate: outcome.duplicate };
13964
- } catch (error) {
13965
- if (error instanceof ReopenEntryError) return { kind: "reopened_unloadable", reason: error.reason, message: `${REOPENED_NOT_LOADED} ${error.message}` };
13966
- throw error;
14743
+ if (result.status === "applied" || result.status === "duplicate") {
14744
+ if (!result.refund) return { kind: "unknown", reason: "bad_result" };
14745
+ return { kind: "applied", refund: result.refund, duplicate: result.status === "duplicate" };
13967
14746
  }
14747
+ return { kind: "rejected", error: result.error };
13968
14748
  }
13969
14749
 
13970
- // src/tender/tender-state.ts
13971
- var MAX_TENDER_MINOR = 999999999;
13972
- var initialTenderState = {
13973
- view: "select",
13974
- methodId: null,
13975
- readerId: null,
13976
- transport: null,
13977
- entryMinor: 0,
13978
- entryDirty: false,
13979
- entryMode: "money",
13980
- plan: null,
13981
- splitView: false,
13982
- splitTab: "even",
13983
- pickedLineIds: [],
13984
- linesPaidBy: {},
13985
- pickedUnits: {},
13986
- unitAllocations: {}
14750
+ // src/refund/needs-admin-line.ts
14751
+ function refundNeedsAdminLine(reason) {
14752
+ return reason === "session_closed" ? "Not paid. This refund needs a manager to finish it in the store admin." : "Not finished. A manager must check this refund in the store admin before any money is handed over.";
14753
+ }
14754
+
14755
+ // src/refund/pos-refund.ts
14756
+ var posRefundSchema = {
14757
+ title: "POS refunds",
14758
+ version: 0,
14759
+ primaryKey: "id",
14760
+ type: "object",
14761
+ additionalProperties: false,
14762
+ properties: {
14763
+ id: { type: "string", maxLength: 64 },
14764
+ commandId: { type: "string", maxLength: 64 },
14765
+ orderId: { type: "string", maxLength: 64 },
14766
+ sessionId: { type: "string", maxLength: 64 },
14767
+ registerId: { type: "string", maxLength: 64 },
14768
+ envelope: { type: "object", additionalProperties: true },
14769
+ status: { type: "string", enum: ["pending", "applied", "rejected", "unsent"], maxLength: 10 },
14770
+ result: { type: "object", additionalProperties: true },
14771
+ duplicate: { type: "boolean" },
14772
+ error: { type: "object", properties: {
14773
+ code: { type: "string" },
14774
+ message: { type: "string" },
14775
+ data: { type: "object", additionalProperties: true }
14776
+ }, required: ["code", "message"], additionalProperties: false },
14777
+ createdAt: { type: "string" },
14778
+ updatedAt: { type: "string" }
14779
+ },
14780
+ required: ["id", "commandId", "orderId", "sessionId", "registerId", "envelope", "status", "createdAt", "updatedAt"],
14781
+ indexes: [["sessionId"]]
13987
14782
  };
13988
- function initTenderState({
13989
- methodId,
13990
- balanceMinor,
13991
- payments
13992
- }) {
13993
- const state = payments ? { ...initialTenderState, unitAllocations: unitAllocationsFromLegs(payments ?? []) } : initialTenderState;
13994
- if (!methodId) return state;
13995
- return { ...state, view: "amount", methodId, entryMinor: balanceMinor };
14783
+ var posRefundCollection = () => ({ schema: posRefundSchema });
14784
+
14785
+ // src/refund/submit-order-refund.ts
14786
+ import { RxError } from "rxdb";
14787
+ var RefundAnswerPendingError = class extends Error {
14788
+ constructor(record2) {
14789
+ super("This refund's answer is still unknown. Send it again before trying a new refund attempt.");
14790
+ this.record = record2;
14791
+ this.name = "RefundAnswerPendingError";
14792
+ }
14793
+ code = "REFUND_ANSWER_PENDING";
14794
+ };
14795
+ var inFlight = /* @__PURE__ */ new WeakMap();
14796
+ async function submitOrderRefund(args) {
14797
+ const { refunds, envelope: envelope2 } = args;
14798
+ let calls = inFlight.get(refunds);
14799
+ if (!calls) {
14800
+ calls = /* @__PURE__ */ new Map();
14801
+ inFlight.set(refunds, calls);
14802
+ }
14803
+ const key = `${envelope2.payload.clientRefundId} ${envelope2.id}`;
14804
+ const run = (calls.get(key) ?? Promise.resolve()).catch(() => void 0).then(() => submitOnce(args));
14805
+ calls.set(key, run);
14806
+ try {
14807
+ return await run;
14808
+ } finally {
14809
+ if (calls.get(key) === run) calls.delete(key);
14810
+ }
13996
14811
  }
13997
- function tenderReducer(state, action) {
13998
- switch (action.type) {
13999
- case "pick-method":
14000
- return {
14001
- ...state,
14002
- view: "amount",
14003
- methodId: action.methodId,
14004
- readerId: action.readerId,
14005
- transport: action.transport ?? null,
14006
- entryMinor: state.entryDirty ? state.entryMinor : action.prefillMinor,
14007
- entryDirty: state.entryDirty
14008
- };
14009
- case "pick-transport":
14010
- return { ...state, transport: action.transport };
14011
- case "pick-reader":
14012
- return { ...state, readerId: action.readerId };
14013
- case "key": {
14014
- if (state.view !== "amount") {
14015
- return state;
14016
- }
14017
- if (action.key === "backspace") {
14018
- return { ...state, entryMinor: Math.floor(state.entryMinor / 10), entryDirty: true };
14019
- }
14020
- if (action.key === "clear") {
14021
- return { ...state, entryMinor: 0, entryDirty: true };
14022
- }
14023
- const digit = Number(action.key);
14024
- if (!state.entryDirty) {
14025
- return { ...state, entryMinor: digit, entryDirty: true };
14026
- }
14027
- const entryMinor = state.entryMinor * 10 + digit;
14028
- return entryMinor > MAX_TENDER_MINOR ? state : { ...state, entryMinor };
14812
+ async function submitOnce({ refunds, transport, envelope: envelope2, now = () => (/* @__PURE__ */ new Date()).toISOString() }) {
14813
+ const id2 = envelope2.payload.clientRefundId;
14814
+ let mayBeHeld = true;
14815
+ let doc = await refunds.findOne(id2).exec();
14816
+ if (!doc) {
14817
+ const at2 = now();
14818
+ const { orderId, sessionId, registerId } = envelope2.payload;
14819
+ try {
14820
+ doc = await refunds.insert({
14821
+ id: id2,
14822
+ commandId: envelope2.id,
14823
+ orderId,
14824
+ sessionId,
14825
+ registerId,
14826
+ envelope: envelope2,
14827
+ status: "pending",
14828
+ createdAt: at2,
14829
+ updatedAt: at2
14830
+ });
14831
+ mayBeHeld = false;
14832
+ } catch (error) {
14833
+ if (!(error instanceof RxError) || error.code !== "CONFLICT") throw error;
14834
+ doc = await refunds.findOne(id2).exec();
14029
14835
  }
14030
- case "set-entry":
14031
- return {
14032
- ...state,
14033
- entryMinor: Math.max(0, Math.min(action.minor, MAX_TENDER_MINOR)),
14034
- entryDirty: true
14035
- };
14036
- case "set-entry-mode":
14037
- return { ...state, entryMode: action.mode, entryMinor: 0, entryDirty: false };
14038
- case "tender-started": {
14039
- const leg = action.units ?? state.pickedUnits;
14040
- const freeze = action.paymentId !== void 0 && Object.keys(leg).length > 0;
14041
- const clear = action.paymentId !== void 0 && Object.keys(state.pickedUnits).length > 0;
14042
- const units = {
14043
- ...freeze ? { unitAllocations: { ...state.unitAllocations, [String(action.paymentId)]: leg } } : {},
14044
- ...clear ? { pickedUnits: {} } : {}
14045
- };
14046
- return { ...state, entryMinor: 0, entryDirty: false, entryMode: "money", splitView: false, ...units };
14836
+ }
14837
+ let record2 = doc.toJSON();
14838
+ for (let pass = 0; ; pass++) {
14839
+ if (pass === 2) throw new RefundAnswerPendingError(record2);
14840
+ if (record2.status === "applied") {
14841
+ return { outcome: { kind: "applied", refund: record2.result, duplicate: true }, record: record2 };
14047
14842
  }
14048
- case "back":
14049
- return {
14050
- ...state,
14051
- view: "select",
14052
- methodId: null,
14053
- readerId: null,
14054
- transport: null,
14055
- entryMinor: 0,
14056
- entryDirty: false,
14057
- entryMode: "money"
14058
- };
14059
- case "tender-recorded": {
14060
- const linesPaidBy = { ...state.linesPaidBy };
14061
- if (state.plan?.kind === "items" && action.rowsSinceFrom.reduce((sum4, row) => sum4 + row.amountMinor, 0) >= state.plan.firstMinor) {
14062
- for (const id2 of state.plan.lineIds) {
14063
- linesPaidBy[id2] ??= [...new Set(action.rowsSinceFrom.map((row) => row.title))];
14064
- }
14065
- } else if (state.plan?.kind === "items") {
14066
- for (const id2 of state.plan.lineIds) {
14067
- delete linesPaidBy[id2];
14068
- }
14843
+ if (record2.status === "pending") {
14844
+ if (record2.commandId !== envelope2.id) throw new RefundAnswerPendingError(record2);
14845
+ break;
14846
+ }
14847
+ if (record2.status === "rejected" && record2.commandId === envelope2.id) {
14848
+ return { outcome: { kind: "rejected", error: record2.error }, record: record2 };
14849
+ }
14850
+ if (record2.status === "unsent" && record2.commandId === envelope2.id) {
14851
+ doc = await doc.incrementalModify((stored) => {
14852
+ mayBeHeld = true;
14853
+ if (stored.status !== "unsent" || stored.commandId !== envelope2.id) return stored;
14854
+ const { error, ...rest } = stored;
14855
+ mayBeHeld = false;
14856
+ return { ...rest, status: "pending", updatedAt: now() };
14857
+ });
14858
+ record2 = doc.toJSON();
14859
+ continue;
14860
+ }
14861
+ doc = await doc.incrementalModify((stored) => {
14862
+ mayBeHeld = true;
14863
+ if (stored.status !== "rejected" && stored.status !== "unsent") return stored;
14864
+ const { result, duplicate, error, ...rest } = stored;
14865
+ mayBeHeld = false;
14866
+ return { ...rest, commandId: envelope2.id, envelope: envelope2, status: "pending", updatedAt: now() };
14867
+ });
14868
+ record2 = doc.toJSON();
14869
+ if (record2.commandId === envelope2.id) break;
14870
+ }
14871
+ const outcome = await sendOrderRefund(transport, envelope2);
14872
+ if (outcome.kind !== "unknown") {
14873
+ doc = await doc.incrementalModify((stored) => {
14874
+ if (stored.status !== "pending" || stored.commandId !== envelope2.id) return stored;
14875
+ if ((outcome.kind === "refused" || outcome.kind === "unauthorized") && (mayBeHeld || stored.error?.code === "needs_admin")) return stored;
14876
+ const updatedAt = now();
14877
+ if (outcome.kind === "needs_admin") {
14878
+ return { ...stored, error: {
14879
+ code: "needs_admin",
14880
+ message: outcome.message,
14881
+ data: { reason: outcome.reason, at: updatedAt }
14882
+ }, updatedAt };
14069
14883
  }
14070
- const rows = action.rowsSinceFrom.map((row) => ({
14071
- minor: row.amountMinor,
14072
- title: row.title
14073
- }));
14074
- const plan = activePlan(state.plan, rows.length, action.balanceMinor);
14075
- const entryMinor = plan ? planLegs(plan, rows, action.balanceMinor).thisPaymentMinor : action.balanceMinor;
14076
- return {
14077
- ...state,
14078
- view: state.methodId ? "amount" : "select",
14079
- entryMinor,
14080
- entryDirty: false,
14081
- entryMode: "money",
14082
- // Split closed means no picks: while units are picked (a leg recorded or settled elsewhere), Split stays open.
14083
- splitView: Object.keys(state.pickedUnits).length > 0 ? state.splitView : false,
14084
- pickedLineIds: [],
14085
- linesPaidBy
14086
- };
14884
+ if (outcome.kind === "applied") {
14885
+ const { error: error2, ...rest } = stored;
14886
+ return { ...rest, status: "applied", result: outcome.refund, duplicate: outcome.duplicate, updatedAt };
14887
+ }
14888
+ if (outcome.kind === "rejected") return { ...stored, status: "rejected", error: outcome.error, updatedAt };
14889
+ const error = outcome.kind === "refused" ? { code: "refused", message: outcome.reason, data: { status: outcome.status } } : { code: "unauthorized", message: "unauthorized" };
14890
+ return { ...stored, status: "unsent", error, updatedAt };
14891
+ });
14892
+ }
14893
+ return { outcome, record: doc.getLatest().toJSON() };
14894
+ }
14895
+
14896
+ // src/refund/refundable-lines.ts
14897
+ import { refundableLines, priceRefund } from "@tallyui/core";
14898
+
14899
+ // src/reopen/send-order-reopen.ts
14900
+ import { parseCommandResult as parseCommandResult2 } from "@tallyui/core";
14901
+ var inFlight2 = /* @__PURE__ */ new Set();
14902
+ async function sendOrderReopen(transport, envelope2) {
14903
+ const orderId = envelope2.payload.orderId;
14904
+ if (inFlight2.has(orderId)) return { kind: "in_flight" };
14905
+ inFlight2.add(orderId);
14906
+ try {
14907
+ let outcome;
14908
+ try {
14909
+ outcome = await transport.send([envelope2]);
14910
+ } catch {
14911
+ return { kind: "unknown", reason: "transport_error" };
14087
14912
  }
14088
- case "open-split":
14089
- return {
14090
- ...state,
14091
- splitView: true,
14092
- pickedLineIds: state.plan?.kind === "items" ? state.plan.lineIds.filter((id2) => !state.linesPaidBy[id2]) : state.pickedLineIds
14093
- };
14094
- // Split closed means no picks: every action that closes Split clears pickedUnits, except tender-recorded (above) and tender-started without a payment id (S5); allocations stay.
14095
- case "close-split":
14096
- return { ...state, splitView: false, pickedUnits: {} };
14097
- case "set-split-tab":
14098
- return { ...state, splitTab: action.tab };
14099
- case "toggle-split-line":
14100
- if (state.linesPaidBy[action.lineId]) return state;
14913
+ if (outcome.kind === "retry") {
14101
14914
  return {
14102
- ...state,
14103
- pickedLineIds: state.pickedLineIds.includes(action.lineId) ? state.pickedLineIds.filter((id2) => id2 !== action.lineId) : [...state.pickedLineIds, action.lineId]
14915
+ kind: "unknown",
14916
+ reason: outcome.reason,
14917
+ ...outcome.retryAfterMs !== void 0 ? { retryAfterMs: outcome.retryAfterMs } : {}
14104
14918
  };
14105
- case "set-split-units": {
14106
- if (!Number.isInteger(action.units) || action.units < 0) return state;
14107
- if (!Number.isInteger(action.unpaidUnits) || action.unpaidUnits < 0) return state;
14108
- if (state.plan && action.units > 0) return state;
14109
- const units = Math.min(action.units, action.unpaidUnits);
14110
- const next = { ...state.pickedUnits, [String(action.lineId)]: units };
14111
- return { ...state, pickedUnits: Object.fromEntries(Object.entries(next).filter(([, n]) => n > 0)) };
14112
14919
  }
14113
- case "set-plan":
14114
- return {
14115
- ...state,
14116
- plan: action.plan,
14117
- splitView: false,
14118
- pickedUnits: {},
14119
- pickedLineIds: [],
14120
- entryMinor: state.view === "amount" ? planLegs(action.plan, [], action.balanceMinor).thisPaymentMinor : state.entryMinor,
14121
- entryDirty: state.view !== "amount" && state.entryDirty,
14122
- entryMode: "money"
14123
- };
14124
- case "clear-plan":
14125
- case "arm-custom":
14126
- return {
14127
- ...state,
14128
- plan: null,
14129
- splitView: false,
14130
- pickedUnits: {},
14131
- view: action.type === "arm-custom" ? "amount" : state.view,
14132
- entryMinor: action.type === "clear-plan" ? action.balanceMinor : 0,
14133
- entryDirty: false,
14134
- entryMode: "money"
14135
- };
14136
- case "request-cancel":
14137
- return { ...state, view: "cancel", splitView: false, pickedUnits: {} };
14138
- case "reset":
14139
- return initialTenderState;
14920
+ if (outcome.kind === "refused" || outcome.kind === "unauthorized") return outcome;
14921
+ const matches = outcome.results.filter((result2) => result2.id === envelope2.id);
14922
+ if (matches.length !== 1) return { kind: "unknown", reason: "missing_result" };
14923
+ let result;
14924
+ try {
14925
+ result = parseCommandResult2(matches[0]);
14926
+ } catch {
14927
+ return { kind: "unknown", reason: "bad_result" };
14928
+ }
14929
+ if (result.status === "applied" || result.status === "duplicate") {
14930
+ if (!result.reopen) return { kind: "unknown", reason: "bad_result" };
14931
+ return { kind: "applied", reopen: result.reopen, duplicate: result.status === "duplicate" };
14932
+ }
14933
+ return { kind: "rejected", error: result.error };
14934
+ } finally {
14935
+ inFlight2.delete(orderId);
14140
14936
  }
14141
14937
  }
14142
- function appliedMinor(entryMinor, balanceMinor) {
14143
- return Math.max(0, Math.min(entryMinor, balanceMinor));
14938
+ function isOrderReopenInFlight(orderId) {
14939
+ return inFlight2.has(orderId);
14144
14940
  }
14145
- function changeMinor(entryMinor, appliedAmountMinor, givesChange) {
14146
- return givesChange ? Math.max(0, entryMinor - appliedAmountMinor) : 0;
14941
+ function isReopenOffered(input) {
14942
+ return (input.orderReopen ?? 0) >= 1 && (input.orderCreate ?? 0) >= 5 && input.online && !input.storageDegraded && !isOrderReopenInFlight(input.orderId);
14147
14943
  }
14148
- function quickTenderedAmounts(balanceMinor, stepsMinor) {
14149
- if (balanceMinor === 0) {
14150
- return [];
14944
+
14945
+ // src/reopen/reopen-entry.ts
14946
+ var REOPEN_REFUSED_STATUSES = ["cancelled", "failed", "trash"];
14947
+ var ReopenEntryError = class extends Error {
14948
+ constructor(reason, message) {
14949
+ super(message);
14950
+ this.reason = reason;
14951
+ this.name = "ReopenEntryError";
14151
14952
  }
14152
- const amounts = /* @__PURE__ */ new Set([balanceMinor]);
14153
- for (const stepMinor of stepsMinor) {
14154
- if (stepMinor <= 0) continue;
14155
- const remainder = balanceMinor % stepMinor;
14156
- amounts.add(remainder === 0 ? balanceMinor : balanceMinor + stepMinor - remainder);
14953
+ };
14954
+ function storeOrderForReopen(read, options) {
14955
+ if (REOPEN_REFUSED_STATUSES.includes(read.status.toLowerCase())) {
14956
+ throw new ReopenEntryError("status", `An order that is ${read.status.toLowerCase()} cannot be reopened`);
14157
14957
  }
14158
- return [...amounts].sort((left, right) => left - right);
14159
- }
14160
- function evenSplitShareMinor(balanceMinor, ways) {
14161
- if (ways < 2) {
14162
- return balanceMinor;
14958
+ const lineTaxes = /* @__PURE__ */ new Map();
14959
+ for (const line of read.lines) {
14960
+ if (!line.productId) continue;
14961
+ const tax = options.catalogue(line);
14962
+ if (tax === null) throw new ReopenEntryError("catalogue", `"${line.name}" is no longer in the till's catalogue`);
14963
+ lineTaxes.set(line, tax);
14163
14964
  }
14164
- const wholeShare = Math.floor(balanceMinor / ways);
14165
- const remainder = balanceMinor % ways;
14166
- return wholeShare + (remainder * 2 >= ways ? 1 : 0);
14167
- }
14168
- function percentOfMinor(balanceMinor, percent) {
14169
- return Math.max(0, Math.min(balanceMinor, Math.round(balanceMinor * percent / 100)));
14170
- }
14171
- function activePlan(plan, taken, balanceMinor) {
14172
- if (!plan || balanceMinor === 0) return null;
14173
- if (plan.kind !== "items" && taken >= (plan.kind === "even" ? plan.ways : 1 + (plan.thenWays ?? 1)))
14174
- return null;
14175
- return plan;
14176
- }
14177
- function planLegs(plan, rowsSinceFrom, balanceMinor) {
14178
- const taken = rowsSinceFrom.length;
14179
- const legs = rowsSinceFrom.map((row) => ({ ...row, state: "done" }));
14180
- const groupPaid = rowsSinceFrom.reduce((sum4, row) => sum4 + row.minor, 0);
14181
- const groupLeft = plan.kind === "items" ? Math.min(balanceMinor, Math.max(0, plan.firstMinor - groupPaid)) : balanceMinor;
14182
- const rest = plan.kind === "items" && groupLeft === 0;
14183
- const ways = plan.kind === "fixed" ? 1 + (plan.thenWays ?? 1) : Math.max(plan.ways, taken + 1);
14184
- const firstFixed = plan.kind === "fixed" && taken === 0;
14185
- const left = firstFixed || rest ? 1 : Math.max(1, ways - taken);
14186
- const amount = rest ? balanceMinor : groupLeft;
14187
- const each = plan.kind === "fixed" && taken === 0 ? Math.min(plan.firstMinor, balanceMinor) : evenSplitShareMinor(amount, left);
14188
- let remaining = amount;
14189
- for (let i = 0; i < left; i++) {
14190
- const minor2 = Math.min(remaining, i === left - 1 && !firstFixed ? remaining : each);
14191
- legs.push({ minor: minor2, state: i === 0 ? "now" : "todo" });
14192
- remaining -= minor2;
14965
+ let builder;
14966
+ try {
14967
+ builder = orderBuilderFromStoreOrder(read, {
14968
+ currency: options.currency,
14969
+ taxContext: options.taxContext,
14970
+ lineTax: (line) => lineTaxes.get(line)
14971
+ });
14972
+ } catch (error) {
14973
+ if (error instanceof StoreOrderRebuildError) throw new ReopenEntryError(error.reason, error.message);
14974
+ throw error;
14193
14975
  }
14194
- if (firstFixed && remaining > 0) {
14195
- const thenWays = plan.thenWays ?? 1;
14196
- const share = evenSplitShareMinor(remaining, thenWays);
14197
- for (let i = 0; i < thenWays; i++) {
14198
- const minor2 = Math.min(remaining, i === thenWays - 1 ? remaining : share);
14199
- legs.push({ minor: minor2, state: "todo" });
14200
- remaining -= minor2;
14201
- }
14976
+ if (read.payments.reduce((sum4, payment) => sum4 + payment.amountMinor, 0) > read.totalMinor) {
14977
+ throw new ReopenEntryError("overpaid", "This order is paid more than its total");
14202
14978
  }
14203
- if (plan.kind === "items" && !rest && balanceMinor > groupLeft)
14204
- legs.push({ minor: balanceMinor - groupLeft, state: "rest" });
14205
- const title = plan.kind === "fixed" && taken === 0 ? plan.title : null;
14206
- return { legs, thisPaymentMinor: each, label: { n: taken + 1, ways, rest, title } };
14979
+ return builder;
14207
14980
  }
14208
14981
 
14209
- // src/tender/cash-rounding.ts
14210
- function roundToIncrement(minor2, incrementMinor, mode) {
14211
- if (!Number.isInteger(incrementMinor) || incrementMinor <= 1) return minor2;
14212
- const remainder = minor2 % incrementMinor;
14213
- if (remainder === 0) return minor2;
14214
- const down = minor2 - remainder;
14215
- if (mode === "down") return down;
14216
- if (mode === "up") return down + incrementMinor;
14217
- return remainder * 2 >= incrementMinor ? down + incrementMinor : down;
14218
- }
14219
- function roundedDue(balanceMinor, method) {
14220
- const rounding = method?.capture.mode === "manual" ? method.defaults.rounding : null;
14221
- if (!rounding) return { dueMinor: balanceMinor, roundingMinor: 0 };
14222
- const dueMinor = roundToIncrement(balanceMinor, rounding.incrementMinor, rounding.mode);
14223
- return { dueMinor, roundingMinor: dueMinor - balanceMinor };
14224
- }
14225
- function settlesAtRoundedDue(facts) {
14226
- const { amountMinor, tenderedMinor, balanceMinor, dueMinor } = facts;
14227
- return amountMinor >= Math.min(balanceMinor, dueMinor) && tenderedMinor >= dueMinor;
14228
- }
14229
- function tenderRounding(state, balanceMinor, method) {
14230
- const roundedDueMinor = roundedDue(balanceMinor, method).dueMinor;
14231
- const entryMinor = !state.entryDirty && state.entryMinor === balanceMinor ? roundedDueMinor : state.entryMinor;
14232
- const legMinor = appliedMinor(entryMinor, balanceMinor);
14233
- const roundingMinor = settlesAtRoundedDue({
14234
- amountMinor: legMinor,
14235
- tenderedMinor: entryMinor,
14236
- balanceMinor,
14237
- dueMinor: roundedDueMinor
14238
- }) ? roundedDueMinor - balanceMinor : 0;
14239
- return { roundedDueMinor, roundingMinor, entryMinor, appliedMinor: roundingMinor !== 0 ? roundedDueMinor : legMinor };
14982
+ // src/reopen/reopen-store-order.ts
14983
+ var REOPENED_NOT_LOADED = "The store has reopened this order, but the till could not load it. Check the order in the store before trying again.";
14984
+ var STORE_ORDER_OPEN_HERE = "This order is already open on this till. Find it in the current sale or the parked sales.";
14985
+ async function reopenStoreOrder(read, deps) {
14986
+ const options = { currency: deps.currency, taxContext: deps.taxContext, catalogue: deps.catalogue };
14987
+ try {
14988
+ storeOrderForReopen(read, { ...options, taxContext: deps.taxContextFor ? deps.taxContextFor(storeOrderCustomer(read)).taxContext : deps.taxContext });
14989
+ } catch (error) {
14990
+ if (error instanceof ReopenEntryError) return { kind: "refused", reason: error.reason, message: error.message };
14991
+ throw error;
14992
+ }
14993
+ if (await deps.openHere(read.id)) return { kind: "refused", reason: "open_here", message: STORE_ORDER_OPEN_HERE };
14994
+ if (deps.resend && deps.resend.payload.orderId !== read.id) throw new Error("reopenStoreOrder: resend is for another order");
14995
+ const at2 = deps.resend ? 0 : (deps.now ?? Date.now)(), createdAt = new Date(at2).toISOString();
14996
+ const { cashierRef, registerId, storeId, deviceId } = deps.identity;
14997
+ const envelope2 = deps.resend ? { ...deps.resend, attempt: deps.resend.attempt + 1 } : {
14998
+ id: uuidv7(at2),
14999
+ type: "order.reopen",
15000
+ version: 1,
15001
+ createdAt,
15002
+ deviceId,
15003
+ attempt: 1,
15004
+ payload: {
15005
+ orderId: read.id,
15006
+ ...read.clientOrderId !== void 0 ? { clientOrderId: read.clientOrderId } : {},
15007
+ baseRevision: read.revision,
15008
+ cashierRef,
15009
+ registerId,
15010
+ ...storeId !== void 0 ? { storeId } : {},
15011
+ createdAt
15012
+ }
15013
+ };
15014
+ const outcome = await sendOrderReopen(deps.transport, envelope2);
15015
+ if (outcome.kind !== "applied") return { kind: "not_reopened", outcome, envelope: envelope2 };
15016
+ let reread;
15017
+ try {
15018
+ reread = (await deps.getOrders([read.id])).find((order) => order.id === read.id);
15019
+ } catch {
15020
+ return { kind: "reopened_unloadable", reason: "reread", message: `${REOPENED_NOT_LOADED} The order could not be read again.` };
15021
+ }
15022
+ if (!reread) return { kind: "reopened_unloadable", reason: "reread", message: `${REOPENED_NOT_LOADED} The order could not be read again.` };
15023
+ if (outcome.reopen.revision !== void 0 && reread.revision !== outcome.reopen.revision)
15024
+ return { kind: "reopened_unloadable", reason: "reread", message: `${REOPENED_NOT_LOADED} The order read back does not match the reopen.` };
15025
+ try {
15026
+ const builder = storeOrderForReopen(reread, { ...options, taxContext: deps.taxContextFor ? deps.taxContextFor(storeOrderCustomer(reread)).taxContext : deps.taxContext });
15027
+ return { kind: "reopened", order: builder.getSnapshot(), duplicate: outcome.duplicate };
15028
+ } catch (error) {
15029
+ if (error instanceof ReopenEntryError) return { kind: "reopened_unloadable", reason: error.reason, message: `${REOPENED_NOT_LOADED} ${error.message}` };
15030
+ throw error;
15031
+ }
14240
15032
  }
14241
15033
 
14242
15034
  // src/tender/tender-figures.ts
@@ -14255,7 +15047,7 @@ function tenderFigures(facts) {
14255
15047
  const groupDone = plan?.kind === "items" && done.reduce((sum4, leg) => sum4 + leg.minor, 0) >= plan.firstMinor;
14256
15048
  const thisPaymentMinor = split?.thisPaymentMinor ?? balanceMinor;
14257
15049
  const legCapMinor = method?.capabilities.change ? thisPaymentMinor : balanceMinor;
14258
- const roundedDueMinor = roundedDue(balanceMinor, method).dueMinor;
15050
+ const roundedDueMinor = roundedDue(balanceMinor, method, facts.entriesMinor ?? 0).dueMinor;
14259
15051
  const percent = state.entryMode === "percent";
14260
15052
  const percentMinor = percent ? percentOfMinor(balanceMinor, state.entryMinor) : null;
14261
15053
  const entryMinor = percentMinor ?? (!state.entryDirty && state.entryMinor === balanceMinor ? roundedDueMinor : state.entryMinor);
@@ -14407,12 +15199,15 @@ function marginOf(lines) {
14407
15199
  margin.marginPct = costed && margin.costedNetMinor !== 0 ? margin.profitMinor / margin.costedNetMinor : null;
14408
15200
  return margin;
14409
15201
  }
15202
+ function medianMinor(values) {
15203
+ const sorted = [...values].sort((a, b) => a - b);
15204
+ const middle = Math.floor(sorted.length / 2);
15205
+ if (!sorted.length) return 0;
15206
+ return sorted.length % 2 ? sorted[middle] : Math.round((sorted[middle - 1] + sorted[middle]) / 2);
15207
+ }
14410
15208
  function orderSpread(totals) {
14411
15209
  const values = [...totals].sort((a, b) => a - b);
14412
- const middle = Math.floor(values.length / 2);
14413
- if (!values.length) return { medianMinor: 0, largestMinor: null };
14414
- const medianMinor = values.length % 2 ? values[middle] : Math.round((values[middle - 1] + values[middle]) / 2);
14415
- return { medianMinor, largestMinor: values[values.length - 1] };
15210
+ return { medianMinor: medianMinor(values), largestMinor: values.length ? values[values.length - 1] : null };
14416
15211
  }
14417
15212
  function periodFigures(input, range) {
14418
15213
  const orders = input.orders.filter((order) => inRange(order.at, range, input.timezone));
@@ -14425,16 +15220,20 @@ function periodFigures(input, range) {
14425
15220
  discountMinor: 0,
14426
15221
  refundsMinor: 0,
14427
15222
  embeddedRefundsMinor: 0,
15223
+ roundingMinor: 0,
14428
15224
  orderCount: orders.length,
14429
15225
  averageMinor: 0,
14430
15226
  items: lines.reduce((sum4, line) => sum4 + (Number.isFinite(line.quantity) ? line.quantity : 0), 0),
14431
- margin: marginOf(lines)
15227
+ margin: marginOf(lines),
15228
+ refundBasis: input.refunds !== void 0 ? "dated" : "embedded",
15229
+ grossAfterRefundsMinor: 0
14432
15230
  };
14433
15231
  const series = daysOf(range).map((day) => ({ day, grossMinor: 0, orderCount: 0, refundsMinor: 0 }));
14434
15232
  const byDay = new Map(series.map((point) => [point.day, point]));
14435
15233
  for (const order of orders) {
14436
15234
  totals.grossMinor += order.totalMinor;
14437
15235
  totals.taxMinor += order.taxMinor;
15236
+ totals.roundingMinor += order.roundingMinor ?? 0;
14438
15237
  totals.discountMinor += order.discountMinor;
14439
15238
  totals.embeddedRefundsMinor += order.refunds.reduce((sum4, refund) => sum4 + Math.abs(refund.amountMinor), 0);
14440
15239
  const point = byDay.get(businessDayOf(order.at, input.timezone));
@@ -14445,7 +15244,8 @@ function periodFigures(input, range) {
14445
15244
  totals.refundsMinor += Math.abs(refund.amountMinor);
14446
15245
  byDay.get(businessDayOf(refund.at, input.timezone)).refundsMinor += Math.abs(refund.amountMinor);
14447
15246
  }
14448
- totals.netMinor = totals.grossMinor - totals.taxMinor;
15247
+ totals.netMinor = totals.grossMinor - totals.taxMinor - totals.roundingMinor;
15248
+ totals.grossAfterRefundsMinor = totals.grossMinor - (totals.refundBasis === "dated" ? totals.refundsMinor : totals.embeddedRefundsMinor);
14449
15249
  totals.averageMinor = orders.length ? Math.round(totals.grossMinor / orders.length) : 0;
14450
15250
  Object.assign(totals, orderSpread(orders.map((order) => order.totalMinor)));
14451
15251
  return { orders, refunds, totals, series };
@@ -14553,6 +15353,7 @@ function reportOrderFromPosOrder(order, join, methodTitle2) {
14553
15353
  const taxes = recordedTaxByRate(order) ?? taxLinesByRate(taxedLines, order.taxMinor, void 0, order.taxRounding);
14554
15354
  const till = tillPayments(order.payments);
14555
15355
  const amountOf = (payments) => payments.reduce((total, payment) => total + payment.amountMinor, 0);
15356
+ const roundingMinor = (order.cashRoundings ?? []).reduce((total, entry) => total + entry.minor, 0);
14556
15357
  return {
14557
15358
  id: order.id,
14558
15359
  at: order.createdAt,
@@ -14578,6 +15379,7 @@ function reportOrderFromPosOrder(order, join, methodTitle2) {
14578
15379
  return { method, ...label ? { label } : {}, amountMinor: payment.amountMinor };
14579
15380
  }),
14580
15381
  ...order.storeOrderId !== void 0 ? { paidEarlierMinor: amountOf(order.payments) - amountOf(till) } : {},
15382
+ ...roundingMinor !== 0 ? { roundingMinor } : {},
14581
15383
  taxes: taxes.map((row) => ({
14582
15384
  ratePpm: row.ratePpm,
14583
15385
  ...row.code !== void 0 ? { code: row.code } : {},
@@ -14590,7 +15392,7 @@ function reportOrderFromPosOrder(order, join, methodTitle2) {
14590
15392
  function reportOrderFromStoreOrder(order, join) {
14591
15393
  return {
14592
15394
  id: order.id,
14593
- at: order.placedAt,
15395
+ at: order.paidAt ?? order.placedAt,
14594
15396
  totalMinor: order.totalMinor,
14595
15397
  taxMinor: order.taxMinor,
14596
15398
  discountMinor: order.discountMinor,
@@ -14610,7 +15412,8 @@ function reportOrderFromStoreOrder(order, join) {
14610
15412
  taxMinor: amountMinor,
14611
15413
  netMinor: null
14612
15414
  })),
14613
- refunds: order.refunds.map(({ id: id2, amountMinor }) => ({ id: id2, amountMinor }))
15415
+ refunds: order.refunds.map(({ id: id2, amountMinor }) => ({ id: id2, amountMinor })),
15416
+ ...order.needsPayment !== void 0 ? { needsPayment: order.needsPayment } : {}
14614
15417
  };
14615
15418
  }
14616
15419
  function reportRefundFromPosRefund(refund) {
@@ -14629,9 +15432,15 @@ export {
14629
15432
  ADDRESS_CHANGE_REFUSED,
14630
15433
  AFTER_CLOSE_PAYMENTS_CHANGED,
14631
15434
  APP_SETTING_DEFINITIONS,
15435
+ BLUETOOTH_PRINT_SERVICES,
14632
15436
  CAMERA_BARCODE_TYPES,
14633
15437
  CAMERA_CONSTRAINTS,
14634
15438
  CART_COLUMN_IDS,
15439
+ CASH_NOT_PAYABLE,
15440
+ CASH_PICK_ENTRIES_MAX,
15441
+ CASH_PICK_LIMIT,
15442
+ CASH_SETTLE_LIMIT,
15443
+ CASH_WAITS_FOR_PAYMENT,
14635
15444
  COLLECT_POLL_MS,
14636
15445
  CONNECT_TIMEOUT_MS,
14637
15446
  COUPONS_NEED_CONNECTION,
@@ -14672,17 +15481,22 @@ export {
14672
15481
  META_CHANGE_REFUSED,
14673
15482
  META_INVALID,
14674
15483
  MICROS_PER_MINOR,
15484
+ NEEDS_ADMIN_RETRY_PREFIX,
15485
+ NOTHING_DUE,
15486
+ NOTHING_TO_ROUND_AGAINST,
14675
15487
  OPEN_ORDERS_POSITIONS,
14676
15488
  OPEN_SIGNAL_POLL_MS,
14677
15489
  OrderContentMismatchError,
14678
15490
  PAPER_COLUMNS,
14679
15491
  PAYMENT_IN_MOTION,
15492
+ PAYMENT_TAKEN,
14680
15493
  PENDING_POLL_MS,
14681
15494
  PRINTER_PROFILES_COLLECTION,
14682
15495
  PRODUCT_SORT_FIELDS,
14683
15496
  PosOrderOpenClosedError,
14684
15497
  PrintError,
14685
15498
  RECEIPT_SCHEMA_VERSION,
15499
+ REGISTER_CLOSING,
14686
15500
  REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS,
14687
15501
  REOPENABLE_CODES,
14688
15502
  REOPENED_NOT_LOADED,
@@ -14697,6 +15511,7 @@ export {
14697
15511
  RegisterMovementStrandedError,
14698
15512
  RegisterNeedsUpgradeError,
14699
15513
  RegisterReapproveError,
15514
+ RegisterSaleSavingError,
14700
15515
  RegisterSessionAlreadyOpenError,
14701
15516
  RegisterSessionClosedError,
14702
15517
  RegisterSessionConflictError,
@@ -14706,6 +15521,7 @@ export {
14706
15521
  RegisterTenderInProgressError,
14707
15522
  ReopenEntryError,
14708
15523
  ReopenRefusedOrderError,
15524
+ SALE_CARD_IN_PROGRESS,
14709
15525
  SALE_FINISHED,
14710
15526
  SALE_HAS_PAYMENT,
14711
15527
  SALE_IN_TENDER,
@@ -14742,6 +15558,7 @@ export {
14742
15558
  UPDATE_UNSENDABLE,
14743
15559
  UPDATE_UNSENDABLE_MESSAGE,
14744
15560
  UnsupportedOrderVersionError,
15561
+ VOID_LATER_CASH_FIRST,
14745
15562
  WCPOS_DEFAULT_I18N,
14746
15563
  WCPOS_TAX_ID_LABELS,
14747
15564
  WEDGE_END_OF_SCAN_MS,
@@ -14776,6 +15593,7 @@ export {
14776
15593
  capturedMinor,
14777
15594
  cartQuantities,
14778
15595
  cashMovementSchema,
15596
+ cashVoidRefusal,
14779
15597
  catalogueEntries,
14780
15598
  catalogueViewReducer,
14781
15599
  changeMinor,
@@ -14784,6 +15602,7 @@ export {
14784
15602
  closeSession,
14785
15603
  closureApprovalStatus,
14786
15604
  closureCommand,
15605
+ closureFigures,
14787
15606
  closureSchema,
14788
15607
  closureVariance,
14789
15608
  comparisonRange,
@@ -14828,6 +15647,8 @@ export {
14828
15647
  createTillDisplayService,
14829
15648
  createTillPairing,
14830
15649
  createTillPeerLink,
15650
+ createWebBluetoothSink,
15651
+ createWebUsbSink,
14831
15652
  createWedgeDetector,
14832
15653
  createWedgeState,
14833
15654
  csvCell,
@@ -14905,6 +15726,7 @@ export {
14905
15726
  markAttentionHandled,
14906
15727
  matchVariant,
14907
15728
  matchesPresetFilters,
15729
+ medianMinor,
14908
15730
  messageBytes,
14909
15731
  methodDrivers,
14910
15732
  methodForProvider,
@@ -14915,6 +15737,8 @@ export {
14915
15737
  movementCommand,
14916
15738
  movementFieldError,
14917
15739
  nativeBarcodeDetector,
15740
+ nearestPayableCash,
15741
+ needsAdminReasonOf,
14918
15742
  needsAttention,
14919
15743
  networkSinkFor,
14920
15744
  nextSaleCounter,
@@ -14966,6 +15790,7 @@ export {
14966
15790
  recordMovement,
14967
15791
  recordRegisterFact,
14968
15792
  refundDueOf,
15793
+ refundNeedsAdminLine,
14969
15794
  refundableLines,
14970
15795
  registerCommandCollection,
14971
15796
  registerCommandSchema,
@@ -14974,6 +15799,7 @@ export {
14974
15799
  registerSessionCollection,
14975
15800
  registerSessionSchema,
14976
15801
  registerSessionsLogger,
15802
+ remainderEntriesMinor,
14977
15803
  removeScannerProfile,
14978
15804
  renderEscpos,
14979
15805
  renderHtml,
@@ -14998,10 +15824,12 @@ export {
14998
15824
  retailCodeTwin,
14999
15825
  roundMicrosToMinor,
15000
15826
  roundedDue,
15827
+ roundedPickTarget,
15001
15828
  runsWholeOrder,
15002
15829
  saleLogger,
15003
15830
  saleTaxContexts,
15004
15831
  salesFigures,
15832
+ salesRangeQuery,
15005
15833
  sameSale,
15006
15834
  sanitizeHtml,
15007
15835
  saveScannerProfile,
@@ -15042,6 +15870,7 @@ export {
15042
15870
  taxMicros,
15043
15871
  taxProviderProps,
15044
15872
  taxSettingsForLocation,
15873
+ taxedLinesFor,
15045
15874
  templateColumns,
15046
15875
  tenderFigures,
15047
15876
  tenderReducer,
@@ -15076,6 +15905,8 @@ export {
15076
15905
  useSale,
15077
15906
  useSaleDisplay,
15078
15907
  useScanHub,
15908
+ useStoreOrdersInRange,
15909
+ useStoreRefundsInRange,
15079
15910
  useStoreSettings,
15080
15911
  useTax,
15081
15912
  useTillDisplays,