@tallyui/pos 5.1.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -669,25 +669,33 @@ function createEnvelope(order, deviceId, attempt2, options, floor) {
669
669
  ...base === 6 && line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {},
670
670
  ...base === 6 && line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}
671
671
  })),
672
- ...base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
673
- clientFeeId: fee.id,
674
- name: fee.name,
675
- amountMinor: wireChargeMinor(order, fee, order.display?.fees),
676
- taxStatus: fee.taxStatus,
677
- ...fee.taxClass !== void 0 ? { taxClass: fee.taxClass } : {},
678
- // #1131: WooCommerce totals a fee line's tax per rate, as its own order totals do.
679
- taxMinor: order.taxRounding?.granularity === "woocommerce" ? woocommerceChargeTaxMinor(fee, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax) : roundMicrosToMinor(BigInt(fee.taxMicros))
680
- })) } : {},
681
- ...base >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
682
- clientShippingId: charge.id,
683
- name: charge.name,
684
- ...charge.methodId !== void 0 ? { methodId: charge.methodId } : {},
685
- amountMinor: wireChargeMinor(order, charge, order.display?.shipping),
686
- taxStatus: charge.taxStatus,
687
- ...charge.taxClass !== void 0 ? { taxClass: charge.taxClass } : {},
688
- // #1120: WooCommerce totals a shipping line's tax per rate, as its own order totals do.
689
- taxMinor: order.taxRounding?.granularity === "woocommerce" ? woocommerceChargeTaxMinor(charge, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax) : roundMicrosToMinor(BigInt(charge.taxMicros))
690
- })) } : {},
672
+ ...base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => {
673
+ const sent = fee.entered?.sent === true ? fee.entered : void 0;
674
+ return {
675
+ clientFeeId: fee.id,
676
+ name: fee.name,
677
+ amountMinor: sent?.amountMinor ?? wireChargeMinor(order, fee, order.display?.fees),
678
+ ...sent ? { amountIncludesTax: sent.amountIncludesTax } : {},
679
+ taxStatus: fee.taxStatus,
680
+ ...fee.taxClass !== void 0 ? { taxClass: fee.taxClass } : {},
681
+ // #1131: WooCommerce totals a fee line's tax per rate, as its own order totals do.
682
+ taxMinor: order.taxRounding?.granularity === "woocommerce" ? woocommerceChargeTaxMinor(fee, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax) : roundMicrosToMinor(BigInt(fee.taxMicros))
683
+ };
684
+ }) } : {},
685
+ ...base >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => {
686
+ const sent = charge.entered?.sent === true ? charge.entered : void 0;
687
+ return {
688
+ clientShippingId: charge.id,
689
+ name: charge.name,
690
+ ...charge.methodId !== void 0 ? { methodId: charge.methodId } : {},
691
+ amountMinor: sent?.amountMinor ?? wireChargeMinor(order, charge, order.display?.shipping),
692
+ ...sent ? { amountIncludesTax: sent.amountIncludesTax } : {},
693
+ taxStatus: charge.taxStatus,
694
+ ...charge.taxClass !== void 0 ? { taxClass: charge.taxClass } : {},
695
+ // #1120: WooCommerce totals a shipping line's tax per rate, as its own order totals do.
696
+ taxMinor: order.taxRounding?.granularity === "woocommerce" ? woocommerceChargeTaxMinor(charge, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax) : roundMicrosToMinor(BigInt(charge.taxMicros))
697
+ };
698
+ }) } : {},
691
699
  ...base === 6 && redeemable.length ? { coupons: redeemable.map(({ code, couponId, discountMinor: discountMinor2, discountTaxMinor, lines }) => ({
692
700
  code,
693
701
  couponId,
@@ -914,6 +922,13 @@ function taxDerivation(settings, taxLocation) {
914
922
  }
915
923
 
916
924
  // src/tax/taxed-lines.ts
925
+ function storedCharges(charges) {
926
+ return charges.map((charge) => charge.entered === void 0 ? charge : {
927
+ ...charge,
928
+ amountIncludesTax: charge.entered.amountIncludesTax,
929
+ ...charge.totalMinor === void 0 ? { netMinor: charge.entered.amountMinor } : {}
930
+ });
931
+ }
917
932
  function taxedLinesFor(lines, charges, pricesIncludeTax, rounding) {
918
933
  return [
919
934
  ...lines.map((line) => ({ ...line, taxInclusive: rounding?.granularity === "woocommerce" && line.netMicros !== void 0 ? pricesIncludeTax : line.taxInclusive ?? pricesIncludeTax })),
@@ -2184,6 +2199,16 @@ import { map as map3 } from "rxjs";
2184
2199
  function tillPayments(payments) {
2185
2200
  return payments.filter((payment) => payment.storePaymentId === void 0);
2186
2201
  }
2202
+ function settledAwayOnStore(order) {
2203
+ const settlement = order.storeSettlement;
2204
+ return (settlement?.kind === "cancel" || settlement?.kind === "reverse") && settlement.state === "done";
2205
+ }
2206
+ function countedTillPayments(order) {
2207
+ const settlement = order.storeSettlement;
2208
+ if (settledAwayOnStore(order)) return [];
2209
+ const payments = tillPayments(order.payments);
2210
+ return settlement?.kind === "reverse" ? payments.filter((payment) => !settlement.legs?.some((leg) => leg.done && leg.paymentId === payment.id)) : payments;
2211
+ }
2187
2212
 
2188
2213
  // src/order/taken-at.ts
2189
2214
  function isTakenAt(value) {
@@ -2692,7 +2717,7 @@ function receiptRounding(order) {
2692
2717
  return amountMinor !== 0 ? { rounding: { name: "Rounding", amountMinor } } : {};
2693
2718
  }
2694
2719
  function buildReceiptData(order, config) {
2695
- const taxedLines = taxedLinesFor(order.lineItems, [...order.fees ?? [], ...order.shipping ?? []], order.pricesIncludeTax, order.taxRounding);
2720
+ const taxedLines = taxedLinesFor(order.lineItems, storedCharges([...order.fees ?? [], ...order.shipping ?? []]), order.pricesIncludeTax, order.taxRounding);
2696
2721
  const taxLines = taxLinesByRate(taxedLines, order.taxMinor, config.taxLabels, order.taxRounding).map(
2697
2722
  ({ label: label2, code, ratePpm, amountMinor }) => ({ label: label2, code, ratePpm, amountMinor })
2698
2723
  );
@@ -2864,7 +2889,7 @@ function buildReceiptDataFromPosOrder(order, config) {
2864
2889
  displayDiscounts
2865
2890
  };
2866
2891
  });
2867
- const taxedLines = taxedLinesFor(order.lines, [...order.fees ?? [], ...order.shipping ?? []], order.pricesIncludeTax, order.taxRounding);
2892
+ const taxedLines = taxedLinesFor(order.lines, storedCharges([...order.fees ?? [], ...order.shipping ?? []]), order.pricesIncludeTax, order.taxRounding);
2868
2893
  const recorded = recordedTaxByRate(order);
2869
2894
  const taxLines = recorded ? recorded.map((row) => ({
2870
2895
  label: config.taxLabels?.[row.ratePpm] ?? row.label ?? `Tax ${row.ratePpm / 1e4}%`,
@@ -7984,14 +8009,20 @@ var AFTER_CLOSE_PAYMENTS_CHANGED = "This sale was counted in a closed register.
7984
8009
  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);
7985
8010
  var sameCharges = (a = [], b = []) => a.length === b.length && a.every((charge, i) => charge.totalMinor === b[i].totalMinor && sameTaxes(charge, b[i]));
7986
8011
  var MESSAGE_NAME_MAX = 61;
7987
- function storedCharge(charge, pricesIncludeTax, displayMinor) {
8012
+ function storedCharge(charge, pricesIncludeTax, displayMinor, keep) {
7988
8013
  if (charge.amountIncludesTax === void 0 && charge.percent === void 0) return charge;
7989
- const { amountIncludesTax: _mode, percent: _percent, ...rest } = charge;
8014
+ const { amountIncludesTax, percent: _percent, ...rest } = charge;
7990
8015
  const amountMinor = charge.totalMinor === void 0 && displayMinor !== void 0 ? displayMinor : chargeOrderModeMinor(charge, pricesIncludeTax);
7991
- return { ...rest, amountMinor, ...charge.totalMinor === void 0 ? { netMinor: amountMinor } : {} };
8016
+ return {
8017
+ ...rest,
8018
+ amountMinor,
8019
+ ...charge.totalMinor === void 0 ? { netMinor: amountMinor } : {},
8020
+ ...amountIncludesTax !== void 0 && amountIncludesTax !== pricesIncludeTax && keep.granularity !== "woocommerce" ? { entered: { amountMinor: charge.amountMinor, amountIncludesTax, ...keep.chargeTaxMode === true ? { sent: true } : {} } } : {}
8021
+ };
7992
8022
  }
7993
8023
  function withSentForm(order, posOrder) {
7994
8024
  const customer = order.customer && { ...order.customer };
8025
+ const keep = { granularity: order.taxRounding?.granularity };
7995
8026
  if (customer && posOrder.customer?.email === void 0) delete customer.email;
7996
8027
  if (customer && posOrder.customer?.id === void 0) delete customer.id;
7997
8028
  return {
@@ -7999,9 +8030,9 @@ function withSentForm(order, posOrder) {
7999
8030
  customer,
8000
8031
  note: posOrder.note ?? order.note,
8001
8032
  lineItems: order.lineItems.map((line, i) => ({ ...line, name: posOrder.lines[i].name })),
8002
- ...order.fees ? { fees: order.fees.map((fee, i) => ({ ...storedCharge(fee, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor), name: posOrder.fees[i].name })) } : {},
8033
+ ...order.fees ? { fees: order.fees.map((fee, i) => ({ ...storedCharge(fee, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor, keep), name: posOrder.fees[i].name })) } : {},
8003
8034
  ...order.shipping ? { shipping: order.shipping.map((charge, i) => ({
8004
- ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor),
8035
+ ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor, keep),
8005
8036
  name: posOrder.shipping[i].name
8006
8037
  })) } : {},
8007
8038
  display: posOrder.display ? {
@@ -8217,8 +8248,9 @@ function finalizeOrder(order, options = {}) {
8217
8248
  taxLines: line.taxLines.map((tax) => ({ ...tax })),
8218
8249
  ...line.priceTaxModeConverted ? { taxInclusive: line.taxInclusive } : {}
8219
8250
  }));
8220
- const fees = order.fees?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
8221
- const shipping = order.shipping?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
8251
+ const keep = { chargeTaxMode: options.capabilities?.chargeTaxMode, granularity: order.taxRounding?.granularity };
8252
+ const fees = order.fees?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor, keep), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
8253
+ const shipping = order.shipping?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor, keep), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
8222
8254
  const payments = order.payments.map((payment) => ({
8223
8255
  id: newId(),
8224
8256
  ...payment.storePaymentId !== void 0 ? { storePaymentId: payment.storePaymentId } : {},
@@ -8371,7 +8403,7 @@ var orderAddressSchema = { type: "object", additionalProperties: false, properti
8371
8403
  phone: { type: "string" }
8372
8404
  } };
8373
8405
  var posOrderSchema = {
8374
- version: 22,
8406
+ version: 23,
8375
8407
  primaryKey: "id",
8376
8408
  type: "object",
8377
8409
  additionalProperties: false,
@@ -8477,6 +8509,11 @@ var posOrderSchema = {
8477
8509
  required: ["id", "productId", "name", "sku", "quantity", "unitPriceMinor", "discountMinor", "netMinor", "taxLines"]
8478
8510
  } },
8479
8511
  fees: { type: "array", items: { type: "object", additionalProperties: false, properties: {
8512
+ entered: { type: "object", additionalProperties: false, properties: {
8513
+ amountMinor: { type: "integer", minimum: 0 },
8514
+ amountIncludesTax: { type: "boolean" },
8515
+ sent: { type: "boolean", enum: [true] }
8516
+ }, required: ["amountMinor", "amountIncludesTax"] },
8480
8517
  storeLineId: { type: "string", minLength: 1, maxLength: 64 },
8481
8518
  id: { type: "string", maxLength: 36 },
8482
8519
  name: { type: "string", minLength: 1, maxLength: 255 },
@@ -8496,6 +8533,11 @@ var posOrderSchema = {
8496
8533
  }, required: ["ratePpm", "taxMicros"] } }
8497
8534
  }, required: ["id", "name", "amountMinor", "taxStatus", "taxLines", "netMinor", "taxMicros"] } },
8498
8535
  shipping: { type: "array", items: { type: "object", additionalProperties: false, properties: {
8536
+ entered: { type: "object", additionalProperties: false, properties: {
8537
+ amountMinor: { type: "integer", minimum: 0 },
8538
+ amountIncludesTax: { type: "boolean" },
8539
+ sent: { type: "boolean", enum: [true] }
8540
+ }, required: ["amountMinor", "amountIncludesTax"] },
8499
8541
  storeLineId: { type: "string", minLength: 1, maxLength: 64 },
8500
8542
  id: { type: "string", maxLength: 36 },
8501
8543
  name: { type: "string", minLength: 1, maxLength: 255 },
@@ -8664,7 +8706,7 @@ function posOrderCollection() {
8664
8706
  };
8665
8707
  return {
8666
8708
  schema: posOrderSchema,
8667
- 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, 22: identity2 }
8709
+ 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, 22: identity2, 23: identity2 }
8668
8710
  };
8669
8711
  }
8670
8712
 
@@ -8888,6 +8930,7 @@ function storeOrderLeft(order) {
8888
8930
  }
8889
8931
 
8890
8932
  // src/pos-order/store-settlement.ts
8933
+ var TILL_SESSION_CLOSED = "till_session_closed";
8891
8934
  function settledOnStore(order) {
8892
8935
  const state = order.storeSettlement?.state;
8893
8936
  if (state === "done") return true;
@@ -8896,31 +8939,54 @@ function settledOnStore(order) {
8896
8939
  return !left || left.recordedMinor === 0;
8897
8940
  }
8898
8941
  function canCancelOnStore(order) {
8942
+ if (order.storeSettlement?.code === TILL_SESSION_CLOSED) return false;
8899
8943
  const left = storeOrderLeft(order);
8900
8944
  if (!left || left.recordedMinor !== 0 || settledOnStore(order)) return false;
8901
8945
  const settlement = order.storeSettlement;
8902
8946
  return settlement === void 0 || settlement.kind === "cancel" || settlement.state === "changed" || settlement.state === "refused";
8903
8947
  }
8904
- function unrecordedLegs(order) {
8948
+ function recordedCount(order) {
8905
8949
  const recorded = order.error?.data?.recorded;
8906
- return order.payments.slice(Number.isSafeInteger(recorded) && recorded > 0 ? recorded : 0);
8950
+ return Number.isSafeInteger(recorded) && recorded > 0 ? recorded : 0;
8951
+ }
8952
+ function recordedLegs(order) {
8953
+ return order.payments.slice(0, recordedCount(order));
8954
+ }
8955
+ function unrecordedLegs(order) {
8956
+ return order.payments.slice(recordedCount(order));
8957
+ }
8958
+ function canReverseOnStore(order) {
8959
+ if (order.storeSettlement?.code === TILL_SESSION_CLOSED) return false;
8960
+ const left = storeOrderLeft(order), stored = order.storeSettlement;
8961
+ if (!left || left.recordedMinor <= 0 || settledOnStore(order)) return false;
8962
+ const legs = recordedLegs(order);
8963
+ if (!legs.length || !legs.every((leg) => leg.amountMinor > 0)) return false;
8964
+ return !stored || stored.kind === "reverse" && ["sending", "changed", "refused"].includes(stored.state) || stored.kind === "pay" && ["changed", "refused"].includes(stored.state) && !stored.payments?.some((payment) => payment.done);
8907
8965
  }
8908
8966
  function canPayRestOnStore(order) {
8967
+ if (order.storeSettlement?.code === TILL_SESSION_CLOSED) return false;
8909
8968
  const left = storeOrderLeft(order);
8910
8969
  if (!left || left.recordedMinor <= 0 || settledOnStore(order)) return false;
8911
8970
  const legs = unrecordedLegs(order);
8912
8971
  if (legs.length === 0 || !legs.every((leg) => leg.amountMinor > 0)) return false;
8913
8972
  const settlement = order.storeSettlement;
8914
8973
  if (settlement?.state === "gone") return false;
8974
+ if (settlement?.kind === "reverse" && settlement.legs?.some((leg) => leg.done)) return false;
8915
8975
  return settlement === void 0 || settlement.kind === "pay" || settlement.state === "changed" || settlement.state === "refused";
8916
8976
  }
8917
8977
 
8918
8978
  // src/pos-order/needs-attention.ts
8919
8979
  var UPDATE_UNSENDABLE = "update_unsendable";
8920
8980
  var UPDATE_UNSENDABLE_MESSAGE = "The store can't accept this change yet. Ask the owner to update the POS plugin, then press Retry.";
8981
+ function roundingBridgeTolerance(order) {
8982
+ return Math.ceil((order.lines.length + (order.fees?.length ?? 0) + (order.shipping?.length ?? 0)) / 2);
8983
+ }
8921
8984
  function needsAttention(orders, options = {}) {
8922
8985
  const replaced = replacedOrderIds(orders);
8923
- return orders.filter((order) => order.syncStatus === "rejected" && !settledOnStore(order) || order.syncStatus === "pending" && order.error?.code === UPDATE_UNSENDABLE || (order.localWarnings?.length ?? 0) > 0 || order.syncStatus === "applied" && knownWarnings(order.warnings).some((warning) => warning.code !== "register_session_unknown") || order.lateSessionId !== void 0 || order.syncStatus === "pending" && options.stuckCommandIds?.includes(order.commandId) === true).filter((order) => !replaced.has(order.id) && !(order.attentionHandledFor !== void 0 && order.attentionHandledFor === order.commandId && storeOrderLeft(order) === void 0)).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
8986
+ return orders.filter((order) => {
8987
+ const tolerance = roundingBridgeTolerance(order);
8988
+ return order.syncStatus === "rejected" && !settledOnStore(order) || order.syncStatus === "pending" && order.error?.code === UPDATE_UNSENDABLE || (order.localWarnings?.length ?? 0) > 0 || order.syncStatus === "applied" && knownWarnings(order.warnings).some((warning) => warning.code !== "register_session_unknown" && !(warning.code === "total_mismatch" && warning.bridgeMinor !== void 0 && Math.abs(warning.bridgeMinor) <= tolerance)) || order.lateSessionId !== void 0 || order.syncStatus === "pending" && options.stuckCommandIds?.includes(order.commandId) === true;
8989
+ }).filter((order) => !replaced.has(order.id) && !(order.attentionHandledFor !== void 0 && order.attentionHandledFor === order.commandId && storeOrderLeft(order) === void 0)).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
8924
8990
  }
8925
8991
 
8926
8992
  // src/pos-order/attention-handled.ts
@@ -8963,7 +9029,7 @@ function refundAmounts(refund) {
8963
9029
  return Object.entries(byMethod).filter(([method, amount]) => method.length > 0 && Number.isSafeInteger(amount) && amount >= 0);
8964
9030
  }
8965
9031
  function paymentLedgerRows(orders) {
8966
- return orders.flatMap((order) => tillPayments(order.payments).map((payment) => ({
9032
+ return orders.flatMap((order) => countedTillPayments(order).map((payment) => ({
8967
9033
  session_id: payment.sessionId ?? order.sessionId,
8968
9034
  kind: payment.method === "cash" ? "cash" : "other",
8969
9035
  method_id: payment.method,
@@ -9050,7 +9116,7 @@ function deriveDrawerTerms(input) {
9050
9116
  function takingsByMethod(orders, sessionId, extra = []) {
9051
9117
  const takings = /* @__PURE__ */ Object.create(null);
9052
9118
  for (const order of [...orders, { payments: extra }]) {
9053
- for (const payment of tillPayments(order.payments)) {
9119
+ for (const payment of countedTillPayments(order)) {
9054
9120
  if ((payment.sessionId ?? order.sessionId) !== sessionId) continue;
9055
9121
  const term = takings[legMethodId(payment)] ??= { amountMinor: 0, count: 0 };
9056
9122
  term.amountMinor += payment.amountMinor;
@@ -9689,11 +9755,12 @@ async function writeClosure({
9689
9755
  const taxRateKey = (code, ratePpm) => `${ratePpm}:${(code ?? "").replace(/[%.[\]\\]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`;
9690
9756
  const taxRates = /* @__PURE__ */ new Map();
9691
9757
  const roundings = /* @__PURE__ */ new Set();
9692
- for (const order of bound) {
9758
+ const transactions = bound.filter((order) => !settledAwayOnStore(order));
9759
+ for (const order of transactions) {
9693
9760
  const recorded = order.taxRounding ?? DEFAULT_TAX_ROUNDING;
9694
9761
  const rounding = recorded.granularity === "custom" ? DEFAULT_TAX_ROUNDING : recorded;
9695
9762
  roundings.add(rounding.granularity === "woocommerce" ? `woocommerce ${rounding.roundAtSubtotal}` : `${rounding.granularity} ${rounding.mode}`);
9696
- const taxedLines = taxedLinesFor(order.lines, [...order.fees ?? [], ...order.shipping ?? []], order.pricesIncludeTax, order.taxRounding);
9763
+ const taxedLines = taxedLinesFor(order.lines, storedCharges([...order.fees ?? [], ...order.shipping ?? []]), order.pricesIncludeTax, order.taxRounding);
9697
9764
  for (const { ratePpm, code, netMinor, amountMinor } of taxLinesByRate(taxedLines, order.taxMinor, void 0, order.taxRounding)) {
9698
9765
  const existing2 = taxRates.get(taxRateKey(code, ratePpm));
9699
9766
  taxRates.set(taxRateKey(code, ratePpm), {
@@ -9706,7 +9773,7 @@ async function writeClosure({
9706
9773
  }
9707
9774
  const unsynced = bound.filter((order) => order.syncStatus === "pending");
9708
9775
  const cashRoundingMinor = sum4(bound.flatMap((order) => {
9709
- const legs = new Map(tillPayments(order.payments).map((payment) => [payment.id, payment]));
9776
+ const legs = new Map(countedTillPayments(order).map((payment) => [payment.id, payment]));
9710
9777
  return (order.cashRoundings ?? []).filter((entry) => {
9711
9778
  const leg = legs.get(entry.paymentId);
9712
9779
  return leg !== void 0 && (leg.sessionId ?? order.sessionId) === session.id;
@@ -9775,7 +9842,7 @@ async function writeClosure({
9775
9842
  created_by: created_by ?? null,
9776
9843
  voided_by: voided_by ?? null
9777
9844
  })),
9778
- transaction_count: bound.length,
9845
+ transaction_count: transactions.length,
9779
9846
  refund_count: countedRefunds.length,
9780
9847
  ...refunds !== void 0 ? {
9781
9848
  refund_ids: countedRefunds.map((refund) => refund.id),
@@ -9891,13 +9958,13 @@ async function reopenRefusedOrder(orderId, deps, options) {
9891
9958
  }
9892
9959
  for (const fee of order.fees ?? []) builder.addFee({
9893
9960
  name: fee.name,
9894
- amountMinor: fee.amountMinor,
9961
+ ...fee.entered ? { amountMinor: fee.entered.amountMinor, amountIncludesTax: fee.entered.amountIncludesTax } : { amountMinor: fee.amountMinor },
9895
9962
  ...fee.taxClass !== void 0 ? { taxClass: fee.taxClass } : {},
9896
9963
  ...fee.taxStatus !== void 0 ? { taxStatus: fee.taxStatus } : {}
9897
9964
  });
9898
9965
  for (const shipping of order.shipping ?? []) builder.addShipping({
9899
9966
  name: shipping.name,
9900
- amountMinor: shipping.amountMinor,
9967
+ ...shipping.entered ? { amountMinor: shipping.entered.amountMinor, amountIncludesTax: shipping.entered.amountIncludesTax } : { amountMinor: shipping.amountMinor },
9901
9968
  ...shipping.taxClass !== void 0 ? { taxClass: shipping.taxClass } : {},
9902
9969
  ...shipping.taxStatus !== void 0 ? { taxStatus: shipping.taxStatus } : {},
9903
9970
  ...shipping.methodId !== void 0 ? { methodId: shipping.methodId } : {}
@@ -14603,12 +14670,71 @@ function createHttpCommandTransport(options) {
14603
14670
  }
14604
14671
 
14605
14672
  // src/outbox/store-settlement.ts
14673
+ var inOpenSession = (order, open) => open !== void 0 && tillPayments(order.payments).every((payment) => (payment.sessionId ?? order.sessionId) === open);
14674
+ function markClosed(data, kind, at2, attemptId) {
14675
+ const stored = data.storeSettlement;
14676
+ if (stored?.kind === kind && stored.state === "sending" && (attemptId === void 0 || stored.attemptId === attemptId)) {
14677
+ data.storeSettlement = { kind, state: "refused", code: TILL_SESSION_CLOSED, attemptId: stored.attemptId, at: at2, ...kind === "reverse" && stored.legs && { legs: stored.legs } };
14678
+ data.updatedAt = at2;
14679
+ }
14680
+ return data;
14681
+ }
14682
+ async function closedAtLanding(deps, kind, orderId, attemptId, outcome, stamp2) {
14683
+ const open = await deps.openSessionId(), order = await deps.orders.findOne(orderId).exec();
14684
+ if (!order || inOpenSession(order, open)) return false;
14685
+ await order.incrementalModify((data) => markClosed(data, kind, stamp2(), attemptId));
14686
+ outboxLogger.warn("The store answered after the till session closed; a manager must settle the order", { orderId, outcome: outcome.kind });
14687
+ return true;
14688
+ }
14689
+ async function reverseOnStore(deps, orderId) {
14690
+ const stamp2 = () => (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
14691
+ let request;
14692
+ const open = deps.openSessionId && await deps.openSessionId();
14693
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
14694
+ request = void 0;
14695
+ if (data._deleted || !canReverseOnStore(data)) return data;
14696
+ if (deps.openSessionId && !inOpenSession(data, open)) return markClosed(data, "reverse", stamp2());
14697
+ const stored = data.storeSettlement?.kind === "reverse" ? data.storeSettlement : void 0;
14698
+ const again = stored?.state === "sending" ? stored : void 0;
14699
+ if (again && !again.legs?.length) return data;
14700
+ const attemptId = again?.attemptId ?? uuidv7();
14701
+ const legs = again?.legs ?? recordedLegs(data).map(({ id: id2 }) => stored?.legs?.find((leg) => leg.paymentId === id2 && leg.done) ?? { paymentId: id2, commandId: uuidv7() });
14702
+ const requestLegs = [];
14703
+ for (const { paymentId, commandId } of legs) {
14704
+ const payment = data.payments.find(({ id: id2 }) => id2 === paymentId);
14705
+ if (!payment) return data;
14706
+ requestLegs.push({ paymentId, commandId, amountMinor: payment.amountMinor });
14707
+ }
14708
+ const at2 = stamp2();
14709
+ data.storeSettlement = { kind: "reverse", state: "sending", attemptId, at: at2, legs };
14710
+ data.updatedAt = at2;
14711
+ request = { storeOrderId: storeOrderLeft(data).orderId, clientOrderId: data.id, attemptId, legs: requestLegs };
14712
+ return data;
14713
+ });
14714
+ if (!request) return { kind: "not_offered" };
14715
+ const sent = request;
14716
+ const { outcome, voided } = await deps.reverse(sent);
14717
+ if (deps.openSessionId && await closedAtLanding(deps, "reverse", orderId, sent.attemptId, outcome, stamp2)) return { kind: "not_offered" };
14718
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
14719
+ const stored = data.storeSettlement;
14720
+ if (stored?.kind !== "reverse" || stored.attemptId !== sent.attemptId || stored.state !== "sending") return data;
14721
+ const legs = (stored.legs ?? []).map((leg) => voided.includes(leg.paymentId) ? { ...leg, done: true } : leg);
14722
+ if (outcome.kind === "retry" && legs.every((leg, index) => leg.done === stored.legs?.[index]?.done)) return data;
14723
+ const at2 = stamp2(), base = { kind: "reverse", attemptId: sent.attemptId, at: at2, legs };
14724
+ data.storeSettlement = outcome.kind === "retry" ? { ...stored, legs } : outcome.kind === "done" ? { ...base, state: "done", storeStatus: outcome.status } : outcome.kind === "changed" ? { ...base, state: "changed", storeStatus: outcome.status, capturedMinor: outcome.capturedMinor } : outcome.kind === "refused" ? { ...base, state: "refused", code: outcome.code, message: outcome.message } : { ...base, state: "gone" };
14725
+ if (outcome.kind !== "retry") data.updatedAt = at2;
14726
+ return data;
14727
+ });
14728
+ return outcome;
14729
+ }
14606
14730
  async function cancelOnStore(deps, orderId) {
14607
14731
  const stamp2 = () => (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
14608
14732
  let request;
14733
+ const open = deps.openSessionId && await deps.openSessionId();
14609
14734
  await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
14610
14735
  request = void 0;
14611
14736
  if (data._deleted || !canCancelOnStore(data)) return data;
14737
+ if (deps.openSessionId && !inOpenSession(data, open)) return markClosed(data, "cancel", stamp2());
14612
14738
  const stored = data.storeSettlement;
14613
14739
  const attemptId = stored?.kind === "cancel" && stored.state === "sending" ? stored.attemptId : uuidv7();
14614
14740
  const at2 = stamp2();
@@ -14620,6 +14746,7 @@ async function cancelOnStore(deps, orderId) {
14620
14746
  if (!request) return { kind: "not_offered" };
14621
14747
  const sent = request;
14622
14748
  const outcome = await deps.cancel(sent);
14749
+ if (deps.openSessionId && await closedAtLanding(deps, "cancel", orderId, sent.attemptId, outcome, stamp2)) return { kind: "not_offered" };
14623
14750
  if (outcome.kind === "retry") {
14624
14751
  outboxLogger.info("Cancelling the store order got no definite answer; it stays sending", { orderId, reason: outcome.reason });
14625
14752
  return outcome;
@@ -14823,13 +14950,14 @@ function useOrderOutbox(options) {
14823
14950
  return opened && opened.storeKey === storeKey ? opened.outbox.discard(orderId) : false;
14824
14951
  },
14825
14952
  async cancelOnStore(orderId) {
14953
+ if (!latest.current.openSessionId) return { kind: "not_offered" };
14826
14954
  const opened = current.current;
14827
14955
  if (!opened || opened.storeKey !== storeKey) return { kind: "not_offered" };
14828
14956
  const settlement = latest.current.storeSettlement?.(opened.storeKey);
14829
14957
  const cancel = settlement?.cancel?.bind(settlement);
14830
14958
  if (!cancel) return { kind: "not_offered" };
14831
14959
  try {
14832
- return await cancelOnStore({ orders: opened.orders, cancel }, orderId);
14960
+ return await cancelOnStore({ orders: opened.orders, cancel, openSessionId: () => latest.current.openSessionId?.() }, orderId);
14833
14961
  } finally {
14834
14962
  try {
14835
14963
  await refreshOutboxState(opened.outbox);
@@ -14854,6 +14982,23 @@ function useOrderOutbox(options) {
14854
14982
  }
14855
14983
  }
14856
14984
  },
14985
+ async reverseOnStore(orderId) {
14986
+ if (!latest.current.openSessionId) return { kind: "not_offered" };
14987
+ const opened = current.current;
14988
+ if (!opened || opened.storeKey !== storeKey) return { kind: "not_offered" };
14989
+ const settlement = latest.current.storeSettlement?.(opened.storeKey);
14990
+ const reverse = settlement?.reverse?.bind(settlement);
14991
+ if (!reverse) return { kind: "not_offered" };
14992
+ try {
14993
+ return await reverseOnStore({ orders: opened.orders, reverse, openSessionId: () => latest.current.openSessionId?.() }, orderId);
14994
+ } finally {
14995
+ try {
14996
+ await refreshOutboxState(opened.outbox);
14997
+ } catch (cause) {
14998
+ outboxLogger.warn("Failed to refresh the outbox state", { cause });
14999
+ }
15000
+ }
15001
+ },
14857
15002
  savesInFlight: savesInFlightCount,
14858
15003
  stuckCommandIds,
14859
15004
  async record(posOrder) {
@@ -15572,7 +15717,7 @@ function joinedLine(line, join) {
15572
15717
  };
15573
15718
  }
15574
15719
  function reportOrderFromPosOrder(order, join, methodTitle2) {
15575
- const taxedLines = taxedLinesFor(order.lines, [...order.fees ?? [], ...order.shipping ?? []], order.pricesIncludeTax, order.taxRounding);
15720
+ const taxedLines = taxedLinesFor(order.lines, storedCharges([...order.fees ?? [], ...order.shipping ?? []]), order.pricesIncludeTax, order.taxRounding);
15576
15721
  const taxes = recordedTaxByRate(order) ?? taxLinesByRate(taxedLines, order.taxMinor, void 0, order.taxRounding);
15577
15722
  const till = tillPayments(order.payments);
15578
15723
  const amountOf = (payments) => payments.reduce((total, payment) => total + payment.amountMinor, 0);
@@ -15774,6 +15919,7 @@ export {
15774
15919
  TENDER_GATE_FAILED,
15775
15920
  TENDER_SALE_CHANGED,
15776
15921
  TILE_FIELDS,
15922
+ TILL_SESSION_CLOSED,
15777
15923
  TaxProvider,
15778
15924
  UI_SCALES,
15779
15925
  UI_THEMES,
@@ -15814,6 +15960,7 @@ export {
15814
15960
  canMoveLeg,
15815
15961
  canOpenDrawer,
15816
15962
  canPayRestOnStore,
15963
+ canReverseOnStore,
15817
15964
  canVoidLeg,
15818
15965
  cancelOnStore,
15819
15966
  capturedMinor,
@@ -16016,6 +16163,7 @@ export {
16016
16163
  reconcileRegisterCommands,
16017
16164
  recordMovement,
16018
16165
  recordRegisterFact,
16166
+ recordedLegs,
16019
16167
  refundDueOf,
16020
16168
  refundNeedsAdminLine,
16021
16169
  refundableLines,
@@ -16049,6 +16197,7 @@ export {
16049
16197
  resolveStoreSettings,
16050
16198
  restoreOrderDraft,
16051
16199
  retailCodeTwin,
16200
+ reverseOnStore,
16052
16201
  roundMicrosToMinor,
16053
16202
  roundedDue,
16054
16203
  roundedPickTarget,
@@ -16074,6 +16223,7 @@ export {
16074
16223
  serialPortIdentity,
16075
16224
  sessionOpenCommand,
16076
16225
  sessionTransitionCommand,
16226
+ settledAwayOnStore,
16077
16227
  settledOnStore,
16078
16228
  shipsToBilling,
16079
16229
  sortProducts,
@@ -16107,6 +16257,7 @@ export {
16107
16257
  tenderVoidCollection,
16108
16258
  tenderVoidSchema,
16109
16259
  tillLegsTheStoreRefuses,
16260
+ tillPayments,
16110
16261
  toCsv,
16111
16262
  toCustomerInput,
16112
16263
  toCustomerPatch,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/pos",
3
- "version": "5.1.0",
3
+ "version": "5.2.0",
4
4
  "type": "module",
5
5
  "description": "Shared POS business logic for Tally UI — tax, orders, payments, discounts, receipts",
6
6
  "main": "./dist/index.js",
@@ -35,20 +35,20 @@
35
35
  "mustache": "^4.2.0"
36
36
  },
37
37
  "peerDependencies": {
38
- "@tallyui/core": "^5.1.0",
38
+ "@tallyui/core": "^5.2.0",
39
39
  "react": ">=18",
40
40
  "rxdb": "~17.5.0",
41
41
  "rxjs": ">=7"
42
42
  },
43
43
  "devDependencies": {
44
- "@tallyui/core": "5.1.0",
44
+ "@tallyui/core": "5.2.0",
45
45
  "@types/react": ">=18",
46
46
  "react": "^19.2.4",
47
47
  "rxdb": "17.5.0",
48
48
  "rxjs": "7.8.2",
49
- "@tallyui/connector-medusa": "5.1.0",
50
- "@tallyui/connector-woocommerce": "5.1.0",
51
- "@tallyui/database": "5.1.0"
49
+ "@tallyui/connector-medusa": "5.2.0",
50
+ "@tallyui/connector-woocommerce": "5.2.0",
51
+ "@tallyui/database": "5.2.0"
52
52
  },
53
53
  "scripts": {
54
54
  "build": "tsup",
package/src/index.ts CHANGED
@@ -154,9 +154,10 @@ export type {
154
154
  export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, REGISTER_CLOSING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_CARD_IN_PROGRESS, SALE_IN_TENDER, SALE_HAS_PAYMENT, SALE_FINISHED, openSales, isPartlyPaid, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED, COUPONS_NEED_CONNECTION, COUPONS_REPRICING, COUPON_CARRIED, COUPON_CARRY_STALE, TENDER_GATE_FAILED, TENDER_SALE_CHANGED, createStorePricedDiscountCodes, cartQuantities, SPLIT_FIXED_DISCOUNT, variantFits, matchVariant, disabledOptions, orderFiltersQuery } from './sale';
155
155
  export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState, StorePricedAccepted, StorePricedCodePricing, StorePricedDiscountCodesOptions, CartQuantityLine, OptionPicks, OrderFilterValue } from './sale';
156
156
 
157
- export { uuidv7, AFTER_CLOSE_PAYMENTS_CHANGED, finalizeOrder, toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, storeOrderLeft, canCancelOnStore, canPayRestOnStore, settledOnStore, unrecordedLegs, markAttentionHandled, moneyDivergence, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
157
+ export { uuidv7, AFTER_CLOSE_PAYMENTS_CHANGED, finalizeOrder, toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, storeOrderLeft, canCancelOnStore, canPayRestOnStore, canReverseOnStore, recordedLegs, settledOnStore, TILL_SESSION_CLOSED, unrecordedLegs, markAttentionHandled, moneyDivergence, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
158
158
  export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './pos-order';
159
159
  export { noteDelivery, type NoteDelivery } from './pos-order';
160
+ export { settledAwayOnStore, tillPayments } from './pos-order';
160
161
  export { extrasNotSent, type ExtrasNotSent } from './pos-order';
161
162
  export { refundDueOf } from './pos-order';
162
163
  export { lockedRefundDueMinor, tillLegsTheStoreRefuses } from './pos-order/refund-due';
@@ -164,7 +165,7 @@ export { ADDRESS_CHANGE_REFUSED, NOTHING_DUE, NOTHING_TO_ROUND_AGAINST, CASH_NOT
164
165
  export { INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION, TAX_ADDRESS_ORDER_CREATE_VERSION, UNTAXED_ADDRESS_ORDER_CREATE_VERSION } from './pos-order/command';
165
166
  export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, PosOrderStoreSettlement, FinalizeOptions, MoneyDivergence } from './pos-order';
166
167
  export type { PosOrderCouponLine } from './pos-order/types';
167
- export { createHttpCommandTransport, createOrderOutbox, isRequeueable, isRequeueableOrder, useOrderOutbox, outboxLogger, cancelOnStore, payRestOnStore, type CancelOnStoreDeps, type PayRestOnStoreDeps } from './outbox';
168
+ export { createHttpCommandTransport, createOrderOutbox, isRequeueable, isRequeueableOrder, useOrderOutbox, outboxLogger, cancelOnStore, payRestOnStore, reverseOnStore, type CancelOnStoreDeps, type PayRestOnStoreDeps } from './outbox';
168
169
  export { needsAdminReasonOf, NEEDS_ADMIN_RETRY_PREFIX, type NeedsAdminAnswer } from './outbox';
169
170
  export { createRegisterOutbox, isRegisterRequeueable, useRegisterOutbox, summarizeOutboxHealth, watchOutboxHealth, useOutboxHealth } from './outbox';
170
171
  export type { RegisterOutboxOptions, RegisterOutbox, UseRegisterOutboxOptions, UseRegisterOutboxResult } from './outbox';
@@ -142,7 +142,7 @@ export interface ChargeLine {
142
142
  amountMinor: number; // integer >= 0, as entered, in the charge's own mode (amountIncludesTax, else the order's; ADR-075)
143
143
  taxClass?: string;
144
144
  taxStatus: 'taxable' | 'none';
145
- /** The cashier's mode for this charge (v2 "Amount includes tax"); absent means the order's. Never stored on a finalized order. */
145
+ /** The cashier's mode for this charge (v2 "Amount includes tax"); absent means the order's. Never stored on a finalized order; a `chargeTaxMode` store keeps it in the stored charge's `entered`. */
146
146
  amountIncludesTax?: boolean;
147
147
  /** A fee's percentage of the cart (v2 Add Fee "%"): the builder sets `amountMinor` to it on every build. Fees only. Never stored on a finalized order. */
148
148
  percent?: number;
@@ -1,7 +1,7 @@
1
1
  export { createHttpCommandTransport } from './http-transport';
2
2
  export type { HttpTransportOptions } from './http-transport';
3
3
  export { createOrderOutbox, isRequeueable, isRequeueableOrder } from './order-outbox';
4
- export { cancelOnStore, payRestOnStore, type CancelOnStoreDeps, type PayRestOnStoreDeps } from './store-settlement';
4
+ export { cancelOnStore, payRestOnStore, reverseOnStore, type CancelOnStoreDeps, type PayRestOnStoreDeps } from './store-settlement';
5
5
  export type { OrderOutboxOptions, OrderOutbox } from './order-outbox';
6
6
  export { createRegisterOutbox, isRegisterRequeueable } from './register-outbox';
7
7
  export type { RegisterOutboxOptions, RegisterOutbox } from './register-outbox';