@tallyui/components 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.d.ts CHANGED
@@ -11,7 +11,7 @@ import { Separator as Separator$1, Label as Label$1, Tabs as Tabs$1, Dialog as D
11
11
  export { TextClassContext } from '@tallyui/primitives';
12
12
  import { StoreDay, DayRange, CatalogueView, ProductSortValue, ProductSort, ViewfinderStatus, CameraDecoder, RefundableOrderLine, EarlierRefund, OrderFilterValue, useRegisterSession, RegisterSession, MovementType, ApprovalNeeded, SwitchKind, SwitchWarnings, HandoverSlipData, AppSettings, useAppSettings, PairingPhase, PairingError, TillDisplayStatus, TillDisplayEntry, PrinterProfile, TraceAnalysis, TaxDerivation, useSale, Payment, TenderState, TenderAction, AppliedDiscount, Discount, CatalogueEntry, CatalogueViewState, CartQuantityLine, TileFields, CatalogueGridColumns, SentOrder, PosOrder, ReceiptData, OutboxState, ParkedOrderSummary, OpenSale, DisplayState, DisplayClientPhase, SalesFigures, DatePreset } from '@tallyui/pos';
13
13
  import { ScaleOverride, ScaleVariables, ScaleStep, Pointer, TypeSetId, ThemeFontFamily, ThemeType } from '@tallyui/theme';
14
- import { ProductTraits, TraitContext, VariantOptionGroup, VariantSummary, Money, CustomerTraits, CustomerAddress, Customer, CustomerInput, CustomerPatch, OrderRefundPayload, OrderFilterField, PaymentKind, woocommerceTax, ReceiptTemplate, PaymentMethodDescriptor, MoneyFormat, ProductCategory, SyncNotice, StoreSettingsChoices, StoreSettingsChoice, ConnectivityState } from '@tallyui/core';
14
+ import { ProductTraits, TraitContext, VariantOptionGroup, VariantSummary, Money, CustomerTraits, CustomerAddress, Customer, CustomerInput, CustomerPatch, OrderRefundPayload, OrderFilterField, PaymentKind, woocommerceTax, ReceiptTemplate, PaymentMethodDescriptor, MoneyFormat, ProductCategory, SyncNotice, SettleOutcome, StoreSettingsChoices, StoreSettingsChoice, ConnectivityState } from '@tallyui/core';
15
15
  import { TFunction } from 'i18next';
16
16
 
17
17
  declare const textVariants: (props?: ({
@@ -2608,9 +2608,15 @@ declare function TenderLedger({ sale, methods, closing, confirmVoid, beforeVoid,
2608
2608
  }): JSX.Element | null;
2609
2609
 
2610
2610
  /** `taxLabel` names each tax row; VAT isn't universal, so a platform passes its own (medusapos passes `VAT ${rate}%`). */
2611
- declare function Cart({ sale, taxLabel, canEditPrice, onPriceChange, quickDiscounts, taxClasses, afterSubtotal, showTotal, couponDiscountMinor, orderActions, orderDiscountChips, checkout, noteSheet, tenderLedger, picker, lineEditor, lineCommit, columns, chargeTaxSwitch, emptyIcon, emptyText }: {
2611
+ declare function Cart({ sale, taxLabel, taxDisplay, canEditPrice, onPriceChange, quickDiscounts, taxClasses, afterSubtotal, showTotal, couponDiscountMinor, orderActions, orderDiscountChips, checkout, noteSheet, tenderLedger, picker, lineEditor, lineCommit, columns, chargeTaxSwitch, emptyIcon, emptyText }: {
2612
2612
  sale: ReturnType<typeof useSale>;
2613
- taxLabel?: (ratePpm: number) => string;
2613
+ /** Names each tax row from its rate. The second argument carries the row's own tax `code` (when it has one) and `ratePpm`, so two rates with the same percentage can be told apart. */
2614
+ taxLabel?: (ratePpm: number, rate: {
2615
+ code?: string;
2616
+ ratePpm: number;
2617
+ }) => string;
2618
+ /** `itemized` (default): one row per rate, under `taxLabel`. `single`: one "Total Tax" row with the order's total tax, drawn only when that is not 0. */
2619
+ taxDisplay?: 'itemized' | 'single';
2614
2620
  taxClasses?: ReadonlyArray<{
2615
2621
  id: string;
2616
2622
  label: string;
@@ -3294,8 +3300,17 @@ declare function OrderSyncNotices({ order, stuck, children }: OrderSyncNoticesPr
3294
3300
  * `onReopen` adds Reopen to a Needs attention row the store refused with a reopenable code (`REOPENABLE_CODES`), not yet
3295
3301
  * reopened and with no store order: the app wires `reopenRefusedOrder`. When it refuses `coupon_carry_inexact` with a
3296
3302
  * `toCollectMinor`, the row offers "Reopen without the coupon", which calls it again with `{ withoutCoupons: true }`.
3297
- * `onResume` adds Resume to a reopened row; the app resumes the parked sale, whose draft id is the order's id. */
3298
- declare function OrdersList({ orders, onRetry, formatDate, footer, stuck, history, onOpen, onReopen, onResume }: {
3303
+ * `onResume` adds Resume to a reopened row; the app resumes the parked sale, whose draft id is the order's id.
3304
+ * `openSessionId` must match the session of every till payment to offer or finish either store cancellation action.
3305
+ * `onCancelOnStore` adds "Cancel order on store" to a Needs attention row whose refused sale left an unpaid order on the
3306
+ * store (`canCancelOnStore`, #1101), asked in a confirm dialog first: the app wires `useOrderOutbox`'s `cancelOnStore`.
3307
+ * A cancel still `sending` is finished with no dialog. With it, such a row offers no Retry, except an `insufficient_stock`
3308
+ * refusal's, which reads "Try the payment again".
3309
+ * `onPayRestOnStore` adds "Pay the rest on store" to a Needs attention row whose refused sale left a part-paid order on
3310
+ * the store (`canPayRestOnStore`, #1101 slice 3), asked in a confirm dialog naming each leg to record (no money is taken):
3311
+ * the app wires `useOrderOutbox`'s `payRestOnStore`. A pay still `sending` is finished with no dialog. With it, a row
3312
+ * with money recorded on the store offers no Retry. */
3313
+ declare function OrdersList({ orders, onRetry, formatDate, footer, stuck, history, onOpen, onReopen, onResume, onCancelOnStore, onPayRestOnStore, onReverseOnStore, openSessionId }: {
3299
3314
  orders: PosOrder[];
3300
3315
  onRetry(orderIds: string[]): Promise<number>;
3301
3316
  formatDate?: (iso: string) => string;
@@ -3307,6 +3322,16 @@ declare function OrdersList({ orders, onRetry, formatDate, footer, stuck, histor
3307
3322
  withoutCoupons: true;
3308
3323
  }) => Promise<void>;
3309
3324
  onResume?: (order: PosOrder) => void;
3325
+ openSessionId?: string;
3326
+ onCancelOnStore?: (order: PosOrder) => Promise<SettleOutcome | {
3327
+ kind: 'not_offered';
3328
+ }>;
3329
+ onPayRestOnStore?: (order: PosOrder) => Promise<SettleOutcome | {
3330
+ kind: 'not_offered';
3331
+ }>;
3332
+ onReverseOnStore?: (order: PosOrder) => Promise<SettleOutcome | {
3333
+ kind: 'not_offered';
3334
+ }>;
3310
3335
  }): react_jsx_runtime.JSX.Element;
3311
3336
 
3312
3337
  /** 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
@@ -6256,7 +6256,7 @@ function OrderDetail({
6256
6256
  // src/order/refund-form.tsx
6257
6257
  import { useRef as useRef15, useState as useState31 } from "react";
6258
6258
  import { Pressable as Pressable34, ScrollView as ScrollView13, View as View71 } from "react-native";
6259
- import { useFormatMoney as useFormatMoney8, useMoneyFormat as useMoneyFormat3 } from "@tallyui/core";
6259
+ import { useFormatMoney as useFormatMoney8, useMoneyFormat as useMoneyFormat3, useOptionalConnector } from "@tallyui/core";
6260
6260
  import { priceRefund, refundableLines } from "@tallyui/pos";
6261
6261
 
6262
6262
  // src/lib/error-text.ts
@@ -6395,6 +6395,7 @@ function RefundForm({
6395
6395
  }) {
6396
6396
  const formatMoney2 = useFormatMoney8();
6397
6397
  const format2 = useMoneyFormat3();
6398
+ const lineTotalsShrinkOnReturn = useOptionalConnector()?.lineTotalsShrinkOnReturn === true;
6398
6399
  const [quantities, setQuantities] = useState31({});
6399
6400
  const [restock, setRestock] = useState31({});
6400
6401
  const [shippingText, setShippingText] = useState31("");
@@ -6412,6 +6413,11 @@ function RefundForm({
6412
6413
  quantity: Math.min(quantities[orderLineId] ?? 0, refundableQuantity),
6413
6414
  restock: restock[orderLineId] ?? defaultRestock
6414
6415
  })).filter(({ quantity }) => quantity > 0);
6416
+ const missingSoldFigures = lineTotalsShrinkOnReturn && request.find(({ orderLineId, quantity }) => {
6417
+ const index = lines.findIndex((line2) => line2.id === orderLineId);
6418
+ const line = lines[index];
6419
+ return (line.soldTotalMinor === void 0 || line.soldTaxMinor === void 0) && (quantity < line.quantity || available[index].refundedQuantity > 0);
6420
+ });
6415
6421
  const priced = priceRefund(lines, refunds, request);
6416
6422
  const emptiesLines = priced.lines.length > 0 && available.every(({ orderLineId, refundableQuantity }) => (request.find((line) => line.orderLineId === orderLineId)?.quantity ?? 0) === refundableQuantity);
6417
6423
  const roundingShareMinor = emptiesLines ? cashRoundingMinor : 0;
@@ -6420,7 +6426,7 @@ function RefundForm({
6420
6426
  const totalMinor = typeof shippingMinor === "number" && typeof adjustmentMinor === "number" ? priced.totalMinor + shippingMinor + adjustmentMinor + roundingShareMinor : void 0;
6421
6427
  const destination = originalMethod?.available ? picked ?? "original_method" : "cash";
6422
6428
  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;
6429
+ 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
6430
  const disabled = !!invalid || online === false || busy;
6425
6431
  const confirm = async () => {
6426
6432
  if (invalid || online === false || busyRef.current) return;
@@ -10498,6 +10504,7 @@ import { Fragment as Fragment38, jsx as jsx174, jsxs as jsxs111 } from "react/js
10498
10504
  function Cart({
10499
10505
  sale,
10500
10506
  taxLabel: taxLabel2 = (ratePpm) => `Tax ${ratePpm / 1e4}%`,
10507
+ taxDisplay = "itemized",
10501
10508
  canEditPrice = false,
10502
10509
  onPriceChange,
10503
10510
  quickDiscounts,
@@ -10524,7 +10531,7 @@ function Cart({
10524
10531
  const empty = !order.lineItems.length && !order.fees?.length && !order.shipping?.length;
10525
10532
  const money = (amount) => ({ amount, currency: order.currency });
10526
10533
  const { totals, fees, shipping } = buildReceiptData(order, { storeName: "" });
10527
- const taxRows = totals.taxLines.map((line) => ({ label: taxLabel2(line.ratePpm), amount: money(line.amountMinor) }));
10534
+ const taxRows = taxDisplay === "single" ? totals.taxMinor !== 0 ? [{ label: "Total Tax", amount: money(totals.taxMinor) }] : [] : totals.taxLines.map((line) => ({ label: taxLabel2(line.ratePpm, { code: line.code, ratePpm: line.ratePpm }), amount: money(line.amountMinor) }));
10528
10535
  const display = (lineId) => order.display.lines.find((line) => line.lineId === lineId);
10529
10536
  const orderAmounts = order.discounts.length === 1 ? [{ discountId: order.discounts[0].id, amountMinor: order.display.orderDiscountMinor }] : [];
10530
10537
  const [splitError, setSplitError] = useState51(null);
@@ -11010,7 +11017,8 @@ import {
11010
11017
  remainderEntriesMinor,
11011
11018
  roundedPickTarget,
11012
11019
  tenderRounding,
11013
- tillLegsTheStoreRefuses
11020
+ tillLegsTheStoreRefuses,
11021
+ writeOffLeg
11014
11022
  } from "@tallyui/pos";
11015
11023
  import { cn as cn113 } from "@tallyui/theme";
11016
11024
 
@@ -11158,17 +11166,19 @@ function TenderPane({ sale, state, dispatch, methods, ledger = true, back = true
11158
11166
  const partPick = pick !== null && target < balance;
11159
11167
  const rounds = sale.capabilities?.cashRounding === true && inMotionMinor(order.payments) === 0;
11160
11168
  const pickRounding = rounds && method !== null && wireMethodOf5(method) === "cash" && method.capture.mode === "manual" && method.defaults.rounding ? method.defaults.rounding : null;
11161
- const pickTarget = partPick ? roundedPickTarget(target, pickRounding) : target;
11162
- const entry = state.entryDirty ? state.entryMinor : pickTarget;
11163
11169
  const entries = remainderEntriesMinor(order);
11170
+ const pickTarget = partPick ? roundedPickTarget(target, pickRounding, entries) : target;
11171
+ const entry = state.entryDirty ? state.entryMinor : pickTarget;
11164
11172
  const figures = partPick ? tenderRounding({ entryMinor: entry, entryDirty: state.entryDirty }, pickTarget, null) : tenderRounding(state, balance, rounds ? method : null, entries);
11173
+ const promoted = partPick && pickRounding !== null && pickTarget === tenderRounding(state, balance, method, entries).roundedDueMinor;
11174
+ const roundedFrom = promoted ? pickTarget !== balance ? balance : null : partPick ? pickTarget !== target ? target : null : figures.roundingMinor !== 0 ? balance : null;
11165
11175
  const cashNotPayable = rounds && pick === null && method !== null && wireMethodOf5(method) === "cash" && method.capture.mode === "manual" && method.defaults.rounding && figures.roundingMinor === 0 && figures.appliedMinor < figures.roundedDueMinor ? nearestPayableCash(figures.entryMinor, method.defaults.rounding.incrementMinor) : null;
11166
11176
  const cashWaits = sale.capabilities?.cashRounding === true && inMotionMinor(order.payments) > 0 && method !== null && wireMethodOf5(method) === "cash" && method.capture.mode === "manual" && method.defaults.rounding && (partPick ? nearestPayableCash(target, method.defaults.rounding.incrementMinor) !== null : figures.entryMinor > 0 && nearestPayableCash(Math.min(figures.entryMinor, balance - inMotionMinor(order.payments)), method.defaults.rounding.incrementMinor) !== null);
11167
- const pickLimit = partPick && pickTarget !== target && (order.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX;
11177
+ const pickLimit = partPick && !promoted && pickTarget !== target && (order.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX;
11168
11178
  const pickRefused = partPick && entry > 0 && (givesChange ? entry < pickTarget : entry !== pickTarget) || pick !== null && !partPick && figures.appliedMinor > 0 && figures.appliedMinor < figures.roundedDueMinor;
11169
11179
  const zeroDue = sale.capabilities?.cashRounding === true && !partPick && figures.roundedDueMinor === 0 && figures.roundingMinor !== 0 && inMotionMinor(order.payments) === 0;
11170
- const lastCounted = order.payments.filter(countsTowardPaid3).at(-1);
11171
- const settleLimit = !partPick && sale.capabilities?.cashRounding === true && figures.roundingMinor !== 0 && (order.cashRoundings ?? []).length > CASH_PICK_ENTRIES_MAX && !(zeroDue && lastCounted !== void 0 && (order.cashRoundings ?? []).some((e) => e.paymentId === lastCounted.id));
11180
+ const lastCounted = writeOffLeg(order);
11181
+ const settleLimit = (!partPick && sale.capabilities?.cashRounding === true && figures.roundingMinor !== 0 || promoted && pickTarget !== balance) && (order.cashRoundings ?? []).length > CASH_PICK_ENTRIES_MAX && !(zeroDue && lastCounted !== void 0 && (order.cashRoundings ?? []).some((e) => e.paymentId === lastCounted.id));
11172
11182
  const otherWay = offered.some((m) => !(wireMethodOf5(m) === "cash" && m.defaults.rounding));
11173
11183
  const lastRounded = order.payments.filter(countsTowardPaid3).filter((leg) => leg.method === "cash" && (order.cashRoundings ?? []).some((e) => e.paymentId === leg.id)).at(-1);
11174
11184
  const entryChange = zeroDue ? 0 : partPick ? changeMinor(figures.entryMinor, figures.appliedMinor, givesChange) : changeMinor(figures.entryMinor, Math.min(figures.appliedMinor, Math.max(0, balance - inMotionMinor(order.payments)) + figures.roundingMinor), givesChange);
@@ -11260,10 +11270,10 @@ function TenderPane({ sale, state, dispatch, methods, ledger = true, back = true
11260
11270
  /* @__PURE__ */ jsx179(Text50, { testID: "tender-entry-amount", className: "font-semibold text-foreground", children: money(figures.entryMinor) }),
11261
11271
  order.totalMinor !== balance ? ` \xB7 ${t("common.total")} ${money(order.totalMinor)}` : ""
11262
11272
  ] }),
11263
- figures.roundingMinor !== 0 ? /* @__PURE__ */ jsx179(Text50, { className: "text-sm text-muted-foreground", children: t("pos_checkout.rounded_from", { amount: money(balance) }) }) : null
11273
+ roundedFrom !== null ? /* @__PURE__ */ jsx179(Text50, { className: "text-sm text-muted-foreground", children: t("pos_checkout.rounded_from", { amount: money(roundedFrom) }) }) : null
11264
11274
  ] }) : /* @__PURE__ */ jsxs116(Fragment41, { children: [
11265
11275
  /* @__PURE__ */ jsx179(Text50, { testID: "tender-entry-amount", className: cn113("text-4xl font-bold text-foreground", !state.entryDirty && "opacity-70"), children: money(figures.entryMinor) }),
11266
- figures.roundingMinor !== 0 ? /* @__PURE__ */ jsx179(Text50, { className: "text-sm text-muted-foreground", children: t("pos_checkout.rounded_from", { amount: money(balance) }) }) : null,
11276
+ roundedFrom !== null ? /* @__PURE__ */ jsx179(Text50, { className: "text-sm text-muted-foreground", children: t("pos_checkout.rounded_from", { amount: money(roundedFrom) }) }) : null,
11267
11277
  /* @__PURE__ */ jsx179(Text50, { testID: "tender-entry-hint", className: cn113("min-h-6 text-center text-sm", noChange || capped || pickRefused || cashWaits || pickLimit || settleLimit ? "text-warning-text" : "text-muted-foreground"), children: hint })
11268
11278
  ] }) }) : null,
11269
11279
  ledger ? /* @__PURE__ */ jsx179(TenderLedger, { sale, methods, confirmVoid, beforeVoid, afterVoid }) : null,
@@ -12760,7 +12770,7 @@ function SyncStatus({ state, registerState, pluginName = "the POS plugin", pullN
12760
12770
  import { useEffect as useEffect24, useId as useId4, useRef as useRef26, useState as useState57 } from "react";
12761
12771
  import { Pressable as Pressable56, ScrollView as ScrollView23, Text as Text58, View as View118 } from "react-native";
12762
12772
  import { useFormatMoney as useFormatMoney26, knownWarnings } from "@tallyui/core";
12763
- import { extrasNotSent, isRequeueableOrder, needsAdminReasonOf as needsAdminReasonOf2, needsAttention, noteDelivery as noteDelivery2, refundDueOf, REOPENABLE_CODES, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE } from "@tallyui/pos";
12773
+ 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";
12764
12774
  import { Fragment as Fragment48, jsx as jsx190, jsxs as jsxs126 } from "react/jsx-runtime";
12765
12775
  var STATUS_LABEL2 = { pending: "Waiting to sync", applied: "Synced", rejected: "Not accepted" };
12766
12776
  var FIGURE_LABELS = /* @__PURE__ */ new Map([["subtotalMinor", "Subtotal"], ["taxMinor", "Tax"], ["discountMinor", "Discount"]]);
@@ -12781,6 +12791,13 @@ var REFUSAL_SENTENCES = /* @__PURE__ */ new Map([
12781
12791
  ["total_mismatch", "The online store refused this sale: its total didn't match the store's. Reopen it to sell it again."]
12782
12792
  ]);
12783
12793
  var refusalSentence = (code) => REFUSAL_SENTENCES.get(code ?? "") ?? REFUSAL_SENTENCES.get("platform_error");
12794
+ var GIVE_BACK = "If the money was given back, do not record it; a manager must check the order in the store's admin.";
12795
+ var GIVE_BACK_INSTEAD = "If the money was given back, use Give back and cancel instead.";
12796
+ var GIVE = "Give back any of this you have not already given back.";
12797
+ var CLOSED_SESSION_NOTICE = "Taken in a session that has closed: a manager must settle this sale in the store's admin.";
12798
+ var legLabel = (method) => method === "cash" ? "Cash" : "Card";
12799
+ var legWording = (method, amount) => `${legLabel(method)} ${amount}: ${method === "cash" ? "hand it back from the drawer" : "give it back on the card terminal"}`;
12800
+ var methodLabel = (method) => method === "cash" ? "Cash" : "Card terminal";
12784
12801
  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.";
12785
12802
  function defaultFormatDate2(iso2) {
12786
12803
  const date = new Date(iso2);
@@ -12792,11 +12809,49 @@ function OrderSyncNotices({ order, stuck, children }) {
12792
12809
  const formatMoney2 = useFormatMoney26();
12793
12810
  const stuckEntry = order.syncStatus === "pending" ? stuck?.orders.find((entry) => entry.commandId === order.commandId) : void 0;
12794
12811
  const needsAdminReason = stuckEntry ? needsAdminReasonOf2(stuckEntry.reason) : void 0;
12795
- const sentence = order.syncStatus === "rejected" ? order.storeOrderId !== void 0 && ["reopen_required", "revision_conflict"].includes(order.error?.code ?? "") ? REOPEN_AGAIN_SENTENCE : refusalSentence(order.error?.code) : order.syncStatus === "pending" && order.error?.code === UPDATE_UNSENDABLE ? UPDATE_UNSENDABLE_MESSAGE : void 0;
12812
+ const left = storeOrderLeft(order);
12813
+ 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;
12796
12814
  const extras = extrasNotSent(order);
12815
+ const kind = order.storeSettlement?.kind;
12816
+ const settlement = order.syncStatus === "rejected" && (kind === "cancel" || kind === "pay" || kind === "reverse" && order.storeSettlement?.legs?.length) ? order.storeSettlement : void 0;
12817
+ const reference = left?.reference ?? orderReference(order);
12818
+ const money = (amount) => formatMoney2({ amount, currency: order.currency });
12819
+ const sum = (legs) => legs.reduce((total, leg) => total + leg.amountMinor, 0);
12820
+ const paidThere = settlement?.capturedMinor ? `: ${money(settlement.capturedMinor)} is paid there` : "";
12821
+ const recorded = money((left?.recordedMinor ?? 0) + sum(settlement?.payments?.filter((payment) => payment.done) ?? []));
12822
+ const doneMinor = sum(settlement?.payments?.filter((payment) => payment.done) ?? []);
12823
+ const nothing = doneMinor > 0 ? `${money(doneMinor)} was recorded from this till.` : "Nothing was recorded from this till.";
12824
+ 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;
12825
+ const pay = settlement?.kind === "pay";
12826
+ 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;
12827
+ if (settlement?.kind === "reverse" && settlement.state !== "done" && settlement.legs) {
12828
+ const legs = settlement.legs.flatMap((leg) => {
12829
+ const payment = order.payments.find(({ id }) => id === leg.paymentId);
12830
+ return payment ? [{ ...payment, done: leg.done }] : [];
12831
+ });
12832
+ const taken = legs.filter((leg) => leg.done).map((leg) => legWording(leg.method, money(leg.amountMinor))).join("; ");
12833
+ const still = legs.filter((leg) => !leg.done).map((leg) => `${legLabel(leg.method)} ${money(leg.amountMinor)}`).join("; ");
12834
+ const hasDone = settlement.legs.some((leg) => leg.done);
12835
+ const subject = `Order #${reference}`;
12836
+ settledText = void 0;
12837
+ addedText = void 0;
12838
+ 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.`;
12839
+ 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.` : ""}`;
12840
+ 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.` : ""}`;
12841
+ else if (settlement.state === "refused") addedText = `The store did not cancel order #${reference}. Check it in the store's admin.`;
12842
+ 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.`;
12843
+ }
12844
+ if ((kind === "cancel" || kind === "reverse") && order.storeSettlement?.code === TILL_SESSION_CLOSED) {
12845
+ settledText = void 0;
12846
+ addedText = CLOSED_SESSION_NOTICE;
12847
+ }
12848
+ const settled = !!settlement && settledOnStore(order);
12797
12849
  return /* @__PURE__ */ jsxs126(Fragment48, { children: [
12798
12850
  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,
12799
- sentence ? /* @__PURE__ */ jsx190(Text58, { className: "text-destructive", children: sentence }) : null,
12851
+ sentence && !settled ? /* @__PURE__ */ jsx190(Text58, { className: "text-destructive", children: sentence }) : null,
12852
+ settledText ? /* @__PURE__ */ jsx190(Text58, { testID: `order-settlement-${order.id}`, className: settled ? "text-foreground" : "text-destructive", children: settledText }) : null,
12853
+ left && !settledText ? /* @__PURE__ */ jsx190(Text58, { testID: `order-left-on-store-${order.id}`, className: "text-destructive", children: left.recordedMinor === 0 ? `Order #${left.reference} was left pending on the online store. Nothing was paid there.` : `Order #${left.reference} was left part paid on the online store: ${formatMoney2({ amount: left.recordedMinor, currency: order.currency })} of ${formatMoney2({ amount: order.totalMinor, currency: order.currency })}.` }) : null,
12854
+ addedText ? /* @__PURE__ */ jsx190(Text58, { testID: `order-settlement-${order.id}`, className: "text-destructive", children: addedText }) : null,
12800
12855
  order.lateSessionId !== void 0 ? /* @__PURE__ */ jsx190(Text58, { className: "text-foreground", children: "Taken after the register closed. It is not in that register's closure." }) : null,
12801
12856
  order.countedInClosureOf !== void 0 ? /* @__PURE__ */ jsx190(Text58, { className: "text-foreground", children: "Recorded after the register closed. Its payment is in that register's closure." }) : null,
12802
12857
  order.localWarnings?.map((warning, index) => /* @__PURE__ */ jsx190(Text58, { className: "text-foreground", children: warning.code === "customer_omitted" ? `The customer's ${warning.field} couldn't be sent to the store, so the order isn't linked to them.` : "The terminal's payment reference couldn't be kept; the payment is recorded without it." }, index)),
@@ -12808,7 +12863,7 @@ function OrderSyncNotices({ order, stuck, children }) {
12808
12863
  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))
12809
12864
  ] });
12810
12865
  }
12811
- function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer, stuck, history, onOpen, onReopen, onResume }) {
12866
+ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer, stuck, history, onOpen, onReopen, onResume, onCancelOnStore, onPayRestOnStore, onReverseOnStore, openSessionId }) {
12812
12867
  const formatMoney2 = useFormatMoney26();
12813
12868
  const hintId = useId4();
12814
12869
  const retrying = useRef26(/* @__PURE__ */ new Set());
@@ -12836,6 +12891,73 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
12836
12891
  reopening.current.delete(order.id);
12837
12892
  }
12838
12893
  }
12894
+ const cancelling = useRef26(/* @__PURE__ */ new Set());
12895
+ const [cancels, setCancels] = useState57(/* @__PURE__ */ new Map());
12896
+ const [askingCancel, setAskingCancel] = useState57(null);
12897
+ const setCancel = (id, state) => setCancels((current) => {
12898
+ const next = new Map(current);
12899
+ if (state) next.set(id, state);
12900
+ else next.delete(id);
12901
+ return next;
12902
+ });
12903
+ async function cancelOnStore(order) {
12904
+ if (!onCancelOnStore || cancelling.current.has(order.id)) return;
12905
+ cancelling.current.add(order.id);
12906
+ setCancel(order.id, "busy");
12907
+ try {
12908
+ const outcome = await onCancelOnStore(order);
12909
+ setCancel(order.id, outcome.kind === "retry" ? "failed" : void 0);
12910
+ } catch {
12911
+ setCancel(order.id, "failed");
12912
+ } finally {
12913
+ cancelling.current.delete(order.id);
12914
+ }
12915
+ }
12916
+ const paying = useRef26(/* @__PURE__ */ new Set());
12917
+ const [pays, setPays] = useState57(/* @__PURE__ */ new Map());
12918
+ const [askingPay, setAskingPay] = useState57(null);
12919
+ const setPay = (id, state) => setPays((current) => {
12920
+ const next = new Map(current);
12921
+ if (state) next.set(id, state);
12922
+ else next.delete(id);
12923
+ return next;
12924
+ });
12925
+ async function payRestOnStore(order) {
12926
+ if (!onPayRestOnStore || paying.current.has(order.id)) return;
12927
+ paying.current.add(order.id);
12928
+ setPay(order.id, "busy");
12929
+ try {
12930
+ const outcome = await onPayRestOnStore(order);
12931
+ setPay(order.id, outcome.kind !== "retry" ? void 0 : outcome.reason === "not_completed" ? "unfinished" : "failed");
12932
+ } catch {
12933
+ setPay(order.id, "failed");
12934
+ } finally {
12935
+ paying.current.delete(order.id);
12936
+ }
12937
+ }
12938
+ const reversing = useRef26(/* @__PURE__ */ new Set());
12939
+ const [reverses, setReverses] = useState57(/* @__PURE__ */ new Map());
12940
+ const [askingReverse, setAskingReverse] = useState57(null);
12941
+ async function reverseOnStore(order) {
12942
+ if (!onReverseOnStore || reversing.current.has(order.id)) return;
12943
+ reversing.current.add(order.id);
12944
+ setReverses((current) => new Map(current).set(order.id, "busy"));
12945
+ let failed = false;
12946
+ try {
12947
+ failed = (await onReverseOnStore(order)).kind === "retry";
12948
+ } catch {
12949
+ failed = true;
12950
+ } finally {
12951
+ reversing.current.delete(order.id);
12952
+ setReverses((current) => {
12953
+ const next = new Map(current);
12954
+ if (failed) next.set(order.id, "failed");
12955
+ else next.delete(order.id);
12956
+ return next;
12957
+ });
12958
+ }
12959
+ }
12960
+ const inOpenSession = (order) => openSessionId !== void 0 && tillPayments(order.payments).every((payment) => (payment.sessionId ?? order.sessionId) === openSessionId);
12839
12961
  const [expanded, setExpanded] = useState57(/* @__PURE__ */ new Set());
12840
12962
  useEffect24(() => {
12841
12963
  for (const id of retrying.current) {
@@ -12887,6 +13009,18 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
12887
13009
  const attention = section.title === "Needs attention";
12888
13010
  const reopenable = attention && !!onReopen && order.syncStatus === "rejected" && REOPENABLE_CODES.includes(order.error?.code ?? "") && order.storeOrderId === void 0 && order.reopenedAt === void 0;
12889
13011
  const reopenState = reopens.get(order.id);
13012
+ const cancelOffered = attention && !!onCancelOnStore && canCancelOnStore(order);
13013
+ const cancelState = cancels.get(order.id);
13014
+ const finishing = order.storeSettlement?.kind === "cancel" && order.storeSettlement.state === "sending";
13015
+ const left = storeOrderLeft(order);
13016
+ const payable = attention && !!onPayRestOnStore && canPayRestOnStore(order);
13017
+ const payState = pays.get(order.id);
13018
+ const finishingPay = order.storeSettlement?.kind === "pay" && order.storeSettlement.state === "sending";
13019
+ const reverseOffered = attention && !!onReverseOnStore && canReverseOnStore(order);
13020
+ const closedSession = (cancelOffered || reverseOffered) && !inOpenSession(order);
13021
+ const cancellable = cancelOffered && !closedSession, reversible = reverseOffered && !closedSession;
13022
+ const reverseState = reverses.get(order.id), finishingReverse = order.storeSettlement?.kind === "reverse" && order.storeSettlement.state === "sending";
13023
+ 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";
12890
13024
  return /* @__PURE__ */ jsxs126(View118, { className: "gap-1 rounded-md border border-border bg-card p-3", children: [
12891
13025
  /* @__PURE__ */ jsx190(Text58, { id: `${hintId}-${sectionIndex}-${order.id}`, className: "hidden", children: "Shows the items and payments of this sale" }),
12892
13026
  /* @__PURE__ */ jsxs126(
@@ -12929,12 +13063,12 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
12929
13063
  ) : null,
12930
13064
  isExpanded ? /* @__PURE__ */ jsxs126(View118, { testID: `order-detail-${order.id}`, className: "mt-1 gap-1 border-t border-border pt-2", children: [
12931
13065
  order.lines.map((line) => /* @__PURE__ */ jsx190(Text58, { className: "text-foreground", children: `${line.quantity} \xD7 ${line.name}` }, line.id)),
12932
- order.payments.map((payment) => /* @__PURE__ */ jsx190(Text58, { className: "text-muted-foreground", children: `${payment.method === "cash" ? "Cash" : "Card terminal"} ${formatMoney2({ amount: payment.amountMinor, currency: order.currency })}${payment.reference ? ` \xB7 ${payment.reference}` : ""}` }, payment.id)),
13066
+ order.payments.map((payment) => /* @__PURE__ */ jsx190(Text58, { className: "text-muted-foreground", children: `${methodLabel(payment.method)} ${formatMoney2({ amount: payment.amountMinor, currency: order.currency })}${payment.reference ? ` \xB7 ${payment.reference}` : ""}` }, payment.id)),
12933
13067
  refundDueMinor > 0 ? /* @__PURE__ */ jsx190(Text58, { testID: `order-refund-due-${order.id}`, className: "text-foreground", children: `Refund due ${formatMoney2({ amount: refundDueMinor, currency: order.currency })}` }) : null,
12934
13068
  order.note ? /* @__PURE__ */ jsx190(Text58, { testID: `order-note-${order.id}`, className: "text-foreground", children: `Customer note: ${order.note}` }) : null
12935
13069
  ] }) : null,
12936
13070
  /* @__PURE__ */ jsxs126(OrderSyncNotices, { order, stuck, children: [
12937
- section.title === "Needs attention" && isRequeueableOrder(order) ? /* @__PURE__ */ jsx190(Pressable56, { accessibilityRole: "button", disabled: retryingIds.has(order.id), onPress: async () => {
13071
+ section.title === "Needs attention" && isRequeueableOrder(order) && retryLabel ? /* @__PURE__ */ jsx190(Pressable56, { accessibilityRole: "button", disabled: retryingIds.has(order.id), onPress: async () => {
12938
13072
  if (retrying.current.has(order.id)) return;
12939
13073
  retrying.current.add(order.id);
12940
13074
  setRetryingIds(new Set(retrying.current));
@@ -12942,7 +13076,55 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
12942
13076
  retrying.current.delete(order.id);
12943
13077
  setRetryingIds(new Set(retrying.current));
12944
13078
  }
12945
- }, className: "rounded-md bg-primary px-4 py-2", children: /* @__PURE__ */ jsx190(Text58, { className: "text-center font-semibold text-primary-foreground", children: "Retry" }) }) : null,
13079
+ }, className: "rounded-md bg-primary px-4 py-2", children: /* @__PURE__ */ jsx190(Text58, { className: "text-center font-semibold text-primary-foreground", children: retryLabel }) }) : null,
13080
+ closedSession ? /* @__PURE__ */ jsx190(Text58, { className: "text-muted-foreground", children: CLOSED_SESSION_NOTICE }) : null,
13081
+ cancellable ? /* @__PURE__ */ jsx190(
13082
+ Pressable56,
13083
+ {
13084
+ accessibilityRole: "button",
13085
+ testID: `order-${order.id}-cancel-on-store`,
13086
+ disabled: cancelState === "busy",
13087
+ onPress: () => {
13088
+ if (cancelling.current.has(order.id)) return;
13089
+ if (finishing) void cancelOnStore(order);
13090
+ else setAskingCancel(order);
13091
+ },
13092
+ className: "rounded-md border border-border px-4 py-2",
13093
+ children: /* @__PURE__ */ jsx190(Text58, { className: "text-center font-semibold text-foreground", children: cancelState === "busy" ? "Cancelling on store\u2026" : finishing ? "Finish cancelling on store" : "Cancel order on store" })
13094
+ }
13095
+ ) : null,
13096
+ cancellable && cancelState === "failed" ? /* @__PURE__ */ jsx190(Text58, { testID: `order-${order.id}-cancel-on-store-error`, className: "text-muted-foreground", children: "Could not reach the store. Try again." }) : null,
13097
+ payable ? /* @__PURE__ */ jsx190(
13098
+ Pressable56,
13099
+ {
13100
+ accessibilityRole: "button",
13101
+ testID: `order-${order.id}-pay-rest-on-store`,
13102
+ disabled: payState === "busy",
13103
+ onPress: () => {
13104
+ if (paying.current.has(order.id)) return;
13105
+ if (finishingPay) void payRestOnStore(order);
13106
+ else setAskingPay(order);
13107
+ },
13108
+ className: "rounded-md bg-primary px-4 py-2",
13109
+ children: /* @__PURE__ */ jsx190(Text58, { className: "text-center font-semibold text-primary-foreground", children: payState === "busy" ? "Recording on store\u2026" : finishingPay ? "Finish recording on store" : "Pay the rest on store" })
13110
+ }
13111
+ ) : null,
13112
+ 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,
13113
+ reversible ? /* @__PURE__ */ jsx190(
13114
+ Pressable56,
13115
+ {
13116
+ accessibilityRole: "button",
13117
+ testID: `order-${order.id}-reverse-on-store`,
13118
+ disabled: reverseState === "busy",
13119
+ onPress: () => {
13120
+ if (finishingReverse) void reverseOnStore(order);
13121
+ else setAskingReverse(order);
13122
+ },
13123
+ className: "rounded-md border border-border px-4 py-2",
13124
+ 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" })
13125
+ }
13126
+ ) : null,
13127
+ 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,
12946
13128
  attention && order.reopenedAt !== void 0 ? /* @__PURE__ */ jsxs126(Fragment48, { children: [
12947
13129
  /* @__PURE__ */ jsx190(Text58, { testID: `order-${order.id}-reopened`, className: "text-muted-foreground", children: "Reopened as a parked sale." }),
12948
13130
  onResume ? /* @__PURE__ */ jsx190(
@@ -12986,6 +13168,76 @@ function OrdersList({ orders, onRetry, formatDate = defaultFormatDate2, footer,
12986
13168
  ] }, order.id);
12987
13169
  })
12988
13170
  ] }, section.title)),
13171
+ askingCancel && inOpenSession(askingCancel) ? ((reference) => /* @__PURE__ */ jsx190(
13172
+ ConfirmDialog,
13173
+ {
13174
+ testID: `order-${askingCancel.id}-cancel-on-store-dialog`,
13175
+ tone: "destructive",
13176
+ open: true,
13177
+ onOpenChange: (open) => {
13178
+ if (!open) setAskingCancel(null);
13179
+ },
13180
+ title: `Cancel order #${reference} on the store?`,
13181
+ 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.`,
13182
+ cancelLabel: "Keep order",
13183
+ confirmLabel: "Cancel order on store",
13184
+ onConfirm: () => {
13185
+ setAskingCancel(null);
13186
+ void cancelOnStore(askingCancel);
13187
+ }
13188
+ }
13189
+ ))(storeOrderLeft(askingCancel)?.reference ?? orderReference(askingCancel)) : null,
13190
+ askingPay ? ((reference, legs, stored) => /* @__PURE__ */ jsx190(
13191
+ ConfirmDialog,
13192
+ {
13193
+ testID: `order-${askingPay.id}-pay-rest-on-store-dialog`,
13194
+ tone: "default",
13195
+ open: true,
13196
+ onOpenChange: (open) => {
13197
+ if (!open) setAskingPay(null);
13198
+ },
13199
+ title: `Record the rest of order #${reference} on the store?`,
13200
+ description: [
13201
+ ...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.`),
13202
+ "No money is taken now.",
13203
+ onReverseOnStore && canReverseOnStore(askingPay) && inOpenSession(askingPay) ? GIVE_BACK_INSTEAD : GIVE_BACK
13204
+ ].join("\n"),
13205
+ cancelLabel: "Keep as is",
13206
+ confirmLabel: "Record on store",
13207
+ onConfirm: () => {
13208
+ setAskingPay(null);
13209
+ void payRestOnStore(askingPay);
13210
+ }
13211
+ }
13212
+ ))(
13213
+ storeOrderLeft(askingPay)?.reference ?? orderReference(askingPay),
13214
+ // Only the legs still to record: the stored pay is index-aligned with them when the lengths match, as the outbox reuses it.
13215
+ unrecordedLegs(askingPay),
13216
+ askingPay.storeSettlement
13217
+ ) : null,
13218
+ askingReverse && inOpenSession(askingReverse) ? /* @__PURE__ */ jsx190(
13219
+ ConfirmDialog,
13220
+ {
13221
+ testID: `order-${askingReverse.id}-reverse-on-store-dialog`,
13222
+ tone: "destructive",
13223
+ open: true,
13224
+ onOpenChange: (open) => {
13225
+ if (!open) setAskingReverse(null);
13226
+ },
13227
+ title: `Give the money back and cancel order #${storeOrderLeft(askingReverse)?.reference ?? orderReference(askingReverse)}?`,
13228
+ description: [
13229
+ ...askingReverse.payments.map((leg) => `${legWording(leg.method, formatMoney2({ amount: leg.amountMinor, currency: askingReverse.currency }))}.`),
13230
+ "The store stops counting the payments it recorded and cancels the order.",
13231
+ "Hand the money back once this till shows the order cancelled. If you already gave it back, go ahead."
13232
+ ].join("\n"),
13233
+ cancelLabel: "Keep order",
13234
+ confirmLabel: "Give back and cancel",
13235
+ onConfirm: () => {
13236
+ setAskingReverse(null);
13237
+ void reverseOnStore(askingReverse);
13238
+ }
13239
+ }
13240
+ ) : null,
12989
13241
  footer
12990
13242
  ] });
12991
13243
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/components",
3
- "version": "5.0.0",
3
+ "version": "5.2.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.0.0",
33
- "@tallyui/primitives": "^5.0.0",
34
- "@tallyui/theme": "^5.0.0",
32
+ "@tallyui/core": "^5.2.0",
33
+ "@tallyui/primitives": "^5.2.0",
34
+ "@tallyui/theme": "^5.2.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.0.0"
43
+ "@tallyui/pos": "5.2.0"
44
44
  },
45
45
  "devDependencies": {
46
- "@tallyui/connector-medusa": "5.0.0",
47
- "@tallyui/connector-vendure": "5.0.0",
48
- "@tallyui/connector-woocommerce": "5.0.0",
49
- "@tallyui/mock-api": "5.0.0",
46
+ "@tallyui/connector-medusa": "5.2.0",
47
+ "@tallyui/connector-vendure": "5.2.0",
48
+ "@tallyui/connector-woocommerce": "5.2.0",
49
+ "@tallyui/mock-api": "5.2.0",
50
50
  "@types/react": ">=18",
51
51
  "react": "^19.2.4",
52
52
  "react-native-svg": "15.12.1",
@@ -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
@@ -20,10 +20,14 @@ import { useT } from '../i18n';
20
20
  import { saleErrorText } from './sale-error-text';
21
21
 
22
22
  /** `taxLabel` names each tax row; VAT isn't universal, so a platform passes its own (medusapos passes `VAT ${rate}%`). */
23
- export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10000}%`, canEditPrice = false, onPriceChange, quickDiscounts, taxClasses, afterSubtotal, showTotal = true, couponDiscountMinor, orderActions = true, orderDiscountChips = true, checkout, noteSheet, tenderLedger, picker, lineEditor = 'inline',
23
+ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10000}%`, taxDisplay = 'itemized', canEditPrice = false, onPriceChange, quickDiscounts, taxClasses, afterSubtotal, showTotal = true, couponDiscountMinor, orderActions = true, orderDiscountChips = true, checkout, noteSheet, tenderLedger, picker, lineEditor = 'inline',
24
24
  lineCommit = 'apply', columns, chargeTaxSwitch = true,
25
25
  emptyIcon = <ShoppingCartIcon size={48} />, emptyText = 'Tap a product to start a sale' }:
26
- { sale: ReturnType<typeof useSale>; taxLabel?: (ratePpm: number) => string;
26
+ { sale: ReturnType<typeof useSale>;
27
+ /** Names each tax row from its rate. The second argument carries the row's own tax `code` (when it has one) and `ratePpm`, so two rates with the same percentage can be told apart. */
28
+ taxLabel?: (ratePpm: number, rate: { code?: string; ratePpm: number }) => string;
29
+ /** `itemized` (default): one row per rate, under `taxLabel`. `single`: one "Total Tax" row with the order's total tax, drawn only when that is not 0. */
30
+ taxDisplay?: 'itemized' | 'single';
27
31
  taxClasses?: ReadonlyArray<{ id: string; label: string }>;
28
32
  /** Shows a Price action on each line. Pass the till's own permission; the control isn't shown without it. */
29
33
  canEditPrice?: boolean;
@@ -94,7 +98,9 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
94
98
  const money = (amount: number) => ({ amount, currency: order.currency });
95
99
  // order.display's figures (TallyUI ADR-063), with its tax split by rate; never app arithmetic (medusapos ADR 0008).
96
100
  const { totals, fees, shipping } = buildReceiptData(order, { storeName: '' });
97
- const taxRows = totals.taxLines.map((line) => ({ label: taxLabel(line.ratePpm), amount: money(line.amountMinor) }));
101
+ const taxRows = taxDisplay === 'single'
102
+ ? totals.taxMinor !== 0 ? [{ label: 'Total Tax', amount: money(totals.taxMinor) }] : []
103
+ : totals.taxLines.map((line) => ({ label: taxLabel(line.ratePpm, { code: line.code, ratePpm: line.ratePpm }), amount: money(line.amountMinor) }));
98
104
  // Each line before its discounts, with its own discounts' amounts. The order discounts are one figure: a single
99
105
  // order discount's chip carries it; several keep their own labels, as no single one has a display amount.
100
106
  const display = (lineId: string) => order.display.lines.find((line) => line.lineId === lineId)!;
@@ -1,9 +1,10 @@
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 } from '@tallyui/core';
4
- import { extrasNotSent, isRequeueableOrder, needsAdminReasonOf, needsAttention, noteDelivery, refundDueOf, REOPENABLE_CODES, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, type OutboxState, type PosOrder } from '@tallyui/pos';
3
+ import { useFormatMoney, 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
+ import { ConfirmDialog } from '../ui/confirm-dialog';
7
8
 
8
9
  /** One order from the store's own history (ADR-052 amendment 1), mapped by the app from its platform. */
9
10
  export type OrderHistoryRow = {
@@ -34,6 +35,14 @@ const REFUSAL_SENTENCES = new Map([
34
35
  ]);
35
36
  // Any other code, or none: platform_error's sentence, as the generic fallback (approved by the Front desk, 2026-09-30).
36
37
  const refusalSentence = (code: string | undefined) => REFUSAL_SENTENCES.get(code ?? '') ?? REFUSAL_SENTENCES.get('platform_error')!;
38
+ /** Pay the rest on store's dialog (#1101 slice 3): the front desk's wording until slice 4 handles money given back. */
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'}`;
45
+ const methodLabel = (method: string) => (method === 'cash' ? 'Cash' : 'Card terminal');
37
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.";
38
47
 
39
48
  /** Keeps an unparseable value as is, like medusapos's date util, since `Intl` throws on an invalid date. */
@@ -60,11 +69,63 @@ export function OrderSyncNotices({ order, stuck, children }: OrderSyncNoticesPro
60
69
  // The order's own stuck entry: its clock and latest reason, not the earliest across all stuck orders.
61
70
  const stuckEntry = order.syncStatus === 'pending' ? stuck?.orders.find((entry) => entry.commandId === order.commandId) : undefined;
62
71
  const needsAdminReason = stuckEntry ? needsAdminReasonOf(stuckEntry.reason) : undefined;
72
+ const left = storeOrderLeft(order);
73
+ // #1101: the store created this order, so invalid_payload's "a form the store can't read" would be wrong.
63
74
  const sentence = order.syncStatus === 'rejected'
64
75
  ? order.storeOrderId !== undefined && ['reopen_required', 'revision_conflict'].includes(order.error?.code ?? '')
65
- ? REOPEN_AGAIN_SENTENCE : refusalSentence(order.error?.code)
76
+ ? REOPEN_AGAIN_SENTENCE : refusalSentence(left && order.error?.code === 'invalid_payload' ? 'platform_error' : order.error?.code)
66
77
  : order.syncStatus === 'pending' && order.error?.code === UPDATE_UNSENDABLE ? UPDATE_UNSENDABLE_MESSAGE : undefined;
67
78
  const extras = extrasNotSent(order);
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
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).
81
+ const kind = order.storeSettlement?.kind;
82
+ const settlement = order.syncStatus === 'rejected' && (kind === 'cancel' || kind === 'pay' || (kind === 'reverse' && order.storeSettlement?.legs?.length)) ? order.storeSettlement : undefined;
83
+ const reference = left?.reference ?? orderReference(order);
84
+ const money = (amount: number) => formatMoney({ amount, currency: order.currency });
85
+ const sum = (legs: { amountMinor: number }[]) => legs.reduce((total, leg) => total + leg.amountMinor, 0);
86
+ const paidThere = settlement?.capturedMinor ? `: ${money(settlement.capturedMinor)} is paid there` : '';
87
+ // A pay's R: what the store had recorded at the refusal, plus each leg this till has recorded since.
88
+ const recorded = money((left?.recordedMinor ?? 0) + sum(settlement?.payments?.filter((payment) => payment.done) ?? []));
89
+ // What this till has recorded on the stored pay, on this press or an earlier one: true in every state.
90
+ const doneMinor = sum(settlement?.payments?.filter((payment) => payment.done) ?? []);
91
+ const nothing = doneMinor > 0 ? `${money(doneMinor)} was recorded from this till.` : 'Nothing was recorded from this till.';
92
+ let settledText = settlement?.kind === 'pay'
93
+ ? settlement.state === 'done' ? `Order #${reference} is paid on the store.`
94
+ : settlement.state === 'gone' ? `Order #${reference} is not on the store any more; ${recorded} was recorded on it.`
95
+ : settlement.state !== 'changed' ? undefined
96
+ : settlement.storeStatus === 'completed' ? `Order #${reference} is already paid on the store. ${nothing}`
97
+ : `Order #${reference} changed on the store${paidThere}. ${nothing} Check it in the store's admin.`
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}` : ''}`
100
+ : settlement?.state === 'gone' ? `Order #${reference} was removed on the store.`
101
+ : settlement?.state === 'changed' ? `Order #${reference} changed on the store${paidThere}. Nothing was cancelled from this till. Check it in the store's admin.`
102
+ : undefined;
103
+ const pay = settlement?.kind === 'pay';
104
+ let addedText = settlement?.state === 'refused' ? pay
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.`
106
+ : `The store did not cancel order #${reference}. Check it in the store's admin.`
107
+ : settlement?.state === 'sending' ? pay ? `Recording the rest of order #${reference} on the store is not finished.`
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; }
127
+ // A pay gone with money recorded on the store is not settled (`settledOnStore`): it stays a destructive line.
128
+ const settled = !!settlement && settledOnStore(order);
68
129
  return <>
69
130
  {stuckEntry ? <Text className="text-destructive">
70
131
  {/* A parked sale needs a manager; other retries keep the hour as the status line has it (numeric, #245), with no reason code. */}
@@ -73,7 +134,15 @@ export function OrderSyncNotices({ order, stuck, children }: OrderSyncNoticesPro
73
134
  : `Hasn't reached the online store since ${sinceText(stuckEntry)}.`}
74
135
  </Text> : null}
75
136
  {/* The code's sentence alone: the cashier sees no error code and never the store's message. */}
76
- {sentence ? <Text className="text-destructive">{sentence}</Text> : null}
137
+ {sentence && !settled ? <Text className="text-destructive">{sentence}</Text> : null}
138
+ {settledText ? <Text testID={`order-settlement-${order.id}`} className={settled ? 'text-foreground' : 'text-destructive'}>{settledText}</Text> : null}
139
+ {/* What the store had recorded at the refusal, not the order's state now. */}
140
+ {left && !settledText ? <Text testID={`order-left-on-store-${order.id}`} className="text-destructive">
141
+ {left.recordedMinor === 0
142
+ ? `Order #${left.reference} was left pending on the online store. Nothing was paid there.`
143
+ : `Order #${left.reference} was left part paid on the online store: ${formatMoney({ amount: left.recordedMinor, currency: order.currency })} of ${formatMoney({ amount: order.totalMinor, currency: order.currency })}.`}
144
+ </Text> : null}
145
+ {addedText ? <Text testID={`order-settlement-${order.id}`} className="text-destructive">{addedText}</Text> : null}
77
146
  {/* A late sale (ADR-032) needs no Retry of its own; a rejected one still gets its Retry below. */}
78
147
  {order.lateSessionId !== undefined ? <Text className="text-foreground">Taken after the register closed. It is not in that register's closure.</Text> : null}
79
148
  {order.countedInClosureOf !== undefined ? <Text className="text-foreground">Recorded after the register closed. Its payment is in that register's closure.</Text> : null}
@@ -116,14 +185,27 @@ export function OrderSyncNotices({ order, stuck, children }: OrderSyncNoticesPro
116
185
  * `onReopen` adds Reopen to a Needs attention row the store refused with a reopenable code (`REOPENABLE_CODES`), not yet
117
186
  * reopened and with no store order: the app wires `reopenRefusedOrder`. When it refuses `coupon_carry_inexact` with a
118
187
  * `toCollectMinor`, the row offers "Reopen without the coupon", which calls it again with `{ withoutCoupons: true }`.
119
- * `onResume` adds Resume to a reopened row; the app resumes the parked sale, whose draft id is the order's id. */
120
- export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, footer, stuck, history, onOpen, onReopen, onResume }: {
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.
190
+ * `onCancelOnStore` adds "Cancel order on store" to a Needs attention row whose refused sale left an unpaid order on the
191
+ * store (`canCancelOnStore`, #1101), asked in a confirm dialog first: the app wires `useOrderOutbox`'s `cancelOnStore`.
192
+ * A cancel still `sending` is finished with no dialog. With it, such a row offers no Retry, except an `insufficient_stock`
193
+ * refusal's, which reads "Try the payment again".
194
+ * `onPayRestOnStore` adds "Pay the rest on store" to a Needs attention row whose refused sale left a part-paid order on
195
+ * the store (`canPayRestOnStore`, #1101 slice 3), asked in a confirm dialog naming each leg to record (no money is taken):
196
+ * the app wires `useOrderOutbox`'s `payRestOnStore`. A pay still `sending` is finished with no dialog. With it, a row
197
+ * with money recorded on the store offers no Retry. */
198
+ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, footer, stuck, history, onOpen, onReopen, onResume, onCancelOnStore, onPayRestOnStore, onReverseOnStore, openSessionId }: {
121
199
  orders: PosOrder[]; onRetry(orderIds: string[]): Promise<number>; formatDate?: (iso: string) => string; footer?: ReactNode;
122
200
  stuck?: OutboxState['stuck'];
123
201
  history?: OrderHistoryRow[];
124
202
  onOpen?: (row: PosOrder | OrderHistoryRow) => void;
125
203
  onReopen?: (order: PosOrder, options?: { withoutCoupons: true }) => Promise<void>;
126
204
  onResume?: (order: PosOrder) => void;
205
+ openSessionId?: string;
206
+ onCancelOnStore?: (order: PosOrder) => Promise<SettleOutcome | { kind: 'not_offered' }>;
207
+ onPayRestOnStore?: (order: PosOrder) => Promise<SettleOutcome | { kind: 'not_offered' }>;
208
+ onReverseOnStore?: (order: PosOrder) => Promise<SettleOutcome | { kind: 'not_offered' }>;
127
209
  }) {
128
210
  const formatMoney = useFormatMoney();
129
211
  const hintId = useId();
@@ -153,6 +235,71 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
153
235
  reopening.current.delete(order.id);
154
236
  }
155
237
  }
238
+ /** Each row's Cancel order on store (#1101): in flight, or the last press got no answer from the store. */
239
+ const cancelling = useRef(new Set<string>());
240
+ const [cancels, setCancels] = useState(new Map<string, 'busy' | 'failed'>());
241
+ const [askingCancel, setAskingCancel] = useState<PosOrder | null>(null);
242
+ const setCancel = (id: string, state?: 'busy' | 'failed') => setCancels((current) => {
243
+ const next = new Map(current);
244
+ if (state) next.set(id, state); else next.delete(id);
245
+ return next;
246
+ });
247
+ async function cancelOnStore(order: PosOrder) {
248
+ if (!onCancelOnStore || cancelling.current.has(order.id)) return;
249
+ cancelling.current.add(order.id);
250
+ setCancel(order.id, 'busy');
251
+ try {
252
+ const outcome = await onCancelOnStore(order);
253
+ setCancel(order.id, outcome.kind === 'retry' ? 'failed' : undefined);
254
+ } catch {
255
+ setCancel(order.id, 'failed');
256
+ } finally {
257
+ cancelling.current.delete(order.id);
258
+ }
259
+ }
260
+ /** Each row's Pay the rest on store (#1101 slice 3): in flight, the last press got no answer from the store, or the store
261
+ * answered that the order is not completed there yet (`not_completed`). */
262
+ const paying = useRef(new Set<string>());
263
+ const [pays, setPays] = useState(new Map<string, 'busy' | 'failed' | 'unfinished'>());
264
+ const [askingPay, setAskingPay] = useState<PosOrder | null>(null);
265
+ const setPay = (id: string, state?: 'busy' | 'failed' | 'unfinished') => setPays((current) => {
266
+ const next = new Map(current);
267
+ if (state) next.set(id, state); else next.delete(id);
268
+ return next;
269
+ });
270
+ async function payRestOnStore(order: PosOrder) {
271
+ if (!onPayRestOnStore || paying.current.has(order.id)) return;
272
+ paying.current.add(order.id);
273
+ setPay(order.id, 'busy');
274
+ try {
275
+ const outcome = await onPayRestOnStore(order);
276
+ setPay(order.id, outcome.kind !== 'retry' ? undefined : outcome.reason === 'not_completed' ? 'unfinished' : 'failed');
277
+ } catch {
278
+ setPay(order.id, 'failed');
279
+ } finally {
280
+ paying.current.delete(order.id);
281
+ }
282
+ }
283
+ const reversing = useRef(new Set<string>());
284
+ const [reverses, setReverses] = useState(new Map<string, 'busy' | 'failed'>());
285
+ const [askingReverse, setAskingReverse] = useState<PosOrder | null>(null);
286
+ async function reverseOnStore(order: PosOrder) {
287
+ if (!onReverseOnStore || reversing.current.has(order.id)) return;
288
+ reversing.current.add(order.id);
289
+ setReverses((current) => new Map(current).set(order.id, 'busy'));
290
+ let failed = false;
291
+ try {
292
+ failed = (await onReverseOnStore(order)).kind === 'retry';
293
+ } catch { failed = true; } finally {
294
+ reversing.current.delete(order.id);
295
+ setReverses((current) => {
296
+ const next = new Map(current);
297
+ if (failed) next.set(order.id, 'failed'); else next.delete(order.id);
298
+ return next;
299
+ });
300
+ }
301
+ }
302
+ const inOpenSession = (order: PosOrder) => openSessionId !== undefined && tillPayments(order.payments).every((payment) => (payment.sessionId ?? order.sessionId) === openSessionId);
156
303
  const [expanded, setExpanded] = useState(new Set<string>());
157
304
  useEffect(() => {
158
305
  for (const id of retrying.current) {
@@ -194,6 +341,21 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
194
341
  const reopenable = attention && !!onReopen && order.syncStatus === 'rejected' && REOPENABLE_CODES.includes(order.error?.code ?? '')
195
342
  && order.storeOrderId === undefined && order.reopenedAt === undefined;
196
343
  const reopenState = reopens.get(order.id);
344
+ const cancelOffered = attention && !!onCancelOnStore && canCancelOnStore(order);
345
+ const cancelState = cancels.get(order.id);
346
+ const finishing = order.storeSettlement?.kind === 'cancel' && order.storeSettlement.state === 'sending';
347
+ // #1101: with the cancel wired, an unpaid order left on the store is cancelled rather than resent, except a stock refusal.
348
+ const left = storeOrderLeft(order);
349
+ const payable = attention && !!onPayRestOnStore && canPayRestOnStore(order);
350
+ const payState = pays.get(order.id);
351
+ const finishingPay = order.storeSettlement?.kind === 'pay' && order.storeSettlement.state === 'sending';
352
+ // #1101 slice 3: with the pay wired, a part-paid order left on the store has its rest recorded, never resent.
353
+ const reverseOffered = attention && !!onReverseOnStore && canReverseOnStore(order);
354
+ const closedSession = (cancelOffered || reverseOffered) && !inOpenSession(order);
355
+ const cancellable = cancelOffered && !closedSession, reversible = reverseOffered && !closedSession;
356
+ const reverseState = reverses.get(order.id), finishingReverse = order.storeSettlement?.kind === 'reverse' && order.storeSettlement.state === 'sending';
357
+ const retryLabel = (onPayRestOnStore || onReverseOnStore) && left && left.recordedMinor > 0 ? undefined : onCancelOnStore && left?.recordedMinor === 0
358
+ ? order.error?.code === 'insufficient_stock' ? 'Try the payment again' : undefined : 'Retry';
197
359
  return (
198
360
  <View key={order.id} className="gap-1 rounded-md border border-border bg-card p-3">
199
361
  {/* RN-web drops accessibilityHint; aria-describedby carries it on web. */}
@@ -216,7 +378,7 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
216
378
  {isExpanded ? <View testID={`order-detail-${order.id}`} className="mt-1 gap-1 border-t border-border pt-2">
217
379
  {order.lines.map((line) => <Text key={line.id} className="text-foreground">{`${line.quantity} × ${line.name}`}</Text>)}
218
380
  {order.payments.map((payment) => <Text key={payment.id} className="text-muted-foreground">
219
- {`${payment.method === 'cash' ? 'Cash' : 'Card terminal'} ${formatMoney({ amount: payment.amountMinor, currency: order.currency })}${payment.reference ? ` · ${payment.reference}` : ''}`}
381
+ {`${methodLabel(payment.method)} ${formatMoney({ amount: payment.amountMinor, currency: order.currency })}${payment.reference ? ` · ${payment.reference}` : ''}`}
220
382
  </Text>)}
221
383
  {refundDueMinor > 0 ? <Text testID={`order-refund-due-${order.id}`} className="text-foreground">
222
384
  {`Refund due ${formatMoney({ amount: refundDueMinor, currency: order.currency })}`}</Text> : null}
@@ -224,7 +386,7 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
224
386
  </View> : null}
225
387
  <OrderSyncNotices order={order} stuck={stuck}>
226
388
  {/* Retry is offered only for an order the outbox resends (isRequeueableOrder). */}
227
- {section.title === 'Needs attention' && isRequeueableOrder(order)
389
+ {section.title === 'Needs attention' && isRequeueableOrder(order) && retryLabel
228
390
  ? <Pressable accessibilityRole="button" disabled={retryingIds.has(order.id)} onPress={async () => {
229
391
  if (retrying.current.has(order.id)) return;
230
392
  retrying.current.add(order.id);
@@ -234,8 +396,36 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
234
396
  setRetryingIds(new Set(retrying.current));
235
397
  }
236
398
  }} className="rounded-md bg-primary px-4 py-2">
237
- <Text className="text-center font-semibold text-primary-foreground">Retry</Text>
399
+ <Text className="text-center font-semibold text-primary-foreground">{retryLabel}</Text>
238
400
  </Pressable> : null}
401
+ {closedSession ? <Text className="text-muted-foreground">{CLOSED_SESSION_NOTICE}</Text> : null}
402
+ {cancellable ? <Pressable accessibilityRole="button" testID={`order-${order.id}-cancel-on-store`} disabled={cancelState === 'busy'}
403
+ onPress={() => {
404
+ if (cancelling.current.has(order.id)) return;
405
+ if (finishing) void cancelOnStore(order); else setAskingCancel(order);
406
+ }} className="rounded-md border border-border px-4 py-2">
407
+ <Text className="text-center font-semibold text-foreground">
408
+ {cancelState === 'busy' ? 'Cancelling on store…' : finishing ? 'Finish cancelling on store' : 'Cancel order on store'}
409
+ </Text>
410
+ </Pressable> : null}
411
+ {cancellable && cancelState === 'failed' ? <Text testID={`order-${order.id}-cancel-on-store-error`} className="text-muted-foreground">
412
+ Could not reach the store. Try again.</Text> : null}
413
+ {payable ? <Pressable accessibilityRole="button" testID={`order-${order.id}-pay-rest-on-store`} disabled={payState === 'busy'}
414
+ onPress={() => {
415
+ if (paying.current.has(order.id)) return;
416
+ if (finishingPay) void payRestOnStore(order); else setAskingPay(order);
417
+ }} className="rounded-md bg-primary px-4 py-2">
418
+ <Text className="text-center font-semibold text-primary-foreground">
419
+ {payState === 'busy' ? 'Recording on store…' : finishingPay ? 'Finish recording on store' : 'Pay the rest on store'}
420
+ </Text>
421
+ </Pressable> : null}
422
+ {payable && (payState === 'failed' || payState === 'unfinished') ? <Text testID={`order-${order.id}-pay-rest-on-store-error`} className="text-muted-foreground">
423
+ {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}
424
+ {reversible ? <Pressable accessibilityRole="button" testID={`order-${order.id}-reverse-on-store`} disabled={reverseState === 'busy'}
425
+ onPress={() => { if (finishingReverse) void reverseOnStore(order); else setAskingReverse(order); }} className="rounded-md border border-border px-4 py-2">
426
+ <Text className="text-center font-semibold text-foreground">{reverseState === 'busy' ? 'Cancelling on store…' : finishingReverse ? 'Finish cancelling on store' : 'Give back and cancel'}</Text>
427
+ </Pressable> : null}
428
+ {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}
239
429
  {/* Reopen needs a reopenable code, which Retry never resends (NOT_REQUEUEABLE), so the two never show together. */}
240
430
  {attention && order.reopenedAt !== undefined ? <>
241
431
  <Text testID={`order-${order.id}-reopened`} className="text-muted-foreground">Reopened as a parked sale.</Text>
@@ -265,6 +455,25 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
265
455
  })}
266
456
  </View>
267
457
  ))}
458
+ {askingCancel && inOpenSession(askingCancel) ? ((reference) => <ConfirmDialog testID={`order-${askingCancel.id}-cancel-on-store-dialog`} tone="destructive" open
459
+ onOpenChange={(open) => { if (!open) setAskingCancel(null); }} title={`Cancel order #${reference} on the store?`}
460
+ 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.`}
461
+ cancelLabel="Keep order" confirmLabel="Cancel order on store"
462
+ onConfirm={() => { setAskingCancel(null); void cancelOnStore(askingCancel); }} />)(storeOrderLeft(askingCancel)?.reference ?? orderReference(askingCancel)) : null}
463
+ {askingPay ? ((reference, legs, stored) => <ConfirmDialog testID={`order-${askingPay.id}-pay-rest-on-store-dialog`} tone="default" open
464
+ onOpenChange={(open) => { if (!open) setAskingPay(null); }} title={`Record the rest of order #${reference} on the store?`}
465
+ description={[...legs.filter((_leg, index) => !(stored?.kind === 'pay' && stored.payments?.length === legs.length && stored.payments[index].done))
466
+ .map((leg) => `${methodLabel(leg.method)} ${formatMoney({ amount: leg.amountMinor, currency: askingPay.currency })}, already taken on this till.`),
467
+ 'No money is taken now.', onReverseOnStore && canReverseOnStore(askingPay) && inOpenSession(askingPay) ? GIVE_BACK_INSTEAD : GIVE_BACK].join('\n')}
468
+ cancelLabel="Keep as is" confirmLabel="Record on store"
469
+ onConfirm={() => { setAskingPay(null); void payRestOnStore(askingPay); }} />)(storeOrderLeft(askingPay)?.reference ?? orderReference(askingPay),
470
+ // Only the legs still to record: the stored pay is index-aligned with them when the lengths match, as the outbox reuses it.
471
+ unrecordedLegs(askingPay), askingPay.storeSettlement) : null}
472
+ {askingReverse && inOpenSession(askingReverse) ? <ConfirmDialog testID={`order-${askingReverse.id}-reverse-on-store-dialog`} tone="destructive" open
473
+ onOpenChange={(open) => { if (!open) setAskingReverse(null); }} title={`Give the money back and cancel order #${storeOrderLeft(askingReverse)?.reference ?? orderReference(askingReverse)}?`}
474
+ description={[...askingReverse.payments.map((leg) => `${legWording(leg.method, formatMoney({ amount: leg.amountMinor, currency: askingReverse.currency }))}.`),
475
+ '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')}
476
+ cancelLabel="Keep order" confirmLabel="Give back and cancel" onConfirm={() => { setAskingReverse(null); void reverseOnStore(askingReverse); }} /> : null}
268
477
  {footer}
269
478
  </ScrollView>;
270
479
  }
@@ -9,7 +9,7 @@ import { useEffect, useState, type ComponentProps, type JSX } from 'react';
9
9
  import { Pressable, ScrollView, Text, TextInput, View } from 'react-native';
10
10
  import { useFormatMoney, minorUnitDigits, wireMethodOf, type PaymentMethodDescriptor } from '@tallyui/core';
11
11
  import {
12
- activePlan, CASH_PICK_ENTRIES_MAX, changeMinor, countsTowardPaid, evenSplitShareMinor, inMotionMinor, isInMotion, legStatus, lockedRefundDueMinor, nearestPayableCash, planLegs, quickTenderedAmounts, remainderEntriesMinor, roundedPickTarget, tenderRounding, tillLegsTheStoreRefuses,
12
+ activePlan, CASH_PICK_ENTRIES_MAX, changeMinor, countsTowardPaid, evenSplitShareMinor, inMotionMinor, isInMotion, legStatus, lockedRefundDueMinor, nearestPayableCash, planLegs, quickTenderedAmounts, remainderEntriesMinor, roundedPickTarget, tenderRounding, tillLegsTheStoreRefuses, writeOffLeg,
13
13
  type TenderAction, type TenderKey, type TenderPlan, type TenderState, type useSale,
14
14
  } from '@tallyui/pos';
15
15
  import { cn } from '@tallyui/theme';
@@ -94,12 +94,16 @@ export function TenderPane({ sale, state, dispatch, methods, ledger = true, back
94
94
  const partPick = pick !== null && target < balance;
95
95
  // ADR-094: the pane rounds exactly when addTender does: only on a store whose connector declares cashRounding, and only while no leg is in motion.
96
96
  const rounds = sale.capabilities?.cashRounding === true && inMotionMinor(order.payments) === 0;
97
- // ADR-094 (cash picks): a cash part pick rounds its own target; addTender rounds the leg, the pane shows the same figure.
97
+ // ADR-094 item 7 (carry): a cash part pick rounds its target less the live entries; addTender rounds the leg, the pane shows the same figure.
98
98
  const pickRounding = rounds && method !== null && wireMethodOf(method) === 'cash' && method.capture.mode === 'manual' && method.defaults.rounding ? method.defaults.rounding : null;
99
- const pickTarget = partPick ? roundedPickTarget(target, pickRounding) : target;
100
- const entry = state.entryDirty ? state.entryMinor : pickTarget;
101
99
  const entries = remainderEntriesMinor(order);
100
+ const pickTarget = partPick ? roundedPickTarget(target, pickRounding, entries) : target;
101
+ const entry = state.entryDirty ? state.entryMinor : pickTarget;
102
102
  const figures = partPick ? tenderRounding({ entryMinor: entry, entryDirty: state.entryDirty }, pickTarget, null) : tenderRounding(state, balance, rounds ? method : null, entries);
103
+ // Promotion: a carried pick at the whole-settle due is taken as that settle (addTender), so it meets the settle's 16-entry cap.
104
+ const promoted = partPick && pickRounding !== null && pickTarget === tenderRounding(state, balance, method, entries).roundedDueMinor;
105
+ // "Rounded from": a pick's own goods when its amount differs from them; a settle's balance.
106
+ const roundedFrom = promoted ? (pickTarget !== balance ? balance : null) : partPick ? (pickTarget !== target ? target : null) : figures.roundingMinor !== 0 ? balance : null;
103
107
  const cashNotPayable = rounds && pick === null && method !== null && wireMethodOf(method) === 'cash' && method.capture.mode === 'manual' && method.defaults.rounding
104
108
  && figures.roundingMinor === 0 && figures.appliedMinor < figures.roundedDueMinor
105
109
  ? nearestPayableCash(figures.entryMinor, method.defaults.rounding.incrementMinor) : null;
@@ -108,7 +112,7 @@ export function TenderPane({ sale, state, dispatch, methods, ledger = true, back
108
112
  ? nearestPayableCash(target, method.defaults.rounding.incrementMinor) !== null
109
113
  : figures.entryMinor > 0 && nearestPayableCash(Math.min(figures.entryMinor, balance - inMotionMinor(order.payments)), method.defaults.rounding.incrementMinor) !== null);
110
114
  // order-payload-shape.ts's 16-entry cap: a pick that would add an entry is refused once the sale has CASH_PICK_ENTRIES_MAX.
111
- const pickLimit = partPick && pickTarget !== target && (order.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX;
115
+ const pickLimit = partPick && !promoted && pickTarget !== target && (order.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX;
112
116
  const pickRefused = (partPick && entry > 0 && (givesChange ? entry < pickTarget : entry !== pickTarget))
113
117
  || (pick !== null && !partPick && figures.appliedMinor > 0 && figures.appliedMinor < figures.roundedDueMinor);
114
118
  // Row 500: judged against the due less the legs in motion, as addTender records the leg's change.
@@ -116,8 +120,8 @@ export function TenderPane({ sale, state, dispatch, methods, ledger = true, back
116
120
  const zeroDue = sale.capabilities?.cashRounding === true && !partPick && figures.roundedDueMinor === 0 && figures.roundingMinor !== 0
117
121
  && inMotionMinor(order.payments) === 0;
118
122
  // The 16-entry cap as addTender applies it: a settle that adds an entry is refused at 16; a write-off onto a leg with one is not.
119
- const lastCounted = order.payments.filter(countsTowardPaid).at(-1);
120
- const settleLimit = !partPick && sale.capabilities?.cashRounding === true && figures.roundingMinor !== 0
123
+ const lastCounted = writeOffLeg(order);
124
+ const settleLimit = ((!partPick && sale.capabilities?.cashRounding === true && figures.roundingMinor !== 0) || (promoted && pickTarget !== balance))
121
125
  && (order.cashRoundings ?? []).length > CASH_PICK_ENTRIES_MAX
122
126
  && !(zeroDue && lastCounted !== undefined && (order.cashRoundings ?? []).some((e) => e.paymentId === lastCounted.id));
123
127
  // With no other method, a cash-only store frees an entry by voiding its latest rounded cash leg, which no later cash leg's entry blocks; offered methods are all manual capture.
@@ -224,10 +228,10 @@ export function TenderPane({ sale, state, dispatch, methods, ledger = true, back
224
228
  {changeLeads ? <>
225
229
  <Text testID="tender-entry-hint" className="text-4xl font-bold text-success">{hint}</Text>
226
230
  <Text testID="tender-tendered-line" className="min-h-6 text-sm text-muted-foreground">{t('pos_checkout.tendered')} <Text testID="tender-entry-amount" className="font-semibold text-foreground">{money(figures.entryMinor)}</Text>{order.totalMinor !== balance ? ` · ${t('common.total')} ${money(order.totalMinor)}` : ''}</Text>
227
- {figures.roundingMinor !== 0 ? <Text className="text-sm text-muted-foreground">{t('pos_checkout.rounded_from', { amount: money(balance) })}</Text> : null}
231
+ {roundedFrom !== null ? <Text className="text-sm text-muted-foreground">{t('pos_checkout.rounded_from', { amount: money(roundedFrom) })}</Text> : null}
228
232
  </> : <>
229
233
  <Text testID="tender-entry-amount" className={cn('text-4xl font-bold text-foreground', !state.entryDirty && 'opacity-70')}>{money(figures.entryMinor)}</Text>
230
- {figures.roundingMinor !== 0 ? <Text className="text-sm text-muted-foreground">{t('pos_checkout.rounded_from', { amount: money(balance) })}</Text> : null}
234
+ {roundedFrom !== null ? <Text className="text-sm text-muted-foreground">{t('pos_checkout.rounded_from', { amount: money(roundedFrom) })}</Text> : null}
231
235
  <Text testID="tender-entry-hint" className={cn('min-h-6 text-center text-sm', noChange || capped || pickRefused || cashWaits || pickLimit || settleLimit ? 'text-warning-text' : 'text-muted-foreground')}>{hint}</Text>
232
236
  </>}
233
237
  </View> : null}