@tallyui/components 3.13.0 → 3.15.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 (44) hide show
  1. package/dist/index.d.ts +357 -27
  2. package/dist/index.js +2386 -1370
  3. package/package.json +9 -9
  4. package/src/cart/cart-columns.tsx +57 -0
  5. package/src/cart/cart-foot.tsx +82 -0
  6. package/src/cart/cart-line.tsx +37 -17
  7. package/src/cart/index.ts +2 -0
  8. package/src/checkout/cash-tendered.tsx +5 -7
  9. package/src/index.ts +26 -3
  10. package/src/input/index.ts +1 -0
  11. package/src/input/keypad.tsx +38 -0
  12. package/src/lib/error-text.ts +5 -0
  13. package/src/order/refund-form.tsx +2 -1
  14. package/src/product/category-tile.tsx +43 -0
  15. package/src/product/in-cart-badge.tsx +26 -0
  16. package/src/product/index.ts +2 -0
  17. package/src/register/closure-sheet.tsx +2 -1
  18. package/src/register/handover-slip.tsx +46 -0
  19. package/src/register/index.ts +2 -0
  20. package/src/register/movement-sheet.tsx +2 -1
  21. package/src/register/open-register-card.tsx +2 -1
  22. package/src/register/register-bar.tsx +57 -11
  23. package/src/register/register-column.tsx +2 -1
  24. package/src/register/register-count.tsx +30 -11
  25. package/src/register/register-panel.tsx +45 -4
  26. package/src/register/switch-confirm.tsx +102 -0
  27. package/src/sale/cart.tsx +63 -31
  28. package/src/sale/catalogue.tsx +34 -5
  29. package/src/sale/customer-display-screen.tsx +92 -0
  30. package/src/sale/index.ts +5 -2
  31. package/src/sale/line-popover.tsx +145 -0
  32. package/src/sale/parked-sales.tsx +2 -1
  33. package/src/sale/price-form.tsx +37 -4
  34. package/src/sale/product-filter-bar.tsx +58 -0
  35. package/src/sale/tender-pane.tsx +171 -0
  36. package/src/sale/tender.tsx +20 -35
  37. package/src/shell/app-shell.tsx +71 -0
  38. package/src/shell/index.ts +4 -0
  39. package/src/shell/nav-drawer.tsx +130 -0
  40. package/src/shell/nav-item.tsx +70 -0
  41. package/src/shell/nav-rail.tsx +58 -0
  42. package/src/shell/shell-context.ts +18 -0
  43. package/src/ui/icon/menu-icon.tsx +10 -0
  44. package/src/sale/split-tender.tsx +0 -81
@@ -1,10 +1,15 @@
1
+ import type { ReactNode } from 'react';
1
2
  import { Pressable, View } from 'react-native';
2
3
  import type { useRegisterSession } from '@tallyui/pos';
3
4
 
4
5
  import { cn } from '@tallyui/theme';
6
+ import { useShell } from '../shell/shell-context';
7
+ import { Avatar } from '../ui/avatar';
5
8
  import { Badge } from '../ui/badge';
6
9
  import { Button } from '../ui/button';
7
10
  import { HStack } from '../ui/hstack';
11
+ import { IconButton } from '../ui/icon-button';
12
+ import { MenuIcon } from '../ui/icon/menu-icon';
8
13
  import { Text } from '../ui/text';
9
14
  import { describeRegisterBarPill } from './register-bar.helpers';
10
15
 
@@ -21,17 +26,30 @@ export interface RegisterBarProps {
21
26
  onOpenPanel: () => void;
22
27
  /** Turns the pill into a button (opens the gate/picker or the panel) when given; the plain badge otherwise. */
23
28
  onPressPill?: () => void;
29
+ /** The store's name. With `multiRegister` and a bound register the bar reads "Store · Register". */
30
+ storeName?: string;
31
+ /** The signed-in cashier: an initials avatar, pressable when `onPress` is given. */
32
+ cashier?: { name: string; onPress?: () => void };
33
+ /** The app's sync state (a badge or a line), drawn before the cashier. */
34
+ syncStatus?: ReactNode;
35
+ /** Opens the navigation; inside a phone `AppShell` the shell supplies it. Hidden when neither. */
36
+ onOpenMenu?: () => void;
24
37
  className?: string;
25
38
  }
26
39
 
40
+ function initials(name: string): string {
41
+ return name.split(/\s+/).filter(Boolean).slice(0, 2).map((word) => word[0].toUpperCase()).join('');
42
+ }
43
+
27
44
  /**
28
- * The till's one status bar: which register (multi-register stores only), one status pill
29
- * (LEDGER 48), and the button that opens the register panel. Port provenance (ADR-032 amendment
30
- * 1): WCPOS `next` `3b5331b5c` `register-bar.tsx`.
45
+ * The till's one status bar: the menu (phones), the place (the store, and the register for
46
+ * multi-register stores), one status pill (LEDGER 48), the sync state, the button that opens the
47
+ * register panel, and the cashier. Port provenance (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`
48
+ * `register-bar.tsx`; the menu, the place and the cashier from v2 `main` `51e7c4351`
49
+ * `packages/core/src/screens/main/pos/cart/register-bar.tsx` and `components/bar-controls`, MIT, WCPOS.
31
50
  *
32
- * Dropped for this neutral port: the user avatar and user sheet, switch-store, and the
33
- * WooCommerce OAuth-return rehosting — all app/backend concerns `useRegisterSession` never
34
- * carries. The drawer/menu button is gone too: TallyUI has no fixed navigation shell to open.
51
+ * Dropped for this neutral port: the user sheet, switch-store, the notification bell and the
52
+ * WooCommerce OAuth-return rehosting — all app/backend concerns `useRegisterSession` never carries.
35
53
  */
36
54
  export function RegisterBar({
37
55
  register,
@@ -41,9 +59,15 @@ export function RegisterBar({
41
59
  multiRegister,
42
60
  onOpenPanel,
43
61
  onPressPill,
62
+ storeName,
63
+ cashier,
64
+ syncStatus,
65
+ onOpenMenu,
44
66
  className,
45
67
  }: RegisterBarProps) {
46
68
  const { session, overdue, enabled, lastClosure, closing } = register;
69
+ const shell = useShell();
70
+ const openMenu = onOpenMenu ?? shell?.openMenu;
47
71
  const pill = describeRegisterBarPill({
48
72
  registerId,
49
73
  online,
@@ -53,14 +77,24 @@ export function RegisterBar({
53
77
  sessionsOn: enabled,
54
78
  closing,
55
79
  });
80
+ const named = multiRegister && registerId !== null && registerName ? registerName : '';
81
+ // Store · Register: the larger container first, as every v2 line that names both reads.
82
+ const place = storeName ? (named ? `${storeName} · ${named}` : storeName) : named;
56
83
  return (
57
- <HStack testID="register-bar" className={cn('bg-card border-border h-12 border-b px-3', className)}>
84
+ <HStack testID="register-bar" className={cn('bg-card border-border h-12 gap-2 border-b px-2', className)}>
85
+ {openMenu && (
86
+ <IconButton testID="register-bar-menu" accessibilityLabel="Open menu" onPress={openMenu}>
87
+ <View className="text-foreground">
88
+ <MenuIcon size={24} />
89
+ </View>
90
+ </IconButton>
91
+ )}
58
92
  <View className="min-w-0 flex-1 shrink">
59
- {multiRegister && registerId !== null && (
60
- <Text testID="register-bar-name" numberOfLines={1}>
61
- {registerName}
93
+ {place ? (
94
+ <Text testID="register-bar-name" className={storeName ? 'font-semibold' : undefined} numberOfLines={1}>
95
+ {place}
62
96
  </Text>
63
- )}
97
+ ) : null}
64
98
  </View>
65
99
  {pill && (onPressPill ? (
66
100
  <Pressable testID="register-bar-pill" accessibilityRole="button" accessibilityLabel={pill} onPress={onPressPill}>
@@ -69,6 +103,7 @@ export function RegisterBar({
69
103
  ) : (
70
104
  <Badge testID="register-bar-pill" label={pill} variant="warning" />
71
105
  ))}
106
+ {syncStatus}
72
107
  {(session || lastClosure) && (
73
108
  <Button
74
109
  variant="ghost"
@@ -80,6 +115,17 @@ export function RegisterBar({
80
115
  <Text className={overdue ? 'text-warning' : undefined}>Register ›</Text>
81
116
  </Button>
82
117
  )}
118
+ {cashier && (
119
+ <Pressable
120
+ testID="register-bar-cashier"
121
+ accessibilityRole={cashier.onPress ? 'button' : undefined}
122
+ accessibilityLabel={`Cashier: ${cashier.name}`}
123
+ disabled={!cashier.onPress}
124
+ onPress={cashier.onPress}
125
+ >
126
+ <Avatar size="sm" fallback={initials(cashier.name)} />
127
+ </Pressable>
128
+ )}
83
129
  </HStack>
84
130
  );
85
131
  }
@@ -2,6 +2,7 @@ import { useState, type ReactNode } from 'react';
2
2
  import { View } from 'react-native';
3
3
  import type { useRegisterSession } from '@tallyui/pos';
4
4
 
5
+ import { errorText } from '../lib/error-text';
5
6
  import { Button } from '../ui/button';
6
7
  import { Text } from '../ui/text';
7
8
  import { OpenRegisterCard } from './open-register-card';
@@ -96,7 +97,7 @@ function FinishClose({ register, busy, setBusy }: { register: ReturnType<typeof
96
97
  // ignored for a session already closed), and the approval gate doesn't run again.
97
98
  await register.actions.closeSession({ counted: register.session?.counted ?? {} });
98
99
  } catch (e) {
99
- setError(e instanceof Error ? e.message : String(e));
100
+ setError(errorText(e));
100
101
  } finally {
101
102
  setBusy(false);
102
103
  }
@@ -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,40 @@
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, CartFoot, CartLine, CartLineActions, CartPanel, CartTotal, type CartFootAction } 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';
11
+ import { LinePopover } from './line-popover';
10
12
 
11
13
  /** `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 }:
14
+ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10000}%`, canEditPrice = false, onPriceChange, quickDiscounts, taxClasses, afterSubtotal, couponDiscountMinor, orderActions = true, checkout, lineEditor = 'inline' }:
13
15
  { sale: ReturnType<typeof useSale>; taxLabel?: (ratePpm: number) => string;
14
16
  taxClasses?: ReadonlyArray<{ id: string; label: string }>;
15
17
  /** Shows a Price action on each line. Pass the till's own permission; the control isn't shown without it. */
16
18
  canEditPrice?: boolean;
17
19
  /** Called after a price is applied, for the app's audit log. The reason is kept only here. */
18
20
  onPriceChange?: (change: { lineId: string; fromMinor: number; toMinor: number; reason?: string }) => void;
21
+ /** v2's quick-discount keys on each line's Price form (e.g. the app's `cart.quickDiscounts` setting); needs `canEditPrice`. */
22
+ quickDiscounts?: readonly number[];
19
23
  /** Rows under the totals' Subtotal, e.g. the platform's coupon chips (passed to CartTotal). */
20
24
  afterSubtotal?: ReactNode;
21
25
  /** The coupon amount the app itemises in `afterSubtotal` (e.g. Σ `order.display.coupons`), in integer minor units of
22
26
  * the order's currency, in the display mode. When given, the Discount row shows the other discounts only (the
23
27
  * totals' discount minus this) and is hidden when they come to 0. Absent: the Discount row is the whole discount. */
24
28
  couponDiscountMinor?: number;
29
+ /** Cart's own Order discount and Add charge controls; pass `false` when the app hosts them in its own menu (v2's
30
+ * cart "+" menu). Applied discounts and charges still show and can be removed. */
31
+ orderActions?: boolean;
32
+ /** Swaps the Cash and Card terminal row for v2's foot, `CartFoot`: "Checkout {total}" calls `onCheckout`, and the
33
+ * ⋮ menu lists `actions`. Absent: the Cash and Card terminal row. */
34
+ checkout?: { onCheckout: () => void; actions?: readonly CartFootAction[] };
35
+ /** `popover`: tapping a line's quantity or price opens v2's keypad (WCPOS cart cells/quantity-keypad.tsx and
36
+ * cells/price.tsx), the price one with the quick-discount keys. Default `inline`: the − / + buttons and Price form. */
37
+ lineEditor?: 'inline' | 'popover';
25
38
  }) {
26
39
  const { order } = sale;
27
40
  const money = (amount: number) => ({ amount, currency: order.currency });
@@ -36,38 +49,55 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
36
49
  // One open form: a line's discount or price, the order's discount (lineId null), or a charge.
37
50
  const [form, setForm] = useState<{ type: 'discount'; lineId: string | null } | { type: 'price'; lineId: string } | { type: 'charge' } | null>(null);
38
51
  const chargesOffered = (sale.capabilities?.orderCreate ?? 0) >= 5;
52
+ const showOrderDiscount = order.lineItems.length > 0 && (orderActions || order.discounts.length > 0);
53
+ const showCharge = orderActions && chargesOffered;
39
54
  const discountForm = (lineId: string | null, title: string) => form?.type === 'discount' && form.lineId === lineId
40
55
  ? <DiscountForm key={lineId ?? 'order'} title={title} currency={order.currency} onClose={() => setForm(null)}
41
56
  onApply={(discount) => sale.applyDiscount(lineId, discount)} /> : null;
42
57
  const pay = `min-h-12 flex-1 justify-center rounded-md bg-primary px-4 py-3 ${!order.lineItems.length ? 'opacity-50' : ''}`;
58
+ // The Price column folds on a narrow cart or a phone window (v2's rule), in the heads and every line alike.
59
+ const [cartWidth, setCartWidth] = useState<number>();
60
+ const { width: windowWidth, height: windowHeight } = useWindowDimensions();
61
+ const showPrice = cartShowsPrice({ cartWidth, windowWidth, windowHeight });
62
+ // The price popover needs the Price column; on a narrow cart the Price action and form stay.
63
+ const pricePopover = lineEditor === 'popover' && canEditPrice && showPrice;
64
+ // A line's price write, from the Price form or the price popover; the reason is passed only to onPriceChange.
65
+ const applyPrice = (line: typeof order.lineItems[number], amount: number, reason?: string) => {
66
+ const fromMinor = line.unitPriceMinor;
67
+ const refused = sale.setUnitPrice(line.id, amount);
68
+ if (refused === null) onPriceChange?.({ lineId: line.id, fromMinor, toMinor: amount, reason });
69
+ return refused;
70
+ };
43
71
  const renderItem = (line: typeof order.lineItems[number]) => <>
72
+ <CartLine name={line.name} attributes={line.attributes} quantity={line.quantity} unitPrice={money(line.unitPriceMinor)}
73
+ regularUnitPrice={line.regularUnitPriceMinor === undefined ? undefined : money(line.regularUnitPriceMinor)}
74
+ lineTotal={money(display(line.id).amountMinor)} showPrice={showPrice}
75
+ quantitySlot={lineEditor === 'popover' ? <LinePopover kind="quantity" lineName={line.name} currency={order.currency}
76
+ value={line.quantity} onApply={(quantity) => { sale.setQuantity(line.id, quantity); return null; }} /> : undefined}
77
+ priceSlot={pricePopover ? <LinePopover kind="price" lineName={line.name} currency={order.currency} value={line.unitPriceMinor}
78
+ quickDiscounts={quickDiscounts} textClassName="text-right text-muted-foreground" onApply={(amount) => applyPrice(line, amount)} /> : undefined} />
79
+ <DiscountChips discounts={line.discounts} amounts={display(line.id).discounts} currency={order.currency} onRemove={sale.removeDiscount} />
44
80
  <CartLineActions actions={[
45
81
  { id: 'discount', label: 'Discount', color: 'text-primary', onPress: () => setForm({ type: 'discount', lineId: line.id }) },
46
- ...(canEditPrice ? [{ id: 'price', label: 'Price', color: 'text-primary', onPress: () => setForm({ type: 'price', lineId: line.id }) }] : []),
82
+ ...(canEditPrice && !pricePopover ? [{ id: 'price', label: 'Price', color: 'text-primary', onPress: () => setForm({ type: 'price', lineId: line.id }) }] : []),
47
83
  ]}>
48
- <CartLine name={line.name} attributes={line.attributes} quantity={line.quantity} unitPrice={money(line.unitPriceMinor)}
49
- lineTotal={money(display(line.id).amountMinor)} />
84
+ <View className="flex-row gap-4 px-3 py-2">
85
+ <Pressable accessibilityRole="button" accessibilityLabel={`Decrease ${line.name}`}
86
+ 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>
87
+ <Pressable accessibilityRole="button" accessibilityLabel={`Increase ${line.name}`}
88
+ 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>
89
+ <Pressable accessibilityRole="button" accessibilityLabel={`Remove ${line.name}`}
90
+ 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>
91
+ </View>
50
92
  </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
93
  {discountForm(line.id, `Discount on ${line.name}`)}
61
- {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)}
63
- onApply={(amount, reason) => {
64
- const fromMinor = line.unitPriceMinor;
65
- const refused = sale.setUnitPrice(line.id, amount);
66
- if (refused === null) onPriceChange?.({ lineId: line.id, fromMinor, toMinor: amount, reason });
67
- return refused;
68
- }} /> : null}
94
+ {canEditPrice && !pricePopover && form?.type === 'price' && form.lineId === line.id ? <PriceForm key={line.id} lineName={line.name}
95
+ currency={order.currency} currentMinor={line.unitPriceMinor} quickDiscounts={quickDiscounts} onClose={() => setForm(null)}
96
+ onApply={(amount, reason) => applyPrice(line, amount, reason)} /> : null}
69
97
  </>;
70
- return <CartPanel dataSet={{ print: 'hide' }} items={order.lineItems} renderItem={renderItem}
98
+ return <View dataSet={{ print: 'hide' }} className="flex-1 min-h-0" onLayout={(event) => setCartWidth(event.nativeEvent.layout.width)}>
99
+ <CartColumnHeads showPrice={showPrice} />
100
+ <CartPanel items={order.lineItems} renderItem={renderItem}
71
101
  emptyState={<Text testID="cart-empty" className="px-3 py-2 text-muted-foreground">Scan or tap a product to start a sale.</Text>}
72
102
  afterItems={<>
73
103
  {(['fees', 'shipping'] as const).map((kind) => order[kind]?.map((charge, index) =>
@@ -79,15 +109,15 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
79
109
  className="rounded-md border border-border bg-card px-3 py-2 min-h-11 items-center justify-center">
80
110
  <Text className="text-foreground">Remove</Text></Pressable>
81
111
  </View>))}
82
- {order.lineItems.length || chargesOffered ? <View className="gap-3 px-3 py-2">
83
- {order.lineItems.length ? <>
112
+ {showOrderDiscount || showCharge ? <View className="gap-3 px-3 py-2">
113
+ {showOrderDiscount ? <>
84
114
  <DiscountChips discounts={order.discounts} amounts={orderAmounts} currency={order.currency} onRemove={sale.removeDiscount}
85
115
  prefix="Order discount" />
86
- {form?.type === 'discount' && form.lineId === null ? discountForm(null, 'Order discount') : <Pressable accessibilityRole="button"
116
+ {!orderActions ? null : form?.type === 'discount' && form.lineId === null ? discountForm(null, 'Order discount') : <Pressable accessibilityRole="button"
87
117
  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
118
  <Text className="text-foreground">Order discount</Text></Pressable>}
89
119
  </> : null}
90
- {chargesOffered ? form?.type === 'charge' ? <ChargeForm currency={order.currency} lineTax={sale.capabilities?.lineTax}
120
+ {showCharge ? form?.type === 'charge' ? <ChargeForm currency={order.currency} lineTax={sale.capabilities?.lineTax}
91
121
  taxClasses={taxClasses} shippingTaxFromStore={sale.capabilities?.taxRounding?.granularity === 'woocommerce'}
92
122
  onClose={() => setForm(null)} onApply={({ kind, name, amountMinor, taxStatus, taxClass }) => {
93
123
  const result = kind === 'custom' ? sale.addCustomLine({ name, priceMinor: amountMinor, taxStatus, taxClass })
@@ -104,13 +134,15 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
104
134
  discount={money(couponDiscountMinor === undefined ? totals.discountMinor : Math.max(0, totals.discountMinor - couponDiscountMinor))}
105
135
  taxLines={taxRows} taxInclusive={totals.taxInclusive} afterSubtotal={afterSubtotal} />
106
136
  {sale.error ? <Text accessibilityRole="alert" className="text-destructive">{sale.error}</Text> : null}
107
- <View className="flex-row gap-3">
137
+ {checkout ? <CartFoot total={money(totals.totalMinor)} onCheckout={checkout.onCheckout} actions={checkout.actions}
138
+ disabled={!order.lineItems.length} /> : <View className="flex-row gap-3">
108
139
  <Pressable accessibilityRole="button" disabled={!order.lineItems.length} onPress={() => sale.startTender('cash')} className={pay}>
109
140
  <Text className="text-center font-semibold text-primary-foreground">Cash</Text>
110
141
  </Pressable>
111
142
  <Pressable accessibilityRole="button" disabled={!order.lineItems.length} onPress={() => sale.startTender('external')} className={pay}>
112
143
  <Text className="text-center font-semibold text-primary-foreground">Card terminal</Text>
113
144
  </Pressable>
114
- </View>
115
- </View>} />;
145
+ </View>}
146
+ </View>} />
147
+ </View>;
116
148
  }