@tallyui/pos 5.0.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
@@ -562,10 +562,24 @@ function sendableMeta(meta) {
562
562
  }).slice(0, ORDER_META_MAX);
563
563
  }
564
564
  var editedSku = (line) => !line.custom && line.catalogueSku !== void 0 && line.sku !== "" && line.sku !== line.catalogueSku;
565
- function netDiscountMinor(line, pricesIncludeTax, woocommerce) {
566
- if (!(line.taxInclusive ?? pricesIncludeTax) || line.discountMinor === 0) return line.discountMinor;
567
- const ratePpm = line.taxLines.reduce((sum4, tax) => sum4 + tax.ratePpm, 0);
565
+ function netDiscountMinor(line, order) {
566
+ if (!(line.taxInclusive ?? order.pricesIncludeTax) || line.discountMinor === 0) return line.discountMinor;
567
+ const woocommerce = order.taxRounding?.granularity === "woocommerce", stored = line.taxLines;
568
568
  const afterDiscount = line.unitPriceMinor * line.quantity - line.discountMinor;
569
+ if (woocommerce && (order.coupons?.length || stored.some((tax) => tax.compound))) {
570
+ const rates = stored.map((tax, i) => ({
571
+ id: i,
572
+ code: tax.code ?? "",
573
+ label: "",
574
+ rate: (tax.ratePpm / 1e4).toFixed(4),
575
+ priority: i,
576
+ compound: tax.compound ?? false,
577
+ shipping: true
578
+ }));
579
+ const net = (minor2) => BigInt(woocommerceLine(minor2, rates, true, order.currency, false).netMicros);
580
+ return roundMicrosToMinor(net(line.unitPriceMinor * line.quantity) - net(afterDiscount));
581
+ }
582
+ const ratePpm = line.taxLines.reduce((sum4, tax) => sum4 + tax.ratePpm, 0);
569
583
  const taxAfter = !woocommerce && line.netMinor < afterDiscount ? taxMicros(afterDiscount, ratePpm, true) : line.taxLines.reduce((sum4, tax) => sum4 + BigInt(tax.taxMicros), 0n);
570
584
  const taxBefore = taxMicros(line.unitPriceMinor * line.quantity, ratePpm, true);
571
585
  return roundMicrosToMinor(BigInt(line.discountMinor) * MICROS_PER_MINOR - taxBefore + taxAfter);
@@ -582,6 +596,10 @@ function wireNote(note) {
582
596
  const newline = note.indexOf("\n");
583
597
  return newline === -1 ? void 0 : note.slice(newline + 1) || void 0;
584
598
  }
599
+ function wireChargeMinor(order, charge, rows) {
600
+ if (order.taxRounding?.granularity !== "woocommerce") return charge.amountMinor;
601
+ return rows?.find(({ id: id2 }) => id2 === charge.id)?.amountMinor ?? charge.amountMinor;
602
+ }
585
603
  function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
586
604
  if (order.storeOrderId !== void 0) throw new Error(`Order ${order.id} reopened store order ${order.storeOrderId}: it is sent as order.update, never order.create (ADR-090)`);
587
605
  return createEnvelope(order, deviceId, attempt2, options);
@@ -612,7 +630,7 @@ function createEnvelope(order, deviceId, attempt2, options, floor) {
612
630
  const withTaxAddress = version === 8 || version >= 9 && taxAddress !== void 0;
613
631
  const withAddresses = withTaxAddress || version >= UNTAXED_ADDRESS_ORDER_CREATE_VERSION;
614
632
  const taxIds = version >= INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION && sentTaxIds.length ? { taxIds: sentTaxIds } : void 0;
615
- const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order.pricesIncludeTax, order.taxRounding?.granularity === "woocommerce") : line.discountMinor);
633
+ const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order) : line.discountMinor);
616
634
  for (const coupon of carried) {
617
635
  if (!coupon.lines) throw new Error(`Order ${order.id}: a carried coupon has no line shares`);
618
636
  for (const [i, line] of order.lines.entries()) lineDiscounts[i] += coupon.lines.find(({ lineId }) => lineId === line.id)?.discountMinor ?? 0;
@@ -651,25 +669,33 @@ function createEnvelope(order, deviceId, attempt2, options, floor) {
651
669
  ...base === 6 && line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {},
652
670
  ...base === 6 && line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}
653
671
  })),
