@tallyui/components 4.0.1 → 4.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.
@@ -5,6 +5,8 @@ import { cn } from '@tallyui/theme';
5
5
  export interface VariantOption {
6
6
  name: string;
7
7
  values: string[];
8
+ /** Values in this group that no variant takes with the other current picks; drawn dimmed, still pressable. */
9
+ dimmed?: string[];
8
10
  }
9
11
 
10
12
  export interface ProductVariantPickerProps extends Omit<ViewProps, 'children'> {
@@ -36,10 +38,12 @@ export function ProductVariantPicker({
36
38
  return (
37
39
  <Pressable
38
40
  key={value}
41
+ testID={`variant-option-${option.name}-${value}`}
39
42
  onPress={() => handleSelect(option.name, value)}
40
43
  className={cn(
41
44
  'rounded-lg border px-3 py-1.5',
42
45
  active ? 'border-primary bg-primary/10' : 'border-border bg-card',
46
+ option.dimmed?.includes(value) && 'opacity-50',
43
47
  )}
44
48
  >
45
49
  <Text
package/src/sale/cart.tsx CHANGED
@@ -255,8 +255,10 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
255
255
  /** A fee or shipping row on the picker's read-only bill: the row alone, no Edit or Remove strip. */
256
256
  const ReadOnlyStrip = ({ children }: Parameters<typeof CartLineStrip>[0]) => <>{children((content) => content)}</>;
257
257
 
258
- /** Cart's `picker` stepper, v2's `− n of unpaid +` (tender/unit-stepper.tsx), with what the picked units add under it. */
259
- function PickStepper({ picker, id, name, unpaid, currency }: { picker: NonNullable<Parameters<typeof Cart>[0]['picker']>;
258
+ /** WCPOS v2's `− n of unpaid +` stepper (tender/unit-stepper.tsx), the one Cart's `picker` draws in each pickable line's
259
+ * quantity cell, with what the picked units add under it. An app cart built on CartPanel and CartLine passes it as
260
+ * CartLine's `quantitySlot` (with `picking`), with the same `picker` object Cart takes. */
261
+ export function PickStepper({ picker, id, name, unpaid, currency }: { picker: NonNullable<Parameters<typeof Cart>[0]['picker']>;
260
262
  id: string; name: string; unpaid: number; currency: string }) {
261
263
  const t = useT();
262
264
  const formatMoney = useFormatMoney();
@@ -167,8 +167,9 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
167
167
  /** v2's table row extras in table view: thumbnail leads the row, addButton ends it with the + (> for a product
168
168
  * with variants) that does what a row press does. With expand and thumbnail, a product with more than one variant
169
169
  * has its thumbnail show or hide its variants as rows under it: option chips, price, stock and a + that adds that
170
- * variant as the list chooser does. Default: none. */
171
- tableRow?: { thumbnail?: boolean; addButton?: boolean; expand?: boolean };
170
+ * variant as the list chooser does; variationsButton adds v2's '{count} variations' button under the name, which shows
171
+ * or hides the variants as expand does; it needs expand. Default: none. */
172
+ tableRow?: { thumbnail?: boolean; addButton?: boolean; expand?: boolean; variationsButton?: boolean };
172
173
  /** v2's rows between the chips and the products (its ListColumn `rows`): notices such as "Price check only until
173
174
  * the register is open.", rendered under the header and above the grid, table or category tiles. Default none. */
174
175
  rowsSlot?: ReactNode;
@@ -534,7 +535,7 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
534
535
  if (next.has(key)) next.delete(key); else next.add(key);
535
536
  return next;
536
537
  }) : undefined}
537
- renderExpanded={tableRow?.expand ? variantRows : undefined}
538
+ renderExpanded={tableRow?.expand ? variantRows : undefined} variationsButton={tableRow?.variationsButton}
538
539
  cartQuantity={(doc) => quantities.get(traits.getId(doc)) ?? 0} />
539
540
  ) : drillEntries.length > 0 ? <LevelWrap level onBack={() => setDrillId(null)}>
540
541
  {/* v2 drill-in.tsx:44-68: "Products › name" above the variant tiles; at phone width the Breadcrumb drops the separator. */}
@@ -18,19 +18,24 @@ export interface ChargeFormProps {
18
18
  * Add Miscellaneous Product entries); absent, the form opens on Fee with the row. */
19
19
  kind?: 'fee' | 'shipping' | 'custom';
20
20
  /** Given, the form edits that charge: prefilled, titled `Edit <name>` as v2's record dialog. */
21
- initial?: { name: string; amountMinor: number; taxStatus?: 'taxable' | 'none'; taxClass?: string; percent?: number; amountIncludesTax?: boolean };
21
+ initial?: { name: string; amountMinor: number; taxStatus?: 'taxable' | 'none'; taxClass?: string; percent?: number; amountIncludesTax?: boolean;
22
+ sku?: string };
23
+ /** On the custom kind, shows v2's "+ SKU" add-row after the tax rows; pressing it shows the SKU field. */
24
+ sku?: boolean;
22
25
  /** Shows the amount-unit toggle (currency symbol or %) on the fee kind, as v2's AmountUnitToggle. */
23
26
  allowPercent?: boolean;
24
27
  /** The store's tax mode. Given, the fee and shipping kinds show the "Amount Includes Tax" switch (not on a percent fee), which starts at this
25
28
  * value (Desk Q4: default = store tax mode, ADR-075). */
26
29
  pricesIncludeTax?: boolean;
27
30
  onApply: (charge: { kind: 'fee' | 'shipping' | 'custom'; name: string; amountMinor: number;
28
- taxStatus?: 'none'; taxClass?: string; percent?: number; amountIncludesTax?: boolean }) => string | null;
31
+ taxStatus?: 'none'; taxClass?: string; percent?: number; amountIncludesTax?: boolean;
32
+ sku?: string }) => string | null;
29
33
  onClose: () => void;
30
34
  }
31
35
 
32
36
  const NAME_LABEL_ID = 'charge-form-name-label';
33
37
  const AMOUNT_LABEL_ID = 'charge-form-amount-label';
38
+ const SKU_LABEL_ID = 'charge-form-sku-label';
34
39
 
35
40
  const button = 'rounded-md border border-border px-3 py-2 min-h-11 items-center justify-center';
36
41
  /** A blank name takes v2's default for the kind: add-fee.tsx:71 (`pos_cart.fee`), add-shipping.tsx:73
@@ -38,7 +43,7 @@ const button = 'rounded-md border border-border px-3 py-2 min-h-11 items-center
38
43
  const DEFAULT_NAME: Record<'fee' | 'shipping' | 'custom', string> = { fee: 'Fee', shipping: 'Shipping', custom: 'Product' };
39
44
 
40
45
  /** `onApply` returns a refusal to show inline, or null once applied. */
41
- export function ChargeForm({ currency, lineTax, taxClasses, shippingTaxFromStore, shippingNoTax, kind: fixedKind, initial, allowPercent,
46
+ export function ChargeForm({ currency, lineTax, taxClasses, shippingTaxFromStore, shippingNoTax, kind: fixedKind, initial, sku, allowPercent,
42
47
  pricesIncludeTax, onApply, onClose }: ChargeFormProps) {
43
48
  const currencySymbol = useCurrencySymbol();
44
49
  const format = useMoneyFormat();
@@ -54,7 +59,10 @@ export function ChargeForm({ currency, lineTax, taxClasses, shippingTaxFromStore
54
59
  const [noTax, setNoTax] = useState(initial?.taxStatus === 'none');
55
60
  const [includesTax, setIncludesTax] = useState(initial?.amountIncludesTax ?? pricesIncludeTax ?? false);
56
61
  const [taxClass, setTaxClass] = useState(initial?.taxClass ?? '');
62
+ const [skuText, setSkuText] = useState(initial?.sku ?? '');
63
+ const [skuOpen, setSkuOpen] = useState(Boolean(initial?.sku));
57
64
  const [error, setError] = useState<string | null>(null);
65
+ const showSku = Boolean(sku) && kind === 'custom';
58
66
  const storeShipping = kind === 'shipping' && shippingTaxFromStore;
59
67
  const showNoTax = storeShipping ? shippingNoTax : lineTax?.none;
60
68
  const showUnit = Boolean(allowPercent) && kind === 'fee';
@@ -81,6 +89,7 @@ export function ChargeForm({ currency, lineTax, taxClasses, shippingTaxFromStore
81
89
  ...(percentMode ? { percent: parsed } : !showUnit && initial?.percent !== undefined ? { percent: initial.percent } : {}),
82
90
  ...(percentMode ? {} : showIncludesTax ? includesTax !== pricesIncludeTax ? { amountIncludesTax: includesTax } : {}
83
91
  : initial?.amountIncludesTax !== undefined ? { amountIncludesTax: initial.amountIncludesTax } : {}),
92
+ ...(showSku ? skuText.trim() ? { sku: skuText.trim() } : {} : initial?.sku ? { sku: initial.sku } : {}),
84
93
  });
85
94
  setError(refused);
86
95
  if (refused === null) onClose();
@@ -130,6 +139,15 @@ export function ChargeForm({ currency, lineTax, taxClasses, shippingTaxFromStore
130
139
  </Pressable>)}
131
140
  </View> : null}
132
141
  </>}
142
+ {/* v2's "+ SKU" add-row (add-misc-product.tsx) on the custom item. */}
143
+ {showSku ? skuOpen ? <>
144
+ <Label nativeID={SKU_LABEL_ID}>{t('common.sku')}</Label>
145
+ <TextInput testID="charge-form-sku-input" accessibilityLabelledBy={SKU_LABEL_ID} accessibilityLabel={t('common.sku')}
146
+ value={skuText} onChangeText={setSkuText}
147
+ className="min-w-0 rounded-md border border-border bg-background px-3 py-2 text-foreground" />
148
+ </> : <Pressable testID="charge-form-add-sku" accessibilityRole="button" onPress={() => setSkuOpen(true)}
149
+ className={`${button} bg-card self-start`}>
150
+ <Text className="text-foreground">{`+ ${t('common.sku')}`}</Text></Pressable> : null}
133
151
  {error ? <Text accessibilityRole="alert" className="text-destructive">{error}</Text> : null}
134
152
  <View className="flex-row gap-2">
135
153
  <Pressable accessibilityRole="button" onPress={apply} className={`${button} bg-primary`}>
@@ -0,0 +1,6 @@
1
+ import type { Order } from '@tallyui/pos';
2
+
3
+ /** Money taken before this sale was reopened, or that the store holds: the till never voids, removes or re-references it (desk 2026-11-21). */
4
+ export function heldTillLeg(order: Order, leg: Order['payments'][number]): boolean {
5
+ return !!leg.locked || !!leg.reopened || !!order.afterClose?.payments.some((p) => p.id === leg.id);
6
+ }
package/src/sale/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { Cart } from './cart';
1
+ export { Cart, PickStepper } from './cart';
2
2
  export { OrderNoteSheet, type OrderNoteSheetProps } from './order-note-sheet';
3
3
  export { CartBar } from './cart-bar';
4
4
  export { Tender, SplitTender } from './tender';
@@ -10,7 +10,7 @@ export { ChargeForm, type ChargeFormProps } from './charge-form';
10
10
  export { Catalogue, formatStockSyncTime } from './catalogue';
11
11
  export { CatalogueSettingsForm, type CatalogueSettingsFormProps } from './catalogue-settings-form';
12
12
  export { Receipt } from './receipt';
13
- export { ReceiptSheet, type ReceiptSheetEmail, type ReceiptSheetProps, type ReceiptSheetTemplate } from './receipt-sheet';
13
+ export { ReceiptEmailForm, type ReceiptEmailFormProps, ReceiptSheet, type ReceiptSheetEmail, type ReceiptSheetProps, type ReceiptSheetTemplate } from './receipt-sheet';
14
14
  export { orderReference } from './order-reference';
15
15
  export { injectPrintStyle } from './print-style';
16
16
  export { SyncStatus, syncStatusQuiet } from './sync-status';
@@ -124,7 +124,8 @@ export function LinePopover({ kind, lineName, currency, value, onApply, quickDis
124
124
  {mounted ? <Popover.Portal forceMount>
125
125
  <Popover.Overlay testID={`${kind}-popover-overlay`} style={StyleSheet.absoluteFill} />
126
126
  <Popover.Content forceMount testID={`${kind}-popover`} align={price ? 'end' : 'start'} sideOffset={4}
127
- aria-labelledby={titleId} aria-describedby={undefined} onEscapeKeyDown={() => { discard.current = true; }}>
127
+ aria-labelledby={titleId} aria-describedby={undefined} onEscapeKeyDown={() => { discard.current = true; }}
128
+ pointerEvents={open ? 'auto' : 'none'}>
128
129
  <Animated.View className="w-64 rounded-md border border-border bg-popover p-4 shadow-md"
129
130
  style={{ opacity: panel, transform: Platform.OS === 'web' ? [{ translateY: panel.interpolate({ inputRange: [0, 1], outputRange: [-6, 0] }) }] : undefined }}
130
131
  pointerEvents={open ? 'auto' : 'none'}>
@@ -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
3
  import { useFormatMoney, knownWarnings } from '@tallyui/core';
4
- import { extrasNotSent, isRequeueableOrder, needsAttention, noteDelivery, refundDueOf, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, type OutboxState, type PosOrder } from '@tallyui/pos';
4
+ import { extrasNotSent, isRequeueableOrder, needsAttention, noteDelivery, refundDueOf, REOPENABLE_CODES, 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
 
@@ -29,6 +29,8 @@ const REFUSAL_SENTENCES = new Map([
29
29
  ['invalid_quantity', "The online store refused this sale: a quantity or a discount on it isn't allowed."],
30
30
  ['underpaid', 'The online store refused this sale: the payments add up to less than the total.'],
31
31
  ['unsupported_currency', "The online store refused this sale: the store doesn't take this currency."],
32
+ ['coupon_invalid', "The online store refused this sale: a coupon on it isn't valid now. Reopen it to sell it again."],
33
+ ['total_mismatch', "The online store refused this sale: its total didn't match the store's. Reopen it to sell it again."],
32
34
  ]);
33
35
  // Any other code, or none: platform_error's sentence, as the generic fallback (approved by the Front desk, 2026-09-30).
34
36
  const refusalSentence = (code: string | undefined) => REFUSAL_SENTENCES.get(code ?? '') ?? REFUSAL_SENTENCES.get('platform_error')!;
@@ -103,17 +105,47 @@ export function OrderSyncNotices({ order, stuck, children }: OrderSyncNoticesPro
103
105
  * (medusapos: the feedback link). The router and session redirect stay in the app. `stuck` is the outbox's
104
106
  * `state.stuck` (`useOrderOutbox`): those pending orders need attention too, each with its own entry's reason and since.
105
107
  * `onOpen` adds an Open button to each row that passes its order to the app.
106
- * `history` adds read-only store order rows to Recent (ADR-052 amendment 1). */
107
- export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, footer, stuck, history, onOpen }: {
108
+ * `history` adds read-only store order rows to Recent (ADR-052 amendment 1).
109
+ * `onReopen` adds Reopen to a Needs attention row the store refused with a reopenable code (`REOPENABLE_CODES`), not yet
110
+ * reopened and with no store order: the app wires `reopenRefusedOrder`. When it refuses `coupon_carry_inexact` with a
111
+ * `toCollectMinor`, the row offers "Reopen without the coupon", which calls it again with `{ withoutCoupons: true }`.
112
+ * `onResume` adds Resume to a reopened row; the app resumes the parked sale, whose draft id is the order's id. */
113
+ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, footer, stuck, history, onOpen, onReopen, onResume }: {
108
114
  orders: PosOrder[]; onRetry(orderIds: string[]): Promise<number>; formatDate?: (iso: string) => string; footer?: ReactNode;
109
115
  stuck?: OutboxState['stuck'];
110
116
  history?: OrderHistoryRow[];
111
117
  onOpen?: (row: PosOrder | OrderHistoryRow) => void;
118
+ onReopen?: (order: PosOrder, options?: { withoutCoupons: true }) => Promise<void>;
119
+ onResume?: (order: PosOrder) => void;
112
120
  }) {
113
121
  const formatMoney = useFormatMoney();
114
122
  const hintId = useId();
115
123
  const retrying = useRef(new Set<string>());
116
124
  const [retryingIds, setRetryingIds] = useState(new Set<string>());
125
+ /** Each row's Reopen: in flight, the inexact refusal's amount to collect, or the reason it was refused (null: none given). */
126
+ const reopening = useRef(new Set<string>());
127
+ const [reopens, setReopens] = useState(new Map<string, { busy?: true; toCollectMinor?: number; failed?: string | null }>());
128
+ const setReopen = (id: string, state?: { busy?: true; toCollectMinor?: number; failed?: string | null }) => setReopens((current) => {
129
+ const next = new Map(current);
130
+ if (state) next.set(id, state); else next.delete(id);
131
+ return next;
132
+ });
133
+ async function reopen(order: PosOrder, options?: { withoutCoupons: true }) {
134
+ if (!onReopen || reopening.current.has(order.id)) return;
135
+ reopening.current.add(order.id);
136
+ setReopen(order.id, { ...reopens.get(order.id), busy: true });
137
+ try {
138
+ await onReopen(order, options);
139
+ setReopen(order.id);
140
+ } catch (error) {
141
+ const reason = (error as { reason?: unknown } | undefined)?.reason;
142
+ const toCollectMinor = (error as { toCollectMinor?: unknown } | undefined)?.toCollectMinor;
143
+ setReopen(order.id, reason === 'coupon_carry_inexact' && typeof toCollectMinor === 'number' ? { toCollectMinor }
144
+ : { failed: typeof reason === 'string' ? reason : null });
145
+ } finally {
146
+ reopening.current.delete(order.id);
147
+ }
148
+ }
117
149
  const [expanded, setExpanded] = useState(new Set<string>());
118
150
  useEffect(() => {
119
151
  for (const id of retrying.current) {
@@ -151,6 +183,10 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
151
183
  const refundDueMinor = refundDueOf(order);
152
184
  const key = `${section.title}:${order.id}`;
153
185
  const isExpanded = expanded.has(key);
186
+ const attention = section.title === 'Needs attention';
187
+ const reopenable = attention && !!onReopen && order.syncStatus === 'rejected' && REOPENABLE_CODES.includes(order.error?.code ?? '')
188
+ && order.storeOrderId === undefined && order.reopenedAt === undefined;
189
+ const reopenState = reopens.get(order.id);
154
190
  return (
155
191
  <View key={order.id} className="gap-1 rounded-md border border-border bg-card p-3">
156
192
  {/* RN-web drops accessibilityHint; aria-describedby carries it on web. */}
@@ -193,6 +229,29 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
193
229
  }} className="rounded-md bg-primary px-4 py-2">
194
230
  <Text className="text-center font-semibold text-primary-foreground">Retry</Text>
195
231
  </Pressable> : null}
232
+ {/* Reopen needs a reopenable code, which Retry never resends (NOT_REQUEUEABLE), so the two never show together. */}
233
+ {attention && order.reopenedAt !== undefined ? <>
234
+ <Text testID={`order-${order.id}-reopened`} className="text-muted-foreground">Reopened as a parked sale.</Text>
235
+ {onResume ? <Pressable accessibilityRole="button" accessibilityLabel={`Resume order ${orderReference(order)}`}
236
+ testID={`order-${order.id}-resume`} onPress={() => onResume(order)} className="rounded-md bg-primary px-4 py-2">
237
+ <Text className="text-center font-semibold text-primary-foreground">Resume</Text>
238
+ </Pressable> : null}
239
+ </> : null}
240
+ {reopenable && reopenState?.failed !== undefined ? <Text testID={`order-${order.id}-reopen-error`} className="text-muted-foreground">
241
+ {reopenState.failed ? `This sale can't be reopened here (${reopenState.failed}).` : "This sale can't be reopened here."}
242
+ </Text> : reopenable ? <>
243
+ <Pressable accessibilityRole="button" accessibilityLabel={`Reopen order ${orderReference(order)}`} testID={`order-${order.id}-reopen`}
244
+ disabled={reopenState?.busy} onPress={() => reopen(order)} className="rounded-md bg-primary px-4 py-2">
245
+ <Text className="text-center font-semibold text-primary-foreground">Reopen</Text>
246
+ </Pressable>
247
+ {/* The inexact carry's choice is offered, never taken (desk 2026-11-21): its amount is the refusal's toCollectMinor. */}
248
+ {reopenState?.toCollectMinor !== undefined ? <Pressable accessibilityRole="button" testID={`order-${order.id}-reopen-without-coupon`}
249
+ disabled={reopenState.busy} onPress={() => reopen(order, { withoutCoupons: true })} className="rounded-md border border-border px-4 py-2">
250
+ <Text className="text-center font-semibold text-foreground">
251
+ {`Reopen without the coupon: ${formatMoney({ amount: reopenState.toCollectMinor, currency: order.currency })} to collect`}
252
+ </Text>
253
+ </Pressable> : null}
254
+ </> : null}
196
255
  </OrderSyncNotices>
197
256
  </View>
198
257
  );
@@ -32,7 +32,7 @@ export interface ReceiptSheetEmail {
32
32
  offline?: boolean;
33
33
  /** Draws "Save email to the customer" (default off). */
34
34
  saveToCustomer?: boolean;
35
- /** Sends or queues the receipt. Returns a refusal to show, or null once sent or queued; the form then closes. */
35
+ /** Sends or queues the receipt. Returns a refusal to show, or null once sent or queued; the form then shows "Email sent", or "Receipt email queued" when offline. */
36
36
  onSend: (input: { address: string; saveToCustomer: boolean }) => Promise<string | null> | string | null;
37
37
  }
38
38
 
@@ -135,13 +135,31 @@ function PrinterValue({ printers, printerId, autoPrinterName, onPrinterChange }:
135
135
  }
136
136
 
137
137
  const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+$/;
138
+ const SEND_FAILED = 'Could not send the receipt.';
138
139
 
139
- /** v2's email.tsx (MIT, WCPOS) inline: it mounts fresh on each open, so it starts from defaultAddress, switch off, no error. */
140
- function EmailForm({ email, onDone }: { email: ReceiptSheetEmail; onDone: (queued: boolean) => void }) {
140
+ /** The sent/queued line, drawn by ReceiptEmailForm after a send and by ReceiptSheet in the form's place. */
141
+ function EmailSentLine({ queued }: { queued: boolean }) {
142
+ const t = useT();
143
+ return <Text testID="receipt-email-sent" className="py-2 text-sm text-foreground">{t(queued ? 'receipt.email_queued' : 'receipt.email_sent')}</Text>;
144
+ }
145
+
146
+ export interface ReceiptEmailFormProps {
147
+ email: ReceiptSheetEmail;
148
+ /** Called once after `onSend` returns null, with true when `email.offline` was set (queued). */
149
+ onDone?: (queued: boolean) => void;
150
+ }
151
+
152
+ /**
153
+ * v2's email.tsx (MIT, WCPOS) inline, the form ReceiptSheet draws: "Email Address" prefilled from `defaultAddress`,
154
+ * the save switch (off), the offline notice and Send. After `onSend` returns null it shows "Email sent" or
155
+ * "Receipt email queued" in its own place and calls `onDone`. Remount it (for example with a new `key`) to send again.
156
+ */
157
+ export function ReceiptEmailForm({ email, onDone }: ReceiptEmailFormProps): JSX.Element {
141
158
  const [text, setText] = useState(email.defaultAddress ?? '');
142
159
  const [save, setSave] = useState(false);
143
160
  const [error, setError] = useState<string | null>(null);
144
161
  const [sending, setSending] = useState(false);
162
+ const [sent, setSent] = useState<'sent' | 'queued' | null>(null);
145
163
  const send = async () => {
146
164
  if (sending) return;
147
165
  const address = text.trim();
@@ -153,11 +171,14 @@ function EmailForm({ email, onDone }: { email: ReceiptSheetEmail; onDone: (queue
153
171
  if (typeof result === 'string' || result === null) refusal = result;
154
172
  else { setSending(true); refusal = await result; }
155
173
  } catch (cause) {
156
- refusal = cause instanceof Error ? cause.message : 'Could not send the receipt.';
174
+ refusal = cause instanceof Error ? cause.message : SEND_FAILED;
157
175
  }
158
176
  setSending(false);
159
- if (refusal === null) onDone(Boolean(email.offline)); else setError(refusal);
177
+ if (refusal !== null) return setError(refusal || SEND_FAILED);
178
+ setSent(email.offline ? 'queued' : 'sent');
179
+ onDone?.(Boolean(email.offline));
160
180
  };
181
+ if (sent) return <EmailSentLine queued={sent === 'queued'} />;
161
182
  return (
162
183
  <View testID="receipt-email-form" className="gap-2 py-2">
163
184
  <Text className="text-sm font-medium text-foreground">Email Address</Text>
@@ -186,7 +207,6 @@ function EmailForm({ email, onDone }: { email: ReceiptSheetEmail; onDone: (queue
186
207
  export function ReceiptSheet({ open, onOpenChange, title = 'Receipt', templates, templateId, onTemplateChange,
187
208
  printerLabel = 'Browser print dialog', printers, printerId, autoPrinterName, onPrinterChange,
188
209
  onPrint, printing = false, printed = false, onEmail, email, onDownloadPdf, downloadingPdf = false, children }: ReceiptSheetProps): JSX.Element {
189
- const t = useT();
190
210
  const [sent, setSent] = useState<'sent' | 'queued' | null>(null);
191
211
  const [emailOpen, setEmailOpen] = useState(false);
192
212
  // Closing the sheet closes the form too, so it opens fresh next time.
@@ -214,8 +234,8 @@ export function ReceiptSheet({ open, onOpenChange, title = 'Receipt', templates,
214
234
  </View>
215
235
  {/* v2 draws its own WebView preview with zoom and loading states; here the app's preview is the child. */}
216
236
  <ScrollView className="flex-1" contentContainerClassName="pb-2">{children}</ScrollView>
217
- {email && emailOpen ? <EmailForm email={email} onDone={(queued) => { setEmailOpen(false); setSent(queued ? 'queued' : 'sent'); }} /> : null}
218
- {email && sent ? <Text testID="receipt-email-sent" className="py-2 text-sm text-foreground">{t(sent === 'queued' ? 'receipt.email_queued' : 'receipt.email_sent')}</Text> : null}
237
+ {email && emailOpen ? <ReceiptEmailForm email={email} onDone={(queued) => { setEmailOpen(false); setSent(queued ? 'queued' : 'sent'); }} /> : null}
238
+ {email && sent ? <EmailSentLine queued={sent === 'queued'} /> : null}
219
239
  {/* v2's footer also has Sync order, which TallyUI does not have. `email` draws v2's form above, and the app sends. Download PDF is drawn when `onDownloadPdf` is given. */}
220
240
  <DialogFooter bordered className="gap-2" testID="receipt-footer">
221
241
  <DialogClose asChild>
@@ -1,7 +1,10 @@
1
+ // The device's own 12/24-hour format, with no forced leading zero on the hour.
2
+ export function shortTime(t: number | string): string {
3
+ return new Date(t).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
4
+ }
5
+
1
6
  // The time a stuck line names: the real first failure when this run has one, else "about" the virtual since (after a restart
2
7
  // firstFailedAt is gone; see OutboxState.stuck).
3
8
  export function sinceText(clock: { since: number; firstFailedAt?: number }): string {
4
- // The device's own 12/24-hour format, with no forced leading zero on the hour.
5
- const time = (t: number) => new Date(t).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
6
- return clock.firstFailedAt === undefined ? 'about ' + time(clock.since) : time(clock.firstFailedAt);
9
+ return clock.firstFailedAt === undefined ? 'about ' + shortTime(clock.since) : shortTime(clock.firstFailedAt);
7
10
  }
@@ -71,6 +71,8 @@ const REFUSED_DETAIL = 'Refused sales stay on this till under Needs attention, e
71
71
  // on reopen and both sentences name a reopen.
72
72
  const SALES_REFUSED = 'The online store refused the last send. This till will try again with the next sale, or when the app is reopened.';
73
73
  const TILL_UPDATES_REFUSED = 'The online store refused the last send. This till will try again with the next till update, or when the app is reopened.';
74
+ // The line below the sending or retrying line while the shown outbox's lastRetryReason is store_version_unknown.
75
+ const STORE_VERSION_UNKNOWN = "The online store didn't say which POS plugin version it runs.";
74
76
 
75
77
  const count = (n: number, noun: string) => `${n} ${noun}${n === 1 ? '' : 's'}`;
76
78
  // iOS has no live region (accessibilityLiveRegion is Android-only), so there each text is announced when it changes: never on
@@ -147,6 +149,8 @@ export function SyncStatus({ state, registerState, pluginName = 'the POS plugin'
147
149
  {oneDetail ? null : <Text className="px-4 pb-2 text-xs text-muted-foreground">{notice.detail}</Text>}
148
150
  </> : null}<Text accessibilityLabel={spoken} accessibilityLiveRegion="polite" className="px-4 py-2 text-xs text-muted-foreground">{spoken}</Text>
149
151
  {doing ? <Text className="px-4 pb-2 text-xs text-muted-foreground">{doing}</Text> : null}
152
+ {doing && outbox.lastRetryReason === 'store_version_unknown'
153
+ ? <Text className="px-4 pb-2 text-xs text-muted-foreground">{STORE_VERSION_UNKNOWN}</Text> : null}
150
154
  {refused ? <Text className="px-4 pb-2 text-xs text-muted-foreground">{REFUSED_DETAIL}</Text> : null}
151
155
  {oneDetail && notice ? <Text className="px-4 pb-2 text-xs text-muted-foreground">{notice.detail}</Text>
152
156
  : backendMissing ? <Text className="px-4 pb-2 text-xs text-muted-foreground">
@@ -10,7 +10,9 @@ import { canVoidLeg, countsTowardPaid, legStatus, type PaymentLegStatus, type us
10
10
  import { cn } from '@tallyui/theme';
11
11
  import { useT } from '../i18n';
12
12
  import { ConfirmDialog } from '../ui/confirm-dialog';
13
+ import { heldTillLeg } from './held-leg';
13
14
  import { offeredMethods } from './offered-methods';
15
+ import { shortTime } from './since-text';
14
16
 
15
17
  /** v2 labels.ts statusLabel, as catalogue keys. */
16
18
  const STATUS_LABEL: Record<PaymentLegStatus, string> = {
@@ -38,6 +40,9 @@ export function TenderLedger({ sale, methods, closing = false, confirmVoid = fal
38
40
  const money = (minor: number) => formatMoney({ amount: minor, currency: order.currency }) ?? '';
39
41
  const balance = order.balanceDueMinor;
40
42
  const settled = order.payments.some(countsTowardPaid);
43
+ /** v2's paid_in_full_at: the time of the last settled leg (settled.at(-1)); plain Paid in full when it has none. */
44
+ const paidAt = order.payments.filter(countsTowardPaid).at(-1)?.takenAt;
45
+ const paidInFull = paidAt ? t('pos_checkout.paid_in_full_at', { time: shortTime(paidAt) }) : t('pos_checkout.paid_in_full');
41
46
  const firstPending = order.payments.find((leg) => legStatus(leg) === 'pending');
42
47
  const askedLeg = order.payments.find((leg) => leg.id === asking);
43
48
  const asked = askedLeg && descriptorOf(askedLeg);
@@ -58,14 +63,15 @@ export function TenderLedger({ sale, methods, closing = false, confirmVoid = fal
58
63
  <Text testID={`tender-leg-${leg.id}-status`} className={cn('text-sm font-semibold', STATUS_TONE[status])}>{voided ? t('pos_checkout.cancelled') : t(STATUS_LABEL[status])}</Text>
59
64
  </View>
60
65
  {leg.reference ? <Text className="text-sm text-muted-foreground">{leg.reference}</Text> : null}
66
+ {leg.takenAt ? <Text testID={`tender-leg-${leg.id}-time`} className="text-sm text-muted-foreground">{shortTime(leg.takenAt)}</Text> : null}
61
67
  {leg === firstPending ? <Text className="text-sm text-muted-foreground">{t('pos_checkout.next_leg')}</Text> : null}
62
- {descriptor && canVoidLeg(leg, descriptor) ? <Pressable testID={`tender-leg-${leg.id}-void`} accessibilityRole="button" accessibilityLabel={t('pos_checkout.cancel_payment')}
68
+ {descriptor && canVoidLeg(leg, descriptor) && !heldTillLeg(order, leg) ? <Pressable testID={`tender-leg-${leg.id}-void`} accessibilityRole="button" accessibilityLabel={t('pos_checkout.cancel_payment')}
63
69
  onPress={() => (confirmVoid ? setAsking(leg.id) : sale.voidTender(leg.id))} className="self-start min-h-11 justify-center px-2">
64
70
  <Text className="text-destructive">{t('pos_checkout.cancel_payment')}</Text>
65
71
  </Pressable> : null}
66
72
  </View>;
67
73
  })}
68
- {!closing && balance === 0 && settled ? <Text className="text-sm text-success">{t('pos_checkout.paid_in_full')}</Text> : null}
74
+ {!closing && balance === 0 && settled ? <Text className="text-sm text-success">{paidInFull}</Text> : null}
69
75
  {confirmVoid ? <ConfirmDialog testID="tender-leg-void-dialog" tone="destructive" title={t('pos_checkout.cancel_payment_question')} description={question}
70
76
  confirmLabel={t('pos_checkout.cancel_payment')} open={asking !== null} onOpenChange={(open) => { if (!open) setAsking(null); }}
71
77
  onConfirm={() => { if (asking) sale.voidTender(asking); }} /> : null}
@@ -82,7 +88,7 @@ export function TenderLedger({ sale, methods, closing = false, confirmVoid = fal
82
88
  {row(t('common.total'), order.totalMinor)}
83
89
  {row(t('pos_checkout.paid'), order.paidMinor)}
84
90
  <View testID="tender-ledger-lead" className="mt-1.5 flex-row justify-between border-t border-border pt-2">
85
- {balance === 0 && settled ? <Text className="font-semibold text-success">{t('pos_checkout.paid_in_full')}</Text> : <>
91
+ {balance === 0 && settled ? <Text className="font-semibold text-success">{paidInFull}</Text> : <>
86
92
  <Text className="font-semibold text-foreground">{t('pos_checkout.remaining')}</Text>
87
93
  <Text testID="tender-ledger-remaining" className="font-semibold text-foreground">{money(order.balanceDueMinor)}</Text>
88
94
  </>}
@@ -17,6 +17,7 @@ import { QUICK_CASH_STEPS } from '../checkout/cash-tendered';
17
17
  import { useT } from '../i18n';
18
18
  import { DIGIT_ROWS, Keypad } from '../input/keypad';
19
19
  import { offeredMethods, tenderOf } from './offered-methods';
20
+ import { heldTillLeg } from './held-leg';
20
21
  import { TenderLedger } from './tender-ledger';
21
22
  import { pickFigure } from './use-tender';
22
23
  import { BanknoteIcon } from '../ui/icon/banknote-icon';
@@ -105,7 +106,8 @@ export function TenderPane({ sale, state, dispatch, methods, ledger = true, back
105
106
  const balanceChip = method !== null && !givesChange && state.entryMode !== 'percent' ? dueMinor : null;
106
107
  const [onlyLeg] = order.payments;
107
108
  // startTender('external') records the card leg for the total: its reference is edited in place, as before.
108
- const cardReference = order.payments.length === 1 && onlyLeg.method === 'external' && legStatus(onlyLeg) === 'captured' && balance === 0;
109
+ const cardReference = order.payments.length === 1 && onlyLeg.method === 'external' && legStatus(onlyLeg) === 'captured' && balance === 0
110
+ && !heldTillLeg(order, onlyLeg);
109
111
  const hint = partPick ? (pickRefused || entry === target ? t('pos_checkout.pick_amount_due', { amount: money(target) })
110
112
  : givesChange && entry > target ? t('pos_checkout.change_due', { amount: money(entry - target) }) : '')
111
113
  : pickRefused ? t('pos_checkout.pick_amount_due', { amount: money(figures.roundedDueMinor) })
@@ -240,7 +242,7 @@ export function TenderPane({ sale, state, dispatch, methods, ledger = true, back
240
242
 
241
243
  {refused.length > 0 ? <>
242
244
  <Text testID="tender-store-holds" className="text-foreground">{t('pos_checkout.store_holds_payment', { amount: money(refusedMinor) })}</Text>
243
- {refused.map((id) => <Pressable key={id} testID={`tender-leg-${id}-remove`} accessibilityRole="button" onPress={() => sale.removeTender(id)} className={button}>
245
+ {refused.filter((id) => !order.payments.some((leg) => leg.id === id && heldTillLeg(order, leg))).map((id) => <Pressable key={id} testID={`tender-leg-${id}-remove`} accessibilityRole="button" onPress={() => sale.removeTender(id)} className={button}>
244
246
  <Text className="text-center text-foreground">{t('pos_checkout.remove_payment')}</Text>
245
247
  </Pressable>)}
246
248
  </> : null}