@tallyui/components 3.20.1 → 4.0.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 (161) hide show
  1. package/dist/index.d.ts +1114 -90
  2. package/dist/index.js +8077 -3352
  3. package/package.json +10 -11
  4. package/src/cart/cart-charge-line.tsx +58 -0
  5. package/src/cart/cart-columns-form.tsx +98 -0
  6. package/src/cart/cart-columns.tsx +49 -18
  7. package/src/cart/cart-foot.tsx +7 -2
  8. package/src/cart/cart-line-strip.tsx +59 -0
  9. package/src/cart/cart-line.tsx +20 -8
  10. package/src/cart/cart-note-row.tsx +30 -0
  11. package/src/cart/cart-panel.tsx +9 -1
  12. package/src/cart/cart-row-motion.tsx +125 -0
  13. package/src/cart/cart-total.tsx +44 -15
  14. package/src/cart/index.ts +2 -1
  15. package/src/checkout/cash-tendered.tsx +8 -7
  16. package/src/checkout/change-display.tsx +2 -1
  17. package/src/checkout/index.ts +1 -1
  18. package/src/checkout/payment-selector.tsx +6 -2
  19. package/src/checkout/payment-types.test-d.ts +28 -0
  20. package/src/customer/address-editor.tsx +87 -0
  21. package/src/customer/address-fields.tsx +120 -0
  22. package/src/customer/customer-dropdown.tsx +200 -0
  23. package/src/customer/customer-editor.tsx +99 -0
  24. package/src/customer/customer-form.tsx +39 -5
  25. package/src/customer/customer-picker.tsx +38 -14
  26. package/src/customer/customers-list.tsx +83 -0
  27. package/src/customer/index.ts +5 -0
  28. package/src/filter/filter-pills.tsx +63 -0
  29. package/src/i18n/locales/en/components.json +85 -0
  30. package/src/index.ts +40 -2
  31. package/src/input/decimal-entry.ts +21 -0
  32. package/src/layout/checkout-layout.tsx +1 -1
  33. package/src/layout/live-tab-screen.tsx +1 -1
  34. package/src/layout/pos-layout.tsx +80 -4
  35. package/src/layout/settings-layout.tsx +1 -1
  36. package/src/layout/store-settings-choice-screen.tsx +1 -1
  37. package/src/lib/current-row.ts +13 -0
  38. package/src/lib/money-input.ts +16 -0
  39. package/src/lib/motion.ts +22 -0
  40. package/src/lib/use-reduced-motion.ts +20 -0
  41. package/src/order/index.ts +1 -1
  42. package/src/order/order-detail.tsx +123 -5
  43. package/src/order/order-filter-bar.tsx +7 -57
  44. package/src/order/order-status-badge.tsx +42 -19
  45. package/src/order/refund-form.tsx +7 -5
  46. package/src/product/camera-scan-button.tsx +2 -0
  47. package/src/product/category-nav.tsx +8 -0
  48. package/src/product/category-tile.tsx +65 -15
  49. package/src/product/in-cart-badge.tsx +55 -6
  50. package/src/product/index.ts +1 -0
  51. package/src/product/press-veil.tsx +7 -0
  52. package/src/product/product-card.tsx +5 -1
  53. package/src/product/product-grid.tsx +5 -0
  54. package/src/product/product-price.tsx +6 -3
  55. package/src/product/product-stock-badge.tsx +3 -2
  56. package/src/product/product-table.tsx +96 -8
  57. package/src/product/products-screen-columns.tsx +74 -0
  58. package/src/product/variant-tile.tsx +68 -0
  59. package/src/product/variation-picker.tsx +3 -3
  60. package/src/product/view-toggle.tsx +33 -4
  61. package/src/register/cashier-sheet.tsx +195 -0
  62. package/src/register/closure-sheet.tsx +54 -3
  63. package/src/register/handover-slip.tsx +2 -1
  64. package/src/register/index.ts +2 -1
  65. package/src/register/movement-sheet.tsx +66 -7
  66. package/src/register/open-register-card.tsx +11 -11
  67. package/src/register/register-bar.helpers.ts +17 -4
  68. package/src/register/register-bar.tsx +26 -5
  69. package/src/register/register-count.tsx +158 -24
  70. package/src/register/register-panel.tsx +16 -5
  71. package/src/register/register-side-sheet.tsx +32 -8
  72. package/src/register/switch-confirm.tsx +2 -2
  73. package/src/reports/card-panel.tsx +131 -0
  74. package/src/reports/cards.tsx +53 -36
  75. package/src/reports/hero.tsx +2 -1
  76. package/src/reports/index.ts +1 -0
  77. package/src/reports/sales-room.tsx +4 -2
  78. package/src/sale/breadcrumb.tsx +48 -0
  79. package/src/sale/cart-bar.tsx +2 -1
  80. package/src/sale/cart.tsx +127 -38
  81. package/src/sale/catalogue-settings-form.tsx +92 -0
  82. package/src/sale/catalogue.tsx +304 -42
  83. package/src/sale/category-browse.tsx +27 -0
  84. package/src/sale/charge-form.tsx +85 -21
  85. package/src/sale/customer-display-screen.tsx +22 -6
  86. package/src/sale/discount-form.tsx +132 -28
  87. package/src/sale/index.ts +6 -3
  88. package/src/sale/line-popover.tsx +72 -36
  89. package/src/sale/offered-methods.ts +16 -0
  90. package/src/sale/open-sale-tabs.tsx +58 -10
  91. package/src/sale/order-note-sheet.tsx +37 -0
  92. package/src/sale/order-reference.ts +3 -0
  93. package/src/sale/orders-list.tsx +76 -37
  94. package/src/sale/parked-sales.tsx +2 -1
  95. package/src/sale/price-form.tsx +7 -5
  96. package/src/sale/product-filter-bar.tsx +38 -5
  97. package/src/sale/receipt-sheet.tsx +243 -0
  98. package/src/sale/receipt.tsx +19 -9
  99. package/src/sale/sync-status.tsx +10 -0
  100. package/src/sale/tender-ledger.tsx +92 -0
  101. package/src/sale/tender-pane.tsx +159 -73
  102. package/src/sale/tender.tsx +10 -7
  103. package/src/sale/use-tender.ts +63 -0
  104. package/src/scale/min-target.tsx +36 -0
  105. package/src/settings/barcode-scanning-settings.tsx +164 -0
  106. package/src/settings/connector-status.tsx +1 -1
  107. package/src/settings/customer-display-settings.tsx +12 -25
  108. package/src/settings/index.ts +5 -0
  109. package/src/settings/printer-form.tsx +161 -0
  110. package/src/settings/printing-settings.tsx +268 -0
  111. package/src/settings/settings-group.tsx +2 -1
  112. package/src/settings/tax-calculation-settings.tsx +1 -1
  113. package/src/shell/added-to-cart-toast.tsx +61 -0
  114. package/src/shell/app-shell.tsx +5 -1
  115. package/src/shell/connectivity-toast.tsx +70 -0
  116. package/src/shell/index.ts +2 -0
  117. package/src/shell/nav-drawer.tsx +5 -2
  118. package/src/shell/nav-item.tsx +7 -4
  119. package/src/shell/nav-rail.tsx +9 -2
  120. package/src/ui/accordion/index.tsx +86 -8
  121. package/src/ui/alert-dialog/index.tsx +19 -5
  122. package/src/ui/combobox/index.tsx +21 -2
  123. package/src/ui/confirm-dialog/index.tsx +53 -0
  124. package/src/ui/dialog/index.tsx +68 -14
  125. package/src/ui/dialog/motion.ts +54 -0
  126. package/src/ui/icon/activity-heartbeat-icon.tsx +7 -0
  127. package/src/ui/icon/alert-circle-icon.tsx +5 -0
  128. package/src/ui/icon/alert-triangle-icon.tsx +7 -0
  129. package/src/ui/icon/banknote-icon.tsx +11 -0
  130. package/src/ui/icon/cash-register-icon.tsx +10 -0
  131. package/src/ui/icon/category-icon.tsx +7 -0
  132. package/src/ui/icon/chart-line-icon.tsx +5 -0
  133. package/src/ui/icon/check-icon.tsx +5 -0
  134. package/src/ui/icon/chevron-left-icon.tsx +4 -0
  135. package/src/ui/icon/chevron-right-icon.tsx +4 -0
  136. package/src/ui/icon/credit-card-icon.tsx +10 -0
  137. package/src/ui/icon/discount-icon.tsx +11 -0
  138. package/src/ui/icon/gift-icon.tsx +10 -0
  139. package/src/ui/icon/info-circle-icon.tsx +10 -0
  140. package/src/ui/icon/map-pin-icon.tsx +10 -0
  141. package/src/ui/icon/message-question-icon.tsx +7 -0
  142. package/src/ui/icon/pencil-icon.tsx +10 -0
  143. package/src/ui/icon/plus-icon.tsx +9 -0
  144. package/src/ui/icon/printer-icon.tsx +10 -0
  145. package/src/ui/icon/receipt-icon.tsx +7 -0
  146. package/src/ui/icon/settings-icon.tsx +10 -0
  147. package/src/ui/icon/sticky-note-icon.tsx +10 -0
  148. package/src/ui/icon/user-icon.tsx +4 -0
  149. package/src/ui/icon/users-icon.tsx +7 -0
  150. package/src/ui/icon/view-grid-icon.tsx +7 -0
  151. package/src/ui/icon/view-list-icon.tsx +7 -0
  152. package/src/ui/index.ts +24 -1
  153. package/src/ui/list-row/index.tsx +93 -0
  154. package/src/ui/notice/index.tsx +65 -0
  155. package/src/ui/select/index.tsx +2 -0
  156. package/src/ui/skeleton/index.tsx +37 -0
  157. package/src/ui/status-badge/index.tsx +43 -0
  158. package/src/ui/switch/index.tsx +1 -1
  159. package/src/ui/tabs/index.tsx +11 -2
  160. package/src/ui/toggle-group/index.tsx +3 -1
  161. package/src/ui/tone-disc/index.tsx +41 -0
@@ -0,0 +1,200 @@
1
+ // Port of WCPOS v2 (monorepo main) pos/cart/customer.tsx and components/customer-select.tsx (CustomerSearch, CustomerList,
2
+ // CustomerSelectItem): the cart header's customer chip and its search dropdown; MIT, WCPOS.
3
+ import { useEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
4
+ import { Platform, Pressable, ScrollView, StyleSheet, Text, View, type NativeScrollEvent, type NativeSyntheticEvent } from 'react-native';
5
+ import { CustomerServiceError, type Customer } from '@tallyui/core';
6
+ import { Popover } from '@tallyui/primitives';
7
+ import { cn } from '@tallyui/theme';
8
+ import { Avatar, avatarInitials, Input, UserIcon } from '../ui';
9
+ import { MapPinIcon } from '../ui/icon/map-pin-icon';
10
+ import { customerErrorText } from './customer-picker';
11
+
12
+ /** line-popover.tsx's focus targets: here the search field and the rows. */
13
+ const FOCUSABLE = 'button, [href], input, [tabindex]:not([tabindex="-1"])';
14
+ const row = 'min-h-11 flex-row items-center gap-2 rounded-md px-2 py-1.5 web:focus:bg-accent';
15
+ /** v2's SEARCH_SELECT_PAGE_SIZE (monorepo packages/core/src/query/search-select.ts:28): a page shorter than this is the last one. */
16
+ const PAGE_SIZE = 50;
17
+
18
+ export interface CustomerDropdownProps {
19
+ /** The connector's searchCustomers, bound to its context by the app. `page` (1-based) asks for the next 50 when the cashier reaches the end of the list; absent means the first page. */
20
+ search: (query: string, page?: number) => Promise<Customer[]>;
21
+ /** The first customers to list for an empty query (v2's customer browse, e.g. the first 50 by last name). Absent: an empty query lists Guest alone. `page` (1-based) asks for the next 50 when the cashier reaches the end of the list; absent means the first page. */
22
+ browse?: (page?: number) => Promise<Customer[]>;
23
+ selected: Customer | null;
24
+ /** A customer, or null for Guest. */
25
+ onSelect: (customer: Customer | null) => void;
26
+ /** Called for errors the dropdown can't explain to the cashier, including `ConnectorUnauthorizedError`: sign in again only when its `code` is `'unauthorized'` (401). `'forbidden'` (403) means signed in but not allowed; never sign out for it. */
27
+ onError?: (error: unknown) => void;
28
+ /** false disables search; Guest stays selectable. */
29
+ online: boolean;
30
+ /** Debounce before a search, ms. Default 250. */
31
+ debounceMs?: number;
32
+ className?: string;
33
+ /** testID of the chip. Default `customer-dropdown-chip`. */
34
+ testID?: string;
35
+ /** Opens the app's editor for the sale's addresses (v2's split pin beside the chip). Absent: no pin. */
36
+ onEditAddress?: () => void;
37
+ /** Default `false`; false greys the pin until the sale's billing has an address, as in v2. */
38
+ hasAddress?: boolean;
39
+ }
40
+
41
+ /** v2's GuestAvatar: the Guest is not a person, so a neutral glyph on a muted circle, never initials. */
42
+ export function GuestGlyph() {
43
+ return <View className="h-6 w-6 items-center justify-center rounded-full bg-muted text-muted-foreground"><UserIcon size={14} /></View>;
44
+ }
45
+
46
+ /** v2's cart-header customer chip (the sale's customer, or Guest); it opens a search panel anchored under it, Guest first. */
47
+ export function CustomerDropdown({ search, browse, selected, onSelect, onError, online, debounceMs = 250, className, testID = 'customer-dropdown-chip', onEditAddress, hasAddress = false }: CustomerDropdownProps) {
48
+ const [open, setOpen] = useState(false);
49
+ const [query, setQuery] = useState('');
50
+ const [customers, setCustomers] = useState<Customer[]>([]);
51
+ const [error, setError] = useState<string | null>(null);
52
+ const searchRef = useRef(search);
53
+ searchRef.current = search;
54
+ const browseRef = useRef(browse);
55
+ browseRef.current = browse;
56
+ const canBrowse = browse !== undefined;
57
+ const onErrorRef = useRef(onError);
58
+ onErrorRef.current = onError;
59
+ const chip = useRef<View>(null);
60
+ const name = selected?.name ?? 'Guest';
61
+ // The shown rows' paging: their generation (any newer first page makes older pages stale), query, last page loaded
62
+ // (0 until the first page resolves), whether there is no more, and v2's latch (one later page in flight).
63
+ const paging = useRef({ gen: 0, query: '', page: 0, done: false, busy: false });
64
+
65
+ // CustomerPicker's search: debounced, a stale response dropped; nothing sent offline; a blank query sends `browse` while
66
+ // open (when given), else nothing.
67
+ useEffect(() => {
68
+ paging.current = { gen: paging.current.gen + 1, query, page: 0, done: false, busy: false };
69
+ const p = paging.current;
70
+ const stale = () => paging.current.gen !== p.gen;
71
+ setError(null);
72
+ const blank = !query.trim();
73
+ if (!online || (blank && (!canBrowse || !open))) { setCustomers([]); return; }
74
+ const timer = setTimeout(async () => {
75
+ try {
76
+ const results = await (blank ? browseRef.current?.() ?? [] : searchRef.current(query));
77
+ if (stale()) return;
78
+ setCustomers(results);
79
+ p.page = 1;
80
+ p.done = results.length < PAGE_SIZE;
81
+ } catch (error) {
82
+ if (stale()) return;
83
+ setError(customerErrorText(error));
84
+ if (!(error instanceof CustomerServiceError)) onErrorRef.current?.(error);
85
+ }
86
+ }, blank ? 0 : debounceMs);
87
+ return () => { clearTimeout(timer); paging.current.gen++; };
88
+ }, [query, online, debounceMs, open, canBrowse]);
89
+
90
+ // v2's next page at the end of the list: the next 50 for the query the rows came from, one request at a time, never
91
+ // offline; rows are kept by customer id.
92
+ const more = async () => {
93
+ const p = paging.current;
94
+ if (!online || !open || p.page < 1 || p.done || p.busy) return;
95
+ p.busy = true;
96
+ const next = p.page + 1;
97
+ try {
98
+ const results = await (p.query.trim() ? searchRef.current(p.query, next) : browseRef.current?.(next) ?? []);
99
+ if (paging.current.gen !== p.gen) return;
100
+ setError(null);
101
+ const held = new Set(customers.map((customer) => customer.id));
102
+ const fresh = results.filter((customer) => !held.has(customer.id));
103
+ setCustomers((rows) => [...rows, ...fresh]);
104
+ p.page = next;
105
+ if (results.length < PAGE_SIZE) p.done = true;
106
+ if (!fresh.length) p.done = true;
107
+ } catch (error) {
108
+ if (paging.current.gen !== p.gen) return;
109
+ setError(customerErrorText(error));
110
+ if (!(error instanceof CustomerServiceError)) onErrorRef.current?.(error);
111
+ } finally { p.busy = false; }
112
+ };
113
+ // v2's onEndReachedThreshold={0.1}: within a tenth of the visible height of the end.
114
+ const onScroll = ({ nativeEvent: { contentOffset, contentSize, layoutMeasurement } }: NativeSyntheticEvent<NativeScrollEvent>) => {
115
+ if (contentSize.height - (contentOffset.y + layoutMeasurement.height) <= 0.1 * layoutMeasurement.height) void more();
116
+ };
117
+
118
+ // Each open starts, and each close leaves, an empty query with no results.
119
+ const openChange = (next: boolean) => { setQuery(''); setCustomers([]); setOpen(next); };
120
+ const pick = (customer: Customer | null) => { openChange(false); onSelect(customer); };
121
+ const split = onEditAddress !== undefined && !open;
122
+
123
+ // The products column's filter pill, as in v2; lit while open like a pill that is on. With onEditAddress and closed it is
124
+ // the left cell of v2's split chip, the pill frame on the wrapper below.
125
+ const trigger = <Popover.Trigger ref={chip} testID={testID} accessibilityLabel={`Customer: ${name}`}
126
+ className={split ? 'flex-row items-center gap-1.5 rounded-l-full px-3 web:hover:bg-accent'
127
+ : cn('min-h-11 flex-row items-center gap-1.5 rounded-full border border-border px-3', open ? 'border-primary/30 bg-primary/10' : 'bg-card')}>
128
+ {open ? <><View className="text-muted-foreground"><UserIcon size={16} /></View><Text className="text-foreground">Select Customer</Text></>
129
+ : <>{selected ? <Avatar tone="primary" className="h-6 w-6" fallback={avatarInitials(selected.name)} aria-hidden /> : <GuestGlyph />}
130
+ <Text numberOfLines={1} className="text-foreground">{name}</Text></>}
131
+ </Popover.Trigger>;
132
+
133
+ return <View className={cn('flex-row items-center gap-2', className)}>
134
+ <Text className="text-muted-foreground">Customer</Text>
135
+ <Popover.Root open={open} onOpenChange={openChange}>
136
+ {/* The wrapper stays while open (no frame, no pin) so the trigger is not remounted and focus can return to it on close. */}
137
+ {onEditAddress ? <View className={cn('flex-row', split && 'min-h-11 items-stretch rounded-full border border-border bg-card')}>
138
+ {trigger}
139
+ {split && <Pressable role="button" accessibilityLabel="Edit Customer Address" testID="customer-dropdown-address" onPress={onEditAddress}
140
+ className="min-w-11 items-center justify-center rounded-r-full border-l border-border web:hover:bg-accent">
141
+ <View className={hasAddress ? 'text-foreground' : 'text-muted-foreground'}><MapPinIcon size={16} /></View>
142
+ </Pressable>}
143
+ </View> : trigger}
144
+ <Popover.Portal>
145
+ <Popover.Overlay style={StyleSheet.absoluteFill} />
146
+ <Popover.Content testID="customer-dropdown" align="start" sideOffset={4} className="z-50 w-80 rounded-md border border-border bg-popover p-2 shadow-md outline-none">
147
+ <Panel chip={chip} onClose={() => openChange(false)}>
148
+ <Input className="mb-2"><Input.Field accessibilityLabel="Search customers" placeholder="Search Customers" testID="customer-dropdown-search"
149
+ value={query} onChangeText={setQuery} editable={online} /></Input>
150
+ {!online && <Text className="text-sm text-muted-foreground">Connect to search customers.</Text>}
151
+ {error && <Text accessibilityRole="alert" className="text-sm text-destructive">{error}</Text>}
152
+ {/* Guest first, always: v2's cart dropdown prepends it, so a search with no matches shows Guest alone. */}
153
+ <ScrollView className="max-h-60" testID="customer-dropdown-list" onScroll={onScroll} scrollEventThrottle={16}>
154
+ <Pressable role="option" aria-selected={selected === null} testID="customer-dropdown-option-guest" accessibilityLabel="Guest" onPress={() => pick(null)} className={row}>
155
+ <GuestGlyph />
156
+ <Text className="text-foreground">Guest</Text>
157
+ </Pressable>
158
+ {customers.map((customer) => <Pressable key={customer.id} role="option" aria-selected={selected?.id === customer.id} testID={`customer-dropdown-option-${customer.id}`}
159
+ accessibilityLabel={customer.email ? `${customer.name}, ${customer.email}` : customer.name} onPress={() => pick(customer)} className={row}>
160
+ <Avatar tone="primary" className="h-6 w-6" fallback={avatarInitials(customer.name)} aria-hidden />
161
+ <View className="flex-1"><Text className="text-foreground">{customer.name}</Text>
162
+ {customer.email ? <Text className="text-sm text-muted-foreground">{customer.email}</Text> : null}</View>
163
+ </Pressable>)}
164
+ </ScrollView>
165
+ </Panel>
166
+ </Popover.Content>
167
+ </Popover.Portal>
168
+ </Popover.Root>
169
+ </View>;
170
+ }
171
+
172
+ /** Web: focus goes to the search field, and back to the chip on close; arrows move between the field and the rows, wrapping
173
+ * (v2's use-arrow-key-navigation, scoped to the panel); Escape closes; Space picks a focused row (Enter is react-native-web's own press). */
174
+ function Panel({ chip, onClose, children }: { chip: RefObject<View | null>; onClose: () => void; children: ReactNode }) {
175
+ const panel = useRef<View>(null);
176
+ const closeRef = useRef(onClose);
177
+ closeRef.current = onClose;
178
+ useEffect(() => {
179
+ if (Platform.OS !== 'web' || typeof document === 'undefined') return;
180
+ const node = panel.current as unknown as HTMLElement | null;
181
+ const trigger = chip.current as unknown as HTMLElement | null;
182
+ node?.querySelector<HTMLElement>(FOCUSABLE)?.focus();
183
+ const onKeyDown = (event: KeyboardEvent) => {
184
+ const items = Array.from(node?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? []);
185
+ const at = items.indexOf(document.activeElement as HTMLElement);
186
+ if (event.key === 'Escape') closeRef.current();
187
+ else if ((event.key === 'ArrowDown' || event.key === 'ArrowUp') && items.length) {
188
+ event.preventDefault();
189
+ items[at < 0 ? 0 : (at + (event.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length].focus();
190
+ } else if (event.key === ' ' && items[at]?.getAttribute('role') === 'option') {
191
+ event.preventDefault();
192
+ items[at].click();
193
+ }
194
+ };
195
+ // Capture phase: react-native-web's TextInput stops keydown propagation (TextInput/index.js, "see #612"), so a bubble listener never hears the field.
196
+ document.addEventListener('keydown', onKeyDown, true);
197
+ return () => { document.removeEventListener('keydown', onKeyDown, true); trigger?.focus?.(); };
198
+ }, [chip]);
199
+ return <View ref={panel}>{children}</View>;
200
+ }
@@ -0,0 +1,99 @@
1
+ /** Adds or edits a customer: CustomerForm with its AddressEditor, an explicit Save and Cancel, and the store call.
2
+ * v2 saves its edit form as you type (customers/edit/form.tsx); here Save is explicit and online-only (desk ruling, 10.1 vet). */
3
+ import { useEffect, useRef, useState } from 'react';
4
+ import { Pressable, Text, View } from 'react-native';
5
+ import type { Customer, CustomerInput, CustomerPatch } from '@tallyui/core';
6
+ import { shipsToBilling, toCustomerInput, toCustomerPatch, type CustomerEditValues } from '@tallyui/pos';
7
+ import { cn } from '@tallyui/theme';
8
+ import { useT } from '../i18n';
9
+ import { CustomerForm, type CustomerFormProps } from './customer-form';
10
+ import { customerEmailError, customerErrorText } from './customer-picker';
11
+
12
+ export interface CustomerEditorProps {
13
+ /** Edit this customer; absent means add a new one. */
14
+ customer?: Customer;
15
+ /** Add mode's store call. */
16
+ create?: (input: CustomerInput) => Promise<Customer>;
17
+ /** Edit mode's store call. */
18
+ update?: (id: string, patch: CustomerPatch) => Promise<Customer>;
19
+ /** Called with the store's customer after a save, or with `customer` when an edit changed nothing. */
20
+ onSaved: (customer: Customer) => void;
21
+ onCancel: () => void;
22
+ /** Save is disabled while offline (desk ruling: online-only Save). */
23
+ online: boolean;
24
+ countries?: CustomerFormProps['countries'];
25
+ statesFor?: CustomerFormProps['statesFor'];
26
+ defaultCountry?: CustomerFormProps['defaultCountry'];
27
+ className?: string;
28
+ /** Default 'customer-editor'. */
29
+ testID?: string;
30
+ }
31
+
32
+ function initialValues(customer: Customer | undefined): CustomerEditValues {
33
+ if (!customer) return { firstName: '', lastName: '', email: '', phone: '' };
34
+ return {
35
+ firstName: customer.firstName ?? '', lastName: customer.lastName ?? '', email: customer.email ?? '', phone: customer.phone ?? '',
36
+ company: customer.company, billing: customer.billing,
37
+ // undefined is "Same as billing" (ShippingAddressFields' convention).
38
+ shipping: shipsToBilling(customer.shipping, customer.billing) ? undefined : customer.shipping,
39
+ };
40
+ }
41
+
42
+ export function CustomerEditor({ customer, create, update, onSaved, onCancel, online, countries, statesFor, defaultCountry, className, testID = 'customer-editor' }: CustomerEditorProps) {
43
+ const t = useT();
44
+ const [values, setValues] = useState<CustomerEditValues>(() => initialValues(customer));
45
+ const [emailError, setEmailError] = useState<string | undefined>();
46
+ const [saveError, setSaveError] = useState<string | undefined>();
47
+ const [saving, setSaving] = useState(false);
48
+ const mounted = useRef(true);
49
+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
50
+ const disabled = !online || saving || !values.email.trim();
51
+
52
+ async function save() {
53
+ if (disabled) return;
54
+ const trimmed: CustomerEditValues = { ...values, firstName: values.firstName.trim(), lastName: values.lastName.trim(),
55
+ email: values.email.trim(), phone: values.phone.trim(), company: values.company?.trim() };
56
+ const error = customerEmailError(trimmed.email);
57
+ if (error) return setEmailError(error);
58
+ let call: Promise<Customer> | undefined;
59
+ if (!customer) call = create?.(toCustomerInput(trimmed));
60
+ else {
61
+ const patch = toCustomerPatch(customer, trimmed);
62
+ if (Object.keys(patch).length === 0) return onSaved(customer);
63
+ call = update?.(customer.id, patch);
64
+ }
65
+ if (!call) return;
66
+ setSaving(true);
67
+ setSaveError(undefined);
68
+ try {
69
+ const result = await call;
70
+ if (mounted.current) onSaved(result);
71
+ } catch (failure) {
72
+ if (mounted.current) setSaveError(customerErrorText(failure));
73
+ } finally {
74
+ if (mounted.current) setSaving(false);
75
+ }
76
+ }
77
+
78
+ const change = (next: Partial<CustomerEditValues>) => {
79
+ setValues((current) => ({ ...current, ...next }));
80
+ setEmailError(undefined);
81
+ setSaveError(undefined);
82
+ };
83
+ const button = 'items-center rounded-lg px-4 py-3';
84
+ return <View className={cn('gap-3', className)}>
85
+ <CustomerForm values={{ ...values, address: '' }} onChangeField={(field, value) => change({ [field]: value })}
86
+ addresses={{ billing: values.billing, shipping: values.shipping }} onChangeAddresses={(next) => change(next)} showCompany
87
+ countries={countries} statesFor={statesFor} defaultCountry={defaultCountry} emailError={emailError} testID={`${testID}-form`} />
88
+ {saveError ? <Text role="alert" testID={`${testID}-error`} className="px-4 text-sm text-destructive">{saveError}</Text> : null}
89
+ <View className="flex-row justify-end gap-3 px-4">
90
+ <Pressable accessibilityRole="button" testID={`${testID}-cancel`} onPress={onCancel} className={cn(button, 'border border-border')}>
91
+ <Text className="text-sm font-semibold text-foreground">{t('common.cancel')}</Text>
92
+ </Pressable>
93
+ <Pressable accessibilityRole="button" testID={`${testID}-save`} disabled={disabled} accessibilityState={{ disabled, busy: saving }}
94
+ onPress={save} className={cn(button, 'bg-primary', disabled && 'opacity-50')}>
95
+ <Text className="text-sm font-semibold text-primary-foreground">{customer ? t('common.save') : t('customers.add_customer')}</Text>
96
+ </Pressable>
97
+ </View>
98
+ </View>;
99
+ }
@@ -2,12 +2,16 @@ import { Pressable, Text, TextInput, View, type ViewProps } from 'react-native';
2
2
 
3
3
  import { cn } from '@tallyui/theme';
4
4
 
5
+ import { useT } from '../i18n';
6
+ import { AddressEditor, type AddressEditorProps, type AddressEditorValue } from './address-editor';
7
+
5
8
  export interface CustomerFormValues {
6
9
  firstName: string;
7
10
  lastName: string;
8
11
  email: string;
9
12
  phone: string;
10
13
  address: string;
14
+ company?: string;
11
15
  }
12
16
 
13
17
  export interface CustomerFormProps extends Omit<ViewProps, 'children'> {
@@ -16,6 +20,20 @@ export interface CustomerFormProps extends Omit<ViewProps, 'children'> {
16
20
  onSubmit?: () => void;
17
21
  submitLabel?: string;
18
22
  showAddress?: boolean;
23
+ /** Billing and shipping. With `onChangeAddresses` too, an `AddressEditor` replaces the free-text Address field. */
24
+ addresses?: AddressEditorValue;
25
+ /** Receives the next billing and shipping; the `AddressEditor` shows only when this and `addresses` are both set. */
26
+ onChangeAddresses?: (next: AddressEditorValue) => void;
27
+ /** Passed through to `AddressEditor`. */
28
+ countries?: AddressEditorProps['countries'];
29
+ /** Passed through to `AddressEditor`. */
30
+ statesFor?: AddressEditorProps['statesFor'];
31
+ /** Passed through to `AddressEditor`: a new address starts in this country. */
32
+ defaultCountry?: AddressEditorProps['defaultCountry'];
33
+ /** A Company field after Email and Phone (v2 customer-form.tsx:171-172). Default false. */
34
+ showCompany?: boolean;
35
+ /** Shown as an alert under the Email field. The form does not validate; the caller decides. */
36
+ emailError?: string;
19
37
  className?: string;
20
38
  }
21
39
 
@@ -45,22 +63,38 @@ export function CustomerForm({
45
63
  onSubmit,
46
64
  submitLabel = 'Save Customer',
47
65
  showAddress = true,
66
+ addresses,
67
+ onChangeAddresses,
68
+ countries,
69
+ statesFor,
70
+ defaultCountry,
71
+ showCompany = false,
72
+ emailError,
48
73
  className,
49
74
  ...viewProps
50
75
  }: CustomerFormProps) {
76
+ const t = useT();
77
+ const id = viewProps.testID ?? 'customer-form';
51
78
  return (
52
79
  <View className={cn('gap-3 p-4', className)} {...viewProps}>
53
80
  <View className="flex-row gap-3">
54
81
  <View className="flex-1">
55
- <FormField label="First Name" value={values.firstName} onChangeText={(v) => onChangeField('firstName', v)} placeholder="First name" />
82
+ <FormField label={t('common.first_name')} value={values.firstName} onChangeText={(v) => onChangeField('firstName', v)} placeholder="First name" />
56
83
  </View>
57
84
  <View className="flex-1">
58
- <FormField label="Last Name" value={values.lastName} onChangeText={(v) => onChangeField('lastName', v)} placeholder="Last name" />
85
+ <FormField label={t('common.last_name')} value={values.lastName} onChangeText={(v) => onChangeField('lastName', v)} placeholder="Last name" />
59
86
  </View>
60
87
  </View>
61
- <FormField label="Email" value={values.email} onChangeText={(v) => onChangeField('email', v)} placeholder="email@example.com" keyboardType="email-address" />
62
- <FormField label="Phone" value={values.phone} onChangeText={(v) => onChangeField('phone', v)} placeholder="Phone number" keyboardType="phone-pad" />
63
- {showAddress && <FormField label="Address" value={values.address} onChangeText={(v) => onChangeField('address', v)} placeholder="Street address" multiline />}
88
+ <FormField label={t('common.email')} value={values.email} onChangeText={(v) => onChangeField('email', v)} placeholder="email@example.com" keyboardType="email-address" />
89
+ {emailError ? <Text role="alert" testID={`${id}-email-error`} className="text-xs text-destructive">{emailError}</Text> : null}
90
+ <FormField label={t('common.phone')} value={values.phone} onChangeText={(v) => onChangeField('phone', v)} placeholder="Phone number" keyboardType="phone-pad" />
91
+ {showCompany && <FormField label={t('common.company')} value={values.company ?? ''} onChangeText={(v) => onChangeField('company', v)} />}
92
+ {addresses && onChangeAddresses ? (
93
+ <AddressEditor value={addresses} onChange={onChangeAddresses} countries={countries} statesFor={statesFor}
94
+ defaultCountry={defaultCountry} testID={`${id}-addresses`} />
95
+ ) : (
96
+ showAddress && <FormField label="Address" value={values.address} onChangeText={(v) => onChangeField('address', v)} placeholder="Street address" multiline />
97
+ )}
64
98
 
65
99
  {onSubmit && (
66
100
  <Pressable onPress={onSubmit} className="items-center rounded-lg bg-primary px-4 py-3">
@@ -4,6 +4,7 @@ import { customerTraits, CustomerServiceError, ConnectorUnauthorizedError, type
4
4
  import { cn } from '@tallyui/theme';
5
5
  import { CustomerCard } from './customer-card';
6
6
  import { CustomerSelect } from './customer-select';
7
+ import { GuestGlyph } from './customer-dropdown';
7
8
  import { CustomerForm, type CustomerFormValues } from './customer-form';
8
9
 
9
10
  export interface CustomerPickerProps {
@@ -22,6 +23,10 @@ export interface CustomerPickerProps {
22
23
  className?: string;
23
24
  /** testID of the search field, for e2e tests. Default `customer-picker-search`. */
24
25
  testID?: string;
26
+ /** Draws v2's initials avatar on each result row (the selected customer's card above stays without one). Default `false`. */
27
+ showAvatar?: boolean;
28
+ /** Draws a Guest row above the results, as v2's `withGuest`; pressing it calls `onSelect(null)`. Default `false`. */
29
+ withGuest?: boolean;
25
30
  }
26
31
 
27
32
  /** `@tallyui/core/server`'s `payloadBoundErrors` bound on `customer.email`, in UTF-16 code units. */
@@ -29,7 +34,23 @@ const EMAIL_MAX = 254;
29
34
  /** A simple shape, not RFC 5322: one `@`, a non-empty local part, a domain with text either side of a dot, no whitespace or NUL. */
30
35
  const EMAIL_SHAPE = /^[^\s@\u0000]+@[^\s@\u0000]+\.[^\s@\u0000]+$/u;
31
36
 
32
- export function CustomerPicker({ search, create, selected, onSelect, onError, online, debounceMs = 250, className, testID = 'customer-picker-search' }: CustomerPickerProps) {
37
+ /** The cashier's text for an email the store's shape check would refuse, else undefined (CustomerPicker's and CustomerEditor's). */
38
+ export function customerEmailError(email: string): string | undefined {
39
+ return email.length > EMAIL_MAX || !EMAIL_SHAPE.test(email) ? `Enter a valid email address (up to ${EMAIL_MAX} characters)` : undefined;
40
+ }
41
+
42
+ /** The cashier's text for a customer search or create error (CustomerPicker's and CustomerDropdown's). */
43
+ export function customerErrorText(error: unknown): string {
44
+ if (error instanceof CustomerServiceError) {
45
+ return error.code === 'network' ? "Couldn't reach the store. Try again."
46
+ : error.code === 'server' ? "The store couldn't do that. Try again." : error.message;
47
+ }
48
+ return error instanceof ConnectorUnauthorizedError && error.code === 'unauthorized' ? 'Sign in again to continue.'
49
+ : error instanceof ConnectorUnauthorizedError && error.code === 'forbidden' ? "Your account isn't allowed to do this on this store. Ask the store owner."
50
+ : 'Something went wrong. Try again.';
51
+ }
52
+
53
+ export function CustomerPicker({ search, create, selected, onSelect, onError, online, debounceMs = 250, className, testID = 'customer-picker-search', showAvatar = false, withGuest = false }: CustomerPickerProps) {
33
54
  const [query, setQuery] = useState('');
34
55
  const [customers, setCustomers] = useState<Customer[]>([]);
35
56
  const [error, setError] = useState<string | null>(null);
@@ -40,17 +61,12 @@ export function CustomerPicker({ search, create, selected, onSelect, onError, on
40
61
  const searchRef = useRef(search);
41
62
  searchRef.current = search;
42
63
  const [noResults, setNoResults] = useState(false);
64
+ const mounted = useRef(true);
65
+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
43
66
 
44
67
  function handleError(error: unknown) {
45
- if (error instanceof CustomerServiceError) {
46
- setError(error.code === 'network' ? "Couldn't reach the store. Try again."
47
- : error.code === 'server' ? "The store couldn't do that. Try again." : error.message);
48
- } else {
49
- setError(error instanceof ConnectorUnauthorizedError && error.code === 'unauthorized' ? 'Sign in again to continue.'
50
- : error instanceof ConnectorUnauthorizedError && error.code === 'forbidden' ? "Your account isn't allowed to do this on this store. Ask the store owner."
51
- : 'Something went wrong. Try again.');
52
- onError?.(error);
53
- }
68
+ setError(customerErrorText(error));
69
+ if (!(error instanceof CustomerServiceError)) onError?.(error);
54
70
  }
55
71
 
56
72
  useEffect(() => {
@@ -73,7 +89,8 @@ export function CustomerPicker({ search, create, selected, onSelect, onError, on
73
89
  const email = values.email.trim();
74
90
  if (!online || !create || creating || !email) return;
75
91
  // The till sends this email in order.create, whose shape check refuses one over 254 characters: refuse it here instead.
76
- if (email.length > EMAIL_MAX || !EMAIL_SHAPE.test(email)) return setError(`Enter a valid email address (up to ${EMAIL_MAX} characters)`);
92
+ const emailError = customerEmailError(email);
93
+ if (emailError) return setError(emailError);
77
94
  setCreating(true);
78
95
  setError(null);
79
96
  try {
@@ -82,13 +99,15 @@ export function CustomerPicker({ search, create, selected, onSelect, onError, on
82
99
  ...(values.lastName.trim() ? { lastName: values.lastName.trim() } : {}),
83
100
  ...(values.phone.trim() ? { phone: values.phone.trim() } : {}),
84
101
  });
102
+ // The host closed the picker while this create was in flight: a late create must not pick a customer.
103
+ if (!mounted.current) return;
85
104
  onSelect(created);
86
105
  setValues({ firstName: '', lastName: '', email: '', phone: '', address: '' });
87
106
  setShowForm(false);
88
107
  } catch (error) {
89
- handleError(error);
108
+ if (mounted.current) handleError(error); else if (!(error instanceof CustomerServiceError)) onError?.(error);
90
109
  } finally {
91
- setCreating(false);
110
+ if (mounted.current) setCreating(false);
92
111
  }
93
112
  }
94
113
 
@@ -104,7 +123,12 @@ export function CustomerPicker({ search, create, selected, onSelect, onError, on
104
123
  {!online && <Text className="text-sm text-muted-foreground">Connect to search or add customers.</Text>}
105
124
  {noResults && <Text className="text-sm text-muted-foreground">No customers found.</Text>}
106
125
  {error && <Text accessibilityRole="alert" className="text-sm text-destructive">{error}</Text>}
107
- <CustomerSelect customers={customers} traits={customerTraits} onSearch={setQuery} showSearch={false}
126
+ {withGuest && <Pressable role="option" aria-selected={selected === null} testID="customer-picker-option-guest" accessibilityLabel="Guest"
127
+ onPress={() => { onSelect(null); setQuery(''); }} className="min-h-11 flex-row items-center gap-2 rounded-md px-2">
128
+ <GuestGlyph />
129
+ <Text className="text-foreground">Guest</Text>
130
+ </Pressable>}
131
+ <CustomerSelect customers={customers} traits={customerTraits} onSearch={setQuery} showSearch={false} showAvatar={showAvatar}
108
132
  onSelect={(customer) => { onSelect(customer); setQuery(''); }} />
109
133
  {create && <Pressable accessibilityRole="button" disabled={!online || creating} onPress={() => setShowForm(true)}
110
134
  className={cn('items-center rounded-lg border border-border px-4 py-3', (!online || creating) && 'opacity-50')}>
@@ -0,0 +1,83 @@
1
+ // Port of WCPOS v2 (monorepo main) screens/main/customers/index.tsx and row.tsx: the Customers screen's search and list; MIT, WCPOS.
2
+ import type * as React from 'react';
3
+ import { ScrollView, View, type NativeScrollEvent, type NativeSyntheticEvent } from 'react-native';
4
+ import type { Customer } from '@tallyui/core';
5
+ import { cn } from '@tallyui/theme';
6
+ import { useT } from '../i18n';
7
+ import { Avatar, avatarInitials } from '../ui/avatar';
8
+ import { Button } from '../ui/button';
9
+ import { ChevronRightIcon } from '../ui/icon/chevron-right-icon';
10
+ import { Input } from '../ui/input';
11
+ import { ListRow } from '../ui/list-row';
12
+ import { Loader } from '../ui/loader';
13
+ import { Text } from '../ui/text';
14
+
15
+ export interface CustomersListProps {
16
+ /** The rows, in the order the app's search returned them. */
17
+ customers: Customer[];
18
+ /** The search field's text. */
19
+ query: string;
20
+ /** Every edit of the search field, and `''` from Clear search. */
21
+ onQueryChange: (query: string) => void;
22
+ /** Absent: rows are not pressable and show no chevron (v2 without canEditCustomers). */
23
+ onOpen?: (customer: Customer) => void;
24
+ /** Called when the list scrolls within a tenth of its visible height of the end, as CustomerDropdown does. */
25
+ onEndReached?: () => void;
26
+ /** A search or page is in flight: a loading row under the rows. */
27
+ loading?: boolean;
28
+ /** A sentence the app wants shown above the rows (a failed search). */
29
+ error?: string;
30
+ /** Before the search field, e.g. an Add button the app gates. */
31
+ actions?: React.ReactNode;
32
+ className?: string;
33
+ /** Default `customers-list`; rows are `${testID}-row-${id}`. */
34
+ testID?: string;
35
+ }
36
+
37
+ /** v2's Customers screen list: a search field, then one row per customer, drawn from props. The app owns the search,
38
+ * paging, the route and the editor. */
39
+ export function CustomersList({ customers, query, onQueryChange, onOpen, onEndReached, loading = false, error, actions, className, testID = 'customers-list' }: CustomersListProps) {
40
+ const t = useT();
41
+ // v2's onEndReachedThreshold={0.1}, CustomerDropdown's own test (customer-dropdown.tsx:113-116).
42
+ const onScroll = ({ nativeEvent: { contentOffset, contentSize, layoutMeasurement } }: NativeSyntheticEvent<NativeScrollEvent>) => {
43
+ if (contentSize.height - (contentOffset.y + layoutMeasurement.height) <= 0.1 * layoutMeasurement.height) onEndReached?.();
44
+ };
45
+ const empty = !customers.length && !loading;
46
+ const blank = query.trim() === '';
47
+
48
+ return <View className={cn('flex-1', className)} testID={testID}>
49
+ <View className="flex-row items-center gap-2 p-2">
50
+ {actions}
51
+ <Input className="flex-1"><Input.Field accessibilityLabel={t('common.search_customers')} placeholder={t('common.search_customers')}
52
+ testID={`${testID}-search`} value={query} onChangeText={onQueryChange} /></Input>
53
+ </View>
54
+ {error ? <Text role="alert" testID={`${testID}-error`} className="px-3 py-2 text-sm text-destructive">{error}</Text> : null}
55
+ <ScrollView testID={`${testID}-scroll`} onScroll={onScroll} scrollEventThrottle={16}>
56
+ {customers.map((customer) => {
57
+ const location = [customer.billing?.city, customer.billing?.country].filter(Boolean).join(', ');
58
+ return <ListRow key={customer.id} testID={`${testID}-row-${customer.id}`}
59
+ onPress={onOpen ? () => onOpen(customer) : undefined}
60
+ accessibilityLabel={onOpen ? `${t('customers.open_customer')}: ${customer.name}` : undefined}
61
+ leading={<Avatar tone="primary" fallback={avatarInitials(customer.name)} aria-hidden />}
62
+ trailing={<>
63
+ <Text numberOfLines={1} className="max-w-1/3 text-sm text-muted-foreground">{location}</Text>
64
+ {onOpen ? <View className="text-muted-foreground"><ChevronRightIcon size={16} /></View> : null}
65
+ </>}>
66
+ <Text numberOfLines={1}>{customer.name}</Text>
67
+ {customer.email ? <Text numberOfLines={1} className="text-sm text-muted-foreground">{customer.email}</Text> : null}
68
+ </ListRow>;
69
+ })}
70
+ {loading ? <View testID={`${testID}-loading`} className="items-center py-4"><Loader /></View> : null}
71
+ {empty && blank ? <View testID={`${testID}-empty`} className="items-center gap-1 p-6">
72
+ <Text role="heading" className="font-medium">{t('customers.no_customers_yet')}</Text>
73
+ <Text className="text-center text-sm text-muted-foreground">{t('customers.no_customers_yet_description')}</Text>
74
+ </View> : null}
75
+ {empty && !blank ? <View testID={`${testID}-no-results`} className="items-center gap-2 p-6">
76
+ <Text role="heading" className="font-medium">{t('customers.nothing_matches_search')}</Text>
77
+ <Button variant="outline" size="sm" testID={`${testID}-clear-search`} onPress={() => onQueryChange('')}>
78
+ <Text>{t('customers.clear_search')}</Text>
79
+ </Button>
80
+ </View> : null}
81
+ </ScrollView>
82
+ </View>;
83
+ }
@@ -1,5 +1,10 @@
1
1
  export { CustomerCard, type CustomerCardProps } from './customer-card';
2
2
  export { CustomerSelect, type CustomerSelectProps } from './customer-select';
3
3
  export { CustomerForm, type CustomerFormProps, type CustomerFormValues } from './customer-form';
4
+ export { CustomerEditor, type CustomerEditorProps } from './customer-editor';
4
5
  export { CustomerOrderHistory, type CustomerOrderHistoryProps } from './customer-order-history';
5
6
  export { CustomerPicker, type CustomerPickerProps } from './customer-picker';
7
+ export { CustomerDropdown, type CustomerDropdownProps } from './customer-dropdown';
8
+ export { CustomersList, type CustomersListProps } from './customers-list';
9
+ export { AddressFields, ShippingAddressFields, type AddressFieldsProps, type ShippingAddressFieldsProps } from './address-fields';
10
+ export { AddressEditor, type AddressEditorProps, type AddressEditorValue } from './address-editor';