654
- ...base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
655
- clientFeeId: fee.id,
656
- name: fee.name,
657
- amountMinor: fee.amountMinor,
658
- taxStatus: fee.taxStatus,
659
- ...fee.taxClass !== void 0 ? { taxClass: fee.taxClass } : {},
660
- // #1131: WooCommerce totals a fee line's tax per rate, as its own order totals do.
661
- taxMinor: order.taxRounding?.granularity === "woocommerce" ? woocommerceChargeTaxMinor(fee, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax) : roundMicrosToMinor(BigInt(fee.taxMicros))
662
- })) } : {},
663
- ...base >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
664
- clientShippingId: charge.id,
665
- name: charge.name,
666
- ...charge.methodId !== void 0 ? { methodId: charge.methodId } : {},
667
- amountMinor: charge.amountMinor,
668
- taxStatus: charge.taxStatus,
669
- ...charge.taxClass !== void 0 ? { taxClass: charge.taxClass } : {},
670
- // #1120: WooCommerce totals a shipping line's tax per rate, as its own order totals do.
671
- taxMinor: order.taxRounding?.granularity === "woocommerce" ? woocommerceChargeTaxMinor(charge, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax) : roundMicrosToMinor(BigInt(charge.taxMicros))
672
- })) } : {},
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
+ }) } : {},
673
699
  ...base === 6 && redeemable.length ? { coupons: redeemable.map(({ code, couponId, discountMinor: discountMinor2, discountTaxMinor, lines }) => ({
674
700
  code,
675
701
  couponId,
@@ -896,6 +922,13 @@ function taxDerivation(settings, taxLocation) {
896
922
  }
897
923
 
898
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
+ }
899
932
  function taxedLinesFor(lines, charges, pricesIncludeTax, rounding) {
900
933
  return [
901
934
  ...lines.map((line) => ({ ...line, taxInclusive: rounding?.granularity === "woocommerce" && line.netMicros !== void 0 ? pricesIncludeTax : line.taxInclusive ?? pricesIncludeTax })),
@@ -2166,6 +2199,16 @@ import { map as map3 } from "rxjs";
2166
2199
  function tillPayments(payments) {
2167
2200
  return payments.filter((payment) => payment.storePaymentId === void 0);
2168
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
+ }
2169
2212
 
2170
2213
  // src/order/taken-at.ts
2171
2214
  function isTakenAt(value) {
@@ -2674,7 +2717,7 @@ function receiptRounding(order) {
2674
2717
  return amountMinor !== 0 ? { rounding: { name: "Rounding", amountMinor } } : {};
2675
2718
  }
2676
2719
  function buildReceiptData(order, config) {
2677
- 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);
2678
2721
  const taxLines = taxLinesByRate(taxedLines, order.taxMinor, config.taxLabels, order.taxRounding).map(
2679
2722
  ({ label: label2, code, ratePpm, amountMinor }) => ({ label: label2, code, ratePpm, amountMinor })
2680
2723
  );
@@ -2846,7 +2889,7 @@ function buildReceiptDataFromPosOrder(order, config) {
2846
2889
  displayDiscounts
2847
2890
  };
2848
2891
  });
2849
- 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);
2850
2893
  const recorded = recordedTaxByRate(order);
2851
2894
  const taxLines = recorded ? recorded.map((row) => ({
2852
2895
  label: config.taxLabels?.[row.ratePpm] ?? row.label ?? `Tax ${row.ratePpm / 1e4}%`,
@@ -7966,14 +8009,20 @@ var AFTER_CLOSE_PAYMENTS_CHANGED = "This sale was counted in a closed register.
7966
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);
7967
8010
  var sameCharges = (a = [], b = []) => a.length === b.length && a.every((charge, i) => charge.totalMinor === b[i].totalMinor && sameTaxes(charge, b[i]));
7968
8011
  var MESSAGE_NAME_MAX = 61;
7969
- function storedCharge(charge, pricesIncludeTax, displayMinor) {
8012
+ function storedCharge(charge, pricesIncludeTax, displayMinor, keep) {
7970
8013
  if (charge.amountIncludesTax === void 0 && charge.percent === void 0) return charge;
7971
- const { amountIncludesTax: _mode, percent: _percent, ...rest } = charge;
8014
+ const { amountIncludesTax, percent: _percent, ...rest } = charge;
7972
8015
  const amountMinor = charge.totalMinor === void 0 && displayMinor !== void 0 ? displayMinor : chargeOrderModeMinor(charge, pricesIncludeTax);
7973
- 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
+ };
7974
8022
  }
7975
8023
  function withSentForm(order, posOrder) {
7976
8024
  const customer = order.customer && { ...order.customer };
8025
+ const keep = { granularity: order.taxRounding?.granularity };
7977
8026
  if (customer && posOrder.customer?.email === void 0) delete customer.email;
7978
8027
  if (customer && posOrder.customer?.id === void 0) delete customer.id;
7979
8028
  return {
@@ -7981,9 +8030,9 @@ function withSentForm(order, posOrder) {
7981
8030
  customer,
7982
8031
  note: posOrder.note ?? order.note,
7983
8032
  lineItems: order.lineItems.map((line, i) => ({ ...line, name: posOrder.lines[i].name })),
7984
- ...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 })) } : {},
7985
8034
  ...order.shipping ? { shipping: order.shipping.map((charge, i) => ({
7986
- ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor),
8035
+ ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor, keep),
7987
8036
  name: posOrder.shipping[i].name
7988
8037
  })) } : {},
7989
8038
  display: posOrder.display ? {
@@ -8199,8 +8248,9 @@ function finalizeOrder(order, options = {}) {
8199
8248
  taxLines: line.taxLines.map((tax) => ({ ...tax })),
8200
8249
  ...line.priceTaxModeConverted ? { taxInclusive: line.taxInclusive } : {}
8201
8250
  }));
8202
- const fees = order.fees?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
8203
- 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 })) }));
8204
8254
  const payments = order.payments.map((payment) => ({
8205
8255
  id: newId(),
8206
8256
  ...payment.storePaymentId !== void 0 ? { storePaymentId: payment.storePaymentId } : {},
@@ -8353,7 +8403,7 @@ var orderAddressSchema = { type: "object", additionalProperties: false, properti
8353
8403
  phone: { type: "string" }
8354
8404
  } };
8355
8405
  var posOrderSchema = {
8356
- version: 21,
8406
+ version: 23,
8357
8407
  primaryKey: "id",
8358
8408
  type: "object",
8359
8409
  additionalProperties: false,
@@ -8367,6 +8417,34 @@ var posOrderSchema = {
8367
8417
  updatedAt: { type: "string" },
8368
8418
  reopenedAt: { type: "string", maxLength: 40 },
8369
8419
  attentionHandledFor: { type: "string", maxLength: 36 },
8420
+ storeSettlement: { type: "object", additionalProperties: false, properties: {
8421
+ kind: { type: "string", enum: ["cancel", "pay", "reverse"] },
8422
+ state: { type: "string", enum: ["sending", "done", "changed", "refused", "gone"] },
8423
+ attemptId: { type: "string", maxLength: 36 },
8424
+ at: { type: "string", maxLength: 40 },
8425
+ storeStatus: { type: "string" },
8426
+ capturedMinor: { type: "integer" },
8427
+ code: { type: "string" },
8428
+ message: { type: "string" },
8429
+ payments: { type: "array", items: { type: "object", additionalProperties: false, properties: {
8430
+ id: { type: "string", maxLength: 36 },
8431
+ method: { type: "string" },
8432
+ amountMinor: { type: "integer" },
8433
+ tenderedMinor: { type: "integer" },
8434
+ done: { type: "boolean" }
8435
+ }, required: ["id", "method", "amountMinor"] } },
8436
+ closeId: { type: "string", maxLength: 36 },
8437
+ legs: { type: "array", items: {
8438
+ type: "object",
8439
+ additionalProperties: false,
8440
+ properties: {
8441
+ paymentId: { type: "string", maxLength: 36 },
8442
+ commandId: { type: "string", maxLength: 36 },
8443
+ done: { type: "boolean" }
8444
+ },
8445
+ required: ["paymentId", "commandId"]
8446
+ } }
8447
+ }, required: ["kind", "state", "attemptId", "at"] },
8370
8448
  currency: { type: "string" },
8371
8449
  pricesIncludeTax: { type: "boolean" },
8372
8450
  subtotalMinor: { type: "integer" },
@@ -8431,6 +8509,11 @@ var posOrderSchema = {
8431
8509
  required: ["id", "productId", "name", "sku", "quantity", "unitPriceMinor", "discountMinor", "netMinor", "taxLines"]
8432
8510
  } },
8433
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"] },
8434
8517
  storeLineId: { type: "string", minLength: 1, maxLength: 64 },
8435
8518
  id: { type: "string", maxLength: 36 },
8436
8519
  name: { type: "string", minLength: 1, maxLength: 255 },
@@ -8450,6 +8533,11 @@ var posOrderSchema = {
8450
8533
  }, required: ["ratePpm", "taxMicros"] } }
8451
8534
  }, required: ["id", "name", "amountMinor", "taxStatus", "taxLines", "netMinor", "taxMicros"] } },
8452
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"] },
8453
8541
  storeLineId: { type: "string", minLength: 1, maxLength: 64 },
8454
8542
  id: { type: "string", maxLength: 36 },
8455
8543
  name: { type: "string", minLength: 1, maxLength: 255 },
@@ -8618,7 +8706,7 @@ function posOrderCollection() {
8618
8706
  };
8619
8707
  return {
8620
8708
  schema: posOrderSchema,
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 }
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 }
8622
8710
  };
8623
8711
  }
8624
8712
 
@@ -8828,12 +8916,77 @@ function replacedOrderIds(orders) {
8828
8916
  return new Set(orders.filter((order) => order.syncStatus === "rejected" && predecessors.has(order.id)).map((order) => order.id));
8829
8917
  }
8830
8918
 
8919
+ // src/pos-order/store-order-left.ts
8920
+ function storeOrderLeft(order) {
8921
+ const data = order.error?.data;
8922
+ if (order.syncStatus !== "rejected" || order.storeOrderId !== void 0 || typeof data?.orderId !== "string" || !data.orderId) return void 0;
8923
+ const { orderId, displayId, recorded } = data;
8924
+ const count = Number.isSafeInteger(recorded) && recorded > 0 ? recorded : 0;
8925
+ return {
8926
+ orderId,
8927
+ reference: typeof displayId === "string" && displayId ? displayId : orderId,
8928
+ recordedMinor: order.payments.slice(0, count).reduce((sum4, payment) => sum4 + payment.amountMinor, 0)
8929
+ };
8930
+ }
8931
+
8932
+ // src/pos-order/store-settlement.ts
8933
+ var TILL_SESSION_CLOSED = "till_session_closed";
8934
+ function settledOnStore(order) {
8935
+ const state = order.storeSettlement?.state;
8936
+ if (state === "done") return true;
8937
+ if (state !== "gone") return false;
8938
+ const left = "syncStatus" in order ? storeOrderLeft(order) : void 0;
8939
+ return !left || left.recordedMinor === 0;
8940
+ }
8941
+ function canCancelOnStore(order) {
8942
+ if (order.storeSettlement?.code === TILL_SESSION_CLOSED) return false;
8943
+ const left = storeOrderLeft(order);
8944
+ if (!left || left.recordedMinor !== 0 || settledOnStore(order)) return false;
8945
+ const settlement = order.storeSettlement;
8946
+ return settlement === void 0 || settlement.kind === "cancel" || settlement.state === "changed" || settlement.state === "refused";
8947
+ }
8948
+ function recordedCount(order) {
8949
+ const recorded = order.error?.data?.recorded;
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);
8965
+ }
8966
+ function canPayRestOnStore(order) {
8967
+ if (order.storeSettlement?.code === TILL_SESSION_CLOSED) return false;
8968
+ const left = storeOrderLeft(order);
8969
+ if (!left || left.recordedMinor <= 0 || settledOnStore(order)) return false;
8970
+ const legs = unrecordedLegs(order);
8971
+ if (legs.length === 0 || !legs.every((leg) => leg.amountMinor > 0)) return false;
8972
+ const settlement = order.storeSettlement;
8973
+ if (settlement?.state === "gone") return false;
8974
+ if (settlement?.kind === "reverse" && settlement.legs?.some((leg) => leg.done)) return false;
8975
+ return settlement === void 0 || settlement.kind === "pay" || settlement.state === "changed" || settlement.state === "refused";
8976
+ }
8977
+
8831
8978
  // src/pos-order/needs-attention.ts
8832
8979
  var UPDATE_UNSENDABLE = "update_unsendable";
8833
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
+ }
8834
8984
  function needsAttention(orders, options = {}) {
8835
8985
  const replaced = replacedOrderIds(orders);
8836
- return orders.filter((order) => order.syncStatus === "rejected" || 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)).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));
8837
8990
  }
8838
8991
 
8839
8992
  // src/pos-order/attention-handled.ts
@@ -8876,7 +9029,7 @@ function refundAmounts(refund) {
8876
9029
  return Object.entries(byMethod).filter(([method, amount]) => method.length > 0 && Number.isSafeInteger(amount) && amount >= 0);
8877
9030
  }
8878
9031
  function paymentLedgerRows(orders) {
8879
- return orders.flatMap((order) => tillPayments(order.payments).map((payment) => ({
9032
+ return orders.flatMap((order) => countedTillPayments(order).map((payment) => ({
8880
9033
  session_id: payment.sessionId ?? order.sessionId,
8881
9034
  kind: payment.method === "cash" ? "cash" : "other",
8882
9035
  method_id: payment.method,
@@ -8963,7 +9116,7 @@ function deriveDrawerTerms(input) {
8963
9116
  function takingsByMethod(orders, sessionId, extra = []) {
8964
9117
  const takings = /* @__PURE__ */ Object.create(null);
8965
9118
  for (const order of [...orders, { payments: extra }]) {
8966
- for (const payment of tillPayments(order.payments)) {
9119
+ for (const payment of countedTillPayments(order)) {
8967
9120
  if ((payment.sessionId ?? order.sessionId) !== sessionId) continue;
8968
9121
  const term = takings[legMethodId(payment)] ??= { amountMinor: 0, count: 0 };
8969
9122
  term.amountMinor += payment.amountMinor;
@@ -9602,11 +9755,12 @@ async function writeClosure({
9602
9755
  const taxRateKey = (code, ratePpm) => `${ratePpm}:${(code ?? "").replace(/[%.[\]\\]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`;
9603
9756
  const taxRates = /* @__PURE__ */ new Map();
9604
9757
  const roundings = /* @__PURE__ */ new Set();
9605
- for (const order of bound) {
9758
+ const transactions = bound.filter((order) => !settledAwayOnStore(order));
9759
+ for (const order of transactions) {
9606
9760
  const recorded = order.taxRounding ?? DEFAULT_TAX_ROUNDING;
9607
9761
  const rounding = recorded.granularity === "custom" ? DEFAULT_TAX_ROUNDING : recorded;
9608
9762
  roundings.add(rounding.granularity === "woocommerce" ? `woocommerce ${rounding.roundAtSubtotal}` : `${rounding.granularity} ${rounding.mode}`);
9609
- 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);
9610
9764
  for (const { ratePpm, code, netMinor, amountMinor } of taxLinesByRate(taxedLines, order.taxMinor, void 0, order.taxRounding)) {
9611
9765
  const existing2 = taxRates.get(taxRateKey(code, ratePpm));
9612
9766
  taxRates.set(taxRateKey(code, ratePpm), {
@@ -9619,7 +9773,7 @@ async function writeClosure({
9619
9773
  }
9620
9774
  const unsynced = bound.filter((order) => order.syncStatus === "pending");
9621
9775
  const cashRoundingMinor = sum4(bound.flatMap((order) => {
9622
- const legs = new Map(tillPayments(order.payments).map((payment) => [payment.id, payment]));
9776
+ const legs = new Map(countedTillPayments(order).map((payment) => [payment.id, payment]));
9623
9777
  return (order.cashRoundings ?? []).filter((entry) => {
9624
9778
  const leg = legs.get(entry.paymentId);
9625
9779
  return leg !== void 0 && (leg.sessionId ?? order.sessionId) === session.id;
@@ -9688,7 +9842,7 @@ async function writeClosure({
9688
9842
  created_by: created_by ?? null,
9689
9843
  voided_by: voided_by ?? null
9690
9844
  })),
9691
- transaction_count: bound.length,
9845
+ transaction_count: transactions.length,
9692
9846
  refund_count: countedRefunds.length,
9693
9847
  ...refunds !== void 0 ? {
9694
9848
  refund_ids: countedRefunds.map((refund) => refund.id),
@@ -9804,13 +9958,13 @@ async function reopenRefusedOrder(orderId, deps, options) {
9804
9958
  }
9805
9959
  for (const fee of order.fees ?? []) builder.addFee({
9806
9960
  name: fee.name,
9807
- amountMinor: fee.amountMinor,
9961
+ ...fee.entered ? { amountMinor: fee.entered.amountMinor, amountIncludesTax: fee.entered.amountIncludesTax } : { amountMinor: fee.amountMinor },
9808
9962
  ...fee.taxClass !== void 0 ? { taxClass: fee.taxClass } : {},
9809
9963
  ...fee.taxStatus !== void 0 ? { taxStatus: fee.taxStatus } : {}
9810
9964
  });
9811
9965
  for (const shipping of order.shipping ?? []) builder.addShipping({
9812
9966
  name: shipping.name,
9813
- amountMinor: shipping.amountMinor,
9967
+ ...shipping.entered ? { amountMinor: shipping.entered.amountMinor, amountIncludesTax: shipping.entered.amountIncludesTax } : { amountMinor: shipping.amountMinor },
9814
9968
  ...shipping.taxClass !== void 0 ? { taxClass: shipping.taxClass } : {},
9815
9969
  ...shipping.taxStatus !== void 0 ? { taxStatus: shipping.taxStatus } : {},
9816
9970
  ...shipping.methodId !== void 0 ? { methodId: shipping.methodId } : {}
@@ -10168,14 +10322,17 @@ function roundedRemainder(balanceMinor, entriesMinor, rounding) {
10168
10322
  const unrounded = balanceMinor - entriesMinor;
10169
10323
  return unrounded <= 0 ? 0 : roundToIncrement(unrounded, rounding.incrementMinor, rounding.mode);
10170
10324
  }
10171
- function roundedPickTarget(targetMinor, rounding) {
10172
- return rounding ? roundToIncrement(targetMinor, rounding.incrementMinor, rounding.mode) : targetMinor;
10325
+ function roundedPickTarget(targetMinor, rounding, entriesMinor = 0) {
10326
+ if (!rounding) return targetMinor;
10327
+ const unrounded = targetMinor - entriesMinor;
10328
+ return unrounded <= 0 ? 0 : roundToIncrement(unrounded, rounding.incrementMinor, rounding.mode);
10173
10329
  }
10174
10330
  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);
10331
+ return (order.cashRoundings ?? []).reduce((sum4, entry) => sum4 + entry.minor, 0);
10332
+ }
10333
+ function writeOffLeg(order) {
10334
+ const counted2 = order.payments.filter(countsTowardPaid);
10335
+ return counted2.filter((leg) => leg.method === "cash").at(-1) ?? counted2.at(-1);
10179
10336
  }
10180
10337
  function cashVoidRefusal(order, paymentId) {
10181
10338
  const carries = (id2) => (order.cashRoundings ?? []).some((entry) => entry.paymentId === id2 && entry.minor !== 0);
@@ -11134,6 +11291,7 @@ function isRequeueable(code) {
11134
11291
  return !NOT_REQUEUEABLE.has(code ?? "");
11135
11292
  }
11136
11293
  function isRequeueableOrder(order) {
11294
+ if (order.storeSettlement !== void 0) return false;
11137
11295
  return order.syncStatus === "pending" ? order.error?.code === UPDATE_UNSENDABLE : order.syncStatus === "rejected" && isRequeueable(order.error?.code) && !(order.storeOrderId !== void 0 && ["reopen_required", "revision_conflict"].includes(order.error?.code ?? ""));
11138
11296
  }
11139
11297
  var REFUSAL_LOG_MESSAGE_MAX = 200;
@@ -11237,7 +11395,7 @@ function createOrderOutbox(options) {
11237
11395
  const refused = await readFresh(collection, { selector: { syncStatus: "rejected" } });
11238
11396
  const successors = refused.length ? await readFresh(collection, { selector: { saleId: { $in: refused.map((order) => order.id) } } }) : [];
11239
11397
  const replaced = replacedOrderIds([...refused, ...successors]);
11240
- const rejected = refused.filter((order) => !replaced.has(order.id)).length;
11398
+ const rejected = refused.filter((order) => !replaced.has(order.id) && !settledOnStore(order)).length;
11241
11399
  state$.next({ ...state$.value, ...patch, pending, rejected, stuck: stuckState() });
11242
11400
  }
11243
11401
  function isolate(id2, reason, retryAfterMs = 0) {
@@ -11636,7 +11794,7 @@ function createOrderOutbox(options) {
11636
11794
  });
11637
11795
  let commandId;
11638
11796
  await (await collection.findOne(orderId).exec())?.incrementalModify((data) => {
11639
- commandId = data.syncStatus === "rejected" ? data.commandId : void 0;
11797
+ commandId = data.syncStatus === "rejected" && storeOrderLeft(data) === void 0 ? data.commandId : void 0;
11640
11798
  if (commandId === void 0) return data;
11641
11799
  data._deleted = true;
11642
11800
  return data;
@@ -13625,7 +13783,7 @@ function useSale(settings, opts) {
13625
13783
  });
13626
13784
  },
13627
13785
  setTender,
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). */
13786
+ /** 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 target less the live entries on a cashRounding store, and one that reaches the whole-settle due is taken as that settle (ADR-094 item 7). */
13629
13787
  addTender(input) {
13630
13788
  const { rounding, ...tender } = input;
13631
13789
  if (stageNow.current.kind === "receipt") {
@@ -13651,12 +13809,21 @@ function useSale(settings, opts) {
13651
13809
  const unpaid = unpaidUnitsByLine(lineItems.map(({ id: id2, quantity }) => ({ id: id2, quantity, totalMinor: 0 })), heldUnitsByLine(payments));
13652
13810
  if (Object.entries(tender.units).some(([id2, units]) => !id2 || !Number.isInteger(units) || units <= 0 || !Object.hasOwn(unpaid, id2) || units > unpaid[id2])) return null;
13653
13811
  }
13654
- const pickMinor = pickRule && tender.tenderedMinor !== void 0 ? roundedPickTarget(tender.amountMinor, pickRule) : tender.amountMinor;
13812
+ const pickMinor = pickRule && tender.tenderedMinor !== void 0 ? roundedPickTarget(tender.amountMinor, pickRule, remainderEntriesMinor(builderNow.current.getSnapshot())) : tender.amountMinor;
13655
13813
  if (tender.tenderedMinor !== void 0 && pickMinor === 0) return null;
13656
13814
  if (tender.tenderedMinor !== void 0 && (tender.method !== "cash" || !tender.units || !Object.keys(tender.units).length || !Number.isInteger(tender.tenderedMinor) || tender.tenderedMinor < pickMinor)) return null;
13657
13815
  if (tender.tenderedMinor !== void 0) {
13658
13816
  const snapshot = builderNow.current.getSnapshot();
13659
13817
  if (tender.amountMinor > snapshot.balanceDueMinor - inMotionMinor(snapshot.payments)) return null;
13818
+ const due = snapshot.balanceDueMinor;
13819
+ if (pickRule && pickMinor === roundedRemainder(due, remainderEntriesMinor(snapshot), pickRule)) {
13820
+ if ((snapshot.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX + 1 && pickMinor !== due) {
13821
+ setError(CASH_SETTLE_LIMIT);
13822
+ return null;
13823
+ }
13824
+ clearStaleError();
13825
+ return addOne({ ...tender, amountMinor: pickMinor, changeMinor: tender.tenderedMinor - pickMinor }, true, pickMinor !== due ? { minor: pickMinor - due } : void 0);
13826
+ }
13660
13827
  if (pickMinor !== tender.amountMinor && (snapshot.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX) {
13661
13828
  setError(CASH_PICK_LIMIT);
13662
13829
  return null;
@@ -13683,7 +13850,7 @@ function useSale(settings, opts) {
13683
13850
  const entries2 = remainderEntriesMinor(snapshot);
13684
13851
  const dueMinor = rule ? roundedRemainder(due, entries2, rule) : due;
13685
13852
  if (rule && settlesAtRoundedDue({ amountMinor: Math.min(tender.amountMinor, due), tenderedMinor: tender.amountMinor, balanceMinor: due, dueMinor })) {
13686
- const against = snapshot.payments.filter(countsTowardPaid).at(-1);
13853
+ const against = writeOffLeg(snapshot);
13687
13854
  const roundings = snapshot.cashRoundings ?? [];
13688
13855
  if (roundings.length >= CASH_PICK_ENTRIES_MAX + 1 && (dueMinor > 0 ? dueMinor !== due : against !== void 0 && !roundings.some((entry) => entry.paymentId === against.id))) {
13689
13856
  setError(CASH_SETTLE_LIMIT);
@@ -14502,6 +14669,157 @@ function createHttpCommandTransport(options) {
14502
14669
  };
14503
14670
  }
14504
14671
 
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
+ }
14730
+ async function cancelOnStore(deps, orderId) {
14731
+ const stamp2 = () => (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
14732
+ let request;
14733
+ const open = deps.openSessionId && await deps.openSessionId();
14734
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
14735
+ request = void 0;
14736
+ if (data._deleted || !canCancelOnStore(data)) return data;
14737
+ if (deps.openSessionId && !inOpenSession(data, open)) return markClosed(data, "cancel", stamp2());
14738
+ const stored = data.storeSettlement;
14739
+ const attemptId = stored?.kind === "cancel" && stored.state === "sending" ? stored.attemptId : uuidv7();
14740
+ const at2 = stamp2();
14741
+ data.storeSettlement = { kind: "cancel", state: "sending", attemptId, at: at2 };
14742
+ data.updatedAt = at2;
14743
+ request = { storeOrderId: storeOrderLeft(data).orderId, clientOrderId: data.id, attemptId };
14744
+ return data;
14745
+ });
14746
+ if (!request) return { kind: "not_offered" };
14747
+ const sent = request;
14748
+ const outcome = await deps.cancel(sent);
14749
+ if (deps.openSessionId && await closedAtLanding(deps, "cancel", orderId, sent.attemptId, outcome, stamp2)) return { kind: "not_offered" };
14750
+ if (outcome.kind === "retry") {
14751
+ outboxLogger.info("Cancelling the store order got no definite answer; it stays sending", { orderId, reason: outcome.reason });
14752
+ return outcome;
14753
+ }
14754
+ if (outcome.kind === "refused") outboxLogger.warn("The store refused to cancel the order", { orderId, code: outcome.code, message: outcome.message });
14755
+ if (outcome.kind === "changed") {
14756
+ outboxLogger.warn("The store order changed; nothing was cancelled", { orderId, status: outcome.status, capturedMinor: outcome.capturedMinor });
14757
+ }
14758
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
14759
+ const stored = data.storeSettlement;
14760
+ if (stored?.attemptId !== sent.attemptId || stored.state !== "sending") return data;
14761
+ const at2 = stamp2();
14762
+ const base = { kind: "cancel", attemptId: sent.attemptId, at: at2 };
14763
+ const settled = 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" };
14764
+ data.storeSettlement = settled;
14765
+ data.updatedAt = at2;
14766
+ return data;
14767
+ });
14768
+ return outcome;
14769
+ }
14770
+ async function payRestOnStore(deps, orderId) {
14771
+ const stamp2 = () => (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
14772
+ let request;
14773
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
14774
+ request = void 0;
14775
+ if (data._deleted || !canPayRestOnStore(data)) return data;
14776
+ const stored = data.storeSettlement;
14777
+ const legs = unrecordedLegs(data);
14778
+ const again = stored?.kind === "pay" && stored.payments?.length === legs.length ? stored : void 0;
14779
+ const attemptId = again?.state === "sending" ? again.attemptId : uuidv7();
14780
+ const payments = again?.payments ?? legs.map((leg) => ({
14781
+ id: uuidv7(),
14782
+ method: leg.method,
14783
+ amountMinor: leg.amountMinor,
14784
+ ...leg.method === "cash" && leg.tenderedMinor !== void 0 ? { tenderedMinor: leg.tenderedMinor } : {}
14785
+ }));
14786
+ const at2 = stamp2();
14787
+ data.storeSettlement = { kind: "pay", state: "sending", attemptId, at: at2, payments };
14788
+ data.updatedAt = at2;
14789
+ request = {
14790
+ storeOrderId: storeOrderLeft(data).orderId,
14791
+ clientOrderId: data.id,
14792
+ attemptId,
14793
+ currency: data.currency,
14794
+ payments: payments.map(({ done: _done, ...payment }) => payment)
14795
+ };
14796
+ return data;
14797
+ });
14798
+ if (!request) return { kind: "not_offered" };
14799
+ const sent = request;
14800
+ const { outcome, recorded } = await deps.pay(sent);
14801
+ if (outcome.kind === "retry") {
14802
+ outboxLogger.info("Recording the rest on the store got no definite answer; it stays sending", { orderId, reason: outcome.reason, recorded: recorded.length });
14803
+ }
14804
+ if (outcome.kind === "refused") outboxLogger.warn("The store refused to record the rest of the order", { orderId, code: outcome.code, message: outcome.message });
14805
+ if (outcome.kind === "changed") {
14806
+ outboxLogger.warn("The store order changed; nothing more was recorded", { orderId, status: outcome.status, capturedMinor: outcome.capturedMinor });
14807
+ }
14808
+ const done = new Set(recorded);
14809
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
14810
+ const stored = data.storeSettlement;
14811
+ if (stored?.attemptId !== sent.attemptId || stored.state !== "sending") return data;
14812
+ const payments = (stored.payments ?? []).map((payment) => done.has(payment.id) ? { ...payment, done: true } : payment);
14813
+ if (outcome.kind === "retry" && payments.every((payment, index) => payment.done === stored.payments?.[index]?.done)) return data;
14814
+ const at2 = stamp2();
14815
+ const base = { kind: "pay", attemptId: sent.attemptId, at: at2, payments };
14816
+ data.storeSettlement = outcome.kind === "retry" ? { ...stored, payments } : 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" };
14817
+ data.updatedAt = outcome.kind === "retry" ? data.updatedAt : at2;
14818
+ return data;
14819
+ });
14820
+ return outcome;
14821
+ }
14822
+
14505
14823
  // src/outbox/use-register-outbox.ts
14506
14824
  import { useEffect as useEffect13, useRef as useRef9, useState as useState12 } from "react";
14507
14825
  var idle = { pending: 0, sending: false };
@@ -14631,6 +14949,56 @@ function useOrderOutbox(options) {
14631
14949
  const opened = current.current;
14632
14950
  return opened && opened.storeKey === storeKey ? opened.outbox.discard(orderId) : false;
14633
14951
  },
14952
+ async cancelOnStore(orderId) {
14953
+ if (!latest.current.openSessionId) return { kind: "not_offered" };
14954
+ const opened = current.current;
14955
+ if (!opened || opened.storeKey !== storeKey) return { kind: "not_offered" };
14956
+ const settlement = latest.current.storeSettlement?.(opened.storeKey);
14957
+ const cancel = settlement?.cancel?.bind(settlement);
14958
+ if (!cancel) return { kind: "not_offered" };
14959
+ try {
14960
+ return await cancelOnStore({ orders: opened.orders, cancel, openSessionId: () => latest.current.openSessionId?.() }, orderId);
14961
+ } finally {
14962
+ try {
14963
+ await refreshOutboxState(opened.outbox);
14964
+ } catch (cause) {
14965
+ outboxLogger.warn("Failed to refresh the outbox state", { cause });
14966
+ }
14967
+ }
14968
+ },
14969
+ async payRestOnStore(orderId) {
14970
+ const opened = current.current;
14971
+ if (!opened || opened.storeKey !== storeKey) return { kind: "not_offered" };
14972
+ const settlement = latest.current.storeSettlement?.(opened.storeKey);
14973
+ const pay = settlement?.pay?.bind(settlement);
14974
+ if (!pay) return { kind: "not_offered" };
14975
+ try {
14976
+ return await payRestOnStore({ orders: opened.orders, pay }, orderId);
14977
+ } finally {
14978
+ try {
14979
+ await refreshOutboxState(opened.outbox);
14980
+ } catch (cause) {
14981
+ outboxLogger.warn("Failed to refresh the outbox state", { cause });
14982
+ }
14983
+ }
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
+ },
14634
15002
  savesInFlight: savesInFlightCount,
14635
15003
  stuckCommandIds,
14636
15004
  async record(posOrder) {
@@ -15349,7 +15717,7 @@ function joinedLine(line, join) {
15349
15717
  };
15350
15718
  }
15351
15719
  function reportOrderFromPosOrder(order, join, methodTitle2) {
15352
- 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);
15353
15721
  const taxes = recordedTaxByRate(order) ?? taxLinesByRate(taxedLines, order.taxMinor, void 0, order.taxRounding);
15354
15722
  const till = tillPayments(order.payments);
15355
15723
  const amountOf = (payments) => payments.reduce((total, payment) => total + payment.amountMinor, 0);
@@ -15551,6 +15919,7 @@ export {
15551
15919
  TENDER_GATE_FAILED,
15552
15920
  TENDER_SALE_CHANGED,
15553
15921
  TILE_FIELDS,
15922
+ TILL_SESSION_CLOSED,
15554
15923
  TaxProvider,
15555
15924
  UI_SCALES,
15556
15925
  UI_THEMES,
@@ -15587,9 +15956,13 @@ export {
15587
15956
  callbackSink,
15588
15957
  cameraErrorStatus,
15589
15958
  can,
15959
+ canCancelOnStore,
15590
15960
  canMoveLeg,
15591
15961
  canOpenDrawer,
15962
+ canPayRestOnStore,
15963
+ canReverseOnStore,
15592
15964
  canVoidLeg,
15965
+ cancelOnStore,
15593
15966
  capturedMinor,
15594
15967
  cartQuantities,
15595
15968
  cashMovementSchema,
@@ -15761,6 +16134,7 @@ export {
15761
16134
  parkedOrderSummaries$,
15762
16135
  parseMinor,
15763
16136
  parseXml,
16137
+ payRestOnStore,
15764
16138
  percentOfMinor,
15765
16139
  pickedUnitsMinor,
15766
16140
  planLegs,
@@ -15789,6 +16163,7 @@ export {
15789
16163
  reconcileRegisterCommands,
15790
16164
  recordMovement,
15791
16165
  recordRegisterFact,
16166
+ recordedLegs,
15792
16167
  refundDueOf,
15793
16168
  refundNeedsAdminLine,
15794
16169
  refundableLines,
@@ -15822,6 +16197,7 @@ export {
15822
16197
  resolveStoreSettings,
15823
16198
  restoreOrderDraft,
15824
16199
  retailCodeTwin,
16200
+ reverseOnStore,
15825
16201
  roundMicrosToMinor,
15826
16202
  roundedDue,
15827
16203
  roundedPickTarget,
@@ -15847,6 +16223,8 @@ export {
15847
16223
  serialPortIdentity,
15848
16224
  sessionOpenCommand,
15849
16225
  sessionTransitionCommand,
16226
+ settledAwayOnStore,
16227
+ settledOnStore,
15850
16228
  shipsToBilling,
15851
16229
  sortProducts,
15852
16230
  splitUnitLines,
@@ -15856,6 +16234,7 @@ export {
15856
16234
  stockOverlay$,
15857
16235
  stockOverlayAsOf$,
15858
16236
  storeOrderForReopen,
16237
+ storeOrderLeft,
15859
16238
  stripBoundary,
15860
16239
  submitOrderRefund,
15861
16240
  suggestFloat,
@@ -15878,6 +16257,7 @@ export {
15878
16257
  tenderVoidCollection,
15879
16258
  tenderVoidSchema,
15880
16259
  tillLegsTheStoreRefuses,
16260
+ tillPayments,
15881
16261
  toCsv,
15882
16262
  toCustomerInput,
15883
16263
  toCustomerPatch,
@@ -15888,6 +16268,7 @@ export {
15888
16268
  unitAllocationsFromLegs,
15889
16269
  unitsMinor,
15890
16270
  unpaidUnitsByLine,
16271
+ unrecordedLegs,
15891
16272
  useAppSettings,
15892
16273
  useBarcodeScanner,
15893
16274
  useCameraScan,
@@ -15929,5 +16310,6 @@ export {
15929
16310
  woocommerce_exports as woocommerceDiscountCodes,
15930
16311
  writeAppSetting,
15931
16312
  writeClosure,
16313
+ writeOffLeg,
15932
16314
  writeOrderDraft
15933
16315
  };