@tallyui/components 5.1.0 → 5.3.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.d.ts CHANGED
@@ -1186,6 +1186,9 @@ interface CartLineProps extends Omit<HStackProps, 'children'> {
1186
1186
  picking?: boolean;
1187
1187
  locale?: string;
1188
1188
  className?: string;
1189
+ /** The line strip's press target (`CartLineStrip`): wraps the Total cell's content, or with Total hidden the last visible
1190
+ * cell's that holds no button of its own (not Quantity, nor Price while `priceSlot` is set). */
1191
+ wrapTotal?: (content: ReactNode) => ReactNode;
1189
1192
  }
1190
1193
  /**
1191
1194
  * A single cart line in the columns of CartColumnHeads: quantity, the name with its attributes, the unit price
@@ -1195,7 +1198,7 @@ interface CartLineProps extends Omit<HStackProps, 'children'> {
1195
1198
  * <CartLine name="Coffee" quantity={2} unitPrice={unitPrice} lineTotal={lineTotal} />
1196
1199
  * ```
1197
1200
  */
1198
- declare function CartLine({ name, attributes, quantity, unitPrice, regularUnitPrice, lineTotal, showPrice, quantitySlot, priceSlot, columns, sku, imageUrl, onSplit, picking, locale, className, ...props }: CartLineProps): react_jsx_runtime.JSX.Element;
1201
+ declare function CartLine({ name, attributes, quantity, unitPrice, regularUnitPrice, lineTotal, showPrice, quantitySlot, priceSlot, columns, sku, imageUrl, onSplit, picking, locale, className, wrapTotal, ...props }: CartLineProps): react_jsx_runtime.JSX.Element;
1199
1202
 
1200
1203
  interface CartColumnsFormProps extends Omit<ViewProps, 'children'> {
1201
1204
  /** The saved columns (default `{}`, today's look). */
@@ -3301,6 +3304,7 @@ declare function OrderSyncNotices({ order, stuck, children }: OrderSyncNoticesPr
3301
3304
  * reopened and with no store order: the app wires `reopenRefusedOrder`. When it refuses `coupon_carry_inexact` with a
3302
3305
  * `toCollectMinor`, the row offers "Reopen without the coupon", which calls it again with `{ withoutCoupons: true }`.
3303
3306
  * `onResume` adds Resume to a reopened row; the app resumes the parked sale, whose draft id is the order's id.
3307
+ * `openSessionId` must match the session of every till payment to offer or finish either store cancellation action.
3304
3308
  * `onCancelOnStore` adds "Cancel order on store" to a Needs attention row whose refused sale left an unpaid order on the
3305
3309
  * store (`canCancelOnStore`, #1101), asked in a confirm dialog first: the app wires `useOrderOutbox`'s `cancelOnStore`.
3306
3310
  * A cancel still `sending` is finished with no dialog. With it, such a row offers no Retry, except an `insufficient_stock`
@@ -3309,7 +3313,7 @@ declare function OrderSyncNotices({ order, stuck, children }: OrderSyncNoticesPr
3309
3313
  * the store (`canPayRestOnStore`, #1101 slice 3), asked in a confirm dialog naming each leg to record (no money is taken):
3310
3314
  * the app wires `useOrderOutbox`'s `payRestOnStore`. A pay still `sending` is finished with no dialog. With it, a row
3311
3315
  * with money recorded on the store offers no Retry. */
3312
- declare function OrdersList({ orders, onRetry, formatDate, footer, stuck, history, onOpen, onReopen, onResume, onCancelOnStore, onPayRestOnStore }: {
3316
+ declare function OrdersList({ orders, onRetry, formatDate, footer, stuck, history, onOpen, onReopen, onResume, onCancelOnStore, onPayRestOnStore, onReverseOnStore, openSessionId }: {
3313
3317
  orders: PosOrder[];
3314
3318
  onRetry(orderIds: string[]): Promise<number>;
3315
3319
  formatDate?: (iso: string) => string;
@@ -3321,12 +3325,16 @@ declare function OrdersList({ orders, onRetry, formatDate, footer, stuck, histor
3321
3325
  withoutCoupons: true;
3322
3326
  }) => Promise<void>;
3323
3327
  onResume?: (order: PosOrder) => void;
3328
+ openSessionId?: string;
3324
3329
  onCancelOnStore?: (order: PosOrder) => Promise<SettleOutcome | {
3325
3330
  kind: 'not_offered';
3326
3331
  }>;
3327
3332
  onPayRestOnStore?: (order: PosOrder) => Promise<SettleOutcome | {
3328
3333
  kind: 'not_offered';
3329
3334
  }>;
3335
+ onReverseOnStore?: (order: PosOrder) => Promise<SettleOutcome | {
3336
+ kind: 'not_offered';
3337
+ }>;
3330
3338
  }): react_jsx_runtime.JSX.Element;
3331
3339
 
3332
3340
  /** Pass `useParkedSales(drafts)`'s `parked` and `discard`, or your own parked store's list and handlers (`onPark`, `onResume`, `onDiscard`) with the same results. */
package/dist/index.js CHANGED
@@ -3718,6 +3718,7 @@ function CameraScannerPanel({
3718
3718
  }
3719
3719
 
3720
3720
  // src/cart/cart-line.tsx
3721
+ import { Children as Children2, cloneElement as cloneElement2 } from "react";
3721
3722
  import { Pressable as Pressable16, View as View41 } from "react-native";
3722
3723
  import { useFormatMoney as useFormatMoney2 } from "@tallyui/core";
3723
3724
  import { Image as Image4 } from "@tallyui/primitives";
@@ -3991,6 +3992,7 @@ function CartLine({
3991
3992
  picking = false,
3992
3993
  locale,
3993
3994
  className,
3995
+ wrapTotal,
3994
3996
  ...props
3995
3997
  }) {
3996
3998
  const formatMoney2 = useFormatMoney2();
@@ -3998,6 +4000,8 @@ function CartLine({
3998
4000
  const options = Object.entries(attributes ?? {}).map(([key, value]) => `${key}: ${value}`).join(" \xB7 ");
3999
4001
  const sameCurrency = regularUnitPrice?.currency === unitPrice.currency;
4000
4002
  const regular = (columns?.price?.onSale ?? true) && regularUnitPrice && sameCurrency && regularUnitPrice.amount > unitPrice.amount ? formatMoney2(regularUnitPrice, locale) ?? "\u2014" : null;
4003
+ const slots = cartColumnSlots(columns, { showPrice });
4004
+ const target = slots.includes("total") ? "total" : slots.filter((id) => id !== "quantity" && !(id === "price" && priceSlot)).pop();
4001
4005
  const cells = {
4002
4006
  fill: /* @__PURE__ */ jsx96(View41, { className: "flex-1" }, "fill"),
4003
4007
  quantity: /* @__PURE__ */ jsxs40(View41, { className: (picking ? CART_PICKING_QUANTITY : CART_COLUMNS.quantity).cell, children: [
@@ -4046,7 +4050,7 @@ function CartLine({
4046
4050
  regularPrice: /* @__PURE__ */ jsx96(View41, { className: CART_COLUMNS.regularPrice.cell, children: /* @__PURE__ */ jsx96(Text, { testID: "cart-line-regular-price", className: "text-right text-sm tabular-nums text-muted-foreground", children: formatMoney2(regularUnitPrice && sameCurrency ? regularUnitPrice : unitPrice, locale) ?? "\u2014" }) }, "regularPrice"),
4047
4051
  total: /* @__PURE__ */ jsx96(View41, { className: CART_COLUMNS.total.cell, children: /* @__PURE__ */ jsx96(Text, { className: "text-right text-sm font-semibold tabular-nums", children: formatMoney2(lineTotal, locale) ?? "\u2014" }) }, "total")
4048
4052
  };
4049
- return /* @__PURE__ */ jsx96(HStack, { space: "none", className: cn60("py-2.5", className), ...props, children: cartColumnSlots(columns, { showPrice }).map((id) => cells[id]) });
4053
+ return /* @__PURE__ */ jsx96(HStack, { space: "none", className: cn60("py-2.5", className), ...props, children: slots.map((id) => wrapTotal && id === target ? cloneElement2(cells[id], {}, wrapTotal(Children2.toArray(cells[id].props.children))) : cells[id]) });
4050
4054
  }
4051
4055
 
4052
4056
  // src/cart/cart-columns-form.tsx
@@ -6256,7 +6260,7 @@ function OrderDetail({
6256
6260
  // src/order/refund-form.tsx
6257
6261
  import { useRef as useRef15, useState as useState31 } from "react";
6258
6262
  import { Pressable as Pressable34, ScrollView as ScrollView13, View as View71 } from "react-native";
6259
- import { useFormatMoney as useFormatMoney8, useMoneyFormat as useMoneyFormat3 } from "@tallyui/core";
6263
+ import { useFormatMoney as useFormatMoney8, useMoneyFormat as useMoneyFormat3, useOptionalConnector } from "@tallyui/core";
6260
6264
  import { priceRefund, refundableLines } from "@tallyui/pos";
6261
6265
 
6262
6266
  // src/lib/error-text.ts
@@ -6395,6 +6399,7 @@ function RefundForm({
6395
6399
  }) {
6396
6400
  const formatMoney2 = useFormatMoney8();
6397
6401
  const format2 = useMoneyFormat3();
6402
+ const lineTotalsShrinkOnReturn = useOptionalConnector()?.lineTotalsShrinkOnReturn === true;
6398
6403
  const [quantities, setQuantities] = useState31({});
6399
6404
  const [restock, setRestock] = useState31({});
6400
6405
  const [shippingText, setShippingText] = useState31("");
@@ -6412,6 +6417,11 @@ function RefundForm({
6412
6417
  quantity: Math.min(quantities[orderLineId] ?? 0, refundableQuantity),
6413
6418
  restock: restock[orderLineId] ?? defaultRestock
6414
6419
  })).filter(({ quantity }) => quantity > 0);
6420
+ const missingSoldFigures = lineTotalsShrinkOnReturn && request.find(({ orderLineId, quantity }) => {
6421
+ const index = lines.findIndex((line2) => line2.id === orderLineId);
6422
+ const line = lines[index];
6423
+ return (line.soldTotalMinor === void 0 || line.soldTaxMinor === void 0) && (quantity < line.quantity || available[index].refundedQuantity > 0);
6424
+ });
6415
6425
  const priced = priceRefund(lines, refunds, request);
6416
6426
  const emptiesLines = priced.lines.length > 0 && available.every(({ orderLineId, refundableQuantity }) => (request.find((line) => line.orderLineId === orderLineId)?.quantity ?? 0) === refundableQuantity);
6417
6427
  const roundingShareMinor = emptiesLines ? cashRoundingMinor : 0;
@@ -6420,7 +6430,7 @@ function RefundForm({
6420
6430
  const totalMinor = typeof shippingMinor === "number" && typeof adjustmentMinor === "number" ? priced.totalMinor + shippingMinor + adjustmentMinor + roundingShareMinor : void 0;
6421
6431
  const destination = originalMethod?.available ? picked ?? "original_method" : "cash";
6422
6432
  const cashStep = destination === "cash" && Number.isInteger(cashIncrementMinor) && cashIncrementMinor > 1 && typeof totalMinor === "number" && totalMinor > 0 && totalMinor % cashIncrementMinor !== 0;
6423
- const invalid = typeof shippingMinor === "string" ? shippingMinor : typeof adjustmentMinor === "string" ? adjustmentMinor : shippingMinor > refundableShippingMinor ? `Shipping can be at most ${fmt(refundableShippingMinor)}.` : priced.lines.length === 0 && shippingMinor === 0 && adjustmentMinor === 0 ? "Choose something to refund." : totalMinor <= 0 ? "The refund total must be more than 0." : totalMinor > orderTotalMinor - refundedMinor ? `You can refund at most ${fmt(orderTotalMinor - refundedMinor)}.` : reason.trim() === "" ? "Enter a reason." : null;
6433
+ const invalid = typeof shippingMinor === "string" ? shippingMinor : typeof adjustmentMinor === "string" ? adjustmentMinor : missingSoldFigures ? `Update the store's plugin to refund part of ${lines.find((line) => line.id === missingSoldFigures.orderLineId).name}.` : shippingMinor > refundableShippingMinor ? `Shipping can be at most ${fmt(refundableShippingMinor)}.` : priced.lines.length === 0 && shippingMinor === 0 && adjustmentMinor === 0 ? "Choose something to refund." : totalMinor <= 0 ? "The refund total must be more than 0." : totalMinor > orderTotalMinor - refundedMinor ? `You can refund at most ${fmt(orderTotalMinor - refundedMinor)}.` : reason.trim() === "" ? "Enter a reason." : null;
6424
6434
  const disabled = !!invalid || online === false || busy;
6425
6435
  const confirm = async () => {
6426
6436
  if (invalid || online === false || busyRef.current) return;
@@ -9533,8 +9543,24 @@ function CartChargeLine({ name, price, total, showPrice = true, columns, locale,
9533
9543
 
9534
9544
  // src/cart/cart-line-strip.tsx
9535
9545
  import { useRef as useRef20, useState as useState46 } from "react";
9536
- import { Animated as Animated8, Platform as Platform17, Pressable as Pressable42, View as View101 } from "react-native";
9546
+ import { Animated as Animated8, PanResponder, Platform as Platform17, Pressable as Pressable42, View as View101 } from "react-native";
9547
+
9548
+ // src/cart/line-strip-geometry.ts
9549
+ var REMOVE_SHARE = 0.6;
9550
+ var REMOVE_BAND = 56;
9551
+ var REMOVE_FLICK = 800;
9552
+ function removePoint(rowWidth, stripWidth) {
9553
+ return Math.max(stripWidth + REMOVE_BAND, Math.round(rowWidth * REMOVE_SHARE));
9554
+ }
9555
+ function releaseOutcome({ revealed, velocityX, rowWidth, stripWidth }) {
9556
+ if (revealed >= removePoint(rowWidth, stripWidth)) return "remove";
9557
+ if (velocityX <= -REMOVE_FLICK && revealed > stripWidth) return "remove";
9558
+ return revealed > stripWidth / 2 ? "open" : "home";
9559
+ }
9560
+
9561
+ // src/cart/cart-line-strip.tsx
9537
9562
  import { jsx as jsx168, jsxs as jsxs105 } from "react/jsx-runtime";
9563
+ var STILL_MS = 50;
9538
9564
  function CartLineStrip({ name, onEdit, onRemove, children }) {
9539
9565
  const reduced = useReducedMotion() !== false;
9540
9566
  const offset = useRef20(new Animated8.Value(0)).current;
@@ -9573,6 +9599,33 @@ function CartLineStrip({ name, onEdit, onRemove, children }) {
9573
9599
  settle(false);
9574
9600
  });
9575
9601
  };
9602
+ const drag = useRef20({ row: 0, strip: 0, base: 0, claimed: 0, settle, leave });
9603
+ Object.assign(drag.current, { row: rowWidth ?? 0, strip: stripWidth, settle, leave });
9604
+ const clamp = (x) => Math.min(0, Math.max(-drag.current.row, x));
9605
+ const pan = useRef20(PanResponder.create({
9606
+ onMoveShouldSetPanResponder: (_, { dx, dy }) => !leaving.current && drag.current.row > 0 && Math.abs(dx) > 8 && Math.abs(dx) > Math.abs(dy) && (drag.current.claimed = dx, true),
9607
+ onPanResponderGrant: () => {
9608
+ const { claimed } = drag.current;
9609
+ drag.current.base = (opened.current ? -drag.current.strip : 0) + claimed;
9610
+ drag.current.claimed = 0;
9611
+ offset.stopAnimation((value) => {
9612
+ drag.current.base = value + claimed;
9613
+ });
9614
+ },
9615
+ onPanResponderMove: (_, { dx }) => offset.setValue(clamp(drag.current.base + dx)),
9616
+ onPanResponderRelease: (event, { dx, vx, _accountsForMovesUpTo }) => {
9617
+ drag.current.claimed = 0;
9618
+ const { row: row2, strip, base } = drag.current;
9619
+ const still = event.touchHistory.mostRecentTimeStamp - _accountsForMovesUpTo > STILL_MS;
9620
+ const outcome = releaseOutcome({ revealed: -clamp(base + dx), velocityX: still ? 0 : vx * 1e3, rowWidth: row2, stripWidth: strip });
9621
+ if (outcome === "remove") drag.current.leave();
9622
+ else drag.current.settle(outcome === "open");
9623
+ },
9624
+ onPanResponderTerminate: () => {
9625
+ drag.current.claimed = 0;
9626
+ drag.current.settle(opened.current);
9627
+ }
9628
+ })).current;
9576
9629
  const peek = (on) => {
9577
9630
  if (opened.current || leaving.current || reduced) return;
9578
9631
  if (on) Animated8.spring(offset, { ...PEEK_SPRING, toValue: -PEEK, useNativeDriver: Platform17.OS !== "web" }).start();
@@ -9609,7 +9662,7 @@ function CartLineStrip({ name, onEdit, onRemove, children }) {
9609
9662
  importantForAccessibility: open ? "auto" : "no-hide-descendants",
9610
9663
  "aria-hidden": !open,
9611
9664
  children: /* @__PURE__ */ jsxs105(View101, { testID: "cart-line-strip-actions", className: "flex-row items-stretch", onLayout: (event) => setStripWidth(event.nativeEvent.layout.width), children: [
9612
- /* @__PURE__ */ jsx168(
9665
+ onEdit ? /* @__PURE__ */ jsx168(
9613
9666
  Button,
9614
9667
  {
9615
9668
  variant: "default",
@@ -9623,7 +9676,7 @@ function CartLineStrip({ name, onEdit, onRemove, children }) {
9623
9676
  },
9624
9677
  children: /* @__PURE__ */ jsx168(Text, { children: "Edit" })
9625
9678
  }
9626
- ),
9679
+ ) : null,
9627
9680
  /* @__PURE__ */ jsx168(
9628
9681
  Button,
9629
9682
  {
@@ -9638,7 +9691,7 @@ function CartLineStrip({ name, onEdit, onRemove, children }) {
9638
9691
  ] })
9639
9692
  }
9640
9693
  ),
9641
- /* @__PURE__ */ jsx168(Animated8.View, { className: "bg-background", style: { transform: [{ translateX: shown2 }] }, children: children(wrapTotal) })
9694
+ /* @__PURE__ */ jsx168(Animated8.View, { ...pan.panHandlers, className: "bg-background", style: { transform: [{ translateX: shown2 }] }, children: children(wrapTotal) })
9642
9695
  ] });
9643
9696
  }
9644
9697
 
@@ -10536,7 +10589,7 @@ function Cart({
10536
10589
  const [priceError, setPriceError] = useState51(null);
10537
10590
  const [openForm, setForm] = useState51(null);
10538
10591
  const form = picker ? null : openForm;
10539
- const ChargeStrip = picker ? ReadOnlyStrip : CartLineStrip;
10592
+ const Strip = picker ? ReadOnlyStrip : CartLineStrip;
10540
10593
  const chargesOffered = (sale.capabilities?.orderCreate ?? 0) >= 5;
10541
10594
  const shippingNoTax = (sale.capabilities?.orderCreate ?? 0) >= 6;
10542
10595
  const showOrderDiscount = !picker && order.lineItems.length > 0 && (orderActions || orderDiscountChips && order.discounts.length > 0);
@@ -10563,10 +10616,14 @@ function Cart({
10563
10616
  if (refused === null) setPriceError((now) => now?.lineId === line.id ? null : now);
10564
10617
  return refused;
10565
10618
  };
10619
+ const removeLine = (id) => {
10620
+ sale.remove(id);
10621
+ return sale.removal("line", id) ? "refused" : null;
10622
+ };
10566
10623
  const unpaid = (line) => line.quantity - (picker?.paid[line.id] ?? 0);
10567
10624
  const pickable = (line) => Number.isInteger(line.quantity) && line.quantity > 0 && display(line.id).amountMinor >= 0 && unpaid(line) > 0;
10568
10625
  const renderItem = (line) => /* @__PURE__ */ jsxs111(Fragment38, { children: [
10569
- /* @__PURE__ */ jsx174(
10626
+ /* @__PURE__ */ jsx174(Strip, { name: line.name, onRemove: () => removeLine(line.id), children: (wrapTotal) => /* @__PURE__ */ jsx174(
10570
10627
  CartLine,
10571
10628
  {
10572
10629
  name: line.name,
@@ -10625,9 +10682,10 @@ function Cart({
10625
10682
  commit: lineCommit,
10626
10683
  onCloseRefused: (message) => setPriceError({ lineId: line.id, message })
10627
10684
  }
10628
- ) : void 0
10685
+ ) : void 0,
10686
+ wrapTotal
10629
10687
  }
10630
- ),
10688
+ ) }),
10631
10689
  splitError?.lineId === line.id ? /* @__PURE__ */ jsx174(
10632
10690
  Text47,
10633
10691
  {
@@ -10730,7 +10788,7 @@ function Cart({
10730
10788
  identity: order.id,
10731
10789
  renderItem: (charge, index) => /* @__PURE__ */ jsxs111(View106, { testID: `cart-${kind === "fees" ? "fee" : "shipping"}-${index}`, children: [
10732
10790
  /* @__PURE__ */ jsx174(
10733
- ChargeStrip,
10791
+ Strip,
10734
10792
  {
10735
10793
  name: charge.name,
10736
10794
  onEdit: () => setForm({ type: "edit-charge", kind, id: charge.id }),
@@ -12763,8 +12821,8 @@ function SyncStatus({ state, registerState, pluginName = "the POS plugin", pullN
12763
12821
  // src/sale/orders-list.tsx
12764
12822
  import { useEffect as useEffect24, useId as useId4, useRef as useRef26, useState as useState57 } from "react";
12765
12823
  import { Pressable as Pressable56, ScrollView as ScrollView23, Text as Text58, View as View118 } from "react-native";
12766
- import { useFormatMoney as useFormatMoney26, knownWarnings } from "@tallyui/core";
12767
- import { canCancelOnStore, canPayRestOnStore, extrasNotSent, isRequeueableOrder, needsAdminReasonOf as needsAdminReasonOf2, needsAttention, noteDelivery as noteDelivery2, refundDueOf, REOPENABLE_CODES, settledOnStore, storeOrderLeft, unrecordedLegs, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE } from "@tallyui/pos";
12824
+ import { useFormatMoney as useFormatMoney26, useOptionalConnector as useOptionalConnector2, knownWarnings } from "@tallyui/core";
12825
+ import { canCancelOnStore, canPayRestOnStore, canReverseOnStore, extrasNotSent, isRequeueableOrder, needsAdminReasonOf as needsAdminReasonOf2, needsAttention, noteDelivery as noteDelivery2, refundDueOf, REOPENABLE_CODES, settledOnStore, storeOrderLeft, TILL_SESSION_CLOSED, tillPayments, unrecordedLegs, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE } from "@tallyui/pos";
12768
12826
  import { Fragment as Fragment48, jsx as jsx190, jsxs as jsxs126 } from "react/jsx-runtime";
12769
12827
  var STATUS_LABEL2 = { pending: "Waiting to sync", applied: "Synced", rejected: "Not accepted" };
12770
12828
  var FIGURE_LABELS = /* @__PURE__ */ new Map([["subtotalMinor", "Subtotal"], ["taxMinor", "Tax"], ["discountMinor", "Discount"]]);
@@ -12786,6 +12844,11 @@ var REFUSAL_SENTENCES = /* @__PURE__ */ new Map([
12786
12844
  ]);
12787
12845
  var refusalSentence = (code) => REFUSAL_SENTENCES.get(code ?? "") ?? REFUSAL_SENTENCES.get("platform_error");
12788
12846
  var GIVE_BACK = "If the money was given back, do not record it; a manager must check the order in the store's admin.";
12847
+ var GIVE_BACK_INSTEAD = "If the money was given back, use Give back and cancel instead.";
12848
+ var GIVE = "Give back any of this you have not already given back.";
12849
+ var CLOSED_SESSION_NOTICE = "Taken in a session that has closed: a manager must settle this sale in the store's admin.";
12850
+ var legLabel = (method) => method === "cash" ? "Cash" : "Card";
12851
+ var legWording = (method, amount) => `${legLabel(method)} ${amount}: ${method === "cash" ? "hand it back from the drawer" : "give it back on the card terminal"}`;
12789
12852
  var methodLabel = (method) => method === "cash" ? "Cash" : "Card terminal";
12790
12853
  var REOPEN_AGAIN_SENTENCE = "This order was changed in the online store after it was reopened here, so your change wasn't sent. Reopen the order and make the change again.";
12791
12854
  function defaultFormatDate2(iso2) {
@@ -12802,18 +12865,38 @@ function OrderSyncNotices({ order, stuck, children }) {
12802
12865
  const sentence = order.syncStatus === "rejected" ? order.storeOrderId !== void 0 && ["reopen_required", "revision_conflict"].includes(order.error?.code ?? "") ? REOPEN_AGAIN_SENTENCE : refusalSentence(left && order.error?.code === "invalid_payload" ? "platform_error" : order.error?.code) : order.syncStatus === "pending" && order.error?.code === UPDATE_UNSENDABLE ? UPDATE_UNSENDABLE_MESSAGE : void 0;
12803
12866
  const extras = extrasNotSent(order);
12804
12867
  const kind = order.storeSettlement?.kind;
12805
- const settlement = order.syncStatus === "rejected" && (kind === "cancel" || kind === "pay") ? order.storeSettlement : void 0;
12868
+ const settlement = order.syncStatus === "rejected" && (kind === "cancel" || kind === "pay" || kind === "reverse" && order.storeSettlement?.legs?.length) ? order.storeSettlement : void 0;
12806
12869
  const reference = left?.reference ?? orderReference(order);
12807
12870
  const money = (amount) => formatMoney2({ amount, currency: order.currency });
12808
12871
  const sum = (legs) => legs.reduce((total, leg) => total + leg.amountMinor, 0);
12809
12872
  const paidThere = settlement?.capturedMinor ? `: ${money(settlement.capturedMinor)} is paid there` : "";
12810
12873
  const recorded = money((left?.recordedMinor ?? 0) + sum(settlement?.payments?.filter((payment) => payment.done) ?? []));
12811
- const cashTaken = sum(order.payments.filter((payment) => payment.method === "cash"));
12812
12874
  const doneMinor = sum(settlement?.payments?.filter((payment) => payment.done) ?? []);
12813
12875
  const nothing = doneMinor > 0 ? `${money(doneMinor)} was recorded from this till.` : "Nothing was recorded from this till.";
12814
- const settledText = settlement?.kind === "pay" ? settlement.state === "done" ? `Order #${reference} is paid on the store.` : settlement.state === "gone" ? `Order #${reference} is not on the store any more; ${recorded} was recorded on it.` : settlement.state !== "changed" ? void 0 : settlement.storeStatus === "completed" ? `Order #${reference} is already paid on the store. ${nothing}` : `Order #${reference} changed on the store${paidThere}. ${nothing} Check it in the store's admin.` : settlement?.state === "done" ? `Order #${reference} was cancelled on the store.${cashTaken ? ` If you gave back the ${money(cashTaken)} cash taken on this till, record it as a pay-out.` : ""}` : settlement?.state === "gone" ? `Order #${reference} was removed on the store.` : settlement?.state === "changed" ? `Order #${reference} changed on the store${paidThere}. Nothing was cancelled from this till. Check it in the store's admin.` : void 0;
12876
+ let settledText = settlement?.kind === "pay" ? settlement.state === "done" ? `Order #${reference} is paid on the store.` : settlement.state === "gone" ? `Order #${reference} is not on the store any more; ${recorded} was recorded on it.` : settlement.state !== "changed" ? void 0 : settlement.storeStatus === "completed" ? `Order #${reference} is already paid on the store. ${nothing}` : `Order #${reference} changed on the store${paidThere}. ${nothing} Check it in the store's admin.` : settlement?.state === "done" ? `Order #${reference} was cancelled on the store.${order.payments.length || kind === "reverse" ? ` The till took: ${order.payments.map((leg) => legWording(leg.method, money(leg.amountMinor))).join("; ")}. ${GIVE}` : ""}` : settlement?.state === "gone" ? `Order #${reference} was removed on the store.` : settlement?.state === "changed" ? `Order #${reference} changed on the store${paidThere}. Nothing was cancelled from this till. Check it in the store's admin.` : void 0;
12815
12877
  const pay = settlement?.kind === "pay";
12816
- const addedText = settlement?.state === "refused" ? pay ? `The store did not record the rest of order #${reference}: ${recorded} of ${money(order.totalMinor)} is recorded there. Check it in the store's admin.` : `The store did not cancel order #${reference}. Check it in the store's admin.` : settlement?.state === "sending" ? pay ? `Recording the rest of order #${reference} on the store is not finished.` : `Cancelling order #${reference} on the store is not finished.` : void 0;
12878
+ let addedText = settlement?.state === "refused" ? pay ? `The store did not record the rest of order #${reference}: ${recorded} of ${money(order.totalMinor)} is recorded there. Check it in the store's admin.` : `The store did not cancel order #${reference}. Check it in the store's admin.` : settlement?.state === "sending" ? pay ? `Recording the rest of order #${reference} on the store is not finished.` : `Cancelling order #${reference} on the store is not finished.` : void 0;
12879
+ if (settlement?.kind === "reverse" && settlement.state !== "done" && settlement.legs) {
12880
+ const legs = settlement.legs.flatMap((leg) => {
12881
+ const payment = order.payments.find(({ id }) => id === leg.paymentId);
12882
+ return payment ? [{ ...payment, done: leg.done }] : [];
12883
+ });
12884
+ const taken = legs.filter((leg) => leg.done).map((leg) => legWording(leg.method, money(leg.amountMinor))).join("; ");
12885
+ const still = legs.filter((leg) => !leg.done).map((leg) => `${legLabel(leg.method)} ${money(leg.amountMinor)}`).join("; ");
12886
+ const hasDone = settlement.legs.some((leg) => leg.done);
12887
+ const subject = `Order #${reference}`;
12888
+ settledText = void 0;
12889
+ addedText = void 0;
12890
+ if (settlement.state === "gone") settledText = `${subject} is not on the store any more.${taken ? ` The store had taken off: ${taken}. ${GIVE}` : ""} Check it in the store's admin.`;
12891
+ else if (settlement.state === "sending") addedText = `Cancelling order #${reference} on the store is not finished.${taken ? ` The store has taken off: ${taken}. ${GIVE}` : ""}${still ? ` Not confirmed taken off yet: ${still}. Keep that until this till shows the order cancelled.` : ""}`;
12892
+ else if (hasDone) addedText = `${subject} was not cancelled on the store.${taken ? ` The store has taken off: ${taken}. ${GIVE}` : ""}${still ? ` Still paid there: ${still}. Keep that; a manager must check it in the store's admin.` : ""}`;
12893
+ else if (settlement.state === "refused") addedText = `The store did not cancel order #${reference}. Check it in the store's admin.`;
12894
+ else settledText = `${subject} changed on the store${paidThere}. Nothing was taken off it or cancelled from this till. Check it in the store's admin.`;
12895
+ }
12896
+ if ((kind === "cancel" || kind === "reverse") && order.storeSettlement?.code === TILL_SESSION_CLOSED) {
12897
+ settledText = void 0;
12898
+ addedText = CLOSED_SESSION_NOTICE;
12899
+ }
12817
12900
  const settled = !!settlement && settledOnStore(order);
12818
12901
  return /* @__PURE__ */ jsxs126(Fragment48, { children: [
12819
12902
  stuckEntry ? /* @__PURE__ */ jsx190(Text58, { className: "text-destructive", children: needsAdminReason !== void 0 ? needsAdminReason === "session_closed" ? NEEDS_ADMIN_SESSION_CLOSED : NEEDS_ADMIN_SALE : `Hasn't reached the online store since ${sinceText(stuckEntry)}.` }) : null,
@@ -12832,8 +12915,9 @@ function OrderSyncNotices({ order, stuck, children }) {
12832
12915
  knownWarnings(order.warnings).filter((warning) => warning.code !== "register_session_unknown").map((warning, index) => /* @__PURE__ */ jsx190(View118, { className: "border-l-4 border-warning pl-2", children: /* @__PURE__ */ jsx190(Text58, { className: "text-foreground", children: warning.code === "insufficient_stock" ? `${warning.quantity} sold without stock: ${order.lines.find((line) => line.variantId === warning.variantId)?.name}` : warning.code === "tax_rate_mismatch" ? `Tax at ${(warning.ratePpm / 1e4).toLocaleString(void 0, { maximumFractionDigits: 4 })}%: store ${formatMoney2({ amount: warning.serverMinor, currency: order.currency })} vs POS ${formatMoney2({ amount: warning.expectedMinor, currency: order.currency })}` : warning.code === "customer_ignored" ? `The online store didn't recognise the customer on this sale, so it was saved as a guest sale. Customer id: ${warning.customerId}.` : warning.code === "figures_mismatch" ? `The online store worked out different figures for this sale. ${warning.fields.map(({ field, tillMinor, serverMinor }) => `${FIGURE_LABELS.get(field) ?? field}: till ${formatMoney2({ amount: tillMinor, currency: order.currency })}, store ${formatMoney2({ amount: serverMinor, currency: order.currency })}.`).join(" ")}` : warning.code === "line_figures_mismatch" ? ((n) => `The online store worked out different figures for ${n === 1 ? "one line" : `${n} lines`} of this sale.`)(new Set(warning.lines.map((line) => line.lineId)).size) : warning.bridgeMinor !== void 0 ? `Store calculated ${formatMoney2({ amount: warning.serverMinor, currency: order.currency })}; a rounding line of ${warning.bridgeMinor > 0 ? "+" : ""}${formatMoney2({ amount: warning.bridgeMinor, currency: order.currency })} brought it to ${formatMoney2({ amount: warning.expectedMinor, currency: order.currency })}` : `Store total ${formatMoney2({ amount: warning.serverMinor, currency: order.currency })} vs POS ${formatMoney2({ amount: warning.expectedMinor, currency: order.currency })}` }) }, index))
12833
12916
  ] });
12834
12917
  }
12835
- function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer, stuck, history, onOpen, onReopen, onResume, onCancelOnStore, onPayRestOnStore }) {
12918
+ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer, stuck, history, onOpen, onReopen, onResume, onCancelOnStore, onPayRestOnStore, onReverseOnStore, openSessionId }) {
12836
12919
  const formatMoney2 = useFormatMoney26();
12920
+ const discountsAreTaxedRows = useOptionalConnector2()?.discountsAreTaxedRows === true;
12837
12921
  const hintId = useId4();
12838
12922
  const retrying = useRef26(/* @__PURE__ */ new Set());
12839
12923
  const [retryingIds, setRetryingIds] = useState57(/* @__PURE__ */ new Set());
@@ -12904,6 +12988,29 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
12904
12988
  paying.current.delete(order.id);
12905
12989
  }
12906
12990
  }
12991
+ const reversing = useRef26(/* @__PURE__ */ new Set());
12992
+ const [reverses, setReverses] = useState57(/* @__PURE__ */ new Map());
12993
+ const [askingReverse, setAskingReverse] = useState57(null);
12994
+ async function reverseOnStore(order) {
12995
+ if (!onReverseOnStore || reversing.current.has(order.id)) return;
12996
+ reversing.current.add(order.id);
12997
+ setReverses((current) => new Map(current).set(order.id, "busy"));
12998
+ let failed = false;
12999
+ try {
13000
+ failed = (await onReverseOnStore(order)).kind === "retry";
13001
+ } catch {
13002
+ failed = true;
13003
+ } finally {
13004
+ reversing.current.delete(order.id);
13005
+ setReverses((current) => {
13006
+ const next = new Map(current);
13007
+ if (failed) next.set(order.id, "failed");
13008
+ else next.delete(order.id);
13009
+ return next;
13010
+ });
13011
+ }
13012
+ }
13013
+ const inOpenSession = (order) => openSessionId !== void 0 && tillPayments(order.payments).every((payment) => (payment.sessionId ?? order.sessionId) === openSessionId);
12907
13014
  const [expanded, setExpanded] = useState57(/* @__PURE__ */ new Set());
12908
13015
  useEffect24(() => {
12909
13016
  for (const id of retrying.current) {
@@ -12920,7 +13027,7 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
12920
13027
  return bTime - aTime;
12921
13028
  });
12922
13029
  return /* @__PURE__ */ jsxs126(ScrollView23, { className: "flex-1 bg-background p-4", children: [
12923
- [{ title: "Needs attention", orders: needsAttention(orders, { stuckCommandIds: stuck?.commandIds }) }, { title: "Recent", orders: recent }].filter((section) => section.title === "Recent" || section.orders.length > 0).map((section, sectionIndex) => /* @__PURE__ */ jsxs126(View118, { className: "mb-6 gap-3", children: [
13030
+ [{ title: "Needs attention", orders: needsAttention(orders, { stuckCommandIds: stuck?.commandIds, discountsAreTaxedRows }) }, { title: "Recent", orders: recent }].filter((section) => section.title === "Recent" || section.orders.length > 0).map((section, sectionIndex) => /* @__PURE__ */ jsxs126(View118, { className: "mb-6 gap-3", children: [
12924
13031
  /* @__PURE__ */ jsx190(Text58, { accessibilityRole: "header", className: "text-xl font-semibold text-foreground", children: section.title }),
12925
13032
  section.title === "Recent" && orders.length === 0 && shown2.length === 0 ? /* @__PURE__ */ jsx190(Text58, { testID: "orders-empty", className: "text-muted-foreground", children: "No sales yet. Completed sales appear here." }) : null,
12926
13033
  section.orders.map((order) => {
@@ -12955,14 +13062,18 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
12955
13062
  const attention = section.title === "Needs attention";
12956
13063
  const reopenable = attention && !!onReopen && order.syncStatus === "rejected" && REOPENABLE_CODES.includes(order.error?.code ?? "") && order.storeOrderId === void 0 && order.reopenedAt === void 0;
12957
13064
  const reopenState = reopens.get(order.id);
12958
- const cancellable = attention && !!onCancelOnStore && canCancelOnStore(order);
13065
+ const cancelOffered = attention && !!onCancelOnStore && canCancelOnStore(order);
12959
13066
  const cancelState = cancels.get(order.id);
12960
13067
  const finishing = order.storeSettlement?.kind === "cancel" && order.storeSettlement.state === "sending";
12961
13068
  const left = storeOrderLeft(order);
12962
13069
  const payable = attention && !!onPayRestOnStore && canPayRestOnStore(order);
12963
13070
  const payState = pays.get(order.id);
12964
13071
  const finishingPay = order.storeSettlement?.kind === "pay" && order.storeSettlement.state === "sending";
12965
- const retryLabel = onPayRestOnStore && left && left.recordedMinor > 0 ? void 0 : onCancelOnStore && left?.recordedMinor === 0 ? order.error?.code === "insufficient_stock" ? "Try the payment again" : void 0 : "Retry";
13072
+ const reverseOffered = attention && !!onReverseOnStore && canReverseOnStore(order);
13073
+ const closedSession = (cancelOffered || reverseOffered) && !inOpenSession(order);
13074
+ const cancellable = cancelOffered && !closedSession, reversible = reverseOffered && !closedSession;
13075
+ const reverseState = reverses.get(order.id), finishingReverse = order.storeSettlement?.kind === "reverse" && order.storeSettlement.state === "sending";
13076
+ const retryLabel = (onPayRestOnStore || onReverseOnStore) && left && left.recordedMinor > 0 ? void 0 : onCancelOnStore && left?.recordedMinor === 0 ? order.error?.code === "insufficient_stock" ? "Try the payment again" : void 0 : "Retry";
12966
13077
  return /* @__PURE__ */ jsxs126(View118, { className: "gap-1 rounded-md border border-border bg-card p-3", children: [
12967
13078
  /* @__PURE__ */ jsx190(Text58, { id: `${hintId}-${sectionIndex}-${order.id}`, className: "hidden", children: "Shows the items and payments of this sale" }),
12968
13079
  /* @__PURE__ */ jsxs126(
@@ -13019,6 +13130,7 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
13019
13130
  setRetryingIds(new Set(retrying.current));
13020
13131
  }
13021
13132
  }, className: "rounded-md bg-primary px-4 py-2", children: /* @__PURE__ */ jsx190(Text58, { className: "text-center font-semibold text-primary-foreground", children: retryLabel }) }) : null,
13133
+ closedSession ? /* @__PURE__ */ jsx190(Text58, { className: "text-muted-foreground", children: CLOSED_SESSION_NOTICE }) : null,
13022
13134
  cancellable ? /* @__PURE__ */ jsx190(
13023
13135
  Pressable56,
13024
13136
  {
@@ -13051,6 +13163,21 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
13051
13163
  }
13052
13164
  ) : null,
13053
13165
  payable && (payState === "failed" || payState === "unfinished") ? /* @__PURE__ */ jsx190(Text58, { testID: `order-${order.id}-pay-rest-on-store-error`, className: "text-muted-foreground", children: payState === "unfinished" ? "The store has not finished this order yet. Try again, or check it in the store's admin." : "Could not reach the store. Try again." }) : null,
13166
+ reversible ? /* @__PURE__ */ jsx190(
13167
+ Pressable56,
13168
+ {
13169
+ accessibilityRole: "button",
13170
+ testID: `order-${order.id}-reverse-on-store`,
13171
+ disabled: reverseState === "busy",
13172
+ onPress: () => {
13173
+ if (finishingReverse) void reverseOnStore(order);
13174
+ else setAskingReverse(order);
13175
+ },
13176
+ className: "rounded-md border border-border px-4 py-2",
13177
+ children: /* @__PURE__ */ jsx190(Text58, { className: "text-center font-semibold text-foreground", children: reverseState === "busy" ? "Cancelling on store\u2026" : finishingReverse ? "Finish cancelling on store" : "Give back and cancel" })
13178
+ }
13179
+ ) : null,
13180
+ reversible && reverseState === "failed" ? /* @__PURE__ */ jsx190(Text58, { testID: `order-${order.id}-reverse-on-store-error`, className: "text-muted-foreground", children: "Could not reach the store. Try again." }) : null,
13054
13181
  attention && order.reopenedAt !== void 0 ? /* @__PURE__ */ jsxs126(Fragment48, { children: [
13055
13182
  /* @__PURE__ */ jsx190(Text58, { testID: `order-${order.id}-reopened`, className: "text-muted-foreground", children: "Reopened as a parked sale." }),
13056
13183
  onResume ? /* @__PURE__ */ jsx190(
@@ -13094,7 +13221,7 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
13094
13221
  ] }, order.id);
13095
13222
  })
13096
13223
  ] }, section.title)),
13097
- askingCancel ? ((reference) => /* @__PURE__ */ jsx190(
13224
+ askingCancel && inOpenSession(askingCancel) ? ((reference) => /* @__PURE__ */ jsx190(
13098
13225
  ConfirmDialog,
13099
13226
  {
13100
13227
  testID: `order-${askingCancel.id}-cancel-on-store-dialog`,
@@ -13126,7 +13253,7 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
13126
13253
  description: [
13127
13254
  ...legs.filter((_leg, index) => !(stored?.kind === "pay" && stored.payments?.length === legs.length && stored.payments[index].done)).map((leg) => `${methodLabel(leg.method)} ${formatMoney2({ amount: leg.amountMinor, currency: askingPay.currency })}, already taken on this till.`),
13128
13255
  "No money is taken now.",
13129
- GIVE_BACK
13256
+ onReverseOnStore && canReverseOnStore(askingPay) && inOpenSession(askingPay) ? GIVE_BACK_INSTEAD : GIVE_BACK
13130
13257
  ].join("\n"),
13131
13258
  cancelLabel: "Keep as is",
13132
13259
  confirmLabel: "Record on store",
@@ -13141,6 +13268,29 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
13141
13268
  unrecordedLegs(askingPay),
13142
13269
  askingPay.storeSettlement
13143
13270
  ) : null,
13271
+ askingReverse && inOpenSession(askingReverse) ? /* @__PURE__ */ jsx190(
13272
+ ConfirmDialog,
13273
+ {
13274
+ testID: `order-${askingReverse.id}-reverse-on-store-dialog`,
13275
+ tone: "destructive",
13276
+ open: true,
13277
+ onOpenChange: (open) => {
13278
+ if (!open) setAskingReverse(null);
13279
+ },
13280
+ title: `Give the money back and cancel order #${storeOrderLeft(askingReverse)?.reference ?? orderReference(askingReverse)}?`,
13281
+ description: [
13282
+ ...askingReverse.payments.map((leg) => `${legWording(leg.method, formatMoney2({ amount: leg.amountMinor, currency: askingReverse.currency }))}.`),
13283
+ "The store stops counting the payments it recorded and cancels the order.",
13284
+ "Hand the money back once this till shows the order cancelled. If you already gave it back, go ahead."
13285
+ ].join("\n"),
13286
+ cancelLabel: "Keep order",
13287
+ confirmLabel: "Give back and cancel",
13288
+ onConfirm: () => {
13289
+ setAskingReverse(null);
13290
+ void reverseOnStore(askingReverse);
13291
+ }
13292
+ }
13293
+ ) : null,
13144
13294
  footer
13145
13295
  ] });
13146
13296
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/components",
3
- "version": "5.1.0",
3
+ "version": "5.3.0",
4
4
  "type": "module",
5
5
  "description": "Universal POS UI components for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -29,9 +29,9 @@
29
29
  "directory": "packages/components"
30
30
  },
31
31
  "peerDependencies": {
32
- "@tallyui/core": "^5.1.0",
33
- "@tallyui/primitives": "^5.1.0",
34
- "@tallyui/theme": "^5.1.0",
32
+ "@tallyui/core": "^5.3.0",
33
+ "@tallyui/primitives": "^5.3.0",
34
+ "@tallyui/theme": "^5.3.0",
35
35
  "react": ">=18",
36
36
  "react-native": ">=0.74",
37
37
  "react-native-svg": ">=15"
@@ -40,13 +40,13 @@
40
40
  "class-variance-authority": "^0.7.1",
41
41
  "i18next": "^26.7.1",
42
42
  "react-i18next": "^17.1.12",
43
- "@tallyui/pos": "5.1.0"
43
+ "@tallyui/pos": "5.3.0"
44
44
  },
45
45
  "devDependencies": {
46
- "@tallyui/connector-medusa": "5.1.0",
47
- "@tallyui/connector-vendure": "5.1.0",
48
- "@tallyui/connector-woocommerce": "5.1.0",
49
- "@tallyui/mock-api": "5.1.0",
46
+ "@tallyui/connector-medusa": "5.3.0",
47
+ "@tallyui/connector-vendure": "5.3.0",
48
+ "@tallyui/connector-woocommerce": "5.3.0",
49
+ "@tallyui/mock-api": "5.3.0",
50
50
  "@types/react": ">=18",
51
51
  "react": "^19.2.4",
52
52
  "react-native-svg": "15.12.1",
@@ -1,14 +1,17 @@
1
- // Ported from WCPOS v2 packages/core/src/screens/main/pos/cart/cells/line-strip.tsx (press to open, Remove flies the row off; the Total peeks on hover; no swipe yet) and cells/edit-cart-item-button.tsx; MIT, WCPOS.
1
+ // Ported from WCPOS v2 packages/core/src/screens/main/pos/cart/cells/line-strip.tsx (press to open, Remove flies the row off; the Total peeks on hover; drag to open or fling off by v2's release rule (line-strip.geometry.ts); no remove-point haptic or Edit swallow) and cells/edit-cart-item-button.tsx; MIT, WCPOS.
2
2
  import { useRef, useState, type JSX, type ReactNode } from 'react';
3
- import { Animated, Platform, Pressable, View } from 'react-native';
3
+ import { Animated, PanResponder, Platform, Pressable, View } from 'react-native';
4
4
  import { Button, Text } from '../ui';
5
5
  import { ARM, EASE_EXIT, PANEL_SLIDE_OUT, PEEK, PEEK_SPRING } from '../lib/motion';
6
6
  import { useReducedMotion } from '../lib/use-reduced-motion';
7
+ import { releaseOutcome } from './line-strip-geometry';
8
+ // A release this long after the last move is not a flick: PanResponder's vx is the last move's speed and survives a pause (react-native-web PanResponder index.js:234-235).
9
+ const STILL_MS = 50;
7
10
 
8
- /** A cart row with v2's hidden strip under it: pressing the row's Total slides the row left onto a solid Edit and Remove. */
11
+ /** A cart row with v2's hidden strip under it: pressing the row's Total slides the row left onto a solid Remove, with Edit beside it when `onEdit` is given. */
9
12
  export function CartLineStrip({ name, onEdit, onRemove, children }: {
10
13
  name: string;
11
- onEdit: () => void;
14
+ onEdit?: () => void;
12
15
  // A returned string is a refusal, and the row comes back.
13
16
  onRemove: () => string | null | void;
14
17
  children: (wrapTotal: (content: ReactNode) => ReactNode) => ReactNode;
@@ -42,6 +45,35 @@ export function CartLineStrip({ name, onEdit, onRemove, children }: {
42
45
  settle(false);
43
46
  });
44
47
  };
48
+ // The pan handlers are created once: they read the widths, the drag's base and the latest settle and leave through this ref.
49
+ const drag = useRef({ row: 0, strip: 0, base: 0, claimed: 0, settle, leave });
50
+ Object.assign(drag.current, { row: rowWidth ?? 0, strip: stripWidth, settle, leave });
51
+ const clamp = (x: number) => Math.min(0, Math.max(-drag.current.row, x));
52
+ const pan = useRef(PanResponder.create({
53
+ onMoveShouldSetPanResponder: (_, { dx, dy }) => !leaving.current && drag.current.row > 0
54
+ && Math.abs(dx) > 8 && Math.abs(dx) > Math.abs(dy) && (drag.current.claimed = dx, true),
55
+ onPanResponderGrant: () => {
56
+ const { claimed } = drag.current;
57
+ // PanResponder zeroes dx at grant (react-native Libraries/Interaction/PanResponder.js onResponderGrant; react-native-web vendor PanResponder index.js:330), so the claimed distance joins the base.
58
+ drag.current.base = (opened.current ? -drag.current.strip : 0) + claimed;
59
+ drag.current.claimed = 0;
60
+ // The row's real place: the callback is synchronous on the JS driver (web). On the native driver it can land after the first moves, so a row
61
+ // grabbed mid-spring can jump once by the distance between the spring's target and its real place; the immediate base above is where it starts until then.
62
+ offset.stopAnimation((value) => { drag.current.base = value + claimed; });
63
+ },
64
+ onPanResponderMove: (_, { dx }) => offset.setValue(clamp(drag.current.base + dx)),
65
+ onPanResponderRelease: (event, { dx, vx, _accountsForMovesUpTo }) => {
66
+ drag.current.claimed = 0;
67
+ const { row, strip, base } = drag.current;
68
+ // gestureState.vx is px per ms, dx over DOM timeStamp ms (react-native-web dist/vendor/react-native/PanResponder/index.js:235); v2's rule takes px/s.
69
+ // react-native's GestureResponderEvent type leaves out touchHistory, which PanResponder itself reads (react-native-web PanResponder index.js:306).
70
+ const still = (event as unknown as { touchHistory: { mostRecentTimeStamp: number } }).touchHistory.mostRecentTimeStamp - _accountsForMovesUpTo > STILL_MS;
71
+ const outcome = releaseOutcome({ revealed: -clamp(base + dx), velocityX: still ? 0 : vx * 1000, rowWidth: row, stripWidth: strip });
72
+ if (outcome === 'remove') drag.current.leave();
73
+ else drag.current.settle(outcome === 'open');
74
+ },
75
+ onPanResponderTerminate: () => { drag.current.claimed = 0; drag.current.settle(opened.current); },
76
+ })).current;
45
77
  // v2's peek: only a closed, staying row, and only with reduced motion known to be off.
46
78
  const peek = (on: boolean) => {
47
79
  if (opened.current || leaving.current || reduced) return;
@@ -61,12 +93,12 @@ export function CartLineStrip({ name, onEdit, onRemove, children }: {
61
93
  style={rowWidth === undefined ? undefined : { width: rowWidth }} pointerEvents={open ? 'auto' : 'none'}
62
94
  accessibilityElementsHidden={!open} importantForAccessibility={open ? 'auto' : 'no-hide-descendants'} aria-hidden={!open}>
63
95
  <View testID="cart-line-strip-actions" className="flex-row items-stretch" onLayout={(event) => setStripWidth(event.nativeEvent.layout.width)}>
64
- <Button variant="default" testID="cart-line-edit" accessibilityLabel={`Edit ${name}`} className={block}
65
- onPress={() => { if (leaving.current) return; settle(false); onEdit(); }}><Text>Edit</Text></Button>
96
+ {onEdit ? <Button variant="default" testID="cart-line-edit" accessibilityLabel={`Edit ${name}`} className={block}
97
+ onPress={() => { if (leaving.current) return; settle(false); onEdit(); }}><Text>Edit</Text></Button> : null}
66
98
  <Button variant="destructive" testID="cart-line-remove" accessibilityLabel={`Remove ${name}`} className={block}
67
99
  onPress={leave}><Text>Remove</Text></Button>
68
100
  </View>
69
101
  </View>
70
- <Animated.View className="bg-background" style={{ transform: [{ translateX: shown }] }}>{children(wrapTotal)}</Animated.View>
102
+ <Animated.View {...pan.panHandlers} className="bg-background" style={{ transform: [{ translateX: shown }] }}>{children(wrapTotal)}</Animated.View>
71
103
  </View>;
72
104
  }
@@ -1,4 +1,4 @@
1
- import type { ReactNode } from 'react';
1
+ import { Children, cloneElement, type ReactElement, type ReactNode } from 'react';
2
2
  import { Pressable, View } from 'react-native';
3
3
  import { useFormatMoney, type Money } from '@tallyui/core';
4
4
  import { Image } from '@tallyui/primitives';
@@ -35,6 +35,9 @@ export interface CartLineProps extends Omit<HStackProps, 'children'> {
35
35
  picking?: boolean;
36
36
  locale?: string;
37
37
  className?: string;
38
+ /** The line strip's press target (`CartLineStrip`): wraps the Total cell's content, or with Total hidden the last visible
39
+ * cell's that holds no button of its own (not Quantity, nor Price while `priceSlot` is set). */
40
+ wrapTotal?: (content: ReactNode) => ReactNode;
38
41
  }
39
42
 
40
43
  // Name and attributes: WCPOS v2 packages/core/src/screens/main/pos/cart/cells/product-name.tsx; price:
@@ -48,14 +51,16 @@ export interface CartLineProps extends Omit<HStackProps, 'children'> {
48
51
  * ```
49
52
  */
50
53
  export function CartLine({ name, attributes, quantity, unitPrice, regularUnitPrice, lineTotal, showPrice = true, quantitySlot, priceSlot,
51
- columns, sku, imageUrl, onSplit, picking = false, locale, className, ...props }: CartLineProps) {
54
+ columns, sku, imageUrl, onSplit, picking = false, locale, className, wrapTotal, ...props }: CartLineProps) {
52
55
  const formatMoney = useFormatMoney();
53
56
  const t = useT();
54
57
  const options = Object.entries(attributes ?? {}).map(([key, value]) => `${key}: ${value}`).join(' · ');
55
58
  const sameCurrency = regularUnitPrice?.currency === unitPrice.currency;
56
59
  const regular = (columns?.price?.onSale ?? true) && regularUnitPrice && sameCurrency && regularUnitPrice.amount > unitPrice.amount
57
60
  ? formatMoney(regularUnitPrice, locale) ?? '—' : null;
58
- const cells: Record<ReturnType<typeof cartColumnSlots>[number], ReactNode> = {
61
+ const slots = cartColumnSlots(columns, { showPrice });
62
+ const target = slots.includes('total') ? 'total' : slots.filter((id) => id !== 'quantity' && !(id === 'price' && priceSlot)).pop();
63
+ const cells: Record<(typeof slots)[number], ReactElement<{ children?: ReactNode }>> = {
59
64
  fill: <View key="fill" className="flex-1" />,
60
65
  quantity: <View key="quantity" className={(picking ? CART_PICKING_QUANTITY : CART_COLUMNS.quantity).cell}>
61
66
  {quantitySlot ?? <Text className="text-sm tabular-nums">{quantity}</Text>}
@@ -90,7 +95,7 @@ export function CartLine({ name, attributes, quantity, unitPrice, regularUnitPri
90
95
  };
91
96
  return (
92
97
  <HStack space="none" className={cn('py-2.5', className)} {...props}>
93
- {cartColumnSlots(columns, { showPrice }).map((id) => cells[id])}
98
+ {slots.map((id) => wrapTotal && id === target ? cloneElement(cells[id], {}, wrapTotal(Children.toArray(cells[id].props.children))) : cells[id])}
94
99
  </HStack>
95
100
  );
96
101
  }
@@ -0,0 +1,28 @@
1
+ // Ported from WCPOS v2 packages/core/src/screens/main/pos/cart/cells/line-strip.geometry.ts (the release rule only); MIT, WCPOS.
2
+
3
+ /**
4
+ * The remove point as a share of the row. Material and Wear commit at a half; our strip
5
+ * already covers 42–47 % of a register column, so a half would leave almost no band between
6
+ * "open" and "remove".
7
+ */
8
+ export const REMOVE_SHARE = 0.6;
9
+ /** The band is never narrower than this past the open strip, whatever the row width. */
10
+ export const REMOVE_BAND = 56;
11
+ /** A flick this fast (px/s, leftwards) past the open strip removes without reaching the line. */
12
+ export const REMOVE_FLICK = 800;
13
+
14
+ /** How far the row has to travel before letting go removes it. */
15
+ export function removePoint(rowWidth: number, stripWidth: number): number {
16
+ return Math.max(stripWidth + REMOVE_BAND, Math.round(rowWidth * REMOVE_SHARE));
17
+ }
18
+
19
+ export type Release = 'remove' | 'open' | 'home';
20
+
21
+ /** `revealed` is how far left the row sits (a positive number), `velocityX` the gesture's, leftwards negative. */
22
+ export function releaseOutcome({ revealed, velocityX, rowWidth, stripWidth }: {
23
+ revealed: number; velocityX: number; rowWidth: number; stripWidth: number;
24
+ }): Release {
25
+ if (revealed >= removePoint(rowWidth, stripWidth)) return 'remove';
26
+ if (velocityX <= -REMOVE_FLICK && revealed > stripWidth) return 'remove';
27
+ return revealed > stripWidth / 2 ? 'open' : 'home';
28
+ }
@@ -1,6 +1,6 @@
1
1
  import { useRef, useState, type JSX } from 'react';
2
2
  import { Pressable, ScrollView, View } from 'react-native';
3
- import { useFormatMoney, useMoneyFormat, type MoneyFormat, type OrderRefundPayload } from '@tallyui/core';
3
+ import { useFormatMoney, useMoneyFormat, useOptionalConnector, type MoneyFormat, type OrderRefundPayload } from '@tallyui/core';
4
4
  import { priceRefund, refundableLines, type EarlierRefund, type RefundableOrderLine } from '@tallyui/pos';
5
5
  import { QuantityStepper } from '../input/quantity-stepper';
6
6
  import { errorText } from '../lib/error-text';
@@ -62,6 +62,7 @@ export function RefundForm({
62
62
  }: RefundFormProps): JSX.Element {
63
63
  const formatMoney = useFormatMoney();
64
64
  const format = useMoneyFormat();
65
+ const lineTotalsShrinkOnReturn = useOptionalConnector()?.lineTotalsShrinkOnReturn === true;
65
66
  const [quantities, setQuantities] = useState<Record<string, number>>({});
66
67
  const [restock, setRestock] = useState<Record<string, boolean>>({});
67
68
  const [shippingText, setShippingText] = useState('');
@@ -79,6 +80,12 @@ export function RefundForm({
79
80
  quantity: Math.min(quantities[orderLineId] ?? 0, refundableQuantity),
80
81
  restock: restock[orderLineId] ?? defaultRestock,
81
82
  })).filter(({ quantity }) => quantity > 0);
83
+ const missingSoldFigures = lineTotalsShrinkOnReturn && request.find(({ orderLineId, quantity }) => {
84
+ const index = lines.findIndex((line) => line.id === orderLineId);
85
+ const line = lines[index];
86
+ return (line.soldTotalMinor === undefined || line.soldTaxMinor === undefined)
87
+ && (quantity < line.quantity || available[index].refundedQuantity > 0);
88
+ });
82
89
  const priced = priceRefund(lines, refunds, request);
83
90
  const emptiesLines = priced.lines.length > 0 && available.every(({ orderLineId, refundableQuantity }) => (request.find((line) => line.orderLineId === orderLineId)?.quantity ?? 0) === refundableQuantity);
84
91
  const roundingShareMinor = emptiesLines ? cashRoundingMinor : 0;
@@ -90,6 +97,7 @@ export function RefundForm({
90
97
  const cashStep = destination === 'cash' && Number.isInteger(cashIncrementMinor) && cashIncrementMinor! > 1 && typeof totalMinor === 'number' && totalMinor > 0 && totalMinor % cashIncrementMinor! !== 0;
91
98
  const invalid = typeof shippingMinor === 'string' ? shippingMinor
92
99
  : typeof adjustmentMinor === 'string' ? adjustmentMinor
100
+ : missingSoldFigures ? `Update the store's plugin to refund part of ${lines.find((line) => line.id === missingSoldFigures.orderLineId)!.name}.`
93
101
  : shippingMinor > refundableShippingMinor ? `Shipping can be at most ${fmt(refundableShippingMinor)}.`
94
102
  : priced.lines.length === 0 && shippingMinor === 0 && adjustmentMinor === 0 ? 'Choose something to refund.'
95
103
  : totalMinor! <= 0 ? 'The refund total must be more than 0.'
package/src/sale/cart.tsx CHANGED
@@ -119,7 +119,7 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
119
119
  | { type: 'edit-charge'; kind: 'fees' | 'shipping'; id: string } | null>(null);
120
120
  // The picker's bill is read-only: no form shows, nor any control that opens one.
121
121
  const form = picker ? null : openForm;
122
- const ChargeStrip = picker ? ReadOnlyStrip : CartLineStrip;
122
+ const Strip = picker ? ReadOnlyStrip : CartLineStrip;
123
123
  const chargesOffered = (sale.capabilities?.orderCreate ?? 0) >= 5;
124
124
  // #1115: front desk 2026-11-20, a Woo store at order.create 6+ takes a No tax shipping line (stock 2.0.4 proof F2).
125
125
  const shippingNoTax = (sale.capabilities?.orderCreate ?? 0) >= 6;
@@ -143,11 +143,16 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
143
143
  if (refused === null) setPriceError((now) => (now?.lineId === line.id ? null : now));
144
144
  return refused;
145
145
  };
146
+ // sale.remove returns nothing, so a refused remove (editRefusal, which sets sale.error) is read back from the builder, and the strip brings the row back.
147
+ const removeLine = (id: string) => {
148
+ sale.remove(id);
149
+ return sale.removal('line', id) ? 'refused' : null;
150
+ };
146
151
  const unpaid = (line: typeof order.lineItems[number]) => line.quantity - (picker?.paid[line.id] ?? 0);
147
152
  const pickable = (line: typeof order.lineItems[number]) => Number.isInteger(line.quantity) && line.quantity > 0
148
153
  && display(line.id).amountMinor >= 0 && unpaid(line) > 0;
149
154
  const renderItem = (line: typeof order.lineItems[number]) => <>
150
- <CartLine name={line.name} attributes={line.attributes} quantity={line.quantity} unitPrice={money(line.unitPriceMinor)}
155
+ <Strip name={line.name} onRemove={() => removeLine(line.id)}>{(wrapTotal) => <CartLine name={line.name} attributes={line.attributes} quantity={line.quantity} unitPrice={money(line.unitPriceMinor)}
151
156
  regularUnitPrice={line.regularUnitPriceMinor === undefined ? undefined : money(line.regularUnitPriceMinor)}
152
157
  lineTotal={money(display(line.id).amountMinor)} showPrice={showPrice}
153
158
  columns={columns} sku={line.sku} imageUrl={line.imageUrl} onSplit={picker ? undefined : () => split(line.id)} picking={picker !== undefined}
@@ -162,7 +167,8 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
162
167
  priceSlot={pricePopover && !picker ? <LinePopover kind="price" lineName={line.name} currency={order.currency} value={line.unitPriceMinor}
163
168
  regularValue={line.regularUnitPriceMinor} actions={[{ id: 'discount', label: 'Discount', onPress: () => setForm({ type: 'discount', lineId: line.id }) }]}
164
169
  quickDiscounts={quickDiscounts} textClassName="text-right text-muted-foreground" onApply={(amount) => applyPrice(line, amount)}
165
- commit={lineCommit} onCloseRefused={(message) => setPriceError({ lineId: line.id, message })} /> : undefined} />
170
+ commit={lineCommit} onCloseRefused={(message) => setPriceError({ lineId: line.id, message })} /> : undefined} wrapTotal={wrapTotal} />}
171
+ </Strip>
166
172
  {splitError?.lineId === line.id ? <Text accessibilityRole="alert" testID="cart-line-split-error"
167
173
  className="px-3 text-sm text-destructive">{splitError.message}</Text> : null}
168
174
  {priceError?.lineId === line.id ? <Text accessibilityRole="alert" testID="cart-line-price-error"
@@ -201,12 +207,12 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
201
207
  {(['fees', 'shipping'] as const).map((kind) => <MotionRows key={kind} items={order[kind] ?? []} keyOf={(charge) => charge.id}
202
208
  pulseKey={() => 0} identity={order.id} renderItem={(charge, index) =>
203
209
  <View testID={`cart-${kind === 'fees' ? 'fee' : 'shipping'}-${index}`}>
204
- <ChargeStrip name={charge.name} onEdit={() => setForm({ type: 'edit-charge', kind, id: charge.id })}
210
+ <Strip name={charge.name} onEdit={() => setForm({ type: 'edit-charge', kind, id: charge.id })}
205
211
  onRemove={() => kind === 'fees' ? sale.removeFee(charge.id) : sale.removeShipping(charge.id)}>
206
212
  {(wrapTotal) => <CartChargeLine name={charge.name} price={money(charge.amountMinor)} percent={charge.percent}
207
213
  total={money(order.display[kind]!.find((row) => row.id === charge.id)!.amountMinor)}
208
214
  showPrice={showPrice} columns={columns} picking={picker !== undefined} testID="cart-charge-line" wrapTotal={wrapTotal} />}
209
- </ChargeStrip>
215
+ </Strip>
210
216
  {form?.type === 'edit-charge' && form.kind === kind && form.id === charge.id ? <ChargeForm key={charge.id}
211
217
  kind={kind === 'fees' ? 'fee' : 'shipping'} initial={charge} currency={order.currency} lineTax={sale.capabilities?.lineTax}
212
218
  allowPercent pricesIncludeTax={chargeTaxSwitch ? order.pricesIncludeTax : undefined}
@@ -260,7 +266,7 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
260
266
  </View>;
261
267
  }
262
268
 
263
- /** A fee or shipping row on the picker's read-only bill: the row alone, no Edit or Remove strip. */
269
+ /** A product, fee or shipping row on the picker's read-only bill: the row alone, no Edit or Remove strip. */
264
270
  const ReadOnlyStrip = ({ children }: Parameters<typeof CartLineStrip>[0]) => <>{children((content) => content)}</>;
265
271
 
266
272
  /** WCPOS v2's `− n of unpaid +` stepper (tender/unit-stepper.tsx), the one Cart's `picker` draws in each pickable line's
@@ -1,7 +1,7 @@
1
1
  import { useEffect, useId, useRef, useState, type ReactNode } from 'react';
2
2
  import { Pressable, ScrollView, Text, View } from 'react-native';
3
- import { useFormatMoney, knownWarnings, type SettleOutcome } from '@tallyui/core';
4
- import { canCancelOnStore, canPayRestOnStore, extrasNotSent, isRequeueableOrder, needsAdminReasonOf, needsAttention, noteDelivery, refundDueOf, REOPENABLE_CODES, settledOnStore, storeOrderLeft, unrecordedLegs, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, type OutboxState, type PosOrder } from '@tallyui/pos';
3
+ import { useFormatMoney, useOptionalConnector, knownWarnings, type SettleOutcome } from '@tallyui/core';
4
+ import { canCancelOnStore, canPayRestOnStore, canReverseOnStore, extrasNotSent, isRequeueableOrder, needsAdminReasonOf, needsAttention, noteDelivery, refundDueOf, REOPENABLE_CODES, settledOnStore, storeOrderLeft, TILL_SESSION_CLOSED, tillPayments, unrecordedLegs, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, type OutboxState, type PosOrder } from '@tallyui/pos';
5
5
  import { META_NOT_SENT, NOTE_NOT_SENT, orderReference, TAX_IDS_NOT_SENT } from './order-reference';
6
6
  import { sinceText } from './since-text';
7
7
  import { ConfirmDialog } from '../ui/confirm-dialog';
@@ -37,6 +37,11 @@ const REFUSAL_SENTENCES = new Map([
37
37
  const refusalSentence = (code: string | undefined) => REFUSAL_SENTENCES.get(code ?? '') ?? REFUSAL_SENTENCES.get('platform_error')!;
38
38
  /** Pay the rest on store's dialog (#1101 slice 3): the front desk's wording until slice 4 handles money given back. */
39
39
  const GIVE_BACK = "If the money was given back, do not record it; a manager must check the order in the store's admin.";
40
+ const GIVE_BACK_INSTEAD = 'If the money was given back, use Give back and cancel instead.';
41
+ const GIVE = 'Give back any of this you have not already given back.';
42
+ const CLOSED_SESSION_NOTICE = "Taken in a session that has closed: a manager must settle this sale in the store's admin.";
43
+ const legLabel = (method: string) => (method === 'cash' ? 'Cash' : 'Card');
44
+ const legWording = (method: string, amount: string | undefined) => `${legLabel(method)} ${amount}: ${method === 'cash' ? 'hand it back from the drawer' : 'give it back on the card terminal'}`;
40
45
  const methodLabel = (method: string) => (method === 'cash' ? 'Cash' : 'Card terminal');
41
46
  const REOPEN_AGAIN_SENTENCE = "This order was changed in the online store after it was reopened here, so your change wasn't sent. Reopen the order and make the change again.";
42
47
 
@@ -74,34 +79,51 @@ export function OrderSyncNotices({ order, stuck, children }: OrderSyncNoticesPro
74
79
  // #1101: where the till's cancel, or pay of the rest, of the order the refused sale left on the store stands. Done, gone
75
80
  // and changed say it in place of the "left" line; refused and sending add to it. The store's code and message never show (#269).
76
81
  const kind = order.storeSettlement?.kind;
77
- const settlement = order.syncStatus === 'rejected' && (kind === 'cancel' || kind === 'pay') ? order.storeSettlement : undefined;
82
+ const settlement = order.syncStatus === 'rejected' && (kind === 'cancel' || kind === 'pay' || (kind === 'reverse' && order.storeSettlement?.legs?.length)) ? order.storeSettlement : undefined;
78
83
  const reference = left?.reference ?? orderReference(order);
79
84
  const money = (amount: number) => formatMoney({ amount, currency: order.currency });
80
85
  const sum = (legs: { amountMinor: number }[]) => legs.reduce((total, leg) => total + leg.amountMinor, 0);
81
86
  const paidThere = settlement?.capturedMinor ? `: ${money(settlement.capturedMinor)} is paid there` : '';
82
87
  // A pay's R: what the store had recorded at the refusal, plus each leg this till has recorded since.
83
88
  const recorded = money((left?.recordedMinor ?? 0) + sum(settlement?.payments?.filter((payment) => payment.done) ?? []));
84
- const cashTaken = sum(order.payments.filter((payment) => payment.method === 'cash'));
85
89
  // What this till has recorded on the stored pay, on this press or an earlier one: true in every state.
86
90
  const doneMinor = sum(settlement?.payments?.filter((payment) => payment.done) ?? []);
87
91
  const nothing = doneMinor > 0 ? `${money(doneMinor)} was recorded from this till.` : 'Nothing was recorded from this till.';
88
- const settledText = settlement?.kind === 'pay'
92
+ let settledText = settlement?.kind === 'pay'
89
93
  ? settlement.state === 'done' ? `Order #${reference} is paid on the store.`
90
94
  : settlement.state === 'gone' ? `Order #${reference} is not on the store any more; ${recorded} was recorded on it.`
91
95
  : settlement.state !== 'changed' ? undefined
92
96
  : settlement.storeStatus === 'completed' ? `Order #${reference} is already paid on the store. ${nothing}`
93
97
  : `Order #${reference} changed on the store${paidThere}. ${nothing} Check it in the store's admin.`
94
- : settlement?.state === 'done' ? `Order #${reference} was cancelled on the store.${cashTaken
95
- ? ` If you gave back the ${money(cashTaken)} cash taken on this till, record it as a pay-out.` : ''}`
98
+ : settlement?.state === 'done' ? `Order #${reference} was cancelled on the store.${order.payments.length || kind === 'reverse'
99
+ ? ` The till took: ${order.payments.map((leg) => legWording(leg.method, money(leg.amountMinor))).join('; ')}. ${GIVE}` : ''}`
96
100
  : settlement?.state === 'gone' ? `Order #${reference} was removed on the store.`
97
101
  : settlement?.state === 'changed' ? `Order #${reference} changed on the store${paidThere}. Nothing was cancelled from this till. Check it in the store's admin.`
98
102
  : undefined;
99
103
  const pay = settlement?.kind === 'pay';
100
- const addedText = settlement?.state === 'refused' ? pay
104
+ let addedText = settlement?.state === 'refused' ? pay
101
105
  ? `The store did not record the rest of order #${reference}: ${recorded} of ${money(order.totalMinor)} is recorded there. Check it in the store's admin.`
102
106
  : `The store did not cancel order #${reference}. Check it in the store's admin.`
103
107
  : settlement?.state === 'sending' ? pay ? `Recording the rest of order #${reference} on the store is not finished.`
104
108
  : `Cancelling order #${reference} on the store is not finished.` : undefined;
109
+ if (settlement?.kind === 'reverse' && settlement.state !== 'done' && settlement.legs) {
110
+ const legs = settlement.legs.flatMap((leg) => {
111
+ const payment = order.payments.find(({ id }) => id === leg.paymentId);
112
+ return payment ? [{ ...payment, done: leg.done }] : [];
113
+ });
114
+ const taken = legs.filter((leg) => leg.done).map((leg) => legWording(leg.method, money(leg.amountMinor))).join('; ');
115
+ const still = legs.filter((leg) => !leg.done).map((leg) => `${legLabel(leg.method)} ${money(leg.amountMinor)}`).join('; ');
116
+ const hasDone = settlement.legs.some((leg) => leg.done);
117
+ const subject = `Order #${reference}`;
118
+ settledText = undefined;
119
+ addedText = undefined;
120
+ if (settlement.state === 'gone') settledText = `${subject} is not on the store any more.${taken ? ` The store had taken off: ${taken}. ${GIVE}` : ''} Check it in the store's admin.`;
121
+ else if (settlement.state === 'sending') addedText = `Cancelling order #${reference} on the store is not finished.${taken ? ` The store has taken off: ${taken}. ${GIVE}` : ''}${still ? ` Not confirmed taken off yet: ${still}. Keep that until this till shows the order cancelled.` : ''}`;
122
+ else if (hasDone) addedText = `${subject} was not cancelled on the store.${taken ? ` The store has taken off: ${taken}. ${GIVE}` : ''}${still ? ` Still paid there: ${still}. Keep that; a manager must check it in the store's admin.` : ''}`;
123
+ else if (settlement.state === 'refused') addedText = `The store did not cancel order #${reference}. Check it in the store's admin.`;
124
+ else settledText = `${subject} changed on the store${paidThere}. Nothing was taken off it or cancelled from this till. Check it in the store's admin.`;
125
+ }
126
+ if ((kind === 'cancel' || kind === 'reverse') && order.storeSettlement?.code === TILL_SESSION_CLOSED) { settledText = undefined; addedText = CLOSED_SESSION_NOTICE; }
105
127
  // A pay gone with money recorded on the store is not settled (`settledOnStore`): it stays a destructive line.
106
128
  const settled = !!settlement && settledOnStore(order);
107
129
  return <>
@@ -164,6 +186,7 @@ export function OrderSyncNotices({ order, stuck, children }: OrderSyncNoticesPro
164
186
  * reopened and with no store order: the app wires `reopenRefusedOrder`. When it refuses `coupon_carry_inexact` with a
165
187
  * `toCollectMinor`, the row offers "Reopen without the coupon", which calls it again with `{ withoutCoupons: true }`.
166
188
  * `onResume` adds Resume to a reopened row; the app resumes the parked sale, whose draft id is the order's id.
189
+ * `openSessionId` must match the session of every till payment to offer or finish either store cancellation action.
167
190
  * `onCancelOnStore` adds "Cancel order on store" to a Needs attention row whose refused sale left an unpaid order on the
168
191
  * store (`canCancelOnStore`, #1101), asked in a confirm dialog first: the app wires `useOrderOutbox`'s `cancelOnStore`.
169
192
  * A cancel still `sending` is finished with no dialog. With it, such a row offers no Retry, except an `insufficient_stock`
@@ -172,17 +195,20 @@ export function OrderSyncNotices({ order, stuck, children }: OrderSyncNoticesPro
172
195
  * the store (`canPayRestOnStore`, #1101 slice 3), asked in a confirm dialog naming each leg to record (no money is taken):
173
196
  * the app wires `useOrderOutbox`'s `payRestOnStore`. A pay still `sending` is finished with no dialog. With it, a row
174
197
  * with money recorded on the store offers no Retry. */
175
- export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, footer, stuck, history, onOpen, onReopen, onResume, onCancelOnStore, onPayRestOnStore }: {
198
+ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, footer, stuck, history, onOpen, onReopen, onResume, onCancelOnStore, onPayRestOnStore, onReverseOnStore, openSessionId }: {
176
199
  orders: PosOrder[]; onRetry(orderIds: string[]): Promise<number>; formatDate?: (iso: string) => string; footer?: ReactNode;
177
200
  stuck?: OutboxState['stuck'];
178
201
  history?: OrderHistoryRow[];
179
202
  onOpen?: (row: PosOrder | OrderHistoryRow) => void;
180
203
  onReopen?: (order: PosOrder, options?: { withoutCoupons: true }) => Promise<void>;
181
204
  onResume?: (order: PosOrder) => void;
205
+ openSessionId?: string;
182
206
  onCancelOnStore?: (order: PosOrder) => Promise<SettleOutcome | { kind: 'not_offered' }>;
183
207
  onPayRestOnStore?: (order: PosOrder) => Promise<SettleOutcome | { kind: 'not_offered' }>;
208
+ onReverseOnStore?: (order: PosOrder) => Promise<SettleOutcome | { kind: 'not_offered' }>;
184
209
  }) {
185
210
  const formatMoney = useFormatMoney();
211
+ const discountsAreTaxedRows = useOptionalConnector()?.discountsAreTaxedRows === true;
186
212
  const hintId = useId();
187
213
  const retrying = useRef(new Set<string>());
188
214
  const [retryingIds, setRetryingIds] = useState(new Set<string>());
@@ -255,6 +281,26 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
255
281
  paying.current.delete(order.id);
256
282
  }
257
283
  }
284
+ const reversing = useRef(new Set<string>());
285
+ const [reverses, setReverses] = useState(new Map<string, 'busy' | 'failed'>());
286
+ const [askingReverse, setAskingReverse] = useState<PosOrder | null>(null);
287
+ async function reverseOnStore(order: PosOrder) {
288
+ if (!onReverseOnStore || reversing.current.has(order.id)) return;
289
+ reversing.current.add(order.id);
290
+ setReverses((current) => new Map(current).set(order.id, 'busy'));
291
+ let failed = false;
292
+ try {
293
+ failed = (await onReverseOnStore(order)).kind === 'retry';
294
+ } catch { failed = true; } finally {
295
+ reversing.current.delete(order.id);
296
+ setReverses((current) => {
297
+ const next = new Map(current);
298
+ if (failed) next.set(order.id, 'failed'); else next.delete(order.id);
299
+ return next;
300
+ });
301
+ }
302
+ }
303
+ const inOpenSession = (order: PosOrder) => openSessionId !== undefined && tillPayments(order.payments).every((payment) => (payment.sessionId ?? order.sessionId) === openSessionId);
258
304
  const [expanded, setExpanded] = useState(new Set<string>());
259
305
  useEffect(() => {
260
306
  for (const id of retrying.current) {
@@ -271,7 +317,7 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
271
317
  return bTime - aTime;
272
318
  });
273
319
  return <ScrollView className="flex-1 bg-background p-4">
274
- {[{ title: 'Needs attention', orders: needsAttention(orders, { stuckCommandIds: stuck?.commandIds }) }, { title: 'Recent', orders: recent }].filter((section) => section.title === 'Recent' || section.orders.length > 0).map((section, sectionIndex) => (
320
+ {[{ title: 'Needs attention', orders: needsAttention(orders, { stuckCommandIds: stuck?.commandIds, discountsAreTaxedRows }) }, { title: 'Recent', orders: recent }].filter((section) => section.title === 'Recent' || section.orders.length > 0).map((section, sectionIndex) => (
275
321
  <View key={section.title} className="mb-6 gap-3">
276
322
  <Text accessibilityRole="header" className="text-xl font-semibold text-foreground">{section.title}</Text>
277
323
  {section.title === 'Recent' && orders.length === 0 && shown.length === 0 ? <Text testID="orders-empty" className="text-muted-foreground">No sales yet. Completed sales appear here.</Text> : null}
@@ -296,7 +342,7 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
296
342
  const reopenable = attention && !!onReopen && order.syncStatus === 'rejected' && REOPENABLE_CODES.includes(order.error?.code ?? '')
297
343
  && order.storeOrderId === undefined && order.reopenedAt === undefined;
298
344
  const reopenState = reopens.get(order.id);
299
- const cancellable = attention && !!onCancelOnStore && canCancelOnStore(order);
345
+ const cancelOffered = attention && !!onCancelOnStore && canCancelOnStore(order);
300
346
  const cancelState = cancels.get(order.id);
301
347
  const finishing = order.storeSettlement?.kind === 'cancel' && order.storeSettlement.state === 'sending';
302
348
  // #1101: with the cancel wired, an unpaid order left on the store is cancelled rather than resent, except a stock refusal.
@@ -305,7 +351,11 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
305
351
  const payState = pays.get(order.id);
306
352
  const finishingPay = order.storeSettlement?.kind === 'pay' && order.storeSettlement.state === 'sending';
307
353
  // #1101 slice 3: with the pay wired, a part-paid order left on the store has its rest recorded, never resent.
308
- const retryLabel = onPayRestOnStore && left && left.recordedMinor > 0 ? undefined : onCancelOnStore && left?.recordedMinor === 0
354
+ const reverseOffered = attention && !!onReverseOnStore && canReverseOnStore(order);
355
+ const closedSession = (cancelOffered || reverseOffered) && !inOpenSession(order);
356
+ const cancellable = cancelOffered && !closedSession, reversible = reverseOffered && !closedSession;
357
+ const reverseState = reverses.get(order.id), finishingReverse = order.storeSettlement?.kind === 'reverse' && order.storeSettlement.state === 'sending';
358
+ const retryLabel = (onPayRestOnStore || onReverseOnStore) && left && left.recordedMinor > 0 ? undefined : onCancelOnStore && left?.recordedMinor === 0
309
359
  ? order.error?.code === 'insufficient_stock' ? 'Try the payment again' : undefined : 'Retry';
310
360
  return (
311
361
  <View key={order.id} className="gap-1 rounded-md border border-border bg-card p-3">
@@ -349,6 +399,7 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
349
399
  }} className="rounded-md bg-primary px-4 py-2">
350
400
  <Text className="text-center font-semibold text-primary-foreground">{retryLabel}</Text>
351
401
  </Pressable> : null}
402
+ {closedSession ? <Text className="text-muted-foreground">{CLOSED_SESSION_NOTICE}</Text> : null}
352
403
  {cancellable ? <Pressable accessibilityRole="button" testID={`order-${order.id}-cancel-on-store`} disabled={cancelState === 'busy'}
353
404
  onPress={() => {
354
405
  if (cancelling.current.has(order.id)) return;
@@ -371,6 +422,11 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
371
422
  </Pressable> : null}
372
423
  {payable && (payState === 'failed' || payState === 'unfinished') ? <Text testID={`order-${order.id}-pay-rest-on-store-error`} className="text-muted-foreground">
373
424
  {payState === 'unfinished' ? "The store has not finished this order yet. Try again, or check it in the store's admin." : 'Could not reach the store. Try again.'}</Text> : null}
425
+ {reversible ? <Pressable accessibilityRole="button" testID={`order-${order.id}-reverse-on-store`} disabled={reverseState === 'busy'}
426
+ onPress={() => { if (finishingReverse) void reverseOnStore(order); else setAskingReverse(order); }} className="rounded-md border border-border px-4 py-2">
427
+ <Text className="text-center font-semibold text-foreground">{reverseState === 'busy' ? 'Cancelling on store…' : finishingReverse ? 'Finish cancelling on store' : 'Give back and cancel'}</Text>
428
+ </Pressable> : null}
429
+ {reversible && reverseState === 'failed' ? <Text testID={`order-${order.id}-reverse-on-store-error`} className="text-muted-foreground">Could not reach the store. Try again.</Text> : null}
374
430
  {/* Reopen needs a reopenable code, which Retry never resends (NOT_REQUEUEABLE), so the two never show together. */}
375
431
  {attention && order.reopenedAt !== undefined ? <>
376
432
  <Text testID={`order-${order.id}-reopened`} className="text-muted-foreground">Reopened as a parked sale.</Text>
@@ -400,7 +456,7 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
400
456
  })}
401
457
  </View>
402
458
  ))}
403
- {askingCancel ? ((reference) => <ConfirmDialog testID={`order-${askingCancel.id}-cancel-on-store-dialog`} tone="destructive" open
459
+ {askingCancel && inOpenSession(askingCancel) ? ((reference) => <ConfirmDialog testID={`order-${askingCancel.id}-cancel-on-store-dialog`} tone="destructive" open
404
460
  onOpenChange={(open) => { if (!open) setAskingCancel(null); }} title={`Cancel order #${reference} on the store?`}
405
461
  description={`Order #${reference} is waiting on the online store with nothing paid. This cancels it there. The payments taken on this till stay as they are.`}
406
462
  cancelLabel="Keep order" confirmLabel="Cancel order on store"
@@ -409,11 +465,16 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
409
465
  onOpenChange={(open) => { if (!open) setAskingPay(null); }} title={`Record the rest of order #${reference} on the store?`}
410
466
  description={[...legs.filter((_leg, index) => !(stored?.kind === 'pay' && stored.payments?.length === legs.length && stored.payments[index].done))
411
467
  .map((leg) => `${methodLabel(leg.method)} ${formatMoney({ amount: leg.amountMinor, currency: askingPay.currency })}, already taken on this till.`),
412
- 'No money is taken now.', GIVE_BACK].join('\n')}
468
+ 'No money is taken now.', onReverseOnStore && canReverseOnStore(askingPay) && inOpenSession(askingPay) ? GIVE_BACK_INSTEAD : GIVE_BACK].join('\n')}
413
469
  cancelLabel="Keep as is" confirmLabel="Record on store"
414
470
  onConfirm={() => { setAskingPay(null); void payRestOnStore(askingPay); }} />)(storeOrderLeft(askingPay)?.reference ?? orderReference(askingPay),
415
471
  // Only the legs still to record: the stored pay is index-aligned with them when the lengths match, as the outbox reuses it.
416
472
  unrecordedLegs(askingPay), askingPay.storeSettlement) : null}
473
+ {askingReverse && inOpenSession(askingReverse) ? <ConfirmDialog testID={`order-${askingReverse.id}-reverse-on-store-dialog`} tone="destructive" open
474
+ onOpenChange={(open) => { if (!open) setAskingReverse(null); }} title={`Give the money back and cancel order #${storeOrderLeft(askingReverse)?.reference ?? orderReference(askingReverse)}?`}
475
+ description={[...askingReverse.payments.map((leg) => `${legWording(leg.method, formatMoney({ amount: leg.amountMinor, currency: askingReverse.currency }))}.`),
476
+ 'The store stops counting the payments it recorded and cancels the order.', 'Hand the money back once this till shows the order cancelled. If you already gave it back, go ahead.'].join('\n')}
477
+ cancelLabel="Keep order" confirmLabel="Give back and cancel" onConfirm={() => { setAskingReverse(null); void reverseOnStore(askingReverse); }} /> : null}
417
478
  {footer}
418
479
  </ScrollView>;
419
480
  }