@tallyui/pos 4.2.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 (57) hide show
  1. package/dist/index.d.ts +465 -162
  2. package/dist/index.js +1752 -1104
  3. package/package.json +7 -6
  4. package/src/index.ts +12 -9
  5. package/src/order/index.ts +1 -0
  6. package/src/order/order-builder.ts +64 -22
  7. package/src/order/order-drafts.ts +77 -25
  8. package/src/order/types.ts +9 -2
  9. package/src/order/woocommerce-tax.ts +9 -12
  10. package/src/outbox/http-transport.ts +16 -1
  11. package/src/outbox/index.ts +2 -1
  12. package/src/outbox/needs-admin-reason.ts +10 -0
  13. package/src/outbox/order-outbox.ts +14 -5
  14. package/src/outbox/register-outbox.ts +4 -3
  15. package/src/outbox/types.ts +3 -1
  16. package/src/outbox/use-order-outbox.ts +7 -3
  17. package/src/pos-order/command.ts +3 -0
  18. package/src/pos-order/finalize.ts +9 -0
  19. package/src/pos-order/reopen.ts +9 -2
  20. package/src/pos-order/schema.ts +5 -2
  21. package/src/pos-order/types.ts +5 -1
  22. package/src/receipt/build-receipt-data.ts +8 -1
  23. package/src/receipt/reprint.ts +2 -0
  24. package/src/receipt/types.ts +2 -0
  25. package/src/receipt-template/template-data.ts +1 -1
  26. package/src/receipt-template/wcpos/from-orders.ts +5 -1
  27. package/src/refund/index.ts +1 -0
  28. package/src/refund/needs-admin-line.ts +6 -0
  29. package/src/refund/refundable-lines.ts +2 -91
  30. package/src/refund/send-order-refund.ts +6 -1
  31. package/src/refund/submit-order-refund.ts +33 -1
  32. package/src/register/closing.ts +15 -0
  33. package/src/register/closure-document.ts +13 -5
  34. package/src/register/closure-figures.ts +83 -0
  35. package/src/register/document-labels.ts +5 -3
  36. package/src/register/expected.ts +30 -9
  37. package/src/register/index.ts +3 -1
  38. package/src/register/register-adoption.ts +42 -4
  39. package/src/register/register-document.ts +17 -0
  40. package/src/register/session-store.ts +48 -12
  41. package/src/register/use-register-session.ts +53 -20
  42. package/src/reports/adapters.ts +5 -1
  43. package/src/reports/index.ts +1 -1
  44. package/src/reports/sales-figures.ts +33 -6
  45. package/src/reports/types.ts +3 -1
  46. package/src/sale/index.ts +1 -1
  47. package/src/sale/use-sale.ts +313 -134
  48. package/src/store-orders/index.ts +3 -0
  49. package/src/store-orders/sales-range-query.ts +18 -0
  50. package/src/store-orders/use-store-refunds-in-range.ts +179 -0
  51. package/src/tax/exact.ts +2 -10
  52. package/src/tender/cash-rounding.ts +49 -6
  53. package/src/tender/index.ts +1 -1
  54. package/src/tender/payment-legs.ts +5 -0
  55. package/src/tender/tender-figures.ts +3 -1
  56. package/src/outbox/types.test-d.ts +0 -27
  57. package/src/print/escpos/sinks.test-d.ts +0 -77
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,
@@ -973,7 +970,7 @@ function useStoreSettings(options) {
973
970
  const retryTimerRef = useRef(void 0);
974
971
  const retryDelayRef = useRef(INITIAL_RETRY_MS);
975
972
  const [state, setState] = useState(LOADING);
976
- const resolve = useCallback2((choice, from, known, previous) => {
973
+ const resolve = useCallback2((choice, from, known2, previous) => {
977
974
  if (from !== void 0 && from !== requestRef.current) return;
978
975
  clearTimeout(retryTimerRef.current);
979
976
  const request = ++requestRef.current;
@@ -986,7 +983,7 @@ function useStoreSettings(options) {
986
983
  const { refreshError: _error, ...refreshing } = previous;
987
984
  setState({ ...refreshing, refreshing: true });
988
985
  } else setState(LOADING);
989
- const rounding = known ?? readTaxRounding(optionsRef.current);
986
+ const rounding = known2 ?? readTaxRounding(optionsRef.current);
990
987
  Promise.all([resolveStoreSettings(optionsRef.current, choice), rounding]).then(
991
988
  ([result, taxRounding]) => {
992
989
  if (!current()) return;
@@ -1130,8 +1127,8 @@ function parseCartColumns(value) {
1130
1127
  parsed[id2] = Object.fromEntries(CART_COLUMN_FIELDS[id2].filter((field) => typeof column[field] === "boolean").map((field) => [field, column[field]]));
1131
1128
  }
1132
1129
  if (Array.isArray(value.order)) {
1133
- const known = value.order.filter((id2) => CART_COLUMN_IDS.includes(id2));
1134
- parsed.order = [...new Set(known)];
1130
+ const known2 = value.order.filter((id2) => CART_COLUMN_IDS.includes(id2));
1131
+ parsed.order = [...new Set(known2)];
1135
1132
  }
1136
1133
  return parsed;
1137
1134
  }
@@ -1326,6 +1323,9 @@ function canMoveLeg(from, to) {
1326
1323
  function canVoidLeg(leg, method) {
1327
1324
  return method.capabilities.void && (isInMotion(leg) || legStatus(leg) === "captured" && method.capture.mode === "manual");
1328
1325
  }
1326
+ function takenLeg(leg) {
1327
+ return (legStatus(leg) === "captured" || legStatus(leg) === "voided") && leg.takenAt !== void 0;
1328
+ }
1329
1329
 
1330
1330
  // src/order/apportion.ts
1331
1331
  function apportionLargestRemainders(weights, totalMinor, fallbackIndex) {
@@ -1441,10 +1441,25 @@ function createOrderBuilder(options) {
1441
1441
  const currency = options.currency.toUpperCase();
1442
1442
  const orderId = options.id ?? uid();
1443
1443
  const woo = taxContext.rounding?.granularity === "woocommerce" && taxContext.getTaxRates ? taxContext.rounding : void 0;
1444
- 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
+ };
1445
1460
  const displayAmount = (line, amount) => {
1446
1461
  if (!woo || line.taxInclusive === taxContext.pricesIncludeTax) return toDisplayMode(line, amount, taxContext.pricesIncludeTax);
1447
- 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);
1448
1463
  return taxContext.pricesIncludeTax ? item.totalMinor : item.netMinor;
1449
1464
  };
1450
1465
  const storeModeMinor = (li) => woo ? taxContext.pricesIncludeTax ? li.totalMinor : li.netMinor : toDisplayMode(li, li.netMinor, taxContext.pricesIncludeTax);
@@ -1453,6 +1468,7 @@ function createOrderBuilder(options) {
1453
1468
  let shipping = [];
1454
1469
  let orderDiscounts = [];
1455
1470
  let payments = [];
1471
+ let cashRoundings = [];
1456
1472
  let customer = null;
1457
1473
  let note = "";
1458
1474
  let meta = [];
@@ -1475,7 +1491,7 @@ function createOrderBuilder(options) {
1475
1491
  discounts: recalcedDiscounts,
1476
1492
  discountMinor,
1477
1493
  orderDiscountMinor,
1478
- ...wooLine(netMinor, line.taxClass, line.taxInclusive, line.taxStatus === "none")
1494
+ ...wooLine(netMinor, line.taxClass, line.taxInclusive, line.taxStatus === "none", false, line.id)
1479
1495
  };
1480
1496
  const combinedRate = line.taxLines.reduce((sum4, tax) => sum4 + tax.ratePpm, 0);
1481
1497
  const inclusiveTax = line.taxInclusive ? taxMicros(netMinor, combinedRate, true) : 0n;
@@ -1522,7 +1538,10 @@ function createOrderBuilder(options) {
1522
1538
  displaySourceLines,
1523
1539
  couponCodes,
1524
1540
  couponContext,
1525
- taxContext.getTaxRates,
1541
+ (line) => {
1542
+ const held = heldFor(line.id);
1543
+ return held ? toWooRates(held) : taxContext.getTaxRates(line.taxClass);
1544
+ },
1526
1545
  currency,
1527
1546
  woo.roundAtSubtotal,
1528
1547
  taxContext.pricesIncludeTax
@@ -1550,7 +1569,8 @@ function createOrderBuilder(options) {
1550
1569
  amountMinor: Number((basis * BigInt(Math.round(fee.percent * 1e4)) + 500000n) / 1000000n)
1551
1570
  }));
1552
1571
  }
1553
- 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) }));
1554
1574
  const charges = [...fees, ...shipping];
1555
1575
  const taxedCharges = charges.map((charge) => ({
1556
1576
  ...charge,
@@ -1678,12 +1698,14 @@ function createOrderBuilder(options) {
1678
1698
  throw new Error(`Display line ${line.lineId} shows ${line.amountMinor}, less than its rows ${rows} and share ${shareMinor} (ADR-063)`);
1679
1699
  }
1680
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);
1681
1703
  const display = {
1682
1704
  taxInclusive,
1683
1705
  subtotalMinor: displaySubtotal,
1684
1706
  discountMinor: displayDiscount,
1685
1707
  taxMinor,
1686
- totalMinor,
1708
+ totalMinor: total,
1687
1709
  lines: displayLines,
1688
1710
  orderDiscountMinor: orderDiscountDisplay,
1689
1711
  ...displayCoupons ? { coupons: displayCoupons } : {},
@@ -1691,8 +1713,8 @@ function createOrderBuilder(options) {
1691
1713
  ...shipping.length ? { shipping: displayShipping } : {}
1692
1714
  };
1693
1715
  const paidMinor = capturedMinor(payments);
1694
- const balanceDueMinor = Math.max(0, totalMinor - paidMinor);
1695
- const changeDueMinor = Math.max(0, paidMinor - totalMinor);
1716
+ const balanceDueMinor = Math.max(0, total - paidMinor);
1717
+ const changeDueMinor = Math.max(0, paidMinor - total);
1696
1718
  const order = {
1697
1719
  id: orderId,
1698
1720
  ...storeOrder !== void 0 ? { storeOrder } : {},
@@ -1704,13 +1726,14 @@ function createOrderBuilder(options) {
1704
1726
  ...shipping.length ? { shipping: [...shipping] } : {},
1705
1727
  discounts: recalcedOrderDiscounts,
1706
1728
  payments: [...payments],
1729
+ ...live.length ? { cashRoundings: live.map((e) => ({ ...e })) } : {},
1707
1730
  customer,
1708
1731
  note,
1709
1732
  ...meta.length ? { meta: meta.map((m) => ({ ...m })) } : {},
1710
1733
  subtotalMinor,
1711
1734
  discountMinor,
1712
1735
  taxMinor,
1713
- totalMinor,
1736
+ totalMinor: total,
1714
1737
  display,
1715
1738
  paidMinor,
1716
1739
  balanceDueMinor,
@@ -1752,7 +1775,8 @@ function createOrderBuilder(options) {
1752
1775
  taxClass === woocommerceTax6.NO_SHIPPING_TAX || shipping2 && untaxed ? void 0 : taxClass,
1753
1776
  inclusive,
1754
1777
  untaxed,
1755
- shipping2
1778
+ shipping2,
1779
+ id2
1756
1780
  );
1757
1781
  return {
1758
1782
  id: id2,
@@ -1765,7 +1789,7 @@ function createOrderBuilder(options) {
1765
1789
  ...line2
1766
1790
  };
1767
1791
  }
1768
- const code = taxContext.getTaxRateCode?.(input.taxClass);
1792
+ const code = taxContext.getTaxRateCode?.(input.taxClass), held = heldFor(id2);
1769
1793
  const line = recalculateLine({
1770
1794
  id: id2,
1771
1795
  productId: id2,
@@ -1773,7 +1797,7 @@ function createOrderBuilder(options) {
1773
1797
  sku: "",
1774
1798
  unitPriceMinor: input.amountMinor,
1775
1799
  quantity: 1,
1776
- taxLines: [{
1800
+ taxLines: held ? held.map(({ code: code2, ratePpm }) => ({ ...code2 !== void 0 ? { code: code2 } : {}, ratePpm, taxMicros: "0" })) : [{
1777
1801
  ...code !== void 0 ? { code } : {},
1778
1802
  ratePpm: taxStatus === "none" ? 0 : taxContext.getTaxRatePpm(input.taxClass),
1779
1803
  taxMicros: "0"
@@ -1807,7 +1831,7 @@ function createOrderBuilder(options) {
1807
1831
  if (input.regularUnitPriceMinor !== void 0 && (!Number.isInteger(input.regularUnitPriceMinor) || input.regularUnitPriceMinor < 0))
1808
1832
  throw new RangeError("Regular price must be integer minor units >= 0");
1809
1833
  const code = woo || input.taxRates ? void 0 : taxContext.getTaxRateCode?.(input.taxClass);
1810
- 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) }];
1811
1835
  const taxInclusive = unitPrice.taxInclusive ?? taxContext.pricesIncludeTax;
1812
1836
  const fromClass = !woo && input.taxRates === void 0;
1813
1837
  const existing = lineItems.find(
@@ -1976,9 +2000,9 @@ function createOrderBuilder(options) {
1976
2000
  },
1977
2001
  restoreItem(kind, item, index) {
1978
2002
  for (const { id: id2 } of kind === "line" ? [item, ...item.discounts] : [item]) idFor(id2);
1979
- const at2 = (list, entry) => {
1980
- const i = Math.min(index, list.length);
1981
- 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)];
1982
2006
  };
1983
2007
  if (kind === "line") lineItems = at2(lineItems, recalculateLine(item));
1984
2008
  else {
@@ -2021,16 +2045,26 @@ function createOrderBuilder(options) {
2021
2045
  });
2022
2046
  emit();
2023
2047
  },
2024
- addPayment(payment) {
2048
+ addPayment(payment, rounding) {
2025
2049
  const id2 = idFor(payment.id);
2026
2050
  payments = [...payments, { ...payment, id: id2 }];
2051
+ if (rounding && rounding.minor !== 0) cashRoundings = [...cashRoundings, { paymentId: id2, minor: rounding.minor }];
2027
2052
  emit();
2028
2053
  return id2;
2029
2054
  },
2030
- setPaymentStatus(paymentId, status, takenAt) {
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) {
2031
2065
  const payment = payments.find((p) => p.id === paymentId);
2032
2066
  if (!payment || payment.locked || !canMoveLeg(legStatus(payment), status)) return false;
2033
- const stamp2 = status === "captured" && takenAt !== void 0 ? { takenAt } : {};
2067
+ const stamp2 = status === "captured" && takenAt !== void 0 ? { takenAt, ...sessionId !== void 0 && payment.sessionId === void 0 ? { sessionId } : {} } : {};
2034
2068
  payments = payments.map((p) => p.id === paymentId ? { ...p, status, ...stamp2 } : p);
2035
2069
  emit();
2036
2070
  return true;
@@ -2090,6 +2124,7 @@ function createOrderBuilder(options) {
2090
2124
  shipping = [];
2091
2125
  orderDiscounts = [];
2092
2126
  payments = [];
2127
+ cashRoundings = [];
2093
2128
  customer = null;
2094
2129
  note = "";
2095
2130
  meta = [];
@@ -2127,6 +2162,11 @@ import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
2127
2162
  // src/order/order-drafts.ts
2128
2163
  import { map as map3 } from "rxjs";
2129
2164
 
2165
+ // src/pos-order/till-payments.ts
2166
+ function tillPayments(payments) {
2167
+ return payments.filter((payment) => payment.storePaymentId === void 0);
2168
+ }
2169
+
2130
2170
  // src/order/taken-at.ts
2131
2171
  function isTakenAt(value) {
2132
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;
@@ -2147,14 +2187,36 @@ var orderDraftSchema = {
2147
2187
  },
2148
2188
  required: ["id", "data"]
2149
2189
  };
2190
+ var savedDraft = (data) => JSON.parse(String(data));
2150
2191
  function draftExtras(data) {
2151
2192
  try {
2152
- const saved = JSON.parse(String(data));
2193
+ const saved = savedDraft(data);
2153
2194
  return { paidMinor: capturedMinor(saved.payments ?? []), balanceDueMinor: saved.balanceDueMinor, firstItem: saved.lineItems?.[0]?.name };
2154
2195
  } catch {
2155
2196
  return {};
2156
2197
  }
2157
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
+ }
2158
2220
  async function writeOrderDraft(drafts, snapshot) {
2159
2221
  await drafts.upsert({
2160
2222
  id: snapshot.id,
@@ -2168,9 +2230,16 @@ async function writeOrderDraft(drafts, snapshot) {
2168
2230
  }
2169
2231
  function restoreOrderDraft(saved, options) {
2170
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;
2171
2239
  const builder = createOrderBuilder({
2172
2240
  currency,
2173
2241
  taxContext,
2242
+ ...heldRates ? { heldRates } : {},
2174
2243
  id: saved.id,
2175
2244
  ...saved.createdAt ? { createdAt: saved.createdAt } : {},
2176
2245
  // #742: with every id below (fees and shipping replay whole)
@@ -2184,6 +2253,25 @@ function restoreOrderDraft(saved, options) {
2184
2253
  builder.setNote(saved.note);
2185
2254
  }
2186
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);
2187
2275
  for (const line of saved.lineItems) {
2188
2276
  const rederive = line.taxFromClass === true && !options.keepTaxRates;
2189
2277
  const lineId = builder.addLine({
@@ -2227,23 +2315,6 @@ function restoreOrderDraft(saved, options) {
2227
2315
  couponCode: discount.couponCode
2228
2316
  });
2229
2317
  }
2230
- for (const payment of saved.payments) {
2231
- builder.addPayment({
2232
- id: payment.id,
2233
- method: payment.method,
2234
- amountMinor: payment.amountMinor,
2235
- tenderedMinor: payment.tenderedMinor,
2236
- changeMinor: payment.changeMinor,
2237
- reference: payment.reference,
2238
- ...payment.status !== void 0 ? { status: payment.status } : {},
2239
- ...payment.storePaymentId !== void 0 ? { storePaymentId: payment.storePaymentId } : {},
2240
- ...payment.locked !== void 0 ? { locked: payment.locked } : {},
2241
- ...payment.reopened !== void 0 ? { reopened: payment.reopened } : {},
2242
- ...payment.methodId !== void 0 ? { methodId: payment.methodId } : {},
2243
- ...payment.units !== void 0 ? { units: payment.units } : {},
2244
- ...isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}
2245
- });
2246
- }
2247
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");
2248
2319
  if (saved.coupons?.length && saved.coupons.every((coupon) => coupon.carried)) {
2249
2320
  builder.setCoupons(saved.coupons.map((c) => c.code), {
@@ -2259,12 +2330,14 @@ function restoreOrderDraft(saved, options) {
2259
2330
  }
2260
2331
  if (options.keepCoupons && saved.coupons?.length && saved.display.coupons?.length === saved.coupons.length) {
2261
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 })) });
2262
2335
  builder.setCoupons(saved.coupons.map((coupon) => coupon.code), {
2263
2336
  kind: "kept",
2264
2337
  coupons: saved.coupons,
2265
2338
  displayRows: saved.display.coupons.map((row) => row.amountMinor),
2266
2339
  lines: new Map(saved.lineItems.map((li) => [li.id, li])),
2267
- basis: saved.couponPricesStale ? "" : couponPricingBasis(restored),
2340
+ basis: saved.couponPricesStale ? "" : keptBasis,
2268
2341
  linesBasis: couponPricingBasis({ ...restored, customer: null }),
2269
2342
  legIds: saved.payments.filter(isLiveLeg).map((p) => p.id)
2270
2343
  });
@@ -2351,6 +2424,11 @@ function useParkedSales(drafts) {
2351
2424
  return { parked, discard };
2352
2425
  }
2353
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
+
2354
2432
  // src/store-orders/use-store-orders-in-range.ts
2355
2433
  import { useEffect as useEffect5, useMemo as useMemo4, useState as useState5 } from "react";
2356
2434
  var PER_PAGE = 100;
@@ -2416,6 +2494,145 @@ function useStoreOrdersInRange(connector, context, query) {
2416
2494
  }, [connector, context, key, read]);
2417
2495
  }
2418
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
+
2419
2636
  // src/pos-order/refund-due.ts
2420
2637
  var sum = (amounts) => amounts.reduce((total, amount) => total + amount, 0);
2421
2638
  function refundDueOf(order) {
@@ -2452,6 +2669,10 @@ function carriedRows(coupons, lineId, inclusiveOf, displayInclusive, displayRows
2452
2669
  var RECEIPT_SCHEMA_VERSION = "1.4.0";
2453
2670
 
2454
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
+ }
2455
2676
  function buildReceiptData(order, config) {
2456
2677
  const taxedLines = taxedLinesFor(order.lineItems, [...order.fees ?? [], ...order.shipping ?? []], order.pricesIncludeTax, order.taxRounding);
2457
2678
  const taxLines = taxLinesByRate(taxedLines, order.taxMinor, config.taxLabels, order.taxRounding).map(
@@ -2525,6 +2746,7 @@ function buildReceiptData(order, config) {
2525
2746
  })),
2526
2747
  fees: (order.display.fees ?? []).map(({ name, amountMinor }) => ({ name, amountMinor })),
2527
2748
  shipping: (order.display.shipping ?? []).map(({ name, amountMinor }) => ({ name, amountMinor })),
2749
+ ...receiptRounding(order),
2528
2750
  orderDiscountMinor: order.display.orderDiscountMinor,
2529
2751
  totals: {
2530
2752
  taxInclusive: order.display.taxInclusive,
@@ -2640,6 +2862,7 @@ function buildReceiptDataFromPosOrder(order, config) {
2640
2862
  discounts: display && display.orderDiscountMinor > 0 ? [{ label: "Order discount", amountMinor: display.orderDiscountMinor }] : [],
2641
2863
  fees: charges(display ? display.fees : order.fees),
2642
2864
  shipping: charges(display ? display.shipping : order.shipping),
2865
+ ...receiptRounding(order),
2643
2866
  orderDiscountMinor: display ? display.orderDiscountMinor : 0,
2644
2867
  totals: display ? {
2645
2868
  taxInclusive: display.taxInclusive,
@@ -2721,8 +2944,8 @@ function parseChildren(parent) {
2721
2944
  const nodes = [];
2722
2945
  for (const child of Array.from(parent.childNodes)) {
2723
2946
  if (child.nodeType === 3) {
2724
- const text2 = child.textContent ?? "";
2725
- 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 });
2726
2949
  continue;
2727
2950
  }
2728
2951
  if (child.nodeType !== 1) continue;
@@ -2928,10 +3151,10 @@ function renderNode(node, widthChars) {
2928
3151
  }
2929
3152
  }
2930
3153
  function pendingCode(kind, value) {
2931
- const text2 = value.trim();
2932
- if (!text2) return "";
3154
+ const text3 = value.trim();
3155
+ if (!text3) return "";
2933
3156
  const safeKind = kind === "qrcode" ? "qrcode" : "barcode";
2934
- 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>`;
2935
3158
  }
2936
3159
  function renderRow(node, widthChars) {
2937
3160
  const cols = node.children.map((col) => renderCol(col, widthChars)).join("");
@@ -3143,7 +3366,7 @@ function receiptTemplateData(receipt, options = {}) {
3143
3366
  subtotal: money(totals.subtotalMinor),
3144
3367
  lineDiscount: lineDiscountMinor > 0 ? `\u2212${money(lineDiscountMinor)}` : "",
3145
3368
  orderDiscount: receipt.orderDiscountMinor > 0 ? `\u2212${money(receipt.orderDiscountMinor)}` : "",
3146
- charges: [...receipt.fees, ...receipt.shipping].map((charge) => ({
3369
+ charges: [...receipt.fees, ...receipt.shipping, ...receipt.rounding ? [receipt.rounding] : []].map((charge) => ({
3147
3370
  label: charge.name,
3148
3371
  amount: money(charge.amountMinor)
3149
3372
  })),
@@ -3315,8 +3538,8 @@ function metaText(value) {
3315
3538
  if (value === null || value === void 0) return "";
3316
3539
  return typeof value === "object" ? JSON.stringify(value) : String(value);
3317
3540
  }
3318
- function taxIdsKey(list) {
3319
- 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) => ({
3320
3543
  type: id2.type,
3321
3544
  value: id2.value,
3322
3545
  ...id2.country ? { country: id2.country } : {},
@@ -3663,7 +3886,7 @@ var WCPOS_TAX_ID_LABELS = {
3663
3886
  ch_uid: "UID"
3664
3887
  };
3665
3888
  var tri = (key) => [key, `${key}_incl`, `${key}_excl`];
3666
- 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;
3667
3890
  var definedOnly = (values) => Object.fromEntries(Object.entries(values).filter((entry) => entry[1] !== void 0));
3668
3891
  function displays(source, keys, format2) {
3669
3892
  const out = {};
@@ -3788,8 +4011,8 @@ function formatWcposReceiptData(data, options = {}) {
3788
4011
  import { paymentMethodOf } from "@tallyui/core";
3789
4012
  function rateKeyOf(rates) {
3790
4013
  const codes2 = new Map(rates.map((rate) => [JSON.stringify([rate.code ?? "", rate.ratePpm]), rate.code ?? ""]));
3791
- const list = [...codes2.values()];
3792
- 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;
3793
4016
  return (rate) => plain ? rate.code : JSON.stringify([rate.code ?? "", rate.ratePpm]);
3794
4017
  }
3795
4018
  var sumTax = (rates) => roundMicrosToMinor(rates.reduce((total, rate) => total + BigInt(rate.taxMicros), 0n));
@@ -3854,7 +4077,11 @@ function tillSource(order, receipt, lines) {
3854
4077
  pricesIncludeTax: order.pricesIncludeTax,
3855
4078
  customer: order.customer && { id: order.customer.id, firstName: order.customer.name, email: order.customer.email },
3856
4079
  lines: lines.map((line) => tillLine(line, key)),
3857
- 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
+ ],
3858
4085
  shipping: (order.shipping ?? []).map((row) => ({
3859
4086
  methodTitle: row.name,
3860
4087
  ...row.methodId !== void 0 ? { methodId: row.methodId } : {},
@@ -4101,11 +4328,11 @@ var PAYLOAD_CHECKS = {
4101
4328
  "display.hello": (p) => isTemplate(p.template),
4102
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)
4103
4330
  };
4104
- function decode(text2) {
4105
- if (!isStr(text2)) return { ok: false, refusal: "malformed" };
4331
+ function decode(text3) {
4332
+ if (!isStr(text3)) return { ok: false, refusal: "malformed" };
4106
4333
  let message;
4107
4334
  try {
4108
- message = JSON.parse(text2);
4335
+ message = JSON.parse(text3);
4109
4336
  } catch {
4110
4337
  return { ok: false, refusal: "malformed" };
4111
4338
  }
@@ -4122,14 +4349,14 @@ var MAX_MESSAGE_BYTES = 200 * 1024;
4122
4349
  var MAX_NOTE_BYTES = 1024;
4123
4350
  var MAX_LINE_ATTRIBUTES = 8;
4124
4351
  var encoder = new TextEncoder();
4125
- function messageBytes(text2) {
4126
- return encoder.encode(text2).byteLength;
4352
+ function messageBytes(text3) {
4353
+ return encoder.encode(text3).byteLength;
4127
4354
  }
4128
- function truncateUtf8(text2, limit) {
4129
- if (messageBytes(text2) <= limit) return text2;
4355
+ function truncateUtf8(text3, limit) {
4356
+ if (messageBytes(text3) <= limit) return text3;
4130
4357
  let bytes = 0;
4131
4358
  let result = "";
4132
- for (const character of text2) {
4359
+ for (const character of text3) {
4133
4360
  bytes += messageBytes(character);
4134
4361
  if (bytes > limit) break;
4135
4362
  result += character;
@@ -4152,10 +4379,10 @@ function trimCart(cart, size) {
4152
4379
  while (size() > MAX_MESSAGE_BYTES && receipt.lineItems.length > 0) receipt.lineItems.shift();
4153
4380
  }
4154
4381
  function encode(envelope2) {
4155
- let text2 = JSON.stringify(envelope2);
4156
- if (messageBytes(text2) <= MAX_MESSAGE_BYTES) return text2;
4157
- const copy = JSON.parse(text2);
4158
- 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));
4159
4386
  if (copy.action === "cart.updated" || copy.action === "payment.state") trimCart(copy.payload, size);
4160
4387
  else if (copy.action === "display.config") {
4161
4388
  copy.payload.i18n = {};
@@ -4164,7 +4391,7 @@ function encode(envelope2) {
4164
4391
  size();
4165
4392
  }
4166
4393
  }
4167
- return text2;
4394
+ return text3;
4168
4395
  }
4169
4396
 
4170
4397
  // src/customer-display/display-state.ts
@@ -4240,7 +4467,7 @@ var quietly = (run) => {
4240
4467
  function createSnapshotSender({ post: post2, clock, onError }) {
4241
4468
  let state = null;
4242
4469
  let stopped = false;
4243
- let inFlight2 = false;
4470
+ let inFlight3 = false;
4244
4471
  let timer = null;
4245
4472
  let timerFor = null;
4246
4473
  let last = null;
@@ -4271,7 +4498,7 @@ function createSnapshotSender({ post: post2, clock, onError }) {
4271
4498
  return state?.active || next.idle && clearing ? next : null;
4272
4499
  };
4273
4500
  const schedule = () => {
4274
- if (stopped || inFlight2) return;
4501
+ if (stopped || inFlight3) return;
4275
4502
  const next = wanted();
4276
4503
  if (!next) return clear();
4277
4504
  if (last?.key === next.key) {
@@ -4289,11 +4516,11 @@ function createSnapshotSender({ post: post2, clock, onError }) {
4289
4516
  };
4290
4517
  function fire() {
4291
4518
  timer = timerFor = null;
4292
- if (stopped || inFlight2) return;
4519
+ if (stopped || inFlight3) return;
4293
4520
  const next = wanted();
4294
4521
  if (!next) return;
4295
4522
  if (last?.key === next.key && clock.now() < last.at + SNAPSHOT_RESEND_MS) return schedule();
4296
- inFlight2 = true;
4523
+ inFlight3 = true;
4297
4524
  void new Promise((resolve) => resolve(post2(next.body))).then(() => {
4298
4525
  last = { key: next.key, at: clock.now(), ok: true };
4299
4526
  cartPostedAt = next.idle ? null : clock.now();
@@ -4303,7 +4530,7 @@ function createSnapshotSender({ post: post2, clock, onError }) {
4303
4530
  if (!retryable(error)) refused = next.key;
4304
4531
  last = { key: next.key, at: clock.now(), ok: false };
4305
4532
  }).finally(() => {
4306
- inFlight2 = false;
4533
+ inFlight3 = false;
4307
4534
  schedule();
4308
4535
  });
4309
4536
  }
@@ -4375,12 +4602,12 @@ function createDisplayLink(transport, options) {
4375
4602
  }
4376
4603
 
4377
4604
  // src/customer-display/use-customer-display.ts
4378
- import { useEffect as useEffect6, useState as useState6 } from "react";
4605
+ import { useEffect as useEffect7, useState as useState7 } from "react";
4379
4606
  var DISPLAY_TEMPLATE = { id: "default", version: 1 };
4380
4607
  var HELLO_RETRY_MS = 2e3;
4381
4608
  function useCustomerDisplay(transport) {
4382
- const [state, setState] = useState6(initialDisplayState);
4383
- useEffect6(() => {
4609
+ const [state, setState] = useState7(initialDisplayState);
4610
+ useEffect7(() => {
4384
4611
  if (!transport) return;
4385
4612
  const hello = makeEnvelope("display.hello", { template: DISPLAY_TEMPLATE });
4386
4613
  let configured = false;
@@ -4483,14 +4710,14 @@ function createSaleDisplayPublisher(link, options = {}) {
4483
4710
  }
4484
4711
 
4485
4712
  // src/customer-display/use-sale-display.ts
4486
- import { useEffect as useEffect7, useRef as useRef2 } from "react";
4713
+ import { useEffect as useEffect8, useRef as useRef2 } from "react";
4487
4714
  function useSaleDisplay(link, sale, options) {
4488
4715
  const latest = useRef2(options);
4489
- useEffect7(() => {
4716
+ useEffect8(() => {
4490
4717
  latest.current = options;
4491
4718
  });
4492
4719
  const held = useRef2(null);
4493
- useEffect7(() => {
4720
+ useEffect8(() => {
4494
4721
  if (!link) return;
4495
4722
  if (held.current?.link !== link) {
4496
4723
  const live = {
@@ -4508,7 +4735,7 @@ function useSaleDisplay(link, sale, options) {
4508
4735
  }
4509
4736
  held.current.publisher.update({ order: sale.order, stage: sale.stage });
4510
4737
  }, [link, sale.order, sale.stage]);
4511
- useEffect7(() => () => {
4738
+ useEffect8(() => () => {
4512
4739
  held.current?.publisher.close();
4513
4740
  held.current = null;
4514
4741
  }, [link]);
@@ -4918,7 +5145,7 @@ function createDisplayClient(options) {
4918
5145
 
4919
5146
  // src/customer-display/use-display-client.ts
4920
5147
  import { useCallback as useCallback3, useSyncExternalStore } from "react";
4921
- var STARTING2 = { phase: { phase: "starting" }, state: initialDisplayState };
5148
+ var STARTING3 = { phase: { phase: "starting" }, state: initialDisplayState };
4922
5149
  var views = /* @__PURE__ */ new WeakMap();
4923
5150
  var noSubscription = () => () => {
4924
5151
  };
@@ -4931,7 +5158,7 @@ function viewOf(client) {
4931
5158
  }
4932
5159
  function useDisplayClient(client) {
4933
5160
  const subscribe = useCallback3((listener) => client ? client.onChange(listener) : noSubscription(), [client]);
4934
- const getSnapshot = useCallback3(() => client ? viewOf(client) : STARTING2, [client]);
5161
+ const getSnapshot = useCallback3(() => client ? viewOf(client) : STARTING3, [client]);
4935
5162
  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
4936
5163
  }
4937
5164
 
@@ -4992,7 +5219,7 @@ function createTillDisplayService(options) {
4992
5219
  let forbidden = false;
4993
5220
  let pauseReason = null;
4994
5221
  let latest = null;
4995
- let entries = [];
5222
+ let entries2 = [];
4996
5223
  const timers = { list: null, signal: null };
4997
5224
  let signalBusy = false;
4998
5225
  let listGeneration = 0;
@@ -5002,7 +5229,7 @@ function createTillDisplayService(options) {
5002
5229
  timers[which] = null;
5003
5230
  };
5004
5231
  const emit = () => {
5005
- 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" }));
5006
5233
  listeners.forEach(quietly);
5007
5234
  };
5008
5235
  const push = (slot) => slot.sender.update({
@@ -5114,8 +5341,8 @@ function createTillDisplayService(options) {
5114
5341
  if (latest) callDisplay(slot.view, latest);
5115
5342
  ensureSignalPoll();
5116
5343
  };
5117
- const addSlot = (record) => {
5118
- const id2 = record.displayId;
5344
+ const addSlot = (record2) => {
5345
+ const id2 = record2.displayId;
5119
5346
  const sender = createSnapshotSender({
5120
5347
  clock,
5121
5348
  onError: (error) => void (error !== NOT_SENT && report(error)),
@@ -5130,8 +5357,8 @@ function createTillDisplayService(options) {
5130
5357
  });
5131
5358
  const slot = {
5132
5359
  id: id2,
5133
- record,
5134
- config: configFor(record),
5360
+ record: record2,
5361
+ config: configFor(record2),
5135
5362
  seq: clock.now() - 1,
5136
5363
  link: null,
5137
5364
  view: null,
@@ -5144,12 +5371,12 @@ function createTillDisplayService(options) {
5144
5371
  return slot;
5145
5372
  };
5146
5373
  const reconcile = (records) => {
5147
- const listed = new Set(records.map((record) => record.displayId));
5374
+ const listed = new Set(records.map((record2) => record2.displayId));
5148
5375
  for (const id2 of [...slots.keys()]) if (!listed.has(id2)) remove(id2);
5149
- for (const record of records) {
5150
- let slot = slots.get(record.displayId);
5151
- if (slot) Object.assign(slot, { record, config: configFor(record) });
5152
- 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);
5153
5380
  connect(slot);
5154
5381
  push(slot);
5155
5382
  }
@@ -5186,7 +5413,7 @@ function createTillDisplayService(options) {
5186
5413
  return pauseReason;
5187
5414
  },
5188
5415
  get displays() {
5189
- return entries;
5416
+ return entries2;
5190
5417
  },
5191
5418
  onChange(listener) {
5192
5419
  listeners.add(listener);
@@ -5759,7 +5986,7 @@ function createScanSession(options) {
5759
5986
  }
5760
5987
 
5761
5988
  // src/scanner/use-barcode-scanner.ts
5762
- import { useEffect as useEffect9, useRef as useRef5 } from "react";
5989
+ import { useEffect as useEffect10, useRef as useRef5 } from "react";
5763
5990
  import { merge, Subject as Subject2 } from "rxjs";
5764
5991
 
5765
5992
  // src/scanner/scan-dedup.ts
@@ -5791,7 +6018,7 @@ function scanTimeOf(event) {
5791
6018
  }
5792
6019
 
5793
6020
  // src/scanner/scan-hub-context.tsx
5794
- import { createContext as createContext3, useCallback as useCallback5, useContext as useContext3, useEffect as useEffect8, useMemo as useMemo5, useRef as useRef4, useState as useState7, 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";
5795
6022
 
5796
6023
  // src/scanner/chooser-cancel.ts
5797
6024
  function isChooserCancel(error) {
@@ -6081,9 +6308,9 @@ function createHidScanner(options) {
6081
6308
  }
6082
6309
 
6083
6310
  // src/scanner/scan-events.ts
6084
- import { EMPTY, Subject } from "rxjs";
6311
+ import { EMPTY as EMPTY2, Subject } from "rxjs";
6085
6312
  var inertScanHub = {
6086
- events$: EMPTY,
6313
+ events$: EMPTY2,
6087
6314
  registerSource: () => () => void 0,
6088
6315
  emit: () => void 0
6089
6316
  };
@@ -6299,7 +6526,7 @@ function useDeviceScanControl(scanner) {
6299
6526
  );
6300
6527
  const getState = useCallback5(() => scanner ? scanner.getState() : DISCONNECTED, [scanner]);
6301
6528
  const state = useSyncExternalStore3(subscribe, getState, getState);
6302
- return useMemo5(
6529
+ return useMemo6(
6303
6530
  () => scanner ? {
6304
6531
  available: scanner.available,
6305
6532
  connect: scanner.connect,
@@ -6313,9 +6540,9 @@ function useDeviceScanControl(scanner) {
6313
6540
  function ScanHubProvider({ children, ...props }) {
6314
6541
  const latest = useRef4(props);
6315
6542
  latest.current = props;
6316
- const [hub] = useState7(() => createScanHub());
6317
- const [controllers, setControllers] = useState7(null);
6318
- useEffect8(() => {
6543
+ const [hub] = useState8(() => createScanHub());
6544
+ const [controllers, setControllers] = useState8(null);
6545
+ useEffect9(() => {
6319
6546
  const nav2 = browserNavigator();
6320
6547
  const shared = {
6321
6548
  profiles: {
@@ -6340,7 +6567,7 @@ function ScanHubProvider({ children, ...props }) {
6340
6567
  }, [hub]);
6341
6568
  const serial = useDeviceScanControl(controllers?.serial ?? null);
6342
6569
  const hid = useDeviceScanControl(controllers?.hid ?? null);
6343
- const controls = useMemo5(() => ({ serial, hid }), [serial, hid]);
6570
+ const controls = useMemo6(() => ({ serial, hid }), [serial, hid]);
6344
6571
  return /* @__PURE__ */ jsx3(ScanHubContext.Provider, { value: hub, children: /* @__PURE__ */ jsx3(DeviceScanControlsContext.Provider, { value: controls, children }) });
6345
6572
  }
6346
6573
  function useScanHub() {
@@ -6356,7 +6583,7 @@ function useBarcodeScanner(options) {
6356
6583
  latest.current = options;
6357
6584
  const enabled = options.enabled ?? true;
6358
6585
  const hub = useScanHub();
6359
- useEffect9(() => {
6586
+ useEffect10(() => {
6360
6587
  if (!enabled) return;
6361
6588
  const wedge$ = new Subject2();
6362
6589
  const subscription = merge(wedge$, hub.events$).pipe(dedupeScans(SCAN_DEDUP_WINDOW_MS, scanTimeOf)).subscribe((event) => {
@@ -6559,15 +6786,15 @@ var CAMERA_CONSTRAINTS = {
6559
6786
  };
6560
6787
 
6561
6788
  // src/scanner/use-camera-scan.ts
6562
- import { useMemo as useMemo6, useRef as useRef6, useState as useState8 } from "react";
6789
+ import { useMemo as useMemo7, useRef as useRef6, useState as useState9 } from "react";
6563
6790
  function useCameraScan(options = {}) {
6564
6791
  const latest = useRef6(options);
6565
6792
  latest.current = options;
6566
6793
  const hub = useScanHub();
6567
6794
  const hubRef = useRef6(hub);
6568
6795
  hubRef.current = hub;
6569
- const [scanCount, setScanCount] = useState8(0);
6570
- const [session] = useState8(() => createScanSession({
6796
+ const [scanCount, setScanCount] = useState9(0);
6797
+ const [session] = useState9(() => createScanSession({
6571
6798
  continuous: true,
6572
6799
  now: () => (latest.current.now ?? Date.now)(),
6573
6800
  onAccept: (code, symbology) => {
@@ -6575,7 +6802,7 @@ function useCameraScan(options = {}) {
6575
6802
  setScanCount((count) => count + 1);
6576
6803
  }
6577
6804
  }));
6578
- return useMemo6(() => ({
6805
+ return useMemo7(() => ({
6579
6806
  offer: (code, symbology) => {
6580
6807
  const { active = true, minChars = DEFAULT_MIN_SCAN_CHARS, onTooShort } = latest.current;
6581
6808
  if (!active) return;
@@ -6926,8 +7153,8 @@ function resolveCodePage(name) {
6926
7153
  return ESCPOS_CODE_PAGES[name] ?? ESCPOS_CODE_PAGES.cp437;
6927
7154
  }
6928
7155
  var PRINTABLE_ASCII = /^[\x20-\x7E]$/;
6929
- function foldText(text2, page) {
6930
- 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, " ");
6931
7158
  return Array.from(normalized, (char) => {
6932
7159
  if (char === "\n" || PRINTABLE_ASCII.test(char) || page.high.includes(char)) return char;
6933
7160
  if (char === "\xD7") return "x";
@@ -7045,10 +7272,10 @@ function escpos(page = resolveCodePage()) {
7045
7272
 
7046
7273
  // src/print/escpos/encode.ts
7047
7274
  import { formatMoney as formatMoney3, moneyToMajor } from "@tallyui/core";
7048
- function wrapText(text2, width) {
7275
+ function wrapText(text3, width) {
7049
7276
  const lines = [];
7050
7277
  let line = "";
7051
- for (let word of text2.split(" ").filter(Boolean)) {
7278
+ for (let word of text3.split(" ").filter(Boolean)) {
7052
7279
  while (word.length > width) {
7053
7280
  if (line) lines.push(line);
7054
7281
  line = "";
@@ -7068,7 +7295,7 @@ function wrapText(text2, width) {
7068
7295
  function encodeEscPos(receipt, options) {
7069
7296
  const { columns, cut = true, openDrawer = false, drawerConnector = "pin2" } = options;
7070
7297
  const page = resolveCodePage(options.codePage);
7071
- const fold = (text2) => foldText(text2, page);
7298
+ const fold = (text3) => foldText(text3, page);
7072
7299
  const money = options.formatMoney ?? ((minor2, currency) => {
7073
7300
  const formatted = formatMoney3({ amount: minor2, currency }) ?? "";
7074
7301
  if (!fold(formatted).includes("?")) return formatted;
@@ -7080,7 +7307,7 @@ function encodeEscPos(receipt, options) {
7080
7307
  for (const line of lines) out.text(`${line}
7081
7308
  `);
7082
7309
  };
7083
- 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));
7084
7311
  const pair = (left, right, indent = "") => {
7085
7312
  const amount = fold(right);
7086
7313
  const space = columns - amount.length - 1;
@@ -7372,7 +7599,7 @@ function openDrawerJob(profile, id2) {
7372
7599
  var PLAIN = { bold: false, underline: false, invert: false, width: 1, height: 1 };
7373
7600
  var TRAILING = /* @__PURE__ */ new Set(["cut", "feed", "drawer"]);
7374
7601
  var BREAK = /\r\n|\r|\n/;
7375
- var leading = (text2) => text2.length - text2.replace(/^ +/, "").length;
7602
+ var leading = (text3) => text3.length - text3.replace(/^ +/, "").length;
7376
7603
  function renderEscpos(ast, options = {}) {
7377
7604
  const page = resolveCodePage(options.codePage);
7378
7605
  const columns = options.columns ?? ast.paperWidth;
@@ -7388,14 +7615,14 @@ function renderEscpos(ast, options = {}) {
7388
7615
  if (next.invert !== printed.invert) out.invert(next.invert);
7389
7616
  printed = next;
7390
7617
  };
7391
- const emit = (text2, styles, mode, scale) => {
7392
- const room = columns - text2.length * scale;
7618
+ const emit = (text3, styles, mode, scale) => {
7619
+ const room = columns - text3.length * scale;
7393
7620
  const pad = Math.floor((mode === "center" ? Math.floor(room / 2) : mode === "right" ? room : 0) / scale);
7394
- if (text2 && pad > 0) {
7621
+ if (text3 && pad > 0) {
7395
7622
  sync({ ...styles[0], underline: false, invert: false });
7396
7623
  out.text(" ".repeat(pad));
7397
7624
  }
7398
- Array.from(text2).forEach((char, i) => {
7625
+ Array.from(text3).forEach((char, i) => {
7399
7626
  sync(styles[i]);
7400
7627
  out.text(char);
7401
7628
  });
@@ -7403,15 +7630,15 @@ function renderEscpos(ast, options = {}) {
7403
7630
  };
7404
7631
  const endLine = (force) => {
7405
7632
  if (!force && !line.length) return;
7406
- const text2 = line.map((run) => run.text).join("");
7633
+ const text3 = line.map((run) => run.text).join("");
7407
7634
  const styles = line.flatMap((run) => Array.from(run.text, () => run.style));
7408
7635
  const scale = Math.max(1, ...line.map((run) => run.style.width));
7409
- const indent = leading(text2);
7636
+ const indent = leading(text3);
7410
7637
  line = [];
7411
7638
  let cursor = indent;
7412
- 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))) {
7413
7640
  const partStyles = Array.from(part, (char) => {
7414
- while (text2[cursor] !== char) cursor++;
7641
+ while (text3[cursor] !== char) cursor++;
7415
7642
  return styles[cursor++];
7416
7643
  });
7417
7644
  emit(" ".repeat(indent) + part, [...styles.slice(0, indent), ...partStyles], align, scale);
@@ -7420,9 +7647,9 @@ function renderEscpos(ast, options = {}) {
7420
7647
  const row = (cols) => {
7421
7648
  const widths = rowWidths(cols, Math.floor(columns / style.width));
7422
7649
  const cells = cols.map((col, i) => {
7423
- const text2 = foldText(extractText(col.children).split(BREAK).join(" "), page);
7424
- const indent = col.align === "left" ? Math.min(leading(text2), widths[i] - 1) : 0;
7425
- 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]));
7426
7653
  });
7427
7654
  const height = Math.max(0, ...cells.map((cell) => cell.length));
7428
7655
  for (let r = 0; r < height; r++) {
@@ -7525,7 +7752,7 @@ var extractText = (nodes) => nodes.map((node) => node.type === "raw-text" ? node
7525
7752
  var hasDrawer = (nodes) => nodes.some((node) => node.type === "drawer" || "children" in node && hasDrawer(node.children));
7526
7753
 
7527
7754
  // src/sale/use-sale.ts
7528
- import { useEffect as useEffect11, useLayoutEffect, useMemo as useMemo8, useRef as useRef8, useState as useState10 } from "react";
7755
+ import { useEffect as useEffect12, useLayoutEffect, useMemo as useMemo9, useRef as useRef8, useState as useState11 } from "react";
7529
7756
  import { ORDER_META_KEY_MAX as ORDER_META_KEY_MAX3, ORDER_META_MAX as ORDER_META_MAX2, paymentMethodOf as paymentMethodOf2 } from "@tallyui/core";
7530
7757
 
7531
7758
  // src/tender/split-units.ts
@@ -7702,11 +7929,11 @@ function orderBuilderFromStoreOrder(read, options) {
7702
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";
7703
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.";
7704
7931
  var TAX_ID_LABEL_MAX = 255;
7705
- function cleanTaxIds(list) {
7706
- if (list.length > ORDER_TAX_IDS_MAX2) return null;
7932
+ function cleanTaxIds(list2) {
7933
+ if (list2.length > ORDER_TAX_IDS_MAX2) return null;
7707
7934
  const seen = /* @__PURE__ */ new Set();
7708
7935
  const cleaned = [];
7709
- for (const taxId of list) {
7936
+ for (const taxId of list2) {
7710
7937
  const type = taxId.type.trim(), value = taxId.value.trim(), country = taxId.country?.trim().toUpperCase(), label = taxId.label?.trim();
7711
7938
  const key = JSON.stringify([type, value]);
7712
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;
@@ -7732,8 +7959,8 @@ var outboxLogger = createLogger("outbox");
7732
7959
  // src/pos-order/finalize.ts
7733
7960
  var ORDER_ADDRESS_KEYS = ["firstName", "lastName", "company", "address1", "address2", "city", "state", "postcode", "country", "phone"];
7734
7961
  function orderAddress(address) {
7735
- const entries = ORDER_ADDRESS_KEYS.flatMap((key) => typeof address?.[key] === "string" && address[key] ? [[key, address[key]]] : []);
7736
- 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;
7737
7964
  }
7738
7965
  var AFTER_CLOSE_PAYMENTS_CHANGED = "This sale was counted in a closed register. Its payments must stay as that closure counted them.";
7739
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);
@@ -7884,6 +8111,9 @@ function finalizeOrder(order, options = {}) {
7884
8111
  if (order.lineItems.some((line) => line.anyAttributes?.length) && (options.capabilities?.orderCreate ?? 1) < 6) {
7885
8112
  throw new Error("finalize: picked options need the store to accept order.create version 6; update the store's TallyUI plugin");
7886
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
+ }
7887
8117
  if (!order.lineItems.length) throw new Error("finalize: no lines");
7888
8118
  if (order.discountMinor < 0 || order.lineItems.some((line) => line.discountMinor < 0) || order.discounts.some((d) => d.amountMinor < 0)) {
7889
8119
  throw new Error("finalize: negative discount");
@@ -7980,7 +8210,8 @@ function finalizeOrder(order, options = {}) {
7980
8210
  ...payment.tenderedMinor !== void 0 ? { tenderedMinor: payment.tenderedMinor } : {},
7981
8211
  ...payment.changeMinor !== void 0 ? { changeMinor: payment.changeMinor } : {},
7982
8212
  ...payment.reference !== void 0 ? { reference: payment.reference } : {},
7983
- ...isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}
8213
+ ...isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {},
8214
+ ...payment.sessionId !== void 0 ? { sessionId: payment.sessionId } : {}
7984
8215
  }));
7985
8216
  const localWarnings = options.localWarnings?.flatMap((warning) => {
7986
8217
  if (warning.code !== "payment_reference_dropped") return [{ ...warning }];
@@ -8062,6 +8293,11 @@ function finalizeOrder(order, options = {}) {
8062
8293
  pricesIncludeTax: order.pricesIncludeTax,
8063
8294
  lines,
8064
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
+ }) } : {},
8065
8301
  ...fees?.length ? { fees } : {},
8066
8302
  ...shipping?.length ? { shipping } : {},
8067
8303
  subtotalMinor: order.subtotalMinor,
@@ -8117,7 +8353,7 @@ var orderAddressSchema = { type: "object", additionalProperties: false, properti
8117
8353
  phone: { type: "string" }
8118
8354
  } };
8119
8355
  var posOrderSchema = {
8120
- version: 20,
8356
+ version: 21,
8121
8357
  primaryKey: "id",
8122
8358
  type: "object",
8123
8359
  additionalProperties: false,
@@ -8248,6 +8484,10 @@ var posOrderSchema = {
8248
8484
  },
8249
8485
  required: ["id", "method", "amountMinor"]
8250
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"] } },
8251
8491
  customer: { type: ["object", "null"], properties: {
8252
8492
  id: { type: "string" },
8253
8493
  name: { type: "string" },
@@ -8378,7 +8618,7 @@ function posOrderCollection() {
8378
8618
  };
8379
8619
  return {
8380
8620
  schema: posOrderSchema,
8381
- 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 }
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 }
8382
8622
  };
8383
8623
  }
8384
8624
 
@@ -8475,13 +8715,13 @@ async function openCollection(db, opener, previous) {
8475
8715
  await (closing() ? checkpoint.close() : checkpoint.remove());
8476
8716
  stopIfClosing();
8477
8717
  const settled = new Subject3();
8478
- let inFlight2 = 0;
8718
+ let inFlight3 = 0;
8479
8719
  let drained;
8480
8720
  const track = (result) => {
8481
8721
  if (!(result instanceof Promise)) return result;
8482
- inFlight2++;
8722
+ inFlight3++;
8483
8723
  return result.finally(() => {
8484
- if (--inFlight2 === 0) drained?.();
8724
+ if (--inFlight3 === 0) drained?.();
8485
8725
  });
8486
8726
  };
8487
8727
  const gate = (target, closed) => new Proxy(target, { get: (t, key) => {
@@ -8517,7 +8757,7 @@ async function openCollection(db, opener, previous) {
8517
8757
  state.cancel = () => {
8518
8758
  if (running) {
8519
8759
  cancelled = true;
8520
- if (inFlight2 === 0) onCancel();
8760
+ if (inFlight3 === 0) onCancel();
8521
8761
  else drained = onCancel;
8522
8762
  }
8523
8763
  return cancel();
@@ -8626,11 +8866,6 @@ function moneyDivergence(order) {
8626
8866
  return orderFields.length === 0 && lineIds.length === 0 ? null : { orderFields, lineIds };
8627
8867
  }
8628
8868
 
8629
- // src/pos-order/till-payments.ts
8630
- function tillPayments(payments) {
8631
- return payments.filter((payment) => payment.storePaymentId === void 0);
8632
- }
8633
-
8634
8869
  // src/register/expected.ts
8635
8870
  import { legMethodId } from "@tallyui/core";
8636
8871
  function refundAmounts(refund) {
@@ -8642,13 +8877,19 @@ function refundAmounts(refund) {
8642
8877
  }
8643
8878
  function paymentLedgerRows(orders) {
8644
8879
  return orders.flatMap((order) => tillPayments(order.payments).map((payment) => ({
8645
- session_id: order.sessionId,
8880
+ session_id: payment.sessionId ?? order.sessionId,
8646
8881
  kind: payment.method === "cash" ? "cash" : "other",
8647
8882
  method_id: payment.method,
8648
8883
  status: "captured",
8649
8884
  amountMinor: payment.amountMinor
8650
8885
  })));
8651
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
+ }
8652
8893
  function deriveExpected({
8653
8894
  session,
8654
8895
  movements,
@@ -8719,11 +8960,11 @@ function deriveDrawerTerms(input) {
8719
8960
  expected: deriveExpected(input)
8720
8961
  };
8721
8962
  }
8722
- function takingsByMethod(orders, sessionId) {
8963
+ function takingsByMethod(orders, sessionId, extra = []) {
8723
8964
  const takings = /* @__PURE__ */ Object.create(null);
8724
- for (const order of orders) {
8725
- if (order.sessionId !== sessionId) continue;
8965
+ for (const order of [...orders, { payments: extra }]) {
8726
8966
  for (const payment of tillPayments(order.payments)) {
8967
+ if ((payment.sessionId ?? order.sessionId) !== sessionId) continue;
8727
8968
  const term = takings[legMethodId(payment)] ??= { amountMinor: 0, count: 0 };
8728
8969
  term.amountMinor += payment.amountMinor;
8729
8970
  term.count += 1;
@@ -8889,6 +9130,13 @@ function renumberClosures(host, storeKey, registerId, rows) {
8889
9130
  });
8890
9131
  });
8891
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
+ }
8892
9140
  function advancePerpetual(host, storeKey, registerId, period) {
8893
9141
  return modifyStore(host, storeKey, (store) => {
8894
9142
  const register = store?.registers?.[registerId] ?? {};
@@ -9019,8 +9267,8 @@ function movementFieldError(input) {
9019
9267
  }
9020
9268
 
9021
9269
  // src/register/register-count.helpers.ts
9022
- function parseMinor(text2, exponent) {
9023
- const [whole, fraction = ""] = text2.trim().split(".");
9270
+ function parseMinor(text3, exponent) {
9271
+ const [whole, fraction = ""] = text3.trim().split(".");
9024
9272
  if (fraction.length > exponent) return NaN;
9025
9273
  return Number(whole || "0") * 10 ** exponent + Number(fraction.padEnd(exponent, "0") || "0");
9026
9274
  }
@@ -9307,6 +9555,9 @@ async function writeClosure({
9307
9555
  otherTenders,
9308
9556
  movements,
9309
9557
  orders,
9558
+ drafts,
9559
+ liveLegs,
9560
+ liveRoundings,
9310
9561
  refunds,
9311
9562
  tillExpected,
9312
9563
  labels,
@@ -9327,11 +9578,11 @@ async function writeClosure({
9327
9578
  const replaced = replacedOrderIds(orders);
9328
9579
  const bound = orders.filter((order) => order.sessionId === session.id && !replaced.has(order.id));
9329
9580
  const countedRefunds = (refunds ?? []).filter((refund) => refund.status === "applied" && refund.sessionId === session.id);
9330
- const rows = paymentLedgerRows(bound);
9331
- 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);
9332
9583
  const till_expected = tillExpected ?? deriveExpected({
9333
9584
  session: { id: session.id, countedFloatMinor: session.counted_float_minor },
9334
- movements: entries,
9585
+ movements: entries2,
9335
9586
  ledgerRowsBySession: rows,
9336
9587
  refunds
9337
9588
  });
@@ -9348,6 +9599,7 @@ async function writeClosure({
9348
9599
  }
9349
9600
  }
9350
9601
  const payment_methods = Object.fromEntries(methodTotals);
9602
+ const taxRateKey = (code, ratePpm) => `${ratePpm}:${(code ?? "").replace(/[%.[\]\\]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`;
9351
9603
  const taxRates = /* @__PURE__ */ new Map();
9352
9604
  const roundings = /* @__PURE__ */ new Set();
9353
9605
  for (const order of bound) {
@@ -9355,16 +9607,27 @@ async function writeClosure({
9355
9607
  const rounding = recorded.granularity === "custom" ? DEFAULT_TAX_ROUNDING : recorded;
9356
9608
  roundings.add(rounding.granularity === "woocommerce" ? `woocommerce ${rounding.roundAtSubtotal}` : `${rounding.granularity} ${rounding.mode}`);
9357
9609
  const taxedLines = taxedLinesFor(order.lines, [...order.fees ?? [], ...order.shipping ?? []], order.pricesIncludeTax, order.taxRounding);
9358
- for (const { ratePpm, netMinor, amountMinor } of taxLinesByRate(taxedLines, order.taxMinor, void 0, order.taxRounding)) {
9359
- const existing2 = taxRates.get(String(ratePpm));
9360
- 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), {
9361
9613
  ratePpm,
9614
+ code,
9362
9615
  net_minor: (existing2?.net_minor ?? 0) + netMinor,
9363
9616
  tax_minor: (existing2?.tax_minor ?? 0) + amountMinor
9364
9617
  });
9365
9618
  }
9366
9619
  }
9367
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)));
9368
9631
  const draft = {
9369
9632
  id: session.id,
9370
9633
  session_id: session.id,
@@ -9398,21 +9661,24 @@ async function writeClosure({
9398
9661
  ...session.count_note?.trim() ? { variance_note: session.count_note } : {},
9399
9662
  payment_methods,
9400
9663
  tax_rates: Object.fromEntries(
9401
- [...taxRates.values()].map(({ ratePpm, net_minor, tax_minor }) => [
9402
- ratePpm,
9403
- { 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 }
9404
9668
  ])
9405
9669
  ),
9406
9670
  // The session's sales used more than one tax rounding (#287): the Z report says so.
9407
9671
  ...roundings.size > 1 ? { tax_rounding_mixed: true } : {},
9408
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).
9409
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 } : {},
9410
9676
  opening_float: {
9411
9677
  expected_minor: session.expected_float_minor ?? null,
9412
9678
  counted_minor: session.counted_float_minor,
9413
9679
  variance_minor: session.opening_variance_minor ?? null
9414
9680
  },
9415
- 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 }) => ({
9416
9682
  id: id2,
9417
9683
  type,
9418
9684
  amountMinor,
@@ -9434,7 +9700,7 @@ async function writeClosure({
9434
9700
  }))
9435
9701
  },
9436
9702
  order_ids: bound.map((order) => order.id),
9437
- movement_ids: entries.map((row2) => row2.id)
9703
+ movement_ids: entries2.map((row2) => row2.id)
9438
9704
  };
9439
9705
  await mintClosureNumber(register, storeKey, session.register_id, draft);
9440
9706
  const reserved = (await readRegister(register)).stores[storeKey].registers[session.register_id].closure_reservation.row;
@@ -9549,7 +9815,8 @@ async function reopenRefusedOrder(orderId, deps, options) {
9549
9815
  ...shipping.taxStatus !== void 0 ? { taxStatus: shipping.taxStatus } : {},
9550
9816
  ...shipping.methodId !== void 0 ? { methodId: shipping.methodId } : {}
9551
9817
  });
9552
- 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({
9553
9820
  // After close each leg keeps the refused order's id, so finalize knows it for the leg that closure counted.
9554
9821
  ...afterClose ? { id: payment.id } : {},
9555
9822
  method: payment.method,
@@ -9557,8 +9824,13 @@ async function reopenRefusedOrder(orderId, deps, options) {
9557
9824
  reopened: true,
9558
9825
  ...payment.reference !== void 0 ? { reference: payment.reference } : {},
9559
9826
  ...payment.methodId !== void 0 ? { methodId: payment.methodId } : {},
9560
- ...isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}
9561
- });
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
+ }
9562
9834
  if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
9563
9835
  builder.setCustomer({
9564
9836
  id: order.customer.id,
@@ -9634,72 +9906,372 @@ var OrderContentMismatchError = class extends Error {
9634
9906
  }
9635
9907
  };
9636
9908
 
9637
- // src/register/register-count.denominations.ts
9638
- var coinsMinor = [200, 100, 50, 20, 10, 5, 2, 1];
9639
- var denominations = {
9640
- GBP: [5e3, 2e3, 1e3, 500, ...coinsMinor],
9641
- EUR: [5e4, 2e4, 1e4, 5e3, 2e3, 1e3, 500, ...coinsMinor],
9642
- USD: [1e4, 5e3, 2e3, 1e3, 500, 100, 25, 10, 5, 1],
9643
- default: [1e4, 5e3, 2e3, 1e3, 500, 200, 100, 50, 25, 10, 5, 1]
9644
- };
9909
+ // src/tender/cash-rounding.ts
9910
+ import { wireMethodOf } from "@tallyui/core";
9645
9911
 
9646
- // src/register/schemas.ts
9647
- import { addRxPlugin as addRxPlugin2 } from "rxdb";
9648
- import { RxDBLocalDocumentsPlugin } from "rxdb/plugins/local-documents";
9649
- import { RxDBMigrationSchemaPlugin as RxDBMigrationSchemaPlugin2 } from "rxdb/plugins/migration-schema";
9650
- var id = { type: "string", maxLength: 36 };
9651
- var text = { type: "string" };
9652
- var nullableText = { type: ["string", "null"] };
9653
- var minor = { type: "integer" };
9654
- var nullableMinor = { type: ["integer", "null"] };
9655
- var tenders = { type: "object", additionalProperties: minor };
9656
- var registerSessionSchema = {
9657
- title: "Register sessions",
9658
- version: 2,
9659
- primaryKey: "id",
9660
- type: "object",
9661
- additionalProperties: false,
9662
- properties: {
9663
- id,
9664
- register_id: id,
9665
- store_key: nullableText,
9666
- status: { type: "string", maxLength: 20 },
9667
- server_session_id: { ...nullableText, default: null },
9668
- business_day: { type: "string", maxLength: 10 },
9669
- opened_at_gmt: text,
9670
- opened_by: nullableText,
9671
- expected_float_minor: nullableMinor,
9672
- counted_float_minor: minor,
9673
- opening_variance_minor: nullableMinor,
9674
- counting_started_at_gmt: nullableText,
9675
- closed_at_gmt: nullableText,
9676
- closed_by: nullableText,
9677
- approval_required: { type: "boolean", default: false },
9678
- approved_by: nullableText,
9679
- counted: { type: ["object", "null"], additionalProperties: minor },
9680
- closure_id: nullableText,
9681
- pending_status: { ...nullableText, default: null },
9682
- server_status: { ...nullableText, default: null },
9683
- status_at: { ...nullableText, default: null },
9684
- approver_token: { ...nullableText, default: null },
9685
- server_expected: { type: ["object", "null"], additionalProperties: minor, default: null },
9686
- server_sales_count: { type: ["integer", "null"], default: null },
9687
- count_note: { ...nullableText, default: null }
9688
- },
9689
- required: ["id", "register_id", "status", "opened_at_gmt", "counted_float_minor"],
9690
- indexes: [["register_id", "status"]]
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: {}
9691
9929
  };
9692
- function registerSessionCreator() {
9693
- addRxPlugin2(RxDBLocalDocumentsPlugin);
9694
- addRxPlugin2(RxDBMigrationSchemaPlugin2);
9695
- return { schema: registerSessionSchema, localDocuments: true, migrationStrategies: { 1: (doc) => {
9696
- doc.server_session_id ??= null;
9697
- return doc;
9698
- }, 2: (doc) => {
9699
- doc.count_note ??= null;
9700
- return doc;
9701
- } } };
9702
- }
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",
10232
+ type: "object",
10233
+ additionalProperties: false,
10234
+ properties: {
10235
+ id,
10236
+ register_id: id,
10237
+ store_key: nullableText,
10238
+ status: { type: "string", maxLength: 20 },
10239
+ server_session_id: { ...nullableText, default: null },
10240
+ business_day: { type: "string", maxLength: 10 },
10241
+ opened_at_gmt: text,
10242
+ opened_by: nullableText,
10243
+ expected_float_minor: nullableMinor,
10244
+ counted_float_minor: minor,
10245
+ opening_variance_minor: nullableMinor,
10246
+ counting_started_at_gmt: nullableText,
10247
+ closed_at_gmt: nullableText,
10248
+ closed_by: nullableText,
10249
+ approval_required: { type: "boolean", default: false },
10250
+ approved_by: nullableText,
10251
+ counted: { type: ["object", "null"], additionalProperties: minor },
10252
+ closure_id: nullableText,
10253
+ pending_status: { ...nullableText, default: null },
10254
+ server_status: { ...nullableText, default: null },
10255
+ status_at: { ...nullableText, default: null },
10256
+ approver_token: { ...nullableText, default: null },
10257
+ server_expected: { type: ["object", "null"], additionalProperties: minor, default: null },
10258
+ server_sales_count: { type: ["integer", "null"], default: null },
10259
+ count_note: { ...nullableText, default: null }
10260
+ },
10261
+ required: ["id", "register_id", "status", "opened_at_gmt", "counted_float_minor"],
10262
+ indexes: [["register_id", "status"]]
10263
+ };
10264
+ function registerSessionCreator() {
10265
+ addRxPlugin2(RxDBLocalDocumentsPlugin);
10266
+ addRxPlugin2(RxDBMigrationSchemaPlugin2);
10267
+ return { schema: registerSessionSchema, localDocuments: true, migrationStrategies: { 1: (doc) => {
10268
+ doc.server_session_id ??= null;
10269
+ return doc;
10270
+ }, 2: (doc) => {
10271
+ doc.count_note ??= null;
10272
+ return doc;
10273
+ } } };
10274
+ }
9703
10275
  function registerSessionCollection() {
9704
10276
  throw new Error("registerSessionCollection() is gone: open register_sessions with await addRegisterSessionCollection(db). Adding it with addCollections would run RxDB's own migration of an older schema version, which can lose sessions (ADR-078, #371).");
9705
10277
  }
@@ -9856,6 +10428,67 @@ function deriveSettled(recorded, corrections) {
9856
10428
  return { settled, touched };
9857
10429
  }
9858
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
+
9859
10492
  // src/register/float-suggestion.ts
9860
10493
  function suggestFloat({ register, lastCountedCashMinor }) {
9861
10494
  if (register?.defaultFloatMinor != null) return { amountMinor: register.defaultFloatMinor, source: "default" };
@@ -9980,7 +10613,9 @@ var labelKeys = {
9980
10613
  paid_out: "register.paid_out",
9981
10614
  no_sale: "register.no_sale",
9982
10615
  void: "register.void",
9983
- 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"
9984
10619
  };
9985
10620
  var ENGLISH_CLOSURE_LABELS = {
9986
10621
  x_report: "X report",
@@ -10023,7 +10658,8 @@ var ENGLISH_CLOSURE_LABELS = {
10023
10658
  paid_out: "Paid out",
10024
10659
  no_sale: "No sale",
10025
10660
  void: "Void",
10026
- copy: "Copy"
10661
+ copy: "Copy",
10662
+ cash_rounding: "Rounding"
10027
10663
  };
10028
10664
 
10029
10665
  // src/register/closure-rows.ts
@@ -10080,20 +10716,24 @@ function decimalizeBreakdowns(breakdowns, exponent) {
10080
10716
  ])
10081
10717
  );
10082
10718
  };
10083
- const openingFloat = breakdowns.opening_float;
10719
+ const float = closureFigures({ breakdowns }).openingFloat;
10720
+ const decOrNull = (m) => m === void 0 ? null : minorToDecimal(m, exponent);
10084
10721
  return {
10085
10722
  ...breakdowns,
10086
10723
  ...breakdowns.payment_methods ? { payment_methods: group("payment_methods", [["sales_minor", "sales"], ["refunds_minor", "refunds"]]) } : {},
10087
10724
  ...breakdowns.tax_rates ? { tax_rates: group("tax_rates", [["net_minor", "net"], ["tax_minor", "tax"], ["gross_minor", "gross"]]) } : {},
10088
- ...openingFloat ? {
10725
+ ...breakdowns.opening_float ? {
10089
10726
  opening_float: {
10090
- ...openingFloat,
10091
- expected: dec(openingFloat.expected_minor),
10092
- counted: dec(openingFloat.counted_minor),
10093
- 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)
10094
10733
  }
10095
10734
  } : {},
10096
- ...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) } : {}
10097
10737
  };
10098
10738
  }
10099
10739
  function formatClosureDate(value, context) {
@@ -10170,9 +10810,11 @@ function envelope(row, context, xreport = false) {
10170
10810
  ...Object.fromEntries(
10171
10811
  ["payment_methods", "tax_rates", "movements"].map((key) => [`has_${key}`, Object.keys(breakdowns[key] ?? {}).length > 0])
10172
10812
  ),
10813
+ has_cash_rounding: breakdowns.cash_rounding !== void 0,
10173
10814
  ...breakdowns.tax_rounding_mixed === true ? { tax_rounding_note: TAX_ROUNDING_MIXED_NOTE } : {},
10174
10815
  ...breakdowns.tax_includes_store_paid === true ? { tax_store_paid_note: TAX_STORE_PAID_NOTE } : {},
10175
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"]) } : {},
10176
10818
  opened_at_gmt: row.opened_at,
10177
10819
  opened_by: breakdowns.opened_by ?? null,
10178
10820
  closed_by: row.closed_by ?? null,
@@ -10193,7 +10835,7 @@ function envelope(row, context, xreport = false) {
10193
10835
  type_label: context.i18n[String(m.type)] ?? m.type,
10194
10836
  voided: !!m.voided_by
10195
10837
  })),
10196
- cashiers: (breakdowns.cashiers ?? []).map((c) => typeof c === "string" ? { id: c, name: c } : c)
10838
+ cashiers: closureFigures({ breakdowns }).cashiers
10197
10839
  }
10198
10840
  },
10199
10841
  store: context.store,
@@ -10288,7 +10930,7 @@ function buildXReportDocument(session, context) {
10288
10930
  }
10289
10931
 
10290
10932
  // src/register/use-register-session.ts
10291
- import { useEffect as useEffect10, useMemo as useMemo7, useRef as useRef7, useState as useState9, useSyncExternalStore as useSyncExternalStore4 } from "react";
10933
+ import { useEffect as useEffect11, useMemo as useMemo8, useRef as useRef7, useState as useState10, useSyncExternalStore as useSyncExternalStore4 } from "react";
10292
10934
  import { combineLatest, map as map7, of, switchMap } from "rxjs";
10293
10935
 
10294
10936
  // src/outbox/register-outbox.ts
@@ -10415,14 +11057,14 @@ function reconcileRegisterCommands({ commands, sessions, movements, closures, ho
10415
11057
  const rows = await readFresh(sessions, { selector: { register_id: registerId } });
10416
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));
10417
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) => {
10418
- const [entries, closureRows] = await Promise.all([
11060
+ const [entries2, closureRows] = await Promise.all([
10419
11061
  readFresh(movements, { selector: { session_id: session.id } }),
10420
11062
  session.closure_id ? closures.storageInstance.findDocumentsById([session.closure_id], false) : Promise.resolve([])
10421
11063
  ]);
10422
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 })]);
10423
11065
  events.push(
10424
- ...entries.filter((entry) => entry.type !== "void").map(movementCommand),
10425
- ...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)
10426
11068
  );
10427
11069
  if (session.status_at != null && sentStatus(session)) events.push(sessionTransitionCommand({ ...session, status_at: session.status_at }));
10428
11070
  return { session, number: closureRows[0]?.number, built: [
@@ -10499,6 +11141,8 @@ var syncRecordOf = (orderId, outcome) => ({ collection: "pos_orders", recordId:
10499
11141
  var ISOLATE_AFTER_ATTEMPTS = 5;
10500
11142
  var STUCK_AFTER_MS = 15 * 6e4;
10501
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();
10502
11146
  function createOrderOutbox(options) {
10503
11147
  const { collection, transport, deviceId } = options;
10504
11148
  const toEnvelope = (order, attempt2, maxVersion) => order.storeOrderId !== void 0 ? toOrderUpdateEnvelope(order, deviceId, attempt2, { maxVersion }) : toOrderCreateEnvelope(order, deviceId, attempt2, { maxVersion });
@@ -10601,16 +11245,23 @@ function createOrderOutbox(options) {
10601
11245
  const delay = retryDelay(entry.backoff, retryAfterMs, maxBackoff, random);
10602
11246
  isolated.set(id2, { reason, backoff: Math.min(entry.backoff * 2, maxBackoff), nextAt: now() + delay });
10603
11247
  }
10604
- function serverFailed(orders, alone, reason, retryAfterMs) {
11248
+ function serverFailed(orders, alone, reason, retryAfterMs, needsAdminId) {
10605
11249
  const at2 = now();
10606
- 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
+ });
10607
11255
  const id2 = orders[0].commandId;
10608
11256
  if (alone === "isolated") {
10609
11257
  isolate(id2, reason, retryAfterMs);
10610
11258
  if (runProgressed && retryAfterMs === void 0 && reason !== "status_429") return void 0;
10611
11259
  return Math.max(retryAfterMs ?? 0, isolated.get(id2).nextAt - now());
10612
11260
  }
10613
- 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
+ });
10614
11265
  else {
10615
11266
  head = { id: id2, count: head?.id === id2 ? head.count + 1 : 1 };
10616
11267
  if (head.count >= isolateAfter) walk ??= { failed: /* @__PURE__ */ new Map() };
@@ -10764,7 +11415,7 @@ function createOrderOutbox(options) {
10764
11415
  if (outcome.reason === "network") {
10765
11416
  for (const clock of clocks.values()) clock.pausedAt ??= now();
10766
11417
  walk = void 0;
10767
- } 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;
10768
11419
  return scheduleRetry(outcome.reason, floor);
10769
11420
  }
10770
11421
  if (outcome.kind === "unauthorized") {
@@ -10941,7 +11592,7 @@ function createOrderOutbox(options) {
10941
11592
  }
10942
11593
  updateState().catch(() => {
10943
11594
  });
10944
- return {
11595
+ const outbox = {
10945
11596
  state$,
10946
11597
  flush,
10947
11598
  async requeue(orderIds) {
@@ -11023,6 +11674,8 @@ function createOrderOutbox(options) {
11023
11674
  state$.next({ ...state$.value, nextAttemptAt: void 0 });
11024
11675
  }
11025
11676
  };
11677
+ stateRefreshers.set(outbox, () => updateState());
11678
+ return outbox;
11026
11679
  }
11027
11680
 
11028
11681
  // src/outbox/safe-error.ts
@@ -11119,9 +11772,13 @@ function createRegisterOutbox(options) {
11119
11772
  orders: stuck.map(([commandId, { since, firstFailedAt, reason }]) => ({ commandId, since, firstFailedAt, reason }))
11120
11773
  };
11121
11774
  }
11122
- function serverFailed(commands, reason) {
11775
+ function serverFailed(commands, reason, needsAdminId) {
11123
11776
  const at2 = now();
11124
- 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
+ });
11125
11782
  }
11126
11783
  function isNonBlocking(command, abandoned) {
11127
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);
@@ -11215,7 +11872,7 @@ function createRegisterOutbox(options) {
11215
11872
  clock.pausedAt = void 0;
11216
11873
  }
11217
11874
  if (outcome.kind === "retry") {
11218
- if (outcome.reason !== "network") serverFailed(commands, outcome.reason);
11875
+ if (outcome.reason !== "network") serverFailed(commands, outcome.reason, outcome.needsAdmin?.id);
11219
11876
  return scheduleRetry(outcome.reason, outcome.retryAfterMs);
11220
11877
  }
11221
11878
  if (outcome.kind === "unauthorized") {
@@ -11366,6 +12023,20 @@ function createRegisterOutbox(options) {
11366
12023
  };
11367
12024
  }
11368
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
+
11369
12040
  // src/register/register-adoption.ts
11370
12041
  var chains2 = /* @__PURE__ */ new WeakMap();
11371
12042
  var figure = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
@@ -11423,6 +12094,29 @@ async function renumberRefused(commands, closures, host, storeKey, registerId) {
11423
12094
  });
11424
12095
  }
11425
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
+ }
11426
12120
  async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey, closures }) {
11427
12121
  const run = (chains2.get(commands) ?? Promise.resolve()).then(async () => {
11428
12122
  const [answers, transitions, rows] = await Promise.all([
@@ -11457,7 +12151,14 @@ async function adoptRegisterResults({ commands, sessions, registerId, host, stor
11457
12151
  if (row) await row.incrementalModify(modify);
11458
12152
  }
11459
12153
  const counters = answers.filter((answer) => answer.syncStatus === "applied" && answer.result?.counters).map((answer) => answer.result?.counters);
11460
- 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);
11461
12162
  if (host && storeKey && closures) await renumberRefused(commands, closures, host, storeKey, registerId);
11462
12163
  }).catch((error) => {
11463
12164
  registerCommandsLogger.error("Register result adoption failed", { context: { registerId, error: String(error) } });
@@ -11559,6 +12260,12 @@ var RegisterTenderInProgressError = class extends Error {
11559
12260
  this.name = "RegisterTenderInProgressError";
11560
12261
  }
11561
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
+ };
11562
12269
  var RegisterSessionAlreadyOpenError = class extends Error {
11563
12270
  constructor() {
11564
12271
  super("This register already has an open session.");
@@ -11578,15 +12285,6 @@ var RegisterApprovalRequiredError = class extends Error {
11578
12285
  }
11579
12286
  };
11580
12287
  var openingByRegister = /* @__PURE__ */ new Map();
11581
- var closingByRegister = /* @__PURE__ */ new Map();
11582
- var closingListeners = /* @__PURE__ */ new Set();
11583
- var notifyClosing = () => closingListeners.forEach((listener) => listener());
11584
- var subscribeClosing = (listener) => {
11585
- closingListeners.add(listener);
11586
- return () => {
11587
- closingListeners.delete(listener);
11588
- };
11589
- };
11590
12288
  var closedFacts = /* @__PURE__ */ new Set();
11591
12289
  var isTenderMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((figure2) => typeof figure2 === "number");
11592
12290
  function approvalNeededOf(commandRows, sessions) {
@@ -11612,17 +12310,17 @@ function currentSession(rows, closureRows, reservation) {
11612
12310
  if (rows.some((row) => !isKnownSessionStatus(row.status))) return null;
11613
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;
11614
12312
  }
11615
- function ledgerRows(orders, replaced = replacedOrderIds(orders)) {
11616
- 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];
11617
12315
  }
11618
12316
  var closedCount = (counted2) => ({ ...counted2, cash: counted2.cash ?? 0 });
11619
12317
  var sameVariance = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.entries(b).every(([method, value]) => a[method] === value);
11620
12318
  function useRegisterSession(options) {
11621
12319
  const { sessions, movements, closures, orders, register, storeKey, registerId, enabled, actor, timezone, tenderInProgress, expectedCloseTime, labels } = options;
11622
- const { commands, refunds } = options;
12320
+ const { commands, refunds, drafts } = options;
11623
12321
  const varianceThreshold = options.capabilities?.registerApproval?.thresholdMinor ?? options.varianceThreshold;
11624
12322
  const commandEnabled = (options.capabilities?.register ?? 0) >= 1;
11625
- const commandTarget = useMemo7(
12323
+ const commandTarget = useMemo8(
11626
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,
11627
12325
  [enabled, commandEnabled, commands, sessions, movements, closures, register, storeKey, registerId, options.capabilities?.register, options.deviceName]
11628
12326
  );
@@ -11638,15 +12336,15 @@ function useRegisterSession(options) {
11638
12336
  }
11639
12337
  });
11640
12338
  };
11641
- useEffect10(reconcile, [commandTarget]);
11642
- useEffect10(() => {
12339
+ useEffect11(reconcile, [commandTarget]);
12340
+ useEffect11(() => {
11643
12341
  if (!commandTarget) return;
11644
12342
  const subscription = commandTarget.commands.find({ selector: { registerId: commandTarget.registerId } }).$.subscribe(() => {
11645
12343
  void adoptRegisterResults(commandTarget);
11646
12344
  });
11647
12345
  return () => subscription.unsubscribe();
11648
12346
  }, [commandTarget]);
11649
- const source = useMemo7(() => {
12347
+ const source = useMemo8(() => {
11650
12348
  if (!enabled || !sessions || !movements || !closures || !orders || !registerId || !register || refunds === null) return null;
11651
12349
  return combineLatest([
11652
12350
  watchFresh(sessions, { selector: { register_id: registerId } }),
@@ -11658,25 +12356,26 @@ function useRegisterSession(options) {
11658
12356
  } }) : of([])
11659
12357
  ]).pipe(switchMap(([rows, closureRows, reservation, commandRows2]) => {
11660
12358
  const current2 = currentSession(rows, closureRows, reservation);
11661
- 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 });
11662
12360
  return combineLatest([
11663
12361
  watchFresh(movements, { selector: { session_id: current2.id } }),
11664
12362
  watchFresh(orders, { selector: { sessionId: current2.id } }),
11665
- refunds ? watchFresh(refunds, { selector: { sessionId: current2.id } }) : of([])
11666
- ]).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 })));
11667
12366
  }));
11668
- }, [enabled, sessions, movements, closures, orders, register, storeKey, registerId, commandTarget, refunds]);
12367
+ }, [enabled, sessions, movements, closures, orders, register, storeKey, registerId, commandTarget, refunds, drafts]);
11669
12368
  const tender = useRef7(tenderInProgress);
11670
12369
  tender.current = tenderInProgress;
11671
12370
  const closing = useSyncExternalStore4(subscribeClosing, () => closingByRegister.has(registerId ?? ""));
11672
- const [observed, setObserved] = useState9(null);
11673
- useEffect10(() => {
12371
+ const [observed, setObserved] = useState10(null);
12372
+ useEffect11(() => {
11674
12373
  if (!source) return;
11675
12374
  const subscription = source.subscribe((snapshot) => setObserved({ source, snapshot }));
11676
12375
  return () => subscription.unsubscribe();
11677
12376
  }, [source]);
11678
- const [, setMinute] = useState9(0);
11679
- useEffect10(() => {
12377
+ const [, setMinute] = useState10(0);
12378
+ useEffect11(() => {
11680
12379
  if (!enabled || !expectedCloseTime) return;
11681
12380
  const timer = setInterval(() => setMinute((value) => value + 1), 6e4);
11682
12381
  return () => clearInterval(timer);
@@ -11708,7 +12407,7 @@ function useRegisterSession(options) {
11708
12407
  return state.running = run;
11709
12408
  };
11710
12409
  const seen = useRef7(null);
11711
- useEffect10(() => {
12410
+ useEffect11(() => {
11712
12411
  if (!data) return;
11713
12412
  const ids = data.closureRows.map((row) => row.id);
11714
12413
  if (seen.current?.source !== source) {
@@ -11724,10 +12423,13 @@ function useRegisterSession(options) {
11724
12423
  const open = session ? commandRows.find((row) => row.key === `session.open:${session.id}`) : void 0;
11725
12424
  const refusal = open?.error?.data;
11726
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;
11727
- const entries = data?.entries ?? [];
12426
+ const entries2 = data?.entries ?? [];
11728
12427
  const sales = data?.sales ?? [];
11729
12428
  const replaced = replacedOrderIds(sales);
11730
- 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;
11731
12433
  const expected = terms ? terms.expected : {};
11732
12434
  const now = /* @__PURE__ */ new Date();
11733
12435
  const [hour, minute] = String(expectedCloseTime ?? "").split(":").map(Number);
@@ -11750,23 +12452,36 @@ function useRegisterSession(options) {
11750
12452
  };
11751
12453
  const live = () => {
11752
12454
  if (!enabled || !sessions || !movements || !closures || !orders || !registerId || !register || refunds === null) throw new RegisterSessionRequiredError();
11753
- return { sessions, movements, closures, orders, registerId, register, refunds };
12455
+ return { sessions, movements, closures, orders, registerId, register, refunds, drafts, liveSale: options.liveSale };
11754
12456
  };
11755
12457
  const current = () => {
11756
12458
  if (!session) throw new RegisterSessionRequiredError();
11757
12459
  return session;
11758
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;
11759
12470
  const freshExpected = async (row) => {
11760
12471
  const { movements: movements2, orders: orders2, refunds: refunds2 } = live();
11761
12472
  return deriveExpected({
11762
12473
  session: { id: row.id, countedFloatMinor: row.counted_float_minor },
11763
12474
  movements: await readFresh(movements2, { selector: { session_id: row.id } }),
11764
- 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
+ ),
11765
12479
  refunds: refunds2 ? await readFresh(refunds2, { selector: { sessionId: row.id } }) : void 0
11766
12480
  });
11767
12481
  };
11768
12482
  const refuseDuringTender = () => {
11769
12483
  if (tender.current) throw new RegisterTenderInProgressError();
12484
+ if (live().liveSale?.().saving) throw new RegisterSaleSavingError();
11770
12485
  };
11771
12486
  const nameOf2 = (id2) => !id2 ? "" : id2 === actor.id ? actor.name : labels?.resolveCashierName?.(id2) ?? "";
11772
12487
  return {
@@ -11775,7 +12490,7 @@ function useRegisterSession(options) {
11775
12490
  conflict,
11776
12491
  /** Any unknown session status in the current snapshot means the register needs upgrade. */
11777
12492
  needsUpgrade: data?.rows.some((row) => !isKnownSessionStatus(row.status)) ?? false,
11778
- movements: entries,
12493
+ movements: entries2,
11779
12494
  expected,
11780
12495
  /** `expected`'s drawer ledger, term by term with row counts (`deriveDrawerTerms`); `null` without a session. */
11781
12496
  terms,
@@ -11935,6 +12650,8 @@ function useRegisterSession(options) {
11935
12650
  softwareVersion: options.softwareVersion,
11936
12651
  movements: await readFresh(movements2, { selector: { session_id: closed.id } }),
11937
12652
  orders: await readFresh(orders2, { selector: { sessionId: closed.id } }),
12653
+ drafts: await parkedFresh(),
12654
+ ...liveTaken(),
11938
12655
  refunds: refunds2 ? await readFresh(refunds2, { selector: { sessionId: closed.id } }) : void 0,
11939
12656
  resolveCashierName: labels?.resolveCashierName,
11940
12657
  labels: {
@@ -12117,10 +12834,21 @@ var COUPONS_NEED_CONNECTION = "Coupons need a connection to the store";
12117
12834
  var saleLogger = createLogger("sale");
12118
12835
  var DISCOUNTS_UNSUPPORTED = "finalize: discounts are not supported by the server yet (order.create v2)";
12119
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.";
12120
12838
  var PAYMENT_IN_MOTION = "Finish or void the payment in progress before completing the sale";
12121
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.";
12122
12841
  var SALE_IN_TENDER = "Finish or cancel the payment before switching sales";
12123
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.";
12124
12852
  var SALE_FINISHED = "This sale is finished. Start a new sale to change it.";
12125
12853
  var COUPONS_REPRICING = "Coupon prices are being checked; try again in a moment";
12126
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.";
@@ -12137,6 +12865,7 @@ var RESTORE_STALE = "This item can no longer be put back. Add it again.";
12137
12865
  var REFERENCE_DROPPED = "The terminal's payment reference couldn't be kept";
12138
12866
  var KEPT = /* @__PURE__ */ Symbol("kept coupon");
12139
12867
  var HUNG_SAVE_CHECK_MS = 5e3;
12868
+ var SAVE_TIMEOUT_MS = 6e4;
12140
12869
  function refusalOf(run) {
12141
12870
  try {
12142
12871
  return run();
@@ -12158,7 +12887,8 @@ function useSale(settings, opts) {
12158
12887
  }
12159
12888
  const defaultKey = opts.defaultCustomer ? JSON.stringify([opts.defaultCustomer.id, opts.defaultCustomer.name, opts.defaultCustomer.email]) : "";
12160
12889
  const defaultSeen = useRef8(defaultKey);
12161
- const [rendered, setBuilder] = useState10(() => {
12890
+ const resetRefused = useRef8(false);
12891
+ const [rendered, setBuilder] = useState11(() => {
12162
12892
  const customer = defaulted();
12163
12893
  taxNow.current = contextFor(customer);
12164
12894
  const first = createOrderBuilder({ currency: settings.currency, taxContext: taxNow.current.taxContext });
@@ -12175,18 +12905,18 @@ function useSale(settings, opts) {
12175
12905
  function codesFor() {
12176
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;
12177
12907
  }
12178
- const [order, setOrder] = useState10(() => rendered.getSnapshot());
12179
- const [stage, setStage] = useState10({ kind: "cart" });
12180
- const [saleError, setError] = useState10(null);
12908
+ const [order, setOrder] = useState11(() => rendered.getSnapshot());
12909
+ const [stage, setStage] = useState11({ kind: "cart" });
12910
+ const [saleError, setError] = useState11(null);
12181
12911
  const configError = referenceError("cashierRef", opts.cashierRef) ?? referenceError("registerId", opts.registerId);
12182
12912
  const pending = useRef8(null);
12183
- const [saving, setSaving] = useState10(false);
12913
+ const [saving, setSaving] = useState11(false);
12184
12914
  const error = saving && saleError ? saleError : configError ?? saleError;
12185
12915
  const tenderSession = useRef8(null);
12186
12916
  const tenderGatePending = useRef8(false);
12187
12917
  const droppedReferences = useRef8(/* @__PURE__ */ new Set());
12188
12918
  const confirmed = useRef8(null);
12189
- const [canContinue, setCanContinue] = useState10(false);
12919
+ const [canContinue, setCanContinue] = useState11(false);
12190
12920
  const attempts = useRef8(0);
12191
12921
  const hungSaveTimer = useRef8(null);
12192
12922
  const checking = useRef8(null);
@@ -12201,7 +12931,8 @@ function useSale(settings, opts) {
12201
12931
  setCanContinue(!!completion);
12202
12932
  clearHungSaveTimer();
12203
12933
  }
12204
- const inFlight2 = useRef8(null);
12934
+ const inFlight3 = useRef8(null);
12935
+ const moving = useRef8(0);
12205
12936
  const stageNow = useRef8(stage);
12206
12937
  stageNow.current = stage;
12207
12938
  function locked() {
@@ -12210,7 +12941,7 @@ function useSale(settings, opts) {
12210
12941
  return active;
12211
12942
  }
12212
12943
  function busy() {
12213
- return !!(inFlight2.current || pending.current);
12944
+ return !!(inFlight3.current || pending.current);
12214
12945
  }
12215
12946
  function editRefusal() {
12216
12947
  const refusal = busy() ? SALE_SAVING : stageNow.current.kind === "receipt" ? SALE_FINISHED : liveLeg() ? SALE_HAS_PAYMENT : null;
@@ -12224,17 +12955,25 @@ function useSale(settings, opts) {
12224
12955
  return [...applied.current.values()].includes(KEPT);
12225
12956
  }
12226
12957
  const repricing = useRef8(null);
12227
- const [couponsRepricing, setCouponsRepricing] = useState10(false);
12958
+ const [couponsRepricing, setCouponsRepricing] = useState11(false);
12228
12959
  const generation = useRef8(0);
12229
- const saleEpoch = useRef8(0);
12960
+ const removalEpoch = useRef8(0);
12230
12961
  const stopped = useRef8(null);
12231
12962
  const keptCoupons = useRef8(void 0);
12232
12963
  const keptLegIds = useRef8([]);
12964
+ const resumedLegIds = useRef8([]);
12965
+ const resumedTakenIds = useRef8([]);
12233
12966
  function countedLeg(p) {
12234
12967
  return !!builderNow.current.getSnapshot().afterClose?.payments.some((leg) => leg.id === p.id);
12235
12968
  }
12236
12969
  function heldLeg(p) {
12237
- 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));
12238
12977
  }
12239
12978
  function reprice() {
12240
12979
  if (repricing.current) return repricing.current;
@@ -12284,14 +13023,14 @@ function useSale(settings, opts) {
12284
13023
  return builderNow.current.getSnapshot().coupons?.some((coupon) => coupon.carried);
12285
13024
  }
12286
13025
  function resetSale(customer = defaulted(), restored, restoredTax) {
12287
- if (inFlight2.current && !pending.current) return setError(SALE_SAVING);
13026
+ if (inFlight3.current && !pending.current) return setError(SALE_SAVING);
12288
13027
  if (pending.current && confirmed.current !== pending.current) {
12289
- if (inFlight2.current) checkStored(pending.current);
13028
+ if (inFlight3.current) checkStored(pending.current);
12290
13029
  return setError(SALE_SAVING);
12291
13030
  }
12292
13031
  confirm(null);
12293
13032
  pending.current = null;
12294
- inFlight2.current = null;
13033
+ inFlight3.current = null;
12295
13034
  tenderSession.current = null;
12296
13035
  droppedReferences.current.clear();
12297
13036
  setSaving(false);
@@ -12304,20 +13043,22 @@ function useSale(settings, opts) {
12304
13043
  applied.current.clear();
12305
13044
  keptCoupons.current = void 0;
12306
13045
  keptLegIds.current = [];
13046
+ resumedLegIds.current = [];
13047
+ resumedTakenIds.current = [];
12307
13048
  appliedWith.current = null;
12308
13049
  generation.current++;
12309
- saleEpoch.current++;
13050
+ removalEpoch.current++;
12310
13051
  setBuilder(next);
12311
13052
  setOrder(next.getSnapshot());
12312
13053
  stageNow.current = { kind: "cart" };
12313
13054
  setStage(stageNow.current);
12314
13055
  setError(null);
12315
13056
  }
12316
- useEffect11(() => {
13057
+ useEffect12(() => {
12317
13058
  const subscription = rendered.order$.subscribe(setOrder);
12318
13059
  return () => subscription.unsubscribe();
12319
13060
  }, [rendered]);
12320
- useEffect11(() => {
13061
+ useEffect12(() => {
12321
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());
12322
13063
  });
12323
13064
  function dropKept() {
@@ -12328,12 +13069,21 @@ function useSale(settings, opts) {
12328
13069
  setError(COUPONS_UNSUPPORTED);
12329
13070
  }
12330
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
+ }
12331
13076
  useLayoutEffect(() => {
12332
13077
  const live = builderNow.current.getSnapshot();
12333
- 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;
12334
13079
  const newDefault = defaultSeen.current !== defaultKey;
12335
13080
  defaultSeen.current = defaultKey;
12336
- 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
+ }
12337
13087
  });
12338
13088
  function retax(customer, next) {
12339
13089
  const snapshot = { ...builderNow.current.getSnapshot(), customer, ...carriedCoupon() ? { couponPricesStale: true } : {} };
@@ -12352,20 +13102,21 @@ function useSale(settings, opts) {
12352
13102
  return true;
12353
13103
  }
12354
13104
  const liveCustomer = order.customer, taxContextFor = opts.taxContextFor;
12355
- const taxLocation = useMemo8(() => taxContextFor ? { ...taxContextFor(liveCustomer).location, hasCustomer: liveCustomer !== null } : void 0, [liveCustomer, taxContextFor]);
12356
- useEffect11(() => () => {
13105
+ const taxLocation = useMemo9(() => taxContextFor ? { ...taxContextFor(liveCustomer).location, hasCustomer: liveCustomer !== null } : void 0, [liveCustomer, taxContextFor]);
13106
+ useEffect12(() => () => {
12357
13107
  clearHungSaveTimer();
12358
- if (pending.current || inFlight2.current) {
13108
+ if (pending.current || inFlight3.current) {
12359
13109
  saleLogger.error(
12360
13110
  "useSale unmounted with a save pending or in flight",
12361
13111
  { orderId: pending.current?.posOrder.id, stage: stageNow.current.kind }
12362
13112
  );
12363
13113
  }
12364
13114
  }, []);
12365
- function addOne(tender, stamp2) {
13115
+ function addOne(tender, stamp2, rounding) {
12366
13116
  const reason = referenceReason(tender.reference);
12367
13117
  const dropped = reason && (reason === "nul" ? "it contains a NUL character" : `it is over ${PAYLOAD_STRING_MAX} characters`);
12368
- const takenAt = stamp2 && legStatus({ status: tender.status }) === "captured" ? { takenAt: (/* @__PURE__ */ new Date()).toISOString() } : {};
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 } : {} };
12369
13120
  const kept = dropped ? {
12370
13121
  method: tender.method,
12371
13122
  amountMinor: tender.amountMinor,
@@ -12378,7 +13129,7 @@ function useSale(settings, opts) {
12378
13129
  } : { ...tender, ...takenAt };
12379
13130
  const builder = builderNow.current;
12380
13131
  const { units, ...payment } = kept;
12381
- const paymentId = builder.addPayment({ ...payment, ...units && Object.keys(units).length ? { units } : {} });
13132
+ const paymentId = builder.addPayment({ ...payment, ...units && Object.keys(units).length ? { units } : {} }, rounding);
12382
13133
  if (dropped) {
12383
13134
  droppedReferences.current.add(paymentId);
12384
13135
  setError(`${REFERENCE_DROPPED} (${dropped}); the payment is recorded without it.`);
@@ -12400,8 +13151,10 @@ function useSale(settings, opts) {
12400
13151
  if (taxIdsRefused) return setError(taxIdsRefused);
12401
13152
  if (tender && builderNow.current.getSnapshot().afterClose) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
12402
13153
  const builder = builderNow.current;
12403
- for (const payment of builder.getSnapshot().payments) if (!heldLeg(payment)) builder.removePayment(payment.id);
12404
- 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
+ }
12405
13158
  setError(null);
12406
13159
  if (tender) addOne(tender, false);
12407
13160
  }
@@ -12423,12 +13176,27 @@ function useSale(settings, opts) {
12423
13176
  clearHungSaveTimer();
12424
13177
  const timer = opts.isStored ? setInterval(() => {
12425
13178
  if (checking.current === completion) return;
12426
- if (pending.current === completion && inFlight2.current && confirmed.current !== completion) checkStored(completion);
13179
+ if (pending.current === completion && inFlight3.current && confirmed.current !== completion) checkStored(completion);
12427
13180
  else if (hungSaveTimer.current === timer) clearHungSaveTimer();
12428
13181
  }, opts.hungSaveCheckMs ?? HUNG_SAVE_CHECK_MS) : null;
12429
13182
  hungSaveTimer.current = timer;
13183
+ let timeout;
13184
+ let timedOut = false;
12430
13185
  try {
12431
- 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
+ ]);
12432
13200
  } catch (error2) {
12433
13201
  if (hungSaveTimer.current === timer) clearHungSaveTimer();
12434
13202
  const message = error2 instanceof Error ? error2.message : String(error2);
@@ -12440,26 +13208,32 @@ function useSale(settings, opts) {
12440
13208
  checkStored(completion);
12441
13209
  }
12442
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);
12443
13225
  }
12444
- if (hungSaveTimer.current === timer) clearHungSaveTimer();
12445
- if (pending.current !== completion) return;
12446
- pending.current = null;
12447
- droppedReferences.current.clear();
12448
- confirm(null);
12449
- setSaving(false);
12450
- setError(null);
12451
- stageNow.current = { kind: "receipt", order: withSentForm(completion.order, completion.posOrder), posOrder: completion.posOrder };
12452
- setStage(stageNow.current);
12453
13226
  }
12454
13227
  function once(attempt2) {
12455
- if (!inFlight2.current && stageNow.current.kind !== "receipt") {
13228
+ if (!inFlight3.current && stageNow.current.kind !== "receipt") {
12456
13229
  const mine = attempt2().finally(() => {
12457
- if (inFlight2.current === mine) inFlight2.current = null;
13230
+ if (inFlight3.current === mine) inFlight3.current = null;
12458
13231
  });
12459
- inFlight2.current = mine;
13232
+ inFlight3.current = mine;
12460
13233
  }
12461
- return inFlight2.current ?? Promise.resolve();
13234
+ return inFlight3.current ?? Promise.resolve();
12462
13235
  }
13236
+ const legSessionId = () => (tenderSession.current?.session ?? opts.session)?.id;
12463
13237
  function begin(method, options) {
12464
13238
  if (stageNow.current.kind === "receipt") return setError(SALE_FINISHED);
12465
13239
  if (locked()) return;
@@ -12468,7 +13242,7 @@ function useSale(settings, opts) {
12468
13242
  if (couponsUnpriced()) return setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING);
12469
13243
  if (afterCloseChanged(current)) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
12470
13244
  tenderSession.current ??= { session: options?.session ?? opts.session };
12471
- 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);
12472
13246
  if (current.afterClose) setTender(null);
12473
13247
  else if (heldMinor === 0) setTender(method === "external" ? { method, amountMinor: current.totalMinor } : null);
12474
13248
  else setTender(method === "external" && current.totalMinor - heldMinor > 0 ? { method, amountMinor: current.totalMinor - heldMinor } : null);
@@ -12504,14 +13278,14 @@ function useSale(settings, opts) {
12504
13278
  if (held) return held;
12505
13279
  const builder = builderNow.current;
12506
13280
  try {
12507
- const known = new Set(builder.getSnapshot().lineItems.map((line2) => line2.id));
13281
+ const known2 = new Set(builder.getSnapshot().lineItems.map((line2) => line2.id));
12508
13282
  const productId = Number(traits.getId(entry.product));
12509
13283
  if (Number.isSafeInteger(productId) && productId >= 0) {
12510
13284
  const ids = productCategories(entry.product, traits).map(({ id: id2 }) => ({ id: Number(id2) })).filter(({ id: id2 }) => Number.isSafeInteger(id2));
12511
13285
  if (ids.length) categories.current.set(productId, ids);
12512
13286
  }
12513
13287
  const lineId = addEntryToCart(builder, entry, traits, madeWith.current.currency);
12514
- 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));
12515
13289
  const name = line && `"${cutText(line.name, MESSAGE_NAME_MAX)}"`;
12516
13290
  const taxLines = line && (opts.capabilities?.orderCreate ?? 1) >= 3 ? line.taxLines : [];
12517
13291
  const refused = line && [
@@ -12642,21 +13416,19 @@ function useSale(settings, opts) {
12642
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. */
12643
13417
  removal(kind, id2) {
12644
13418
  const order2 = builderNow.current.getSnapshot();
12645
- const list = kind === "line" ? order2.lineItems : kind === "fee" ? order2.fees ?? [] : order2.shipping ?? [];
12646
- const index = list.findIndex((item) => item.id === id2);
12647
- 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 };
12648
13422
  },
12649
- /** #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). */
12650
13424
  restore(removal) {
12651
13425
  const held = editRefusal();
12652
13426
  if (held) return held;
12653
- const order2 = builderNow.current.getSnapshot(), moved = removal.taxContext !== taxNow.current.taxContext;
12654
- 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;
12655
13429
  const ids = [removal.item, ...removal.kind === "line" ? removal.item.discounts : []].map((entry) => entry.id);
12656
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;
12657
- if (moved && (capturedMinor(order2.payments) !== 0 || order2.payments.some(isInMotion) || keptCodes())) return RESTORE_STALE;
12658
13431
  builderNow.current.restoreItem(removal.kind, removal.item, removal.index);
12659
- if (moved) retax(builderNow.current.getSnapshot().customer, taxNow.current);
12660
13432
  return null;
12661
13433
  },
12662
13434
  /** A line's discount, or the order's without a line; returns the refusal to show, or null once applied. */
@@ -12752,6 +13524,7 @@ function useSale(settings, opts) {
12752
13524
  if (same2) taxNow.current = same2;
12753
13525
  builderNow.current.setCustomer(customer);
12754
13526
  }
13527
+ removalEpoch.current++;
12755
13528
  setError((current) => current !== null && (CUSTOMER_REFUSALS.includes(current) || current === CUSTOMER_RETAX_REFUSED || current === TAX_IDS_INVALID) ? null : current);
12756
13529
  },
12757
13530
  /**
@@ -12777,6 +13550,7 @@ function useSale(settings, opts) {
12777
13550
  if (same2) taxNow.current = same2;
12778
13551
  builderNow.current.setCustomer(next);
12779
13552
  }
13553
+ removalEpoch.current++;
12780
13554
  setError((current) => current === ADDRESS_CHANGE_REFUSED ? null : current);
12781
13555
  return true;
12782
13556
  },
@@ -12798,6 +13572,7 @@ function useSale(settings, opts) {
12798
13572
  }
12799
13573
  const { taxIds: _taxIds, ...rest } = customer;
12800
13574
  builderNow.current.setCustomer(cleaned.length ? { ...rest, taxIds: cleaned } : rest);
13575
+ removalEpoch.current++;
12801
13576
  setError((current) => current === TAX_IDS_CHANGE_REFUSED || current === TAX_IDS_INVALID ? null : current);
12802
13577
  return true;
12803
13578
  },
@@ -12814,12 +13589,12 @@ function useSale(settings, opts) {
12814
13589
  return false;
12815
13590
  }
12816
13591
  const name = key.trim();
12817
- const known = meta.some((m) => m.key === name);
12818
- 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) {
12819
13594
  setError(META_INVALID);
12820
13595
  return false;
12821
13596
  }
12822
- 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 }];
12823
13598
  builderNow.current.setMeta(next);
12824
13599
  setError((current) => current === META_CHANGE_REFUSED || current === META_INVALID ? null : current);
12825
13600
  return true;
@@ -12850,13 +13625,17 @@ function useSale(settings, opts) {
12850
13625
  });
12851
13626
  },
12852
13627
  setTender,
12853
- /** 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). */
12854
- 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;
12855
13631
  if (stageNow.current.kind === "receipt") {
12856
13632
  setError(SALE_FINISHED);
12857
13633
  return null;
12858
13634
  }
12859
- 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;
12860
13639
  if (builderNow.current.getSnapshot().afterClose) {
12861
13640
  setError(AFTER_CLOSE_PAYMENTS_CHANGED);
12862
13641
  return null;
@@ -12872,10 +13651,20 @@ function useSale(settings, opts) {
12872
13651
  const unpaid = unpaidUnitsByLine(lineItems.map(({ id: id2, quantity }) => ({ id: id2, quantity, totalMinor: 0 })), heldUnitsByLine(payments));
12873
13652
  if (Object.entries(tender.units).some(([id2, units]) => !id2 || !Number.isInteger(units) || units <= 0 || !Object.hasOwn(unpaid, id2) || units > unpaid[id2])) return null;
12874
13653
  }
12875
- 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;
12876
13657
  if (tender.tenderedMinor !== void 0) {
12877
13658
  const snapshot = builderNow.current.getSnapshot();
12878
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
+ }
12879
13668
  }
12880
13669
  if (tender.method === "external") {
12881
13670
  const snapshot = builderNow.current.getSnapshot();
@@ -12884,8 +13673,52 @@ function useSale(settings, opts) {
12884
13673
  clearStaleError();
12885
13674
  return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) }, true);
12886
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);
13715
+ }
12887
13716
  clearStaleError();
12888
- return addOne({ ...tender, ...tender.tenderedMinor !== void 0 ? { changeMinor: tender.tenderedMinor - tender.amountMinor } : {} }, true);
13717
+ return addOne(
13718
+ { ...tender, amountMinor: pickMinor, changeMinor: tender.tenderedMinor - pickMinor },
13719
+ true,
13720
+ pickMinor !== tender.amountMinor ? { minor: pickMinor - tender.amountMinor } : void 0
13721
+ );
12889
13722
  },
12890
13723
  setTenderStatus(paymentId, status) {
12891
13724
  if (stageNow.current.kind === "receipt") {
@@ -12898,11 +13731,12 @@ function useSale(settings, opts) {
12898
13731
  setError(AFTER_CLOSE_PAYMENTS_CHANGED);
12899
13732
  return false;
12900
13733
  }
12901
- const changed = builderNow.current.setPaymentStatus(paymentId, status, status === "captured" ? (/* @__PURE__ */ new Date()).toISOString() : void 0);
13734
+ const changed = status === "captured" ? builderNow.current.setPaymentStatus(paymentId, status, (/* @__PURE__ */ new Date()).toISOString(), legSessionId()) : builderNow.current.setPaymentStatus(paymentId, status);
12902
13735
  if (changed && status === "failed" && !liveLeg()) setError((current) => current === SALE_HAS_PAYMENT ? null : current);
13736
+ if (changed) setError((current) => current === NOTHING_DUE ? null : current);
12903
13737
  return changed;
12904
13738
  },
12905
- /** 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. */
12906
13740
  voidTender(paymentId) {
12907
13741
  if (stageNow.current.kind === "receipt") {
12908
13742
  setError(SALE_FINISHED);
@@ -12916,6 +13750,10 @@ function useSale(settings, opts) {
12916
13750
  if (payment?.locked) return false;
12917
13751
  if (locked()) return false;
12918
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
+ }
12919
13757
  builderNow.current.setPaymentStatus(paymentId, "voided");
12920
13758
  droppedReferences.current.delete(paymentId);
12921
13759
  clearStaleError();
@@ -12929,10 +13767,16 @@ function useSale(settings, opts) {
12929
13767
  if (payment?.locked) return;
12930
13768
  if (locked()) return;
12931
13769
  if (!payment) return;
13770
+ if (taken(payment)) return setError(PAYMENT_TAKEN);
12932
13771
  builderNow.current.removePayment(paymentId);
12933
13772
  droppedReferences.current.delete(paymentId);
12934
13773
  clearStaleError();
12935
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
+ },
12936
13780
  cancelTender() {
12937
13781
  if (stageNow.current.kind === "receipt") return setError(SALE_FINISHED);
12938
13782
  if (locked()) return;
@@ -12956,8 +13800,9 @@ function useSale(settings, opts) {
12956
13800
  * another is in flight returns that call's promise, and a call on the receipt does nothing. While
12957
13801
  * `cashierRef` or `registerId` is out of bounds (shown as `error`), a call does nothing either,
12958
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).
12959
13804
  */
12960
- 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 () => {
12961
13806
  attempts.current++;
12962
13807
  confirm(null);
12963
13808
  if (pending.current) return deliver(pending.current);
@@ -12973,8 +13818,8 @@ function useSale(settings, opts) {
12973
13818
  setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING);
12974
13819
  return;
12975
13820
  }
12976
- const completedAt = (/* @__PURE__ */ new Date()).toISOString();
12977
- const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid).map((payment) => payment.takenAt === void 0 && !payment.locked && !payment.reopened ? { ...payment, takenAt: completedAt } : payment) };
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) };
12978
13823
  const localWarnings = current.payments.filter((payment) => droppedReferences.current.has(payment.id)).map((payment) => ({ code: "payment_reference_dropped", paymentId: payment.id }));
12979
13824
  let posOrder;
12980
13825
  try {
@@ -13033,24 +13878,56 @@ function useSale(settings, opts) {
13033
13878
  * save still in flight carries on in the background, a throw logged at error) and starts the new
13034
13879
  * sale outright — from the receipt, or an idle cart, there's nothing pending to abandon. Abandoning
13035
13880
  * clears the screen, never the record (the Front desk, 2026-09-25). `newSale()` never deletes,
13036
- * 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.
13037
13885
  */
13038
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);
13039
13889
  resetSale();
13040
13890
  },
13041
- /** 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
+ */
13042
13913
  async park() {
13043
13914
  if (locked()) return SALE_SAVING;
13044
- if (!opts.drafts) throw new Error("useSale: park() needs the drafts option");
13045
- if (stageNow.current.kind !== "cart") return "Finish or cancel the payment before parking the sale";
13046
- const builder = builderNow.current;
13047
- const snapshot = builder.getSnapshot();
13048
- if (!snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length) return "There is nothing to park";
13049
- const refused = await writeParked(opts.drafts, snapshot);
13050
- if (refused) return refused;
13051
- if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return "The sale changed while it was being parked; park it again";
13052
- resetSale();
13053
- 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
+ }
13054
13931
  },
13055
13932
  /** Whether the live sale or a parked draft holds this store order; unreadable drafts do not count. */
13056
13933
  async holdsStoreOrder(orderId) {
@@ -13066,12 +13943,13 @@ function useSale(settings, opts) {
13066
13943
  }
13067
13944
  });
13068
13945
  },
13069
- /** 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. */
13070
13947
  openStoreOrder(order2) {
13071
13948
  if (locked()) return SALE_SAVING;
13072
13949
  if (!order2.storeOrder) throw new Error("useSale: openStoreOrder() takes a reopened store order");
13073
13950
  const liveSnapshot = builderNow.current.getSnapshot();
13074
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;
13075
13953
  if (order2.currency.toUpperCase() !== settings.currency.toUpperCase()) return "That order is in another currency";
13076
13954
  const restoredTax = contextFor(order2.customer && !customerRefusal(order2.customer) ? order2.customer : null);
13077
13955
  const builder = restoreOrderDraft(order2, { currency: settings.currency, taxContext: restoredTax.taxContext });
@@ -13080,103 +13958,123 @@ function useSale(settings, opts) {
13080
13958
  resetSale(null, builder, restoredTax);
13081
13959
  return null;
13082
13960
  },
13083
- /** 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
+ */
13084
13965
  async resume(draftId, options) {
13085
13966
  if (locked()) return SALE_SAVING;
13086
- if (!opts.drafts) throw new Error("useSale: resume() needs the drafts option");
13087
- const live = builderNow.current;
13088
- const liveSnapshot = live.getSnapshot();
13089
- if (stageNow.current.kind !== "cart" || liveSnapshot.lineItems.length || liveSnapshot.fees?.length || liveSnapshot.shipping?.length) return "Park or clear the current sale first";
13090
- const doc = await opts.drafts.findOne(draftId).exec();
13091
- if (!doc) return "That parked sale is no longer there";
13092
- const saved = JSON.parse(doc.toJSON().data);
13093
- if (saved.currency.toUpperCase() !== settings.currency.toUpperCase()) return "That parked sale is in another currency";
13094
- const restoredTax = contextFor(saved.customer && !customerRefusal(saved.customer) ? saved.customer : null);
13095
- const carriedDraft = !!saved.coupons?.length && saved.coupons.every((coupon) => coupon.carried);
13096
- const keep = !carriedDraft && !!saved.coupons?.length && saved.display.coupons?.length === saved.coupons.length && (saved.payments ?? []).some(isLiveLeg);
13097
- const builder = restoreOrderDraft(saved, {
13098
- currency: settings.currency,
13099
- taxContext: restoredTax.taxContext,
13100
- keepTaxRates: keep || capturedMinor(saved.payments ?? []) !== 0,
13101
- keepCoupons: keep
13102
- });
13103
- let n = 0;
13104
- if (opts.currentPrice && !options?.keepParkedPrices && !carriedDraft && !keep && capturedMinor(saved.payments ?? []) === 0 && !saved.storeOrder) {
13105
- for (const line of builder.getSnapshot().lineItems) {
13106
- if (!line.variantId) continue;
13107
- const price = opts.currentPrice(line.variantId);
13108
- if (price !== void 0 && Number.isInteger(price) && price >= 0 && price !== line.unitPriceMinor) {
13109
- builder.setUnitPrice(line.id, price);
13110
- 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
+ }
13111
13997
  }
13112
13998
  }
13113
- }
13114
- const kept = /* @__PURE__ */ new Map(), messages = [];
13115
- const codes2 = !carriedDraft && saved.coupons?.length ? codesFor() : null;
13116
- if (n > 0) messages.push(`Prices changed since this sale was parked: ${n} ${n === 1 ? "line" : "lines"} updated to today's price.`);
13117
- if (!carriedDraft && saved.coupons?.length) {
13118
- const supported = codes2 !== null;
13119
- if (supported) await codes2.beforeResume?.(discountState(builder.getSnapshot(), /* @__PURE__ */ new Map()));
13120
- if (keep) for (const { code } of saved.coupons) kept.set(code, KEPT);
13121
- else for (const { code } of saved.coupons) {
13122
- let reason = supported ? null : COUPONS_UNSUPPORTED;
13123
- if (supported) {
13124
- const result2 = await codes2.find(code, discountState(builder.getSnapshot(), kept));
13125
- if ("refusal" in result2) reason = result2.refusal;
13126
- else {
13127
- reason = codes2.check(code, result2.found, discountState(builder.getSnapshot(), kept));
13128
- if (reason === null) try {
13129
- codes2.apply(builder, discountState(builder.getSnapshot(), new Map([...kept, [code, result2.found]])));
13130
- kept.set(code, result2.found);
13131
- } catch (error2) {
13132
- if (error2 instanceof Error) reason = error2.message;
13133
- 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
+ }
13134
14020
  }
13135
14021
  }
14022
+ if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
13136
14023
  }
13137
- if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
13138
14024
  }
13139
- }
13140
- await doc.remove();
13141
- if (builderNow.current !== live || live.getSnapshot() !== liveSnapshot) {
13142
- await writeOrderDraft(opts.drafts, saved);
13143
- return "The sale changed while it was being resumed; resume it again";
13144
- }
13145
- resetSale(null, builder, restoredTax);
13146
- if (builderNow.current === builder) {
13147
- applied.current = kept;
13148
- if (keep) {
13149
- keptCoupons.current = saved.coupons;
13150
- 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++;
13151
14041
  }
13152
- appliedWith.current = kept.size ? codes2 : null;
13153
- generation.current++;
14042
+ if (messages.length) setError(messages.join(" "));
14043
+ return null;
14044
+ } finally {
14045
+ moving.current--;
13154
14046
  }
13155
- if (messages.length) setError(messages.join(" "));
13156
- return null;
13157
14047
  },
13158
14048
  /**
13159
14049
  * Opens the parked draft `draftId`, or an empty sale for null (New), as a tab switch (u19, v2 cart/tabs.tsx):
13160
14050
  * parks the current sale first when it has lines, fees or shipping (a receipt is done and is not parked).
13161
- * 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
13162
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).
13163
14054
  */
13164
14055
  async switchSale(draftId) {
13165
14056
  if (locked()) return SALE_SAVING;
13166
- if (!opts.drafts) throw new Error("useSale: switchSale() needs the drafts option");
13167
- const builder = builderNow.current;
13168
- const snapshot = builder.getSnapshot();
13169
- if (draftId === snapshot.id) return null;
13170
- if (capturedMinor(snapshot.payments.filter((payment) => !payment.locked)) > 0 && snapshot.balanceDueMinor > 0) return SALE_PARTLY_PAID;
13171
- if (snapshot.payments.some(isInMotion)) return PAYMENT_IN_MOTION;
13172
- if (stageNow.current.kind === "tender") return SALE_IN_TENDER;
13173
- if (stageNow.current.kind !== "receipt" && (snapshot.lineItems.length || snapshot.fees?.length || snapshot.shipping?.length)) {
13174
- const refused = await writeParked(opts.drafts, snapshot);
13175
- if (refused) return refused;
13176
- 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--;
13177
14077
  }
13178
- resetSale();
13179
- return draftId === null ? null : result.resume(draftId);
13180
14078
  },
13181
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.
13182
14080
  * A reopened sale's locked store legs do not stop it closing; the store order stays reopened, as in v2. */
@@ -13469,9 +14367,9 @@ function catalogueEntries(products, traits, context) {
13469
14367
  return variants.map((variant) => ({ product, variant }));
13470
14368
  });
13471
14369
  }
13472
- function findEntryByCode(entries, code) {
13473
- const variant = findVariantByCode(entries.map((entry) => entry.variant), code);
13474
- 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;
13475
14373
  }
13476
14374
  function variantPriceLabel(variant, currency, locale) {
13477
14375
  const price = resolvePrice4(variant.prices, currency);
@@ -13502,65 +14400,36 @@ function matchVariant(variants, groups, picks) {
13502
14400
  function disabledOptions(variants, groups, picks) {
13503
14401
  const disabled = {};
13504
14402
  for (const { name, values } of groups) {
13505
- const others = Object.fromEntries(Object.entries(picks).filter(([group]) => group !== name));
13506
- const fitting = variants.filter((variant) => variantFits(variant, others));
13507
- disabled[name] = new Set(values.filter((value) => !fitting.some((variant) => variantFits(variant, { [name]: value }))));
13508
- }
13509
- return disabled;
13510
- }
13511
-
13512
- // src/sale/in-cart.ts
13513
- function cartQuantities(lines) {
13514
- const quantities = /* @__PURE__ */ new Map();
13515
- for (const line of lines) {
13516
- if (line.custom) continue;
13517
- quantities.set(line.productId, (quantities.get(line.productId) ?? 0) + line.quantity);
13518
- }
13519
- return quantities;
13520
- }
13521
-
13522
- // src/sale/order-filters-query.ts
13523
- var COPIED = ["status", "customerId", "cashierId", "registerId", "paymentMethod", "storeId", "createdVia"];
13524
- var DAY_MS = 864e5;
13525
- function offsetMs(at2, timezone) {
13526
- const format2 = new Intl.DateTimeFormat("en-US", {
13527
- timeZone: timezone,
13528
- hourCycle: "h23",
13529
- year: "numeric",
13530
- month: "numeric",
13531
- day: "numeric",
13532
- hour: "numeric",
13533
- minute: "numeric",
13534
- second: "numeric"
13535
- });
13536
- const part = Object.fromEntries(format2.formatToParts(new Date(at2)).map(({ type, value }) => [type, Number(value)]));
13537
- const wall = Date.UTC(part.year, part.month - 1, part.day, part.hour, part.minute, part.second);
13538
- return wall - Math.floor(at2 / 1e3) * 1e3;
13539
- }
13540
- function dayStart(day, timezone) {
13541
- const [year, month, date] = day.split("-").map(Number);
13542
- if (timezone === "device") return new Date(year, month - 1, date).toISOString();
13543
- const wall = Date.UTC(year, month - 1, date);
13544
- const guess = wall - offsetMs(wall, timezone);
13545
- return new Date(wall - offsetMs(guess, timezone)).toISOString();
13546
- }
13547
- var nextDay = (day) => {
13548
- const [year, month, date] = day.split("-").map(Number);
13549
- return new Date(Date.UTC(year, month - 1, date) + DAY_MS).toISOString().slice(0, 10);
13550
- };
13551
- function orderFiltersQuery(value, timezone) {
13552
- const query = {};
13553
- for (const field of COPIED) {
13554
- if (value[field] !== void 0) query[field] = value[field];
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 }))));
13555
14406
  }
13556
- if (value.dateRange) {
13557
- 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);
13558
14416
  }
13559
- 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;
13560
14430
  }
13561
14431
 
13562
14432
  // src/outbox/http-transport.ts
13563
- import { COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, isCommandBatchResponse } from "@tallyui/core";
13564
14433
  var PERMANENT_STATUSES = /* @__PURE__ */ new Set([400, 403, 413, 415, 422]);
13565
14434
  function createHttpCommandTransport(options) {
13566
14435
  const fetch = options.fetch ?? globalThis.fetch;
@@ -13602,6 +14471,20 @@ function createHttpCommandTransport(options) {
13602
14471
  }
13603
14472
  return { kind: "refused", status: response.status, reason };
13604
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
+ }
13605
14488
  if (response.status !== 200) return retry(`status_${response.status}`);
13606
14489
  let body;
13607
14490
  try {
@@ -13620,15 +14503,15 @@ function createHttpCommandTransport(options) {
13620
14503
  }
13621
14504
 
13622
14505
  // src/outbox/use-register-outbox.ts
13623
- import { useEffect as useEffect12, useRef as useRef9, useState as useState11 } from "react";
14506
+ import { useEffect as useEffect13, useRef as useRef9, useState as useState12 } from "react";
13624
14507
  var idle = { pending: 0, sending: false };
13625
14508
  function useRegisterOutbox(options) {
13626
14509
  const { commands, sessions, deviceId } = options;
13627
14510
  const latest = useRef9(options);
13628
14511
  latest.current = options;
13629
14512
  const current = useRef9(null);
13630
- const [state, setState] = useState11(idle);
13631
- useEffect12(() => {
14513
+ const [state, setState] = useState12(idle);
14514
+ useEffect13(() => {
13632
14515
  setState(idle);
13633
14516
  if (!commands) return;
13634
14517
  const outbox = createRegisterOutbox({
@@ -13667,7 +14550,7 @@ function useRegisterOutbox(options) {
13667
14550
  }
13668
14551
 
13669
14552
  // src/outbox/use-order-outbox.ts
13670
- import { useEffect as useEffect13, useMemo as useMemo9, useRef as useRef10, useState as useState12 } from "react";
14553
+ import { useEffect as useEffect14, useMemo as useMemo10, useRef as useRef10, useState as useState13 } from "react";
13671
14554
  var idle2 = { pending: 0, sending: false };
13672
14555
  var noneStuck = [];
13673
14556
  function useOrderOutbox(options) {
@@ -13677,12 +14560,12 @@ function useOrderOutbox(options) {
13677
14560
  const current = useRef10(null);
13678
14561
  const openingError = useRef10(null);
13679
14562
  const loggedMismatches = useRef10(/* @__PURE__ */ new Set());
13680
- const [orders, setOrders] = useState12(null);
13681
- const [state, setState] = useState12(idle2);
13682
- const [recent, setRecent] = useState12([]);
14563
+ const [orders, setOrders] = useState13(null);
14564
+ const [state, setState] = useState13(idle2);
14565
+ const [recent, setRecent] = useState13([]);
13683
14566
  const savesInFlight = useRef10(0);
13684
- const [savesInFlightCount, setSavesInFlightCount] = useState12(0);
13685
- useEffect13(() => {
14567
+ const [savesInFlightCount, setSavesInFlightCount] = useState13(0);
14568
+ useEffect14(() => {
13686
14569
  let active = true;
13687
14570
  let dispose;
13688
14571
  openingError.current = null;
@@ -13725,13 +14608,13 @@ function useOrderOutbox(options) {
13725
14608
  dispose?.();
13726
14609
  };
13727
14610
  }, [storeKey, deviceId]);
13728
- useEffect13(() => {
14611
+ useEffect14(() => {
13729
14612
  latest.current.onBusy?.(state.sending);
13730
14613
  return () => latest.current.onBusy?.(false);
13731
14614
  }, [state.sending]);
13732
14615
  const ready = current.current?.storeKey === storeKey && !!storeKey;
13733
14616
  const stuckKey = ready ? state.stuck?.commandIds.join(",") ?? "" : "";
13734
- const stuckCommandIds = useMemo9(() => stuckKey ? stuckKey.split(",") : noneStuck, [stuckKey]);
14617
+ const stuckCommandIds = useMemo10(() => stuckKey ? stuckKey.split(",") : noneStuck, [stuckKey]);
13735
14618
  return {
13736
14619
  orders: ready ? orders : null,
13737
14620
  state: ready ? state : idle2,
@@ -13771,7 +14654,14 @@ function useOrderOutbox(options) {
13771
14654
  });
13772
14655
  }
13773
14656
  }
13774
- 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
+ }
13775
14665
  } finally {
13776
14666
  savesInFlight.current--;
13777
14667
  setSavesInFlightCount(savesInFlight.current);
@@ -13812,10 +14702,10 @@ function watchOutboxHealth(sales$, tillUpdates$) {
13812
14702
  }
13813
14703
 
13814
14704
  // src/outbox/use-outbox-health.ts
13815
- import { useMemo as useMemo10 } from "react";
14705
+ import { useMemo as useMemo11 } from "react";
13816
14706
  function useOutboxHealth(options) {
13817
14707
  const { sales, tillUpdates } = options;
13818
- const health = useMemo10(() => summarizeOutboxHealth(sales.state, tillUpdates.state), [sales.state, tillUpdates.state]);
14708
+ const health = useMemo11(() => summarizeOutboxHealth(sales.state, tillUpdates.state), [sales.state, tillUpdates.state]);
13819
14709
  return { health, async flush() {
13820
14710
  await Promise.all([sales.flush(), tillUpdates.flush()]);
13821
14711
  } };
@@ -13827,594 +14717,318 @@ async function sendOrderRefund(transport, envelope2) {
13827
14717
  let outcome;
13828
14718
  try {
13829
14719
  outcome = await transport.send([envelope2]);
13830
- } catch {
13831
- return { kind: "unknown", reason: "transport_error" };
13832
- }
13833
- if (outcome.kind === "retry") {
13834
- return {
13835
- kind: "unknown",
13836
- reason: outcome.reason,
13837
- ...outcome.retryAfterMs !== void 0 ? { retryAfterMs: outcome.retryAfterMs } : {}
13838
- };
13839
- }
13840
- if (outcome.kind === "refused" || outcome.kind === "unauthorized") return outcome;
13841
- const matches = outcome.results.filter((result2) => result2.id === envelope2.id);
13842
- if (matches.length !== 1) return { kind: "unknown", reason: "missing_result" };
13843
- let result;
13844
- try {
13845
- result = parseCommandResult(matches[0]);
13846
- } catch {
13847
- return { kind: "unknown", reason: "bad_result" };
13848
- }
13849
- if (result.status === "applied" || result.status === "duplicate") {
13850
- if (!result.refund) return { kind: "unknown", reason: "bad_result" };
13851
- return { kind: "applied", refund: result.refund, duplicate: result.status === "duplicate" };
13852
- }
13853
- return { kind: "rejected", error: result.error };
13854
- }
13855
-
13856
- // src/refund/pos-refund.ts
13857
- var posRefundSchema = {
13858
- title: "POS refunds",
13859
- version: 0,
13860
- primaryKey: "id",
13861
- type: "object",
13862
- additionalProperties: false,
13863
- properties: {
13864
- id: { type: "string", maxLength: 64 },
13865
- commandId: { type: "string", maxLength: 64 },
13866
- orderId: { type: "string", maxLength: 64 },
13867
- sessionId: { type: "string", maxLength: 64 },
13868
- registerId: { type: "string", maxLength: 64 },
13869
- envelope: { type: "object", additionalProperties: true },
13870
- status: { type: "string", enum: ["pending", "applied", "rejected", "unsent"], maxLength: 10 },
13871
- result: { type: "object", additionalProperties: true },
13872
- duplicate: { type: "boolean" },
13873
- error: { type: "object", properties: {
13874
- code: { type: "string" },
13875
- message: { type: "string" },
13876
- data: { type: "object", additionalProperties: true }
13877
- }, required: ["code", "message"], additionalProperties: false },
13878
- createdAt: { type: "string" },
13879
- updatedAt: { type: "string" }
13880
- },
13881
- required: ["id", "commandId", "orderId", "sessionId", "registerId", "envelope", "status", "createdAt", "updatedAt"],
13882
- indexes: [["sessionId"]]
13883
- };
13884
- var posRefundCollection = () => ({ schema: posRefundSchema });
13885
-
13886
- // src/refund/submit-order-refund.ts
13887
- import { RxError } from "rxdb";
13888
- var RefundAnswerPendingError = class extends Error {
13889
- constructor(record) {
13890
- super("This refund's answer is still unknown. Send it again before trying a new refund attempt.");
13891
- this.record = record;
13892
- this.name = "RefundAnswerPendingError";
13893
- }
13894
- code = "REFUND_ANSWER_PENDING";
13895
- };
13896
- async function submitOrderRefund({ refunds, transport, envelope: envelope2, now = () => (/* @__PURE__ */ new Date()).toISOString() }) {
13897
- const id2 = envelope2.payload.clientRefundId;
13898
- let doc = await refunds.findOne(id2).exec();
13899
- if (!doc) {
13900
- const at2 = now();
13901
- const { orderId, sessionId, registerId } = envelope2.payload;
13902
- try {
13903
- doc = await refunds.insert({
13904
- id: id2,
13905
- commandId: envelope2.id,
13906
- orderId,
13907
- sessionId,
13908
- registerId,
13909
- envelope: envelope2,
13910
- status: "pending",
13911
- createdAt: at2,
13912
- updatedAt: at2
13913
- });
13914
- } catch (error) {
13915
- if (!(error instanceof RxError) || error.code !== "CONFLICT") throw error;
13916
- doc = await refunds.findOne(id2).exec();
13917
- }
13918
- }
13919
- let record = doc.toJSON();
13920
- for (let pass = 0; ; pass++) {
13921
- if (pass === 2) throw new RefundAnswerPendingError(record);
13922
- if (record.status === "applied") {
13923
- return { outcome: { kind: "applied", refund: record.result, duplicate: true }, record };
13924
- }
13925
- if (record.status === "pending") {
13926
- if (record.commandId !== envelope2.id) throw new RefundAnswerPendingError(record);
13927
- break;
13928
- }
13929
- if (record.status === "rejected" && record.commandId === envelope2.id) {
13930
- return { outcome: { kind: "rejected", error: record.error }, record };
13931
- }
13932
- if (record.status === "unsent" && record.commandId === envelope2.id) {
13933
- doc = await doc.incrementalModify((stored) => {
13934
- if (stored.status !== "unsent" || stored.commandId !== envelope2.id) return stored;
13935
- const { error, ...rest } = stored;
13936
- return { ...rest, status: "pending", updatedAt: now() };
13937
- });
13938
- record = doc.toJSON();
13939
- continue;
13940
- }
13941
- doc = await doc.incrementalModify((stored) => {
13942
- if (stored.status !== "rejected" && stored.status !== "unsent") return stored;
13943
- const { result, duplicate, error, ...rest } = stored;
13944
- return { ...rest, commandId: envelope2.id, envelope: envelope2, status: "pending", updatedAt: now() };
13945
- });
13946
- record = doc.toJSON();
13947
- if (record.commandId === envelope2.id) break;
13948
- }
13949
- const outcome = await sendOrderRefund(transport, envelope2);
13950
- if (outcome.kind !== "unknown") {
13951
- doc = await doc.incrementalModify((stored) => {
13952
- if (stored.status !== "pending" || stored.commandId !== envelope2.id) return stored;
13953
- const updatedAt = now();
13954
- if (outcome.kind === "applied") {
13955
- const { error: error2, ...rest } = stored;
13956
- return { ...rest, status: "applied", result: outcome.refund, duplicate: outcome.duplicate, updatedAt };
13957
- }
13958
- if (outcome.kind === "rejected") return { ...stored, status: "rejected", error: outcome.error, updatedAt };
13959
- const error = outcome.kind === "refused" ? { code: "refused", message: outcome.reason, data: { status: outcome.status } } : { code: "unauthorized", message: "unauthorized" };
13960
- return { ...stored, status: "unsent", error, updatedAt };
13961
- });
13962
- }
13963
- return { outcome, record: doc.getLatest().toJSON() };
13964
- }
13965
-
13966
- // src/refund/refundable-lines.ts
13967
- function refundableLines(lines, refunds) {
13968
- const earlier = refunds.flatMap((refund) => refund.lines);
13969
- for (const refund of earlier) {
13970
- if (!Number.isSafeInteger(refund.quantity)) throw new RangeError("Earlier refund quantity must be a safe integer");
13971
- }
13972
- return lines.map((line) => {
13973
- if (!Number.isSafeInteger(line.quantity) || line.quantity < 0 || !Number.isSafeInteger(line.totalMinor) || !Number.isSafeInteger(line.taxMinor)) {
13974
- throw new RangeError("Order line values must be safe integers and quantity non-negative");
13975
- }
13976
- const refundedQuantity = earlier.reduce((sum4, refund) => refund.orderLineId === line.id ? Math.min(line.quantity, sum4 + Math.abs(refund.quantity)) : sum4, 0);
13977
- 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")));
13978
- return {
13979
- orderLineId: line.id,
13980
- refundedQuantity,
13981
- refundableQuantity: line.quantity - refundedQuantity,
13982
- netMinor,
13983
- taxMinor
13984
- };
13985
- });
13986
- }
13987
- function priceRefund(lines, refunds, request) {
13988
- const available = refundableLines(lines, refunds);
13989
- const seen = /* @__PURE__ */ new Set();
13990
- const result = { lines: [], priced: [], clamped: [], netMinor: 0, taxMinor: 0, totalMinor: 0 };
13991
- for (const { orderLineId, quantity: requestedQuantity, restock } of request) {
13992
- if (!Number.isSafeInteger(requestedQuantity) || requestedQuantity < 0 || seen.has(orderLineId)) {
13993
- throw new RangeError("Request quantities must be non-negative safe integers and line ids unique");
13994
- }
13995
- seen.add(orderLineId);
13996
- const index = lines.findIndex((line2) => line2.id === orderLineId);
13997
- const quantity = Math.min(requestedQuantity, available[index]?.refundableQuantity ?? 0);
13998
- if (quantity < requestedQuantity) result.clamped.push({ orderLineId, requestedQuantity, quantity });
13999
- if (quantity < 1) continue;
14000
- const line = lines[index];
14001
- const refundedQuantity = available[index].refundedQuantity;
14002
- 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")));
14003
- const totalMinor = netMinor + taxMinor;
14004
- result.lines.push({ orderLineId, quantity, restock });
14005
- result.priced.push({ orderLineId, quantity, netMinor, taxMinor, totalMinor });
14006
- result.netMinor += netMinor;
14007
- result.taxMinor += taxMinor;
14008
- result.totalMinor += totalMinor;
14009
- }
14010
- return result;
14011
- }
14012
-
14013
- // src/reopen/send-order-reopen.ts
14014
- import { parseCommandResult as parseCommandResult2 } from "@tallyui/core";
14015
- var inFlight = /* @__PURE__ */ new Set();
14016
- async function sendOrderReopen(transport, envelope2) {
14017
- const orderId = envelope2.payload.orderId;
14018
- if (inFlight.has(orderId)) return { kind: "in_flight" };
14019
- inFlight.add(orderId);
14020
- try {
14021
- let outcome;
14022
- try {
14023
- outcome = await transport.send([envelope2]);
14024
- } catch {
14025
- return { kind: "unknown", reason: "transport_error" };
14026
- }
14027
- if (outcome.kind === "retry") {
14028
- return {
14029
- kind: "unknown",
14030
- reason: outcome.reason,
14031
- ...outcome.retryAfterMs !== void 0 ? { retryAfterMs: outcome.retryAfterMs } : {}
14032
- };
14033
- }
14034
- if (outcome.kind === "refused" || outcome.kind === "unauthorized") return outcome;
14035
- const matches = outcome.results.filter((result2) => result2.id === envelope2.id);
14036
- if (matches.length !== 1) return { kind: "unknown", reason: "missing_result" };
14037
- let result;
14038
- try {
14039
- result = parseCommandResult2(matches[0]);
14040
- } catch {
14041
- return { kind: "unknown", reason: "bad_result" };
14042
- }
14043
- if (result.status === "applied" || result.status === "duplicate") {
14044
- if (!result.reopen) return { kind: "unknown", reason: "bad_result" };
14045
- return { kind: "applied", reopen: result.reopen, duplicate: result.status === "duplicate" };
14046
- }
14047
- return { kind: "rejected", error: result.error };
14048
- } finally {
14049
- inFlight.delete(orderId);
14050
- }
14051
- }
14052
- function isOrderReopenInFlight(orderId) {
14053
- return inFlight.has(orderId);
14054
- }
14055
- function isReopenOffered(input) {
14056
- return (input.orderReopen ?? 0) >= 1 && (input.orderCreate ?? 0) >= 5 && input.online && !input.storageDegraded && !isOrderReopenInFlight(input.orderId);
14057
- }
14058
-
14059
- // src/reopen/reopen-entry.ts
14060
- var REOPEN_REFUSED_STATUSES = ["cancelled", "failed", "trash"];
14061
- var ReopenEntryError = class extends Error {
14062
- constructor(reason, message) {
14063
- super(message);
14064
- this.reason = reason;
14065
- this.name = "ReopenEntryError";
14066
- }
14067
- };
14068
- function storeOrderForReopen(read, options) {
14069
- if (REOPEN_REFUSED_STATUSES.includes(read.status.toLowerCase())) {
14070
- throw new ReopenEntryError("status", `An order that is ${read.status.toLowerCase()} cannot be reopened`);
14071
- }
14072
- const lineTaxes = /* @__PURE__ */ new Map();
14073
- for (const line of read.lines) {
14074
- if (!line.productId) continue;
14075
- const tax = options.catalogue(line);
14076
- if (tax === null) throw new ReopenEntryError("catalogue", `"${line.name}" is no longer in the till's catalogue`);
14077
- lineTaxes.set(line, tax);
14078
- }
14079
- let builder;
14080
- try {
14081
- builder = orderBuilderFromStoreOrder(read, {
14082
- currency: options.currency,
14083
- taxContext: options.taxContext,
14084
- lineTax: (line) => lineTaxes.get(line)
14085
- });
14086
- } catch (error) {
14087
- if (error instanceof StoreOrderRebuildError) throw new ReopenEntryError(error.reason, error.message);
14088
- throw error;
14089
- }
14090
- if (read.payments.reduce((sum4, payment) => sum4 + payment.amountMinor, 0) > read.totalMinor) {
14091
- throw new ReopenEntryError("overpaid", "This order is paid more than its total");
14092
- }
14093
- return builder;
14094
- }
14095
-
14096
- // src/reopen/reopen-store-order.ts
14097
- 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.";
14098
- var STORE_ORDER_OPEN_HERE = "This order is already open on this till. Find it in the current sale or the parked sales.";
14099
- async function reopenStoreOrder(read, deps) {
14100
- const options = { currency: deps.currency, taxContext: deps.taxContext, catalogue: deps.catalogue };
14101
- try {
14102
- storeOrderForReopen(read, { ...options, taxContext: deps.taxContextFor ? deps.taxContextFor(storeOrderCustomer(read)).taxContext : deps.taxContext });
14103
- } catch (error) {
14104
- if (error instanceof ReopenEntryError) return { kind: "refused", reason: error.reason, message: error.message };
14105
- throw error;
14720
+ } catch {
14721
+ return { kind: "unknown", reason: "transport_error" };
14106
14722
  }
14107
- if (await deps.openHere(read.id)) return { kind: "refused", reason: "open_here", message: STORE_ORDER_OPEN_HERE };
14108
- if (deps.resend && deps.resend.payload.orderId !== read.id) throw new Error("reopenStoreOrder: resend is for another order");
14109
- const at2 = deps.resend ? 0 : (deps.now ?? Date.now)(), createdAt = new Date(at2).toISOString();
14110
- const { cashierRef, registerId, storeId, deviceId } = deps.identity;
14111
- const envelope2 = deps.resend ? { ...deps.resend, attempt: deps.resend.attempt + 1 } : {
14112
- id: uuidv7(at2),
14113
- type: "order.reopen",
14114
- version: 1,
14115
- createdAt,
14116
- deviceId,
14117
- attempt: 1,
14118
- payload: {
14119
- orderId: read.id,
14120
- ...read.clientOrderId !== void 0 ? { clientOrderId: read.clientOrderId } : {},
14121
- baseRevision: read.revision,
14122
- cashierRef,
14123
- registerId,
14124
- ...storeId !== void 0 ? { storeId } : {},
14125
- 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 };
14126
14727
  }
14127
- };
14128
- const outcome = await sendOrderReopen(deps.transport, envelope2);
14129
- if (outcome.kind !== "applied") return { kind: "not_reopened", outcome, envelope: envelope2 };
14130
- 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;
14131
14738
  try {
14132
- reread = (await deps.getOrders([read.id])).find((order) => order.id === read.id);
14739
+ result = parseCommandResult(matches[0]);
14133
14740
  } catch {
14134
- return { kind: "reopened_unloadable", reason: "reread", message: `${REOPENED_NOT_LOADED} The order could not be read again.` };
14741
+ return { kind: "unknown", reason: "bad_result" };
14135
14742
  }
14136
- if (!reread) return { kind: "reopened_unloadable", reason: "reread", message: `${REOPENED_NOT_LOADED} The order could not be read again.` };
14137
- if (outcome.reopen.revision !== void 0 && reread.revision !== outcome.reopen.revision)
14138
- return { kind: "reopened_unloadable", reason: "reread", message: `${REOPENED_NOT_LOADED} The order read back does not match the reopen.` };
14139
- try {
14140
- const builder = storeOrderForReopen(reread, { ...options, taxContext: deps.taxContextFor ? deps.taxContextFor(storeOrderCustomer(reread)).taxContext : deps.taxContext });
14141
- return { kind: "reopened", order: builder.getSnapshot(), duplicate: outcome.duplicate };
14142
- } catch (error) {
14143
- if (error instanceof ReopenEntryError) return { kind: "reopened_unloadable", reason: error.reason, message: `${REOPENED_NOT_LOADED} ${error.message}` };
14144
- 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" };
14145
14746
  }
14747
+ return { kind: "rejected", error: result.error };
14146
14748
  }
14147
14749
 
14148
- // src/tender/tender-state.ts
14149
- var MAX_TENDER_MINOR = 999999999;
14150
- var initialTenderState = {
14151
- view: "select",
14152
- methodId: null,
14153
- readerId: null,
14154
- transport: null,
14155
- entryMinor: 0,
14156
- entryDirty: false,
14157
- entryMode: "money",
14158
- plan: null,
14159
- splitView: false,
14160
- splitTab: "even",
14161
- pickedLineIds: [],
14162
- linesPaidBy: {},
14163
- pickedUnits: {},
14164
- 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"]]
14165
14782
  };
14166
- function initTenderState({
14167
- methodId,
14168
- balanceMinor,
14169
- payments
14170
- }) {
14171
- const state = payments ? { ...initialTenderState, unitAllocations: unitAllocationsFromLegs(payments ?? []) } : initialTenderState;
14172
- if (!methodId) return state;
14173
- 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
+ }
14174
14811
  }
14175
- function tenderReducer(state, action) {
14176
- switch (action.type) {
14177
- case "pick-method":
14178
- return {
14179
- ...state,
14180
- view: "amount",
14181
- methodId: action.methodId,
14182
- readerId: action.readerId,
14183
- transport: action.transport ?? null,
14184
- entryMinor: state.entryDirty ? state.entryMinor : action.prefillMinor,
14185
- entryDirty: state.entryDirty
14186
- };
14187
- case "pick-transport":
14188
- return { ...state, transport: action.transport };
14189
- case "pick-reader":
14190
- return { ...state, readerId: action.readerId };
14191
- case "key": {
14192
- if (state.view !== "amount") {
14193
- return state;
14194
- }
14195
- if (action.key === "backspace") {
14196
- return { ...state, entryMinor: Math.floor(state.entryMinor / 10), entryDirty: true };
14197
- }
14198
- if (action.key === "clear") {
14199
- return { ...state, entryMinor: 0, entryDirty: true };
14200
- }
14201
- const digit = Number(action.key);
14202
- if (!state.entryDirty) {
14203
- return { ...state, entryMinor: digit, entryDirty: true };
14204
- }
14205
- const entryMinor = state.entryMinor * 10 + digit;
14206
- 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();
14207
14835
  }
14208
- case "set-entry":
14209
- return {
14210
- ...state,
14211
- entryMinor: Math.max(0, Math.min(action.minor, MAX_TENDER_MINOR)),
14212
- entryDirty: true
14213
- };
14214
- case "set-entry-mode":
14215
- return { ...state, entryMode: action.mode, entryMinor: 0, entryDirty: false };
14216
- case "tender-started": {
14217
- const leg = action.units ?? state.pickedUnits;
14218
- const freeze = action.paymentId !== void 0 && Object.keys(leg).length > 0;
14219
- const clear = action.paymentId !== void 0 && Object.keys(state.pickedUnits).length > 0;
14220
- const units = {
14221
- ...freeze ? { unitAllocations: { ...state.unitAllocations, [String(action.paymentId)]: leg } } : {},
14222
- ...clear ? { pickedUnits: {} } : {}
14223
- };
14224
- 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 };
14225
14842
  }
14226
- case "back":
14227
- return {
14228
- ...state,
14229
- view: "select",
14230
- methodId: null,
14231
- readerId: null,
14232
- transport: null,
14233
- entryMinor: 0,
14234
- entryDirty: false,
14235
- entryMode: "money"
14236
- };
14237
- case "tender-recorded": {
14238
- const linesPaidBy = { ...state.linesPaidBy };
14239
- if (state.plan?.kind === "items" && action.rowsSinceFrom.reduce((sum4, row) => sum4 + row.amountMinor, 0) >= state.plan.firstMinor) {
14240
- for (const id2 of state.plan.lineIds) {
14241
- linesPaidBy[id2] ??= [...new Set(action.rowsSinceFrom.map((row) => row.title))];
14242
- }
14243
- } else if (state.plan?.kind === "items") {
14244
- for (const id2 of state.plan.lineIds) {
14245
- delete linesPaidBy[id2];
14246
- }
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 };
14247
14883
  }
14248
- const rows = action.rowsSinceFrom.map((row) => ({
14249
- minor: row.amountMinor,
14250
- title: row.title
14251
- }));
14252
- const plan = activePlan(state.plan, rows.length, action.balanceMinor);
14253
- const entryMinor = plan ? planLegs(plan, rows, action.balanceMinor).thisPaymentMinor : action.balanceMinor;
14254
- return {
14255
- ...state,
14256
- view: state.methodId ? "amount" : "select",
14257
- entryMinor,
14258
- entryDirty: false,
14259
- entryMode: "money",
14260
- // Split closed means no picks: while units are picked (a leg recorded or settled elsewhere), Split stays open.
14261
- splitView: Object.keys(state.pickedUnits).length > 0 ? state.splitView : false,
14262
- pickedLineIds: [],
14263
- linesPaidBy
14264
- };
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" };
14265
14912
  }
14266
- case "open-split":
14267
- return {
14268
- ...state,
14269
- splitView: true,
14270
- pickedLineIds: state.plan?.kind === "items" ? state.plan.lineIds.filter((id2) => !state.linesPaidBy[id2]) : state.pickedLineIds
14271
- };
14272
- // 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.
14273
- case "close-split":
14274
- return { ...state, splitView: false, pickedUnits: {} };
14275
- case "set-split-tab":
14276
- return { ...state, splitTab: action.tab };
14277
- case "toggle-split-line":
14278
- if (state.linesPaidBy[action.lineId]) return state;
14913
+ if (outcome.kind === "retry") {
14279
14914
  return {
14280
- ...state,
14281
- 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 } : {}
14282
14918
  };
14283
- case "set-split-units": {
14284
- if (!Number.isInteger(action.units) || action.units < 0) return state;
14285
- if (!Number.isInteger(action.unpaidUnits) || action.unpaidUnits < 0) return state;
14286
- if (state.plan && action.units > 0) return state;
14287
- const units = Math.min(action.units, action.unpaidUnits);
14288
- const next = { ...state.pickedUnits, [String(action.lineId)]: units };
14289
- return { ...state, pickedUnits: Object.fromEntries(Object.entries(next).filter(([, n]) => n > 0)) };
14290
14919
  }
14291
- case "set-plan":
14292
- return {
14293
- ...state,
14294
- plan: action.plan,
14295
- splitView: false,
14296
- pickedUnits: {},
14297
- pickedLineIds: [],
14298
- entryMinor: state.view === "amount" ? planLegs(action.plan, [], action.balanceMinor).thisPaymentMinor : state.entryMinor,
14299
- entryDirty: state.view !== "amount" && state.entryDirty,
14300
- entryMode: "money"
14301
- };
14302
- case "clear-plan":
14303
- case "arm-custom":
14304
- return {
14305
- ...state,
14306
- plan: null,
14307
- splitView: false,
14308
- pickedUnits: {},
14309
- view: action.type === "arm-custom" ? "amount" : state.view,
14310
- entryMinor: action.type === "clear-plan" ? action.balanceMinor : 0,
14311
- entryDirty: false,
14312
- entryMode: "money"
14313
- };
14314
- case "request-cancel":
14315
- return { ...state, view: "cancel", splitView: false, pickedUnits: {} };
14316
- case "reset":
14317
- 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);
14318
14936
  }
14319
14937
  }
14320
- function appliedMinor(entryMinor, balanceMinor) {
14321
- return Math.max(0, Math.min(entryMinor, balanceMinor));
14938
+ function isOrderReopenInFlight(orderId) {
14939
+ return inFlight2.has(orderId);
14322
14940
  }
14323
- function changeMinor(entryMinor, appliedAmountMinor, givesChange) {
14324
- 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);
14325
14943
  }
14326
- function quickTenderedAmounts(balanceMinor, stepsMinor) {
14327
- if (balanceMinor === 0) {
14328
- 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";
14329
14952
  }
14330
- const amounts = /* @__PURE__ */ new Set([balanceMinor]);
14331
- for (const stepMinor of stepsMinor) {
14332
- if (stepMinor <= 0) continue;
14333
- const remainder = balanceMinor % stepMinor;
14334
- 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`);
14335
14957
  }
14336
- return [...amounts].sort((left, right) => left - right);
14337
- }
14338
- function evenSplitShareMinor(balanceMinor, ways) {
14339
- if (ways < 2) {
14340
- 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);
14341
14964
  }
14342
- const wholeShare = Math.floor(balanceMinor / ways);
14343
- const remainder = balanceMinor % ways;
14344
- return wholeShare + (remainder * 2 >= ways ? 1 : 0);
14345
- }
14346
- function percentOfMinor(balanceMinor, percent) {
14347
- return Math.max(0, Math.min(balanceMinor, Math.round(balanceMinor * percent / 100)));
14348
- }
14349
- function activePlan(plan, taken, balanceMinor) {
14350
- if (!plan || balanceMinor === 0) return null;
14351
- if (plan.kind !== "items" && taken >= (plan.kind === "even" ? plan.ways : 1 + (plan.thenWays ?? 1)))
14352
- return null;
14353
- return plan;
14354
- }
14355
- function planLegs(plan, rowsSinceFrom, balanceMinor) {
14356
- const taken = rowsSinceFrom.length;
14357
- const legs = rowsSinceFrom.map((row) => ({ ...row, state: "done" }));
14358
- const groupPaid = rowsSinceFrom.reduce((sum4, row) => sum4 + row.minor, 0);
14359
- const groupLeft = plan.kind === "items" ? Math.min(balanceMinor, Math.max(0, plan.firstMinor - groupPaid)) : balanceMinor;
14360
- const rest = plan.kind === "items" && groupLeft === 0;
14361
- const ways = plan.kind === "fixed" ? 1 + (plan.thenWays ?? 1) : Math.max(plan.ways, taken + 1);
14362
- const firstFixed = plan.kind === "fixed" && taken === 0;
14363
- const left = firstFixed || rest ? 1 : Math.max(1, ways - taken);
14364
- const amount = rest ? balanceMinor : groupLeft;
14365
- const each = plan.kind === "fixed" && taken === 0 ? Math.min(plan.firstMinor, balanceMinor) : evenSplitShareMinor(amount, left);
14366
- let remaining = amount;
14367
- for (let i = 0; i < left; i++) {
14368
- const minor2 = Math.min(remaining, i === left - 1 && !firstFixed ? remaining : each);
14369
- legs.push({ minor: minor2, state: i === 0 ? "now" : "todo" });
14370
- 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;
14371
14975
  }
14372
- if (firstFixed && remaining > 0) {
14373
- const thenWays = plan.thenWays ?? 1;
14374
- const share = evenSplitShareMinor(remaining, thenWays);
14375
- for (let i = 0; i < thenWays; i++) {
14376
- const minor2 = Math.min(remaining, i === thenWays - 1 ? remaining : share);
14377
- legs.push({ minor: minor2, state: "todo" });
14378
- remaining -= minor2;
14379
- }
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");
14380
14978
  }
14381
- if (plan.kind === "items" && !rest && balanceMinor > groupLeft)
14382
- legs.push({ minor: balanceMinor - groupLeft, state: "rest" });
14383
- const title = plan.kind === "fixed" && taken === 0 ? plan.title : null;
14384
- return { legs, thisPaymentMinor: each, label: { n: taken + 1, ways, rest, title } };
14979
+ return builder;
14385
14980
  }
14386
14981
 
14387
- // src/tender/cash-rounding.ts
14388
- function roundToIncrement(minor2, incrementMinor, mode) {
14389
- if (!Number.isInteger(incrementMinor) || incrementMinor <= 1) return minor2;
14390
- const remainder = minor2 % incrementMinor;
14391
- if (remainder === 0) return minor2;
14392
- const down = minor2 - remainder;
14393
- if (mode === "down") return down;
14394
- if (mode === "up") return down + incrementMinor;
14395
- return remainder * 2 >= incrementMinor ? down + incrementMinor : down;
14396
- }
14397
- function roundedDue(balanceMinor, method) {
14398
- const rounding = method?.capture.mode === "manual" ? method.defaults.rounding : null;
14399
- if (!rounding) return { dueMinor: balanceMinor, roundingMinor: 0 };
14400
- const dueMinor = roundToIncrement(balanceMinor, rounding.incrementMinor, rounding.mode);
14401
- return { dueMinor, roundingMinor: dueMinor - balanceMinor };
14402
- }
14403
- function settlesAtRoundedDue(facts) {
14404
- const { amountMinor, tenderedMinor, balanceMinor, dueMinor } = facts;
14405
- return amountMinor >= Math.min(balanceMinor, dueMinor) && tenderedMinor >= dueMinor;
14406
- }
14407
- function tenderRounding(state, balanceMinor, method) {
14408
- const roundedDueMinor = roundedDue(balanceMinor, method).dueMinor;
14409
- const entryMinor = !state.entryDirty && state.entryMinor === balanceMinor ? roundedDueMinor : state.entryMinor;
14410
- const legMinor = appliedMinor(entryMinor, balanceMinor);
14411
- const roundingMinor = settlesAtRoundedDue({
14412
- amountMinor: legMinor,
14413
- tenderedMinor: entryMinor,
14414
- balanceMinor,
14415
- dueMinor: roundedDueMinor
14416
- }) ? roundedDueMinor - balanceMinor : 0;
14417
- 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
+ }
14418
15032
  }
14419
15033
 
14420
15034
  // src/tender/tender-figures.ts
@@ -14433,7 +15047,7 @@ function tenderFigures(facts) {
14433
15047
  const groupDone = plan?.kind === "items" && done.reduce((sum4, leg) => sum4 + leg.minor, 0) >= plan.firstMinor;
14434
15048
  const thisPaymentMinor = split?.thisPaymentMinor ?? balanceMinor;
14435
15049
  const legCapMinor = method?.capabilities.change ? thisPaymentMinor : balanceMinor;
14436
- const roundedDueMinor = roundedDue(balanceMinor, method).dueMinor;
15050
+ const roundedDueMinor = roundedDue(balanceMinor, method, facts.entriesMinor ?? 0).dueMinor;
14437
15051
  const percent = state.entryMode === "percent";
14438
15052
  const percentMinor = percent ? percentOfMinor(balanceMinor, state.entryMinor) : null;
14439
15053
  const entryMinor = percentMinor ?? (!state.entryDirty && state.entryMinor === balanceMinor ? roundedDueMinor : state.entryMinor);
@@ -14585,12 +15199,15 @@ function marginOf(lines) {
14585
15199
  margin.marginPct = costed && margin.costedNetMinor !== 0 ? margin.profitMinor / margin.costedNetMinor : null;
14586
15200
  return margin;
14587
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
+ }
14588
15208
  function orderSpread(totals) {
14589
15209
  const values = [...totals].sort((a, b) => a - b);
14590
- const middle = Math.floor(values.length / 2);
14591
- if (!values.length) return { medianMinor: 0, largestMinor: null };
14592
- const medianMinor = values.length % 2 ? values[middle] : Math.round((values[middle - 1] + values[middle]) / 2);
14593
- return { medianMinor, largestMinor: values[values.length - 1] };
15210
+ return { medianMinor: medianMinor(values), largestMinor: values.length ? values[values.length - 1] : null };
14594
15211
  }
14595
15212
  function periodFigures(input, range) {
14596
15213
  const orders = input.orders.filter((order) => inRange(order.at, range, input.timezone));
@@ -14603,16 +15220,20 @@ function periodFigures(input, range) {
14603
15220
  discountMinor: 0,
14604
15221
  refundsMinor: 0,
14605
15222
  embeddedRefundsMinor: 0,
15223
+ roundingMinor: 0,
14606
15224
  orderCount: orders.length,
14607
15225
  averageMinor: 0,
14608
15226
  items: lines.reduce((sum4, line) => sum4 + (Number.isFinite(line.quantity) ? line.quantity : 0), 0),
14609
- margin: marginOf(lines)
15227
+ margin: marginOf(lines),
15228
+ refundBasis: input.refunds !== void 0 ? "dated" : "embedded",
15229
+ grossAfterRefundsMinor: 0
14610
15230
  };
14611
15231
  const series = daysOf(range).map((day) => ({ day, grossMinor: 0, orderCount: 0, refundsMinor: 0 }));
14612
15232
  const byDay = new Map(series.map((point) => [point.day, point]));
14613
15233
  for (const order of orders) {
14614
15234
  totals.grossMinor += order.totalMinor;
14615
15235
  totals.taxMinor += order.taxMinor;
15236
+ totals.roundingMinor += order.roundingMinor ?? 0;
14616
15237
  totals.discountMinor += order.discountMinor;
14617
15238
  totals.embeddedRefundsMinor += order.refunds.reduce((sum4, refund) => sum4 + Math.abs(refund.amountMinor), 0);
14618
15239
  const point = byDay.get(businessDayOf(order.at, input.timezone));
@@ -14623,7 +15244,8 @@ function periodFigures(input, range) {
14623
15244
  totals.refundsMinor += Math.abs(refund.amountMinor);
14624
15245
  byDay.get(businessDayOf(refund.at, input.timezone)).refundsMinor += Math.abs(refund.amountMinor);
14625
15246
  }
14626
- 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);
14627
15249
  totals.averageMinor = orders.length ? Math.round(totals.grossMinor / orders.length) : 0;
14628
15250
  Object.assign(totals, orderSpread(orders.map((order) => order.totalMinor)));
14629
15251
  return { orders, refunds, totals, series };
@@ -14731,6 +15353,7 @@ function reportOrderFromPosOrder(order, join, methodTitle2) {
14731
15353
  const taxes = recordedTaxByRate(order) ?? taxLinesByRate(taxedLines, order.taxMinor, void 0, order.taxRounding);
14732
15354
  const till = tillPayments(order.payments);
14733
15355
  const amountOf = (payments) => payments.reduce((total, payment) => total + payment.amountMinor, 0);
15356
+ const roundingMinor = (order.cashRoundings ?? []).reduce((total, entry) => total + entry.minor, 0);
14734
15357
  return {
14735
15358
  id: order.id,
14736
15359
  at: order.createdAt,
@@ -14756,6 +15379,7 @@ function reportOrderFromPosOrder(order, join, methodTitle2) {
14756
15379
  return { method, ...label ? { label } : {}, amountMinor: payment.amountMinor };
14757
15380
  }),
14758
15381
  ...order.storeOrderId !== void 0 ? { paidEarlierMinor: amountOf(order.payments) - amountOf(till) } : {},
15382
+ ...roundingMinor !== 0 ? { roundingMinor } : {},
14759
15383
  taxes: taxes.map((row) => ({
14760
15384
  ratePpm: row.ratePpm,
14761
15385
  ...row.code !== void 0 ? { code: row.code } : {},
@@ -14768,7 +15392,7 @@ function reportOrderFromPosOrder(order, join, methodTitle2) {
14768
15392
  function reportOrderFromStoreOrder(order, join) {
14769
15393
  return {
14770
15394
  id: order.id,
14771
- at: order.placedAt,
15395
+ at: order.paidAt ?? order.placedAt,
14772
15396
  totalMinor: order.totalMinor,
14773
15397
  taxMinor: order.taxMinor,
14774
15398
  discountMinor: order.discountMinor,
@@ -14788,7 +15412,8 @@ function reportOrderFromStoreOrder(order, join) {
14788
15412
  taxMinor: amountMinor,
14789
15413
  netMinor: null
14790
15414
  })),
14791
- 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 } : {}
14792
15417
  };
14793
15418
  }
14794
15419
  function reportRefundFromPosRefund(refund) {
@@ -14811,6 +15436,11 @@ export {
14811
15436
  CAMERA_BARCODE_TYPES,
14812
15437
  CAMERA_CONSTRAINTS,
14813
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,
14814
15444
  COLLECT_POLL_MS,
14815
15445
  CONNECT_TIMEOUT_MS,
14816
15446
  COUPONS_NEED_CONNECTION,
@@ -14851,17 +15481,22 @@ export {
14851
15481
  META_CHANGE_REFUSED,
14852
15482
  META_INVALID,
14853
15483
  MICROS_PER_MINOR,
15484
+ NEEDS_ADMIN_RETRY_PREFIX,
15485
+ NOTHING_DUE,
15486
+ NOTHING_TO_ROUND_AGAINST,
14854
15487
  OPEN_ORDERS_POSITIONS,
14855
15488
  OPEN_SIGNAL_POLL_MS,
14856
15489
  OrderContentMismatchError,
14857
15490
  PAPER_COLUMNS,
14858
15491
  PAYMENT_IN_MOTION,
15492
+ PAYMENT_TAKEN,
14859
15493
  PENDING_POLL_MS,
14860
15494
  PRINTER_PROFILES_COLLECTION,
14861
15495
  PRODUCT_SORT_FIELDS,
14862
15496
  PosOrderOpenClosedError,
14863
15497
  PrintError,
14864
15498
  RECEIPT_SCHEMA_VERSION,
15499
+ REGISTER_CLOSING,
14865
15500
  REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS,
14866
15501
  REOPENABLE_CODES,
14867
15502
  REOPENED_NOT_LOADED,
@@ -14876,6 +15511,7 @@ export {
14876
15511
  RegisterMovementStrandedError,
14877
15512
  RegisterNeedsUpgradeError,
14878
15513
  RegisterReapproveError,
15514
+ RegisterSaleSavingError,
14879
15515
  RegisterSessionAlreadyOpenError,
14880
15516
  RegisterSessionClosedError,
14881
15517
  RegisterSessionConflictError,
@@ -14885,6 +15521,7 @@ export {
14885
15521
  RegisterTenderInProgressError,
14886
15522
  ReopenEntryError,
14887
15523
  ReopenRefusedOrderError,
15524
+ SALE_CARD_IN_PROGRESS,
14888
15525
  SALE_FINISHED,
14889
15526
  SALE_HAS_PAYMENT,
14890
15527
  SALE_IN_TENDER,
@@ -14921,6 +15558,7 @@ export {
14921
15558
  UPDATE_UNSENDABLE,
14922
15559
  UPDATE_UNSENDABLE_MESSAGE,
14923
15560
  UnsupportedOrderVersionError,
15561
+ VOID_LATER_CASH_FIRST,
14924
15562
  WCPOS_DEFAULT_I18N,
14925
15563
  WCPOS_TAX_ID_LABELS,
14926
15564
  WEDGE_END_OF_SCAN_MS,
@@ -14955,6 +15593,7 @@ export {
14955
15593
  capturedMinor,
14956
15594
  cartQuantities,
14957
15595
  cashMovementSchema,
15596
+ cashVoidRefusal,
14958
15597
  catalogueEntries,
14959
15598
  catalogueViewReducer,
14960
15599
  changeMinor,
@@ -14963,6 +15602,7 @@ export {
14963
15602
  closeSession,
14964
15603
  closureApprovalStatus,
14965
15604
  closureCommand,
15605
+ closureFigures,
14966
15606
  closureSchema,
14967
15607
  closureVariance,
14968
15608
  comparisonRange,
@@ -15086,6 +15726,7 @@ export {
15086
15726
  markAttentionHandled,
15087
15727
  matchVariant,
15088
15728
  matchesPresetFilters,
15729
+ medianMinor,
15089
15730
  messageBytes,
15090
15731
  methodDrivers,
15091
15732
  methodForProvider,
@@ -15096,6 +15737,8 @@ export {
15096
15737
  movementCommand,
15097
15738
  movementFieldError,
15098
15739
  nativeBarcodeDetector,
15740
+ nearestPayableCash,
15741
+ needsAdminReasonOf,
15099
15742
  needsAttention,
15100
15743
  networkSinkFor,
15101
15744
  nextSaleCounter,
@@ -15147,6 +15790,7 @@ export {
15147
15790
  recordMovement,
15148
15791
  recordRegisterFact,
15149
15792
  refundDueOf,
15793
+ refundNeedsAdminLine,
15150
15794
  refundableLines,
15151
15795
  registerCommandCollection,
15152
15796
  registerCommandSchema,
@@ -15155,6 +15799,7 @@ export {
15155
15799
  registerSessionCollection,
15156
15800
  registerSessionSchema,
15157
15801
  registerSessionsLogger,
15802
+ remainderEntriesMinor,
15158
15803
  removeScannerProfile,
15159
15804
  renderEscpos,
15160
15805
  renderHtml,
@@ -15179,10 +15824,12 @@ export {
15179
15824
  retailCodeTwin,
15180
15825
  roundMicrosToMinor,
15181
15826
  roundedDue,
15827
+ roundedPickTarget,
15182
15828
  runsWholeOrder,
15183
15829
  saleLogger,
15184
15830
  saleTaxContexts,
15185
15831
  salesFigures,
15832
+ salesRangeQuery,
15186
15833
  sameSale,
15187
15834
  sanitizeHtml,
15188
15835
  saveScannerProfile,
@@ -15259,6 +15906,7 @@ export {
15259
15906
  useSaleDisplay,
15260
15907
  useScanHub,
15261
15908
  useStoreOrdersInRange,
15909
+ useStoreRefundsInRange,
15262
15910
  useStoreSettings,
15263
15911
  useTax,
15264
15912
  useTillDisplays,