@tallyui/components 3.13.0 → 3.14.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.
Files changed (40) hide show
  1. package/dist/index.d.ts +275 -27
  2. package/dist/index.js +1985 -1226
  3. package/package.json +9 -9
  4. package/src/cart/cart-columns.tsx +57 -0
  5. package/src/cart/cart-line.tsx +32 -17
  6. package/src/cart/index.ts +1 -0
  7. package/src/checkout/cash-tendered.tsx +5 -7
  8. package/src/index.ts +18 -2
  9. package/src/lib/error-text.ts +5 -0
  10. package/src/order/refund-form.tsx +2 -1
  11. package/src/product/category-tile.tsx +43 -0
  12. package/src/product/in-cart-badge.tsx +26 -0
  13. package/src/product/index.ts +2 -0
  14. package/src/register/closure-sheet.tsx +2 -1
  15. package/src/register/handover-slip.tsx +46 -0
  16. package/src/register/index.ts +2 -0
  17. package/src/register/movement-sheet.tsx +2 -1
  18. package/src/register/open-register-card.tsx +2 -1
  19. package/src/register/register-bar.tsx +57 -11
  20. package/src/register/register-column.tsx +2 -1
  21. package/src/register/register-count.tsx +30 -11
  22. package/src/register/register-panel.tsx +45 -4
  23. package/src/register/switch-confirm.tsx +102 -0
  24. package/src/sale/cart.tsx +37 -21
  25. package/src/sale/catalogue.tsx +34 -5
  26. package/src/sale/customer-display-screen.tsx +92 -0
  27. package/src/sale/index.ts +4 -2
  28. package/src/sale/parked-sales.tsx +2 -1
  29. package/src/sale/price-form.tsx +28 -4
  30. package/src/sale/product-filter-bar.tsx +58 -0
  31. package/src/sale/tender-pane.tsx +179 -0
  32. package/src/sale/tender.tsx +20 -35
  33. package/src/shell/app-shell.tsx +71 -0
  34. package/src/shell/index.ts +4 -0
  35. package/src/shell/nav-drawer.tsx +130 -0
  36. package/src/shell/nav-item.tsx +70 -0
  37. package/src/shell/nav-rail.tsx +58 -0
  38. package/src/shell/shell-context.ts +18 -0
  39. package/src/ui/icon/menu-icon.tsx +10 -0
  40. package/src/sale/split-tender.tsx +0 -81
@@ -14,6 +14,7 @@ import {
14
14
 
15
15
  import { currencySymbol, formatMoney, minorUnitDigits } from '@tallyui/core';
16
16
  import { cn } from '@tallyui/theme';
17
+ import { errorText } from '../lib/error-text';
17
18
  import { Button } from '../ui/button';
18
19
  import { Input } from '../ui/input';
19
20
  import { Label } from '../ui/label';
@@ -31,10 +32,6 @@ export function varianceWord(key: string): string {
31
32
  return 'over';
32
33
  }
33
34
 
34
- function errorMessage(error: unknown): string {
35
- return error instanceof Error ? error.message : String(error);
36
- }
37
-
38
35
  /**
39
36
  * A tile's face value as a locale-aware whole amount ('€500', '€1') or fraction ('€0.50'), never
40
37
  * a bare '.00' — `Intl`'s `trailingZeroDisplay` (`@tallyui/core`'s `formatMoney` has nothing
@@ -115,11 +112,20 @@ export interface RegisterCountProps {
115
112
  /** ISO 4217 code: denomination faces, parsing and display. */
116
113
  currency: string;
117
114
  /**
118
- * Above `register.varianceThreshold`, Close asks for this first. `null` refuses and the count
119
- * stays; without it, Close refuses outright with `APPROVAL_REQUIRED_TEXT`. Its `approvedBy`
120
- * and `approvedByName` go to `closeSession`, which enforces the same gate and puts them on the Z.
115
+ * Above `register.varianceThreshold`, Close asks for this first, with the count it would close
116
+ * on. `null` refuses and the count stays; without it, Close refuses outright with
117
+ * `APPROVAL_REQUIRED_TEXT`. Its `approvedBy`, `approvedByName`, `approval` (the store's opaque
118
+ * proof, ADR-082) and `approvedVariance` (from `actions.closureVariance`) go to `closeSession`,
119
+ * which enforces the same gate and puts the approver on the Z. A count edited while this is
120
+ * pending, or a variance that moved since (the hook's gate), asks again on the next Close.
121
+ * A zero-argument function still fits.
121
122
  */
122
- approve?: () => Promise<{ approvedBy: string; approvedByName?: string } | null>;
123
+ approve?: (input: { counted: Record<string, number> }) => Promise<{
124
+ approvedBy: string;
125
+ approvedByName?: string;
126
+ approval?: string;
127
+ approvedVariance?: Record<string, number>;
128
+ } | null>;
123
129
  className?: string;
124
130
  }
125
131
 
@@ -172,6 +178,9 @@ export function RegisterCount({ register, currency, approve, className }: Regist
172
178
  cash: amountMinor,
173
179
  ...Object.fromEntries(otherCounted.map(([method, value]) => [method, parseMinor(value, digits)])),
174
180
  };
181
+ // The count on screen now, for an approval that resolves after the cashier edited it.
182
+ const shownCount = useRef('');
183
+ shownCount.current = JSON.stringify(counted);
175
184
 
176
185
  const attempt = async (action: () => Promise<unknown>) => {
177
186
  setBusy(true);
@@ -181,7 +190,7 @@ export function RegisterCount({ register, currency, approve, className }: Regist
181
190
  } catch (e) {
182
191
  // The hook's own gate (by name: components import no class from pos, ADR-064).
183
192
  if (e instanceof Error && e.name === 'RegisterApprovalRequiredError') setRefusal(APPROVAL_REQUIRED_TEXT);
184
- else setError(errorMessage(e));
193
+ else setError(errorText(e));
185
194
  } finally {
186
195
  setBusy(false);
187
196
  }
@@ -197,13 +206,23 @@ export function RegisterCount({ register, currency, approve, className }: Regist
197
206
  return;
198
207
  }
199
208
  if (needsApproval) {
209
+ const asked = shownCount.current;
200
210
  void attempt(async () => {
201
- const result = await approve!();
211
+ const result = await approve!({ counted });
202
212
  if (!result) {
203
213
  setRefusal('Approval was not granted. The count is unchanged.');
204
214
  return;
205
215
  }
206
- await actions.closeSession({ counted, approvedBy: result.approvedBy, approvedByName: result.approvedByName });
216
+ // The approval is for the count it was asked with; one edited meanwhile asks again.
217
+ if (shownCount.current !== asked) {
218
+ setRefusal(APPROVAL_REQUIRED_TEXT);
219
+ return;
220
+ }
221
+ const { approvedBy, approvedByName, approval, approvedVariance } = result;
222
+ await actions.closeSession({
223
+ counted, approvedBy, approvedByName,
224
+ ...(approval ? { approval } : {}), ...(approvedVariance ? { approvedVariance } : {}),
225
+ });
207
226
  });
208
227
  return;
209
228
  }
@@ -1,8 +1,9 @@
1
1
  import { useState } from 'react';
2
2
  import { ScrollView, useWindowDimensions, View } from 'react-native';
3
- import type { MovementType, useRegisterSession } from '@tallyui/pos';
3
+ import type { ApprovalNeeded, MovementType, useRegisterSession } from '@tallyui/pos';
4
4
 
5
5
  import { formatMoney } from '@tallyui/core';
6
+ import { errorText } from '../lib/error-text';
6
7
  import { Button } from '../ui/button';
7
8
  import { Dialog, DialogClose, DialogContent, DialogTitle } from '../ui/dialog';
8
9
  import { IconButton } from '../ui/icon-button';
@@ -24,6 +25,12 @@ export interface RegisterPanelProps {
24
25
  registerName?: string;
25
26
  open: boolean;
26
27
  onOpenChange: (open: boolean) => void;
28
+ /**
29
+ * The host's gate for a closure the store refused (`register.approvalNeeded`, ADR-082 d7): it
30
+ * gets the refusal, including `liveAtStore`, and returns a new proof and approver, or `null`
31
+ * to leave it. Its result goes to `actions.reapproveClosure`. Without it, the card has no button.
32
+ */
33
+ reapprove?: (needed: ApprovalNeeded) => Promise<{ approvedBy: string; approval: string } | null>;
27
34
  className?: string;
28
35
  }
29
36
 
@@ -36,8 +43,9 @@ export interface RegisterPanelProps {
36
43
  * note): refused-movement Retry and "Unsynced" (no outbox here to refuse a movement), the
37
44
  * X-report, Z and print/reprint, and the Reports deep link.
38
45
  */
39
- export function RegisterPanel({ register, currency, registerName, open, onOpenChange, className }: RegisterPanelProps) {
40
- const { session, expected, salesCount, blind, movements, lastClosure, actions } = register;
46
+ export function RegisterPanel({ register, currency, registerName, open, onOpenChange, reapprove, className }: RegisterPanelProps) {
47
+ const { session, expected, salesCount, blind, movements, lastClosure, approvalNeeded, actions } = register;
48
+ const [reapproving, setReapproving] = useState(false);
41
49
  const otherTenders = Object.entries(expected).filter(([method, amount]) => method !== 'cash' && amount !== 0);
42
50
  const { height: windowHeight } = useWindowDimensions();
43
51
  const maxHeight = Math.max(280, windowHeight - DIALOG_VERTICAL_MARGIN);
@@ -48,7 +56,7 @@ export function RegisterPanel({ register, currency, registerName, open, onOpenCh
48
56
  try {
49
57
  await action();
50
58
  } catch (e) {
51
- setError(String(e));
59
+ setError(errorText(e));
52
60
  }
53
61
  };
54
62
  // Refused cash keeps a panel open on its own in WCPOS; there is no outbox here to refuse a
@@ -78,6 +86,39 @@ export function RegisterPanel({ register, currency, registerName, open, onOpenCh
78
86
  </View>
79
87
  <Text testID="register-panel-sales-count">{salesCount} sale{salesCount === 1 ? '' : 's'} this session</Text>
80
88
  <ScrollView testID="register-panel-body" className="flex-1" contentContainerClassName="gap-3">
89
+ {/* Here, not in RegisterCount: a refused closure's session is already closed, and the
90
+ panel is what still shows once a closure exists. Title and button: WCPOS v2's
91
+ `register.approval_needed` and `register.approve` (monorepo core.json:2974-2976). */}
92
+ {approvalNeeded && (
93
+ <View testID="register-panel-reapproval" className="bg-warning/10 gap-2 rounded-md p-3">
94
+ <Text className="font-semibold">Approval needed</Text>
95
+ <Text>The store refused this closure&apos;s manager approval. A manager must approve it again.</Text>
96
+ {reapprove && (
97
+ <Button
98
+ testID="register-panel-reapprove"
99
+ variant="outline"
100
+ className="min-h-11"
101
+ disabled={reapproving}
102
+ onPress={() =>
103
+ attempt(async () => {
104
+ setReapproving(true);
105
+ try {
106
+ const result = await reapprove(approvalNeeded);
107
+ if (!result) return;
108
+ await actions.reapproveClosure({
109
+ closureId: approvalNeeded.closureId, approval: result.approval, approvedBy: result.approvedBy,
110
+ });
111
+ } finally {
112
+ setReapproving(false);
113
+ }
114
+ })
115
+ }
116
+ >
117
+ <Text>Approve</Text>
118
+ </Button>
119
+ )}
120
+ </View>
121
+ )}
81
122
  <View className="flex-row gap-2">
82
123
  {(['paid_in', 'paid_out', 'no_sale'] as const).map((type) => (
83
124
  <Button
@@ -0,0 +1,102 @@
1
+ import { View } from 'react-native';
2
+ import type { SwitchKind, SwitchWarning, SwitchWarnings } from '@tallyui/pos';
3
+
4
+ import { Button } from '../ui/button';
5
+ import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../ui/dialog';
6
+ import { Text } from '../ui/text';
7
+
8
+ /** `{n} {one}` or `{n} {other}`; shared with `HandoverSlip`, not exported from the package. */
9
+ export const countLine = (n: number, one: string, other: string) => `${n} ${n === 1 ? one : other}`;
10
+
11
+ const WARNING_LINES: Record<Exclude<SwitchWarning['code'], 'openSession'>, (n: number) => string> = {
12
+ unsentSales: (n) => countLine(n, 'unsent sale', 'unsent sales'),
13
+ unsentTillUpdates: (n) => countLine(n, 'unsent till update', 'unsent till updates'),
14
+ parkedSales: (n) => countLine(n, 'parked sale', 'parked sales'),
15
+ partlyPaidSale: () => 'A sale is partly paid',
16
+ };
17
+
18
+ export interface SwitchConfirmProps {
19
+ kind: SwitchKind;
20
+ warnings: SwitchWarnings;
21
+ /** The cashier or register switched to; unused for `signOut`. */
22
+ targetName?: string;
23
+ /** The bound register's name, for the descriptions and the sign-out title. */
24
+ registerName?: string;
25
+ /** A formatted expected cash amount for the sign-out title; omit while blind. */
26
+ amount?: string;
27
+ onConfirm: () => void;
28
+ onCancel: () => void;
29
+ /** Sign-out with an open session: renders "Close register", which calls this. */
30
+ onCloseRegister?: () => void;
31
+ /** Cashier switch: renders "Print hand-over slip", which calls this. */
32
+ onPrintHandover?: () => void;
33
+ }
34
+
35
+ /**
36
+ * Confirms a cashier switch, a register switch or a sign-out, naming what it leaves behind (v2 parity A12). Port
37
+ * provenance: WCPOS v2 monorepo `main` 51e7c4351 `packages/core/src/screens/main/pos/cart/switch-confirm.tsx`, with
38
+ * its English copy (`locales/en/core.json`, `register.*`). Not ported: the store switch and its drawer carry, and
39
+ * v2's "The POS reloads as …" lines (a TallyUI app's switch is its platform's own). New here: unsent sales add
40
+ * "anyway" to the confirm, and till updates, parked sales and a partly paid sale are listed too.
41
+ */
42
+ export function SwitchConfirm({
43
+ kind, warnings, targetName = '', registerName, amount, onConfirm, onCancel, onCloseRegister, onPrintHandover,
44
+ }: SwitchConfirmProps) {
45
+ const anyway = warnings.unsentSales > 0 ? ' anyway' : '';
46
+ let title: string;
47
+ let description = '';
48
+ let confirm: string;
49
+ if (kind === 'cashier') {
50
+ title = `Hand the till to ${targetName}?`;
51
+ if (registerName) description = `The drawer stays open on ${registerName}.`;
52
+ confirm = `Hand over to ${targetName}${anyway}`;
53
+ } else if (kind === 'register') {
54
+ title = `Switch to ${targetName}?`;
55
+ description = warnings.sessionOpen && registerName
56
+ ? `This device moves to ${targetName}. ${registerName}'s drawer stays open for whoever is there.`
57
+ : `This device moves to ${targetName}.`;
58
+ confirm = `Switch to ${targetName}${anyway}`;
59
+ } else if (warnings.sessionOpen) {
60
+ const name = registerName ?? 'The register';
61
+ title = amount ? `${name} is still open at ${amount}. Close it first?` : `${name} is still open. Close it first?`;
62
+ description = 'A till left open stays open for the next cashier. The closure records who closed it.';
63
+ confirm = 'Sign out anyway';
64
+ } else {
65
+ title = 'Sign out?';
66
+ confirm = `Sign out${anyway}`;
67
+ }
68
+ const lines = warnings.warnings.flatMap((w) =>
69
+ w.code === 'openSession' ? [] : [{ code: w.code, text: WARNING_LINES[w.code]('count' in w ? w.count : 0) }],
70
+ );
71
+ return (
72
+ <Dialog open onOpenChange={(open) => { if (!open) onCancel(); }}>
73
+ <DialogContent testID="switch-confirm">
74
+ <DialogTitle testID="switch-confirm-title">{title}</DialogTitle>
75
+ {!!description && <DialogDescription testID="switch-confirm-description">{description}</DialogDescription>}
76
+ {lines.length > 0 && (
77
+ <View testID="switch-confirm-warnings" className="gap-1">
78
+ {lines.map((line) => (
79
+ <Text key={line.code} testID={`switch-warning-${line.code}`} className="text-muted-foreground">{line.text}</Text>
80
+ ))}
81
+ </View>
82
+ )}
83
+ <Button testID="switch-confirm-confirm" className="min-h-14" onPress={onConfirm}>
84
+ <Text>{confirm}</Text>
85
+ </Button>
86
+ {kind === 'signOut' && warnings.sessionOpen && !!onCloseRegister && (
87
+ <Button testID="switch-confirm-close-register" variant="outline" className="min-h-14" onPress={onCloseRegister}>
88
+ <Text>Close register</Text>
89
+ </Button>
90
+ )}
91
+ {kind === 'cashier' && !!onPrintHandover && (
92
+ <Button testID="switch-confirm-handover" variant="outline" className="min-h-14" onPress={onPrintHandover}>
93
+ <Text>Print hand-over slip</Text>
94
+ </Button>
95
+ )}
96
+ <Button testID="switch-confirm-cancel" variant="ghost" className="min-h-14" onPress={onCancel}>
97
+ <Text>Cancel</Text>
98
+ </Button>
99
+ </DialogContent>
100
+ </Dialog>
101
+ );
102
+ }
package/src/sale/cart.tsx CHANGED
@@ -1,27 +1,33 @@
1
1
  import { useState, type ReactNode } from 'react';
2
- import { Pressable, Text, View } from 'react-native';
2
+ import { Pressable, Text, View, useWindowDimensions } from 'react-native';
3
3
  import { formatMoney } from '@tallyui/core';
4
4
  import { buildReceiptData } from '@tallyui/pos';
5
5
  import type { useSale } from '@tallyui/pos';
6
- import { CartLine, CartLineActions, CartPanel, CartTotal } from '../cart';
6
+ import { CartColumnHeads, CartLine, CartLineActions, CartPanel, CartTotal } from '../cart';
7
+ import { cartShowsPrice } from '../cart/cart-columns';
7
8
  import { DiscountChips, DiscountForm } from './discount-form';
8
9
  import { PriceForm } from './price-form';
9
10
  import { ChargeForm } from './charge-form';
10
11
 
11
12
  /** `taxLabel` names each tax row; VAT isn't universal, so a platform passes its own (medusapos passes `VAT ${rate}%`). */
12
- export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10000}%`, canEditPrice = false, onPriceChange, taxClasses, afterSubtotal, couponDiscountMinor }:
13
+ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10000}%`, canEditPrice = false, onPriceChange, quickDiscounts, taxClasses, afterSubtotal, couponDiscountMinor, orderActions = true }:
13
14
  { sale: ReturnType<typeof useSale>; taxLabel?: (ratePpm: number) => string;
14
15
  taxClasses?: ReadonlyArray<{ id: string; label: string }>;
15
16
  /** Shows a Price action on each line. Pass the till's own permission; the control isn't shown without it. */
16
17
  canEditPrice?: boolean;
17
18
  /** Called after a price is applied, for the app's audit log. The reason is kept only here. */
18
19
  onPriceChange?: (change: { lineId: string; fromMinor: number; toMinor: number; reason?: string }) => void;
20
+ /** v2's quick-discount keys on each line's Price form (e.g. the app's `cart.quickDiscounts` setting); needs `canEditPrice`. */
21
+ quickDiscounts?: readonly number[];
19
22
  /** Rows under the totals' Subtotal, e.g. the platform's coupon chips (passed to CartTotal). */
20
23
  afterSubtotal?: ReactNode;
21
24
  /** The coupon amount the app itemises in `afterSubtotal` (e.g. Σ `order.display.coupons`), in integer minor units of
22
25
  * the order's currency, in the display mode. When given, the Discount row shows the other discounts only (the
23
26
  * totals' discount minus this) and is hidden when they come to 0. Absent: the Discount row is the whole discount. */
24
27
  couponDiscountMinor?: number;
28
+ /** Cart's own Order discount and Add charge controls; pass `false` when the app hosts them in its own menu (v2's
29
+ * cart "+" menu). Applied discounts and charges still show and can be removed. */
30
+ orderActions?: boolean;
25
31
  }) {
26
32
  const { order } = sale;
27
33
  const money = (amount: number) => ({ amount, currency: order.currency });
@@ -36,30 +42,37 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
36
42
  // One open form: a line's discount or price, the order's discount (lineId null), or a charge.
37
43
  const [form, setForm] = useState<{ type: 'discount'; lineId: string | null } | { type: 'price'; lineId: string } | { type: 'charge' } | null>(null);
38
44
  const chargesOffered = (sale.capabilities?.orderCreate ?? 0) >= 5;
45
+ const showOrderDiscount = order.lineItems.length > 0 && (orderActions || order.discounts.length > 0);
46
+ const showCharge = orderActions && chargesOffered;
39
47
  const discountForm = (lineId: string | null, title: string) => form?.type === 'discount' && form.lineId === lineId
40
48
  ? <DiscountForm key={lineId ?? 'order'} title={title} currency={order.currency} onClose={() => setForm(null)}
41
49
  onApply={(discount) => sale.applyDiscount(lineId, discount)} /> : null;
42
50
  const pay = `min-h-12 flex-1 justify-center rounded-md bg-primary px-4 py-3 ${!order.lineItems.length ? 'opacity-50' : ''}`;
51
+ // The Price column folds on a narrow cart or a phone window (v2's rule), in the heads and every line alike.
52
+ const [cartWidth, setCartWidth] = useState<number>();
53
+ const { width: windowWidth, height: windowHeight } = useWindowDimensions();
54
+ const showPrice = cartShowsPrice({ cartWidth, windowWidth, windowHeight });
43
55
  const renderItem = (line: typeof order.lineItems[number]) => <>
56
+ <CartLine name={line.name} attributes={line.attributes} quantity={line.quantity} unitPrice={money(line.unitPriceMinor)}
57
+ regularUnitPrice={line.regularUnitPriceMinor === undefined ? undefined : money(line.regularUnitPriceMinor)}
58
+ lineTotal={money(display(line.id).amountMinor)} showPrice={showPrice} />
59
+ <DiscountChips discounts={line.discounts} amounts={display(line.id).discounts} currency={order.currency} onRemove={sale.removeDiscount} />
44
60
  <CartLineActions actions={[
45
61
  { id: 'discount', label: 'Discount', color: 'text-primary', onPress: () => setForm({ type: 'discount', lineId: line.id }) },
46
62
  ...(canEditPrice ? [{ id: 'price', label: 'Price', color: 'text-primary', onPress: () => setForm({ type: 'price', lineId: line.id }) }] : []),
47
63
  ]}>
48
- <CartLine name={line.name} attributes={line.attributes} quantity={line.quantity} unitPrice={money(line.unitPriceMinor)}
49
- lineTotal={money(display(line.id).amountMinor)} />
64
+ <View className="flex-row gap-4 px-3 py-2">
65
+ <Pressable accessibilityRole="button" accessibilityLabel={`Decrease ${line.name}`}
66
+ onPress={() => sale.setQuantity(line.id, line.quantity - 1)} className="rounded-md border border-border bg-card px-3 py-2 min-h-11 min-w-11 items-center justify-center"><Text className="text-center text-foreground">−</Text></Pressable>
67
+ <Pressable accessibilityRole="button" accessibilityLabel={`Increase ${line.name}`}
68
+ onPress={() => sale.setQuantity(line.id, line.quantity + 1)} className="rounded-md border border-border bg-card px-3 py-2 min-h-11 min-w-11 items-center justify-center"><Text className="text-center text-foreground">+</Text></Pressable>
69
+ <Pressable accessibilityRole="button" accessibilityLabel={`Remove ${line.name}`}
70
+ onPress={() => sale.remove(line.id)} className="rounded-md border border-border bg-card px-3 py-2 min-h-11 min-w-11 items-center justify-center"><Text className="text-center text-foreground">Remove</Text></Pressable>
71
+ </View>
50
72
  </CartLineActions>
51
- <DiscountChips discounts={line.discounts} amounts={display(line.id).discounts} currency={order.currency} onRemove={sale.removeDiscount} />
52
- <View className="flex-row gap-4 px-3 py-2">
53
- <Pressable accessibilityRole="button" accessibilityLabel={`Decrease ${line.name}`}
54
- onPress={() => sale.setQuantity(line.id, line.quantity - 1)} className="rounded-md border border-border bg-card px-3 py-2 min-h-11 min-w-11 items-center justify-center"><Text className="text-center text-foreground">−</Text></Pressable>
55
- <Pressable accessibilityRole="button" accessibilityLabel={`Increase ${line.name}`}
56
- onPress={() => sale.setQuantity(line.id, line.quantity + 1)} className="rounded-md border border-border bg-card px-3 py-2 min-h-11 min-w-11 items-center justify-center"><Text className="text-center text-foreground">+</Text></Pressable>
57
- <Pressable accessibilityRole="button" accessibilityLabel={`Remove ${line.name}`}
58
- onPress={() => sale.remove(line.id)} className="rounded-md border border-border bg-card px-3 py-2 min-h-11 min-w-11 items-center justify-center"><Text className="text-center text-foreground">Remove</Text></Pressable>
59
- </View>
60
73
  {discountForm(line.id, `Discount on ${line.name}`)}
61
74
  {canEditPrice && form?.type === 'price' && form.lineId === line.id ? <PriceForm key={line.id} lineName={line.name}
62
- currency={order.currency} currentMinor={line.unitPriceMinor} onClose={() => setForm(null)}
75
+ currency={order.currency} currentMinor={line.unitPriceMinor} quickDiscounts={quickDiscounts} onClose={() => setForm(null)}
63
76
  onApply={(amount, reason) => {
64
77
  const fromMinor = line.unitPriceMinor;
65
78
  const refused = sale.setUnitPrice(line.id, amount);
@@ -67,7 +80,9 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
67
80
  return refused;
68
81
  }} /> : null}
69
82
  </>;
70
- return <CartPanel dataSet={{ print: 'hide' }} items={order.lineItems} renderItem={renderItem}
83
+ return <View dataSet={{ print: 'hide' }} className="flex-1 min-h-0" onLayout={(event) => setCartWidth(event.nativeEvent.layout.width)}>
84
+ <CartColumnHeads showPrice={showPrice} />
85
+ <CartPanel items={order.lineItems} renderItem={renderItem}
71
86
  emptyState={<Text testID="cart-empty" className="px-3 py-2 text-muted-foreground">Scan or tap a product to start a sale.</Text>}
72
87
  afterItems={<>
73
88
  {(['fees', 'shipping'] as const).map((kind) => order[kind]?.map((charge, index) =>
@@ -79,15 +94,15 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
79
94
  className="rounded-md border border-border bg-card px-3 py-2 min-h-11 items-center justify-center">
80
95
  <Text className="text-foreground">Remove</Text></Pressable>
81
96
  </View>))}
82
- {order.lineItems.length || chargesOffered ? <View className="gap-3 px-3 py-2">
83
- {order.lineItems.length ? <>
97
+ {showOrderDiscount || showCharge ? <View className="gap-3 px-3 py-2">
98
+ {showOrderDiscount ? <>
84
99
  <DiscountChips discounts={order.discounts} amounts={orderAmounts} currency={order.currency} onRemove={sale.removeDiscount}
85
100
  prefix="Order discount" />
86
- {form?.type === 'discount' && form.lineId === null ? discountForm(null, 'Order discount') : <Pressable accessibilityRole="button"
101
+ {!orderActions ? null : form?.type === 'discount' && form.lineId === null ? discountForm(null, 'Order discount') : <Pressable accessibilityRole="button"
87
102
  onPress={() => setForm({ type: 'discount', lineId: null })} className="self-start rounded-md border border-border bg-card px-4 py-2 min-h-11 justify-center">
88
103
  <Text className="text-foreground">Order discount</Text></Pressable>}
89
104
  </> : null}
90
- {chargesOffered ? form?.type === 'charge' ? <ChargeForm currency={order.currency} lineTax={sale.capabilities?.lineTax}
105
+ {showCharge ? form?.type === 'charge' ? <ChargeForm currency={order.currency} lineTax={sale.capabilities?.lineTax}
91
106
  taxClasses={taxClasses} shippingTaxFromStore={sale.capabilities?.taxRounding?.granularity === 'woocommerce'}
92
107
  onClose={() => setForm(null)} onApply={({ kind, name, amountMinor, taxStatus, taxClass }) => {
93
108
  const result = kind === 'custom' ? sale.addCustomLine({ name, priceMinor: amountMinor, taxStatus, taxClass })
@@ -112,5 +127,6 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
112
127
  <Text className="text-center font-semibold text-primary-foreground">Card terminal</Text>
113
128
  </Pressable>
114
129
  </View>
115
- </View>} />;
130
+ </View>} />
131
+ </View>;
116
132
  }
@@ -3,10 +3,12 @@ import { Pressable, Text, View } from 'react-native';
3
3
  import { useStockOverlaid, useStockOverlayAsOf, type ProductTraits, type ProductCategory } from '@tallyui/core';
4
4
  import { catalogueEntries, findEntryByCode, searchProducts, variantPriceLabel, sortProducts, productSortValue,
5
5
  catalogueViewReducer, normalizeCatalogueViewState, resolveGridColumns, DEFAULT_CATALOGUE_VIEW_STATE,
6
- listCategories, inCategory,
7
- type CatalogueEntry, type CatalogueViewState, type CatalogueViewAction } from '@tallyui/pos';
6
+ listCategories, inCategory, cartQuantities,
7
+ type CatalogueEntry, type CatalogueViewState, type CatalogueViewAction, type CartQuantityLine } from '@tallyui/pos';
8
8
  import { ProductGrid, ProductImage, ProductPrice, ProductStockBadge, ProductTitle, ProductTable, ViewToggle, CategoryNav } from '../product';
9
9
  import { ProductVariantPicker } from '../product/product-variant-picker';
10
+ import { InCartBadge } from '../product/in-cart-badge';
11
+ import { ProductFilterBar, DEFAULT_PRODUCT_FILTERS, type ProductFilterChip, type ProductFilters } from './product-filter-bar';
10
12
  import { SearchInput } from '../input';
11
13
  import { VStack } from '../ui';
12
14
 
@@ -35,7 +37,8 @@ function laterOf(a: Date | null | undefined, b: Date | null | undefined): Date |
35
37
  }
36
38
 
37
39
  export function Catalogue<Doc>({ products, traits, currency, onSelect, statusText, statusAccessory, lastSyncedAt, loading, pullError, lastStockCheckAt, hour12, minCodeLength,
38
- viewState, defaultViewState, loadViewState, saveViewState, onViewStateError, onStateChange, showViewToggle = false, items, onQueryChange, showCategoryNav = false, categories, pickAnyOptions = false }: {
40
+ viewState, defaultViewState, loadViewState, saveViewState, onViewStateError, onStateChange, showViewToggle = false, items, onQueryChange, showCategoryNav = false, categories, pickAnyOptions = false,
41
+ cartLines, showFilterBar = false, filterChips = ['inStock'], filters: filtersProp, onFiltersChange }: {
39
42
  products: Doc[];
40
43
  traits: ProductTraits<Doc>;
41
44
  currency: string;
@@ -85,6 +88,16 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
85
88
  onQueryChange?: (query: string) => void;
86
89
  /** Ask for a value for each of a variant's local "Any" option groups before onSelect (#495); set it only when the store accepts order.create version 6. */
87
90
  pickAnyOptions?: boolean;
91
+ /** The open sale's lines (e.g. useSale's order.lineItems); each grid tile shows its product's summed quantity. */
92
+ cartLines?: readonly CartQuantityLine[];
93
+ /** Show v2's filter chips under the search box. Default false. */
94
+ showFilterBar?: boolean;
95
+ /** Which chips the bar shows. Default ['inStock'], the one Catalogue applies itself. */
96
+ filterChips?: readonly ProductFilterChip[];
97
+ /** Controlled filters; changes are reported through onFiltersChange. */
98
+ filters?: ProductFilters;
99
+ /** The cashier's next filters (requested filters when controlled). */
100
+ onFiltersChange?: (filters: ProductFilters) => void;
88
101
  }) {
89
102
  const [initial] = useState<{
90
103
  state: CatalogueViewState; loaded?: CatalogueViewState; pending?: Promise<unknown>; failed?: boolean; error?: unknown;
@@ -130,6 +143,14 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
130
143
  }
131
144
  }
132
145
 
146
+ const [internalFilters, setInternalFilters] = useState(DEFAULT_PRODUCT_FILTERS);
147
+ const filters = filtersProp ?? internalFilters;
148
+ function changeFilters(next: ProductFilters) {
149
+ if (filtersProp === undefined) setInternalFilters(next);
150
+ onFiltersChange?.(next);
151
+ }
152
+ const quantities = useMemo(() => cartQuantities(cartLines ?? []), [cartLines]);
153
+
133
154
  const isLoading = loading ?? (lastSyncedAt === null && pullError == null);
134
155
  // Idempotent (the adapter's overlay returns just the fields the stock map sets), so an app that already
135
156
  // merges the overlay itself keeps working, and can drop its own merge.
@@ -148,12 +169,16 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
148
169
  const [width, setWidth] = useState(0);
149
170
  const columns = resolveGridColumns(state.gridColumns, width);
150
171
  const entries = useMemo(() => catalogueEntries(shown, traits, { currency }), [shown, traits, currency]);
172
+ // v2's In Stock pill is stock_status 'instock', so it drops backorders too; a stock the backend did not report stays.
173
+ const stockFiltered = showFilterBar && filters.inStock;
151
174
  const results = useMemo(() => {
152
175
  if (items !== undefined) return suppliedItems;
153
- const filtered = searchProducts(activeCategory
176
+ const matched = searchProducts(activeCategory
154
177
  ? shown.filter((doc) => inCategory(doc, activeCategory.id, traits)) : shown, query, traits);
178
+ const filtered = stockFiltered
179
+ ? matched.filter((doc) => !['out_of_stock', 'backorder'].includes(traits.getStock(doc).status)) : matched;
155
180
  return state.sort ? sortProducts(filtered, state.sort, (doc, field) => productSortValue(doc, field, traits, { currency })) : filtered;
156
- }, [items, suppliedItems, shown, query, traits, state.sort, currency, showCategoryNav, activeCategory]);
181
+ }, [items, suppliedItems, shown, query, traits, state.sort, currency, showCategoryNav, activeCategory, stockFiltered]);
157
182
  const choices = useMemo(() => (chooserId === null ? []
158
183
  : entries.filter((entry) => traits.getId(entry.product) === chooserId)), [entries, chooserId, traits]);
159
184
  // A product that leaves the catalogue (a resync, or no longer sellable) closes its chooser.
@@ -197,6 +222,7 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
197
222
 
198
223
  const emptyState = <Text className="mt-10 text-center text-sm text-muted-foreground">
199
224
  {query.trim() ? `No products match "${query.trim()}".` : activeCategory ? `No products in ${activeCategory.name}.`
225
+ : stockFiltered && items === undefined && shown.length > 0 ? 'No products in stock.'
200
226
  : isLoading ? 'Loading products…' : 'No products yet.'}
201
227
  </Text>;
202
228
 
@@ -209,6 +235,7 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
209
235
  const entry = findEntryByCode(entries, query);
210
236
  if (entry) { select(entry); setQuery(''); }
211
237
  }} />
238
+ {showFilterBar ? <ProductFilterBar value={filters} onChange={changeFilters} chips={filterChips} /> : null}
212
239
  {(statusText || statusAccessory || showViewToggle) ? (
213
240
  <View testID="catalogue-status-row" className="flex-row items-center gap-2">
214
241
  {statusText ? <Text className="flex-1 text-xs text-muted-foreground" numberOfLines={statusAccessory ? 1 : undefined}>
@@ -265,6 +292,8 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
265
292
  <ProductPrice doc={product} />
266
293
  <ProductStockBadge doc={product} showAsOf={false} className="self-center" />
267
294
  </VStack>
295
+ <InCartBadge count={quantities.get(traits.getId(product)) ?? 0} className="absolute right-2 top-2"
296
+ testID={`in-cart-${traits.getId(product)}`} />
268
297
  </Pressable>
269
298
  )}
270
299
  emptyState={emptyState} />}
@@ -0,0 +1,92 @@
1
+ import type { ReactNode } from 'react';
2
+ import { Image, ScrollView, Text, View } from 'react-native';
3
+ import { formatMoney } from '@tallyui/core';
4
+ import type { DisplayPayment, DisplayState, ReceiptData } from '@tallyui/pos';
5
+
6
+ // English copy from WCPOS v2's display (Pro packages/display/src/sample-snapshot.json); config.i18n overrides it.
7
+ const COPY = {
8
+ welcome: 'Welcome', your_items: 'Your items', items_appear_here: 'Your items will appear here', subtotal: 'Subtotal',
9
+ discount: 'Discount', total_tax: 'Tax', included_tax: 'Tax included', total: 'Total', paid_so_far: 'Paid so far',
10
+ present_card: 'Please present your card', approved: 'Approved', declined: 'Declined',
11
+ try_another_card: 'Please try another card or ask staff', paid_in_full: 'Paid in full', change: 'Change',
12
+ thank_you: 'Thank you',
13
+ };
14
+
15
+ const CARD = { started: 'bg-primary', approved: 'bg-success', complete: 'bg-success', declined: 'bg-destructive' };
16
+ const CARD_TEXT = { started: 'text-primary-foreground', approved: 'text-success-foreground',
17
+ complete: 'text-success-foreground', declined: 'text-destructive-foreground' };
18
+
19
+ /**
20
+ * What the customer sees on the second screen, laid out as WCPOS v2's default "Ledger" display
21
+ * (Pro templates/display.html): idle shows the store; cart and payment show the items on the left and a panel on the
22
+ * right with the totals, or the payment card.
23
+ */
24
+ export function CustomerDisplayScreen({ state }: { state: DisplayState }) {
25
+ const { config, view } = state;
26
+ const t = (key: keyof typeof COPY) => config?.i18n[key] ?? COPY[key];
27
+ if (view.screen === 'idle') {
28
+ const logo = config?.store.logo;
29
+ return <View testID="customer-display-idle" className="flex-1 items-center justify-center gap-6 bg-primary p-8">
30
+ {logo ? <Image source={{ uri: logo }} accessibilityLabel={config.store.name} resizeMode="contain" style={{ width: 320, height: 180 }} />
31
+ : <Text className="text-5xl font-bold text-primary-foreground">{config?.store.name ?? ''}</Text>}
32
+ <Text className="text-2xl text-primary-foreground">{t('welcome')}</Text>
33
+ </View>;
34
+ }
35
+ const { receipt } = view.cart;
36
+ const money = (amount: number) => formatMoney({ amount, currency: receipt.currency }, config?.store.locale) ?? '';
37
+ const row = (label: string, amount: string, key?: string) => <View key={key} className="flex-row justify-between gap-4 py-1">
38
+ <Text className="text-lg text-muted-foreground">{label}</Text><Text className="text-lg text-muted-foreground">{amount}</Text>
39
+ </View>;
40
+ const total = <View className="mt-3 flex-row items-baseline justify-between gap-4 border-t-2 border-foreground pt-4">
41
+ <Text className="text-base font-semibold uppercase text-foreground">{t('total')}</Text>
42
+ <Text className="text-4xl font-bold text-foreground">{money(receipt.totals.totalMinor)}</Text>
43
+ </View>;
44
+ return <View testID={`customer-display-${view.screen}`} className="flex-1 flex-col bg-card sm:flex-row">
45
+ <ScrollView className="flex-1" contentContainerClassName="p-8 sm:p-12">
46
+ <Text className="mb-5 text-sm font-semibold uppercase text-muted-foreground">{t('your_items')}</Text>
47
+ {receipt.lineItems.length === 0 ? <Text className="py-8 text-center text-xl text-muted-foreground">{t('items_appear_here')}</Text> : null}
48
+ {receipt.lineItems.map((line, index) => <View key={index} className="flex-row items-baseline gap-4 border-b border-border py-4">
49
+ <Text className="w-14 text-xl text-muted-foreground">{`${line.quantity} ×`}</Text>
50
+ <View className="flex-1">
51
+ <Text className="text-xl font-semibold text-foreground">{line.name}</Text>
52
+ {Object.entries(line.attributes ?? {}).map(([name, value]) => <Text key={name} className="text-base text-muted-foreground">{`${name}: ${value}`}</Text>)}
53
+ </View>
54
+ <Text className="text-xl font-semibold text-foreground">{money(line.displayAmountMinor)}</Text>
55
+ </View>)}
56
+ </ScrollView>
57
+ <View className="justify-end border-t border-border p-8 sm:w-96 sm:border-l sm:border-t-0">
58
+ <Text className="mb-auto text-lg font-bold text-foreground">{config?.store.name ?? receipt.header.storeName}</Text>
59
+ {view.screen === 'cart' ? <View>
60
+ {row(t('subtotal'), money(receipt.totals.subtotalMinor))}
61
+ {receipt.fees.map((charge, index) => row(charge.name, money(charge.amountMinor), `fee-${index}`))}
62
+ {receipt.shipping.map((charge, index) => row(charge.name, money(charge.amountMinor), `shipping-${index}`))}
63
+ {receipt.totals.discountMinor > 0 ? row(t('discount'), `-${money(receipt.totals.discountMinor)}`) : null}
64
+ {receipt.totals.taxMinor > 0 ? row(t(receipt.totals.taxInclusive ? 'included_tax' : 'total_tax'), money(receipt.totals.taxMinor)) : null}
65
+ {total}
66
+ </View> : <PaymentCard receipt={receipt} payment={view.payment} money={money} t={t}>{total}</PaymentCard>}
67
+ </View>
68
+ </View>;
69
+ }
70
+
71
+ function PaymentCard({ receipt, payment, money, t, children }: {
72
+ receipt: ReceiptData; payment: DisplayPayment; money: (amount: number) => string; t: (key: keyof typeof COPY) => string;
73
+ children: ReactNode;
74
+ }) {
75
+ const paid = receipt.payments.reduce((sum, { amountMinor }) => sum + amountMinor, 0);
76
+ const due = Math.max(0, receipt.totals.totalMinor - paid);
77
+ const complete = payment.state === 'complete';
78
+ const title = { started: t('present_card'), approved: t('approved'), declined: t('declined'), complete: t('paid_in_full') }[payment.state];
79
+ const message = complete ? t('thank_you') : payment.message ?? (payment.state === 'declined' ? t('try_another_card') : undefined);
80
+ const text = CARD_TEXT[payment.state];
81
+ return <View className="gap-4">
82
+ {complete ? null : <View>{children}{paid > 0 ? <View className="flex-row justify-between py-1">
83
+ <Text className="text-lg text-success">{t('paid_so_far')}</Text><Text className="text-lg text-success">{money(paid)}</Text>
84
+ </View> : null}</View>}
85
+ <View className={`gap-2 rounded-xl p-6 ${CARD[payment.state]}`}>
86
+ <Text className={`text-sm font-semibold uppercase ${text}`}>{title}</Text>
87
+ <Text className={`text-4xl font-bold ${text}`}>{money(complete ? receipt.totals.totalMinor : payment.leg?.amountMinor ?? due)}</Text>
88
+ {complete && receipt.changeDueMinor > 0 ? <Text className={`text-lg ${text}`}>{`${t('change')} ${money(receipt.changeDueMinor)}`}</Text> : null}
89
+ {message ? <Text className={`text-lg ${text}`}>{message}</Text> : null}
90
+ </View>
91
+ </View>;
92
+ }
package/src/sale/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { Cart } from './cart';
2
2
  export { CartBar } from './cart-bar';
3
- export { Tender } from './tender';
4
- export { SplitTender } from './split-tender';
3
+ export { Tender, SplitTender } from './tender';
4
+ export { TenderPane, type TenderPaneProps } from './tender-pane';
5
5
  export { DiscountForm, DiscountChips, parseDiscount, discountLabel } from './discount-form';
6
6
  export { PriceForm, parsePrice } from './price-form';
7
7
  export { ChargeForm, type ChargeFormProps } from './charge-form';
@@ -13,3 +13,5 @@ export { SyncStatus } from './sync-status';
13
13
  export { OrdersList, type OrderHistoryRow } from './orders-list';
14
14
  export { ParkedSales, type ParkedSalesProps } from './parked-sales';
15
15
  export { OpenSaleTabs, type OpenSaleTabsProps } from './open-sale-tabs';
16
+ export { ProductFilterBar, DEFAULT_PRODUCT_FILTERS, PRODUCT_FILTER_CHIPS, type ProductFilterBarProps, type ProductFilterChip, type ProductFilters } from './product-filter-bar';
17
+ export { CustomerDisplayScreen } from './customer-display-screen';
@@ -2,6 +2,7 @@ import { useState, type JSX } from 'react';
2
2
  import { ScrollView, useWindowDimensions, View } from 'react-native';
3
3
  import { formatMoney } from '@tallyui/core';
4
4
  import type { ParkedOrderSummary, useSale } from '@tallyui/pos';
5
+ import { errorText } from '../lib/error-text';
5
6
  import { Button } from '../ui/button';
6
7
  import { Dialog, DialogClose, DialogContent, DialogTitle } from '../ui/dialog';
7
8
  import { IconButton } from '../ui/icon-button';
@@ -33,7 +34,7 @@ export function ParkedSales({ sale, parked, onDiscard, onPark, onResume, currenc
33
34
  try {
34
35
  await action();
35
36
  } catch (e) {
36
- setError(String(e));
37
+ setError(errorText(e));
37
38
  }
38
39
  };
39
40