@tallyui/components 3.18.0 → 3.19.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 (52) hide show
  1. package/dist/index.d.ts +460 -34
  2. package/dist/index.js +3632 -1898
  3. package/package.json +9 -9
  4. package/src/cart/cart-columns.tsx +42 -4
  5. package/src/cart/cart-line.tsx +42 -18
  6. package/src/cart/cart-note-input.tsx +10 -2
  7. package/src/cart/index.ts +1 -1
  8. package/src/customer/customer-select.tsx +21 -3
  9. package/src/index.ts +27 -0
  10. package/src/order/index.ts +1 -0
  11. package/src/order/order-filter-bar.tsx +247 -0
  12. package/src/product/camera-scan-button.tsx +28 -0
  13. package/src/product/camera-scanner-panel.tsx +156 -0
  14. package/src/product/index.ts +5 -0
  15. package/src/product/scanner-viewfinder.tsx +76 -0
  16. package/src/product/variation-picker.tsx +128 -0
  17. package/src/register/register-bar.tsx +2 -6
  18. package/src/register/register-panel.tsx +47 -24
  19. package/src/register/register-side-sheet.tsx +175 -0
  20. package/src/reports/date-range-menu.tsx +109 -0
  21. package/src/reports/filters-bar.tsx +11 -21
  22. package/src/reports/hero.tsx +8 -4
  23. package/src/reports/index.ts +1 -0
  24. package/src/sale/cart.tsx +44 -8
  25. package/src/sale/catalogue.tsx +98 -21
  26. package/src/sale/charge-form.tsx +12 -6
  27. package/src/sale/customer-display-pairing.tsx +111 -0
  28. package/src/sale/index.ts +1 -0
  29. package/src/sale/line-popover.tsx +17 -1
  30. package/src/sale/order-reference.ts +1 -1
  31. package/src/sale/orders-list.tsx +1 -1
  32. package/src/settings/customer-display-settings.tsx +163 -0
  33. package/src/settings/index.ts +2 -0
  34. package/src/settings/tax-calculation-settings.tsx +97 -0
  35. package/src/tax/index.ts +1 -0
  36. package/src/tax/tax-based-on.tsx +196 -0
  37. package/src/ui/avatar/index.tsx +22 -4
  38. package/src/ui/button/index.tsx +1 -1
  39. package/src/ui/calendar/index.tsx +119 -0
  40. package/src/ui/calendar/month-grid.ts +40 -0
  41. package/src/ui/combobox/index.tsx +1 -1
  42. package/src/ui/dialog/index.tsx +20 -8
  43. package/src/ui/icon/chevron-down-icon.tsx +4 -0
  44. package/src/ui/icon/grip-icon.tsx +10 -0
  45. package/src/ui/icon/scan-icon.tsx +13 -0
  46. package/src/ui/icon/shopping-cart-icon.tsx +10 -0
  47. package/src/ui/icon-button/index.tsx +1 -1
  48. package/src/ui/index.ts +11 -1
  49. package/src/ui/input/index.tsx +1 -1
  50. package/src/ui/select/index.tsx +22 -4
  51. package/src/ui/switch/index.tsx +18 -7
  52. package/src/ui/textarea/index.tsx +1 -1
@@ -1,13 +1,17 @@
1
1
  import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
2
- import { Pressable, Text, View } from 'react-native';
3
- import { useStockOverlaid, useStockOverlayAsOf, type ProductTraits, type ProductCategory } from '@tallyui/core';
2
+ import { Pressable, StyleSheet, Text, View } from 'react-native';
3
+ import { useStockOverlaid, useStockOverlayAsOf, type ProductTraits, type ProductCategory, type VariantSummary } from '@tallyui/core';
4
4
  import { catalogueEntries, findEntryByCode, searchProducts, variantPriceLabel, sortProducts, productSortValue,
5
5
  catalogueViewReducer, normalizeCatalogueViewState, resolveGridColumns, DEFAULT_CATALOGUE_VIEW_STATE,
6
6
  listCategories, inCategory, cartQuantities,
7
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 { VariationPicker } from '../product/variation-picker';
10
11
  import { InCartBadge } from '../product/in-cart-badge';
12
+ import { Popover } from '@tallyui/primitives';
13
+ import { CameraScanButton } from '../product/camera-scan-button';
14
+ import { CameraScannerPanel, type CameraScannerPanelProps } from '../product/camera-scanner-panel';
11
15
  import { ProductFilterBar, DEFAULT_PRODUCT_FILTERS, type ProductFilterChip, type ProductFilters } from './product-filter-bar';
12
16
  import { SearchInput } from '../input';
13
17
  import { VStack } from '../ui';
@@ -38,7 +42,7 @@ function laterOf(a: Date | null | undefined, b: Date | null | undefined): Date |
38
42
 
39
43
  export function Catalogue<Doc>({ products, traits, currency, onSelect, statusText, statusAccessory, lastSyncedAt, loading, pullError, lastStockCheckAt, hour12, minCodeLength,
40
44
  viewState, defaultViewState, loadViewState, saveViewState, onViewStateError, onStateChange, showViewToggle = false, items, onQueryChange, showCategoryNav = false, categories, pickAnyOptions = false,
41
- cartLines, showFilterBar = false, filterChips = ['inStock'], filters: filtersProp, onFiltersChange }: {
45
+ cartLines, showFilterBar = false, filterChips = ['inStock'], filters: filtersProp, onFiltersChange, variationsStyle = 'list', cameraScan = false, cameraScanner }: {
42
46
  products: Doc[];
43
47
  traits: ProductTraits<Doc>;
44
48
  currency: string;
@@ -98,6 +102,16 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
98
102
  filters?: ProductFilters;
99
103
  /** The cashier's next filters (requested filters when controlled). */
100
104
  onFiltersChange?: (filters: ProductFilters) => void;
105
+ /** v2's Product settings › Variations. 'list' (default) opens the variant list chooser; 'popover' opens a grid tile's
106
+ * VariationPicker in a popover for a product with option groups. The table view keeps the list chooser. */
107
+ variationsStyle?: 'list' | 'popover';
108
+ /** Show v2's camera scan button beside the search box; it opens an inline CameraScannerPanel. Default false.
109
+ * The button shows only when cameraScanner is passed too. */
110
+ cameraScan?: boolean;
111
+ /** Passed to the CameraScannerPanel. The app owns useCameraScan (inside its ScanHubProvider) and passes its wiring
112
+ * here, { onDetected: camera.offer, onOpen: camera.reset, scanCount: camera.scanCount }, plus height, permission,
113
+ * viewfinder, decoder and readiness; its useBarcodeScanner then handles camera scans like device scans. */
114
+ cameraScanner?: Omit<CameraScannerPanelProps, 'onClose'>;
101
115
  }) {
102
116
  const [initial] = useState<{
103
117
  state: CatalogueViewState; loaded?: CatalogueViewState; pending?: Promise<unknown>; failed?: boolean; error?: unknown;
@@ -163,6 +177,7 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
163
177
  const validOverlayAsOf = parsedOverlayAsOf && !isNaN(parsedOverlayAsOf.getTime()) ? parsedOverlayAsOf : undefined;
164
178
  const stockAsOf = laterOf(laterOf(lastStockCheckAt, validOverlayAsOf), lastSyncedAt);
165
179
  const [query, setQuery] = useState('');
180
+ const [scannerOpen, setScannerOpen] = useState(false);
166
181
  // The chooser is live (medusapos ADR 0007): it holds only the chosen product's id and derives its choices
167
182
  // from the current entries below, so an open chooser shows each reconcile pass as it lands.
168
183
  const [chooserId, setChooserId] = useState<string | null>(null);
@@ -220,22 +235,63 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
220
235
  else { closePicker(); setChooserId(traits.getId(product)); }
221
236
  }
222
237
 
238
+ // The variations popover (#719): the one open popover's product id, and each product's current entries in order.
239
+ const [popoverId, setPopoverId] = useState<string | null>(null);
240
+ const entriesById = useMemo(() => {
241
+ const byId = new Map<string, CatalogueEntry<Doc>[]>();
242
+ if (variationsStyle !== 'popover') return byId;
243
+ for (const entry of entries) {
244
+ const id = traits.getId(entry.product);
245
+ const list = byId.get(id);
246
+ if (list) list.push(entry); else byId.set(id, [entry]);
247
+ }
248
+ return byId;
249
+ }, [entries, traits, variationsStyle]);
250
+ // A product that leaves the catalogue closes its popover.
251
+ useEffect(() => { if (popoverId !== null && !entriesById.has(popoverId)) setPopoverId(null); }, [popoverId, entriesById]);
252
+ // The groups the popover asks for; none means the list chooser. Without pickAnyOptions a group no variant sets is
253
+ // left out: a variant leaving it unset fits any value.
254
+ function popoverGroupsOf(product: Doc) {
255
+ const list = entriesById.get(traits.getId(product)) ?? [];
256
+ if (list.length < 2 || list.every(({ variant }) => variant.options === undefined)) return [];
257
+ return (traits.getVariantOptions?.(product) ?? []).filter(({ id, name, values }) => values.length > 0
258
+ && (list.some(({ variant }) => variant.options !== undefined && Object.prototype.hasOwnProperty.call(variant.options, name))
259
+ || (pickAnyOptions && id === undefined)));
260
+ }
261
+ function addFromPopover(productId: string, variant: VariantSummary, anyPicks: Record<string, string>) {
262
+ const entry = entriesById.get(productId)?.find((candidate) => candidate.variant.id === variant.id);
263
+ if (!entry) return;
264
+ // Only the local "Any" groups the picker step would ask for (#495) travel as picks.
265
+ const picked = Object.fromEntries(anyGroupsOf(entry).filter(({ name }) => anyPicks[name] !== undefined)
266
+ .map(({ name }) => [name, anyPicks[name]]));
267
+ onSelect(pickAnyOptions && Object.keys(picked).length > 0 ? { ...entry, picks: picked } : entry);
268
+ setPopoverId(null);
269
+ }
270
+
223
271
  const emptyState = <Text className="mt-10 text-center text-sm text-muted-foreground">
224
272
  {query.trim() ? `No products match "${query.trim()}".` : activeCategory ? `No products in ${activeCategory.name}.`
225
273
  : stockFiltered && items === undefined && shown.length > 0 ? 'No products in stock.'
226
274
  : isLoading ? 'Loading products…' : 'No products yet.'}
227
275
  </Text>;
228
276
 
277
+ const searchInput = <SearchInput value={query} onChangeText={(text) => { setQuery(text); onQueryChange?.(text); }} placeholder="Search or scan barcode / SKU" autoFocus
278
+ onSubmitEditing={() => {
279
+ if (minCodeLength && query.trim().length < minCodeLength) return;
280
+ const entry = findEntryByCode(entries, query);
281
+ if (entry) { select(entry); setQuery(''); }
282
+ }} />;
283
+
229
284
  return (
230
285
  <View className="flex-1" onLayout={(event) => setWidth(event.nativeEvent.layout.width)}>
231
286
  <View className="gap-2 border-b border-border bg-card px-4 pb-3 pt-3">
232
- <SearchInput value={query} onChangeText={(text) => { setQuery(text); onQueryChange?.(text); }} placeholder="Search or scan barcode / SKU" autoFocus
233
- onSubmitEditing={() => {
234
- if (minCodeLength && query.trim().length < minCodeLength) return;
235
- const entry = findEntryByCode(entries, query);
236
- if (entry) { select(entry); setQuery(''); }
237
- }} />
287
+ {cameraScan && cameraScanner ? (
288
+ <View className="flex-row items-center gap-2">
289
+ <View className="flex-1">{searchInput}</View>
290
+ <CameraScanButton open={scannerOpen} onPress={() => setScannerOpen((open) => !open)} />
291
+ </View>
292
+ ) : searchInput}
238
293
  {showFilterBar ? <ProductFilterBar value={filters} onChange={changeFilters} chips={filterChips} /> : null}
294
+ {cameraScan && cameraScanner && scannerOpen ?<CameraScannerPanel {...cameraScanner} onClose={() => setScannerOpen(false)} /> : null}
239
295
  {(statusText || statusAccessory || showViewToggle) ? (
240
296
  <View testID="catalogue-status-row" className="flex-row items-center gap-2">
241
297
  {statusText ? <Text className="flex-1 text-xs text-muted-foreground" numberOfLines={statusAccessory ? 1 : undefined}>
@@ -281,21 +337,42 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
281
337
  <ProductTable items={results} sort={state.sort} onSortChange={(sort) => changeState({ type: 'setSort', sort })}
282
338
  sortItems={false} onSelect={selectProduct} emptyState={emptyState} />
283
339
  ) : <ProductGrid items={results} numColumns={columns}
284
- renderItem={(product: Doc) => (
340
+ renderItem={(product: Doc) => {
341
+ const id = traits.getId(product);
342
+ const groups = variationsStyle === 'popover' ? popoverGroupsOf(product) : [];
285
343
  // TallyUI's ProductCard has no children slot, so the tile is composed directly here
286
344
  // (same structure/classes as ProductCard) to add the stock badge as a fourth child,
287
345
  // inside the card and centred with the rest, rather than adding a slot to ProductCard (out of scope for TV6b).
288
- <Pressable accessibilityRole="button" testID={`product-tile-${traits.getName(product)}`} onPress={() => selectProduct(product)}>
289
- <VStack space="sm" className="items-center rounded-lg border border-border bg-card p-3">
290
- <ProductImage doc={product} size={80} className="rounded-md" />
291
- <ProductTitle doc={product} className="text-sm" numberOfLines={2} />
292
- <ProductPrice doc={product} />
293
- <ProductStockBadge doc={product} showAsOf={false} className="self-center" />
294
- </VStack>
295
- <InCartBadge count={quantities.get(traits.getId(product)) ?? 0} className="absolute right-2 top-2"
296
- testID={`in-cart-${traits.getId(product)}`} />
297
- </Pressable>
298
- )}
346
+ const tile = (
347
+ <Pressable accessibilityRole="button" testID={`product-tile-${traits.getName(product)}`}
348
+ onPress={groups.length > 0 ? () => { closePicker(); setChooserId(null); } : () => selectProduct(product)}>
349
+ <VStack space="sm" className="items-center rounded-lg border border-border bg-card p-3">
350
+ <ProductImage doc={product} size={80} className="rounded-md" />
351
+ <ProductTitle doc={product} className="text-sm" numberOfLines={2} />
352
+ <ProductPrice doc={product} />
353
+ <ProductStockBadge doc={product} showAsOf={false} className="self-center" />
354
+ </VStack>
355
+ <InCartBadge count={quantities.get(id) ?? 0} className="absolute right-2 top-2" testID={`in-cart-${id}`} />
356
+ </Pressable>
357
+ );
358
+ if (groups.length === 0) return tile;
359
+ // ui's PopoverContent class, built on the primitive as LinePopover is so an Overlay in the same portal closes
360
+ // it on a press outside (v2's outsidePress). Content takes only side 'top' | 'bottom', so v2's side="right" is left out.
361
+ return (
362
+ <Popover.Root open={popoverId === id} onOpenChange={(open) => setPopoverId((current) => open ? id : current === id ? null : current)}>
363
+ <Popover.Trigger asChild>{tile}</Popover.Trigger>
364
+ <Popover.Portal>
365
+ <Popover.Overlay testID="variation-popover-overlay" style={StyleSheet.absoluteFill} />
366
+ <Popover.Content align="center" sideOffset={4}
367
+ className="z-50 w-auto max-w-80 rounded-md border border-border bg-popover p-2 shadow-md outline-none">
368
+ <VariationPicker key={id} title={traits.getName(product)} groups={groups} currency={currency}
369
+ variants={(entriesById.get(id) ?? []).map(({ variant }) => variant)}
370
+ onAdd={(variant, anyPicks) => addFromPopover(id, variant, anyPicks)} />
371
+ </Popover.Content>
372
+ </Popover.Portal>
373
+ </Popover.Root>
374
+ );
375
+ }}
299
376
  emptyState={emptyState} />}
300
377
  </View>
301
378
  );
@@ -7,6 +7,9 @@ export interface ChargeFormProps {
7
7
  lineTax?: { none: boolean; classes: boolean };
8
8
  taxClasses?: ReadonlyArray<{ id: string; label: string }>;
9
9
  shippingTaxFromStore?: boolean;
10
+ /** Given, the form is that kind only and the kind row is not shown (v2's separate Add Fee / Add Shipping /
11
+ * Add Miscellaneous Product entries); absent, the form opens on Fee with the row. */
12
+ kind?: 'fee' | 'shipping' | 'custom';
10
13
  onApply: (charge: { kind: 'fee' | 'shipping' | 'custom'; name: string; amountMinor: number;
11
14
  taxStatus?: 'none'; taxClass?: string }) => string | null;
12
15
  onClose: () => void;
@@ -15,8 +18,11 @@ export interface ChargeFormProps {
15
18
  const button = 'rounded-md border border-border px-3 py-2 min-h-11 items-center justify-center';
16
19
 
17
20
  /** `onApply` returns a refusal to show inline, or null once applied. */
18
- export function ChargeForm({ currency, lineTax, taxClasses, shippingTaxFromStore, onApply, onClose }: ChargeFormProps) {
19
- const [kind, setKind] = useState<'fee' | 'shipping' | 'custom'>('fee');
21
+ export function ChargeForm({ currency, lineTax, taxClasses, shippingTaxFromStore, kind: fixedKind, onApply, onClose }: ChargeFormProps) {
22
+ const [stateKind, setKind] = useState<'fee' | 'shipping' | 'custom'>('fee');
23
+ const kind = fixedKind ?? stateKind;
24
+ const title = fixedKind === undefined ? 'Add charge'
25
+ : fixedKind === 'fee' ? 'Add fee' : fixedKind === 'shipping' ? 'Add shipping' : 'Add custom item';
20
26
  const [name, setName] = useState('');
21
27
  const [text, setText] = useState('');
22
28
  const [noTax, setNoTax] = useState(false);
@@ -33,16 +39,16 @@ export function ChargeForm({ currency, lineTax, taxClasses, shippingTaxFromStore
33
39
  setError(refused);
34
40
  if (refused === null) onClose();
35
41
  }
36
- return <View testID="charge-form" role="group" accessibilityLabel="Add charge" className="gap-2 px-3 py-2">
37
- <Text className="font-semibold text-foreground">Add charge</Text>
38
- <View className="flex-row gap-2">
42
+ return <View testID="charge-form" role="group" accessibilityLabel={title} className="gap-2 px-3 py-2">
43
+ <Text className="font-semibold text-foreground">{title}</Text>
44
+ {fixedKind === undefined ? <View className="flex-row gap-2">
39
45
  {(['fee', 'shipping', 'custom'] as const).map((option) => <Pressable key={option} accessibilityRole="button"
40
46
  accessibilityState={{ selected: kind === option }} aria-selected={kind === option} onPress={() => setKind(option)}
41
47
  className={`${button} ${kind === option ? 'bg-primary' : 'bg-card'}`}>
42
48
  <Text className={kind === option ? 'text-primary-foreground' : 'text-foreground'}>
43
49
  {option === 'fee' ? 'Fee' : option === 'shipping' ? 'Shipping' : 'Custom item'}</Text>
44
50
  </Pressable>)}
45
- </View>
51
+ </View> : null}
46
52
  <TextInput accessibilityLabel="Name" placeholder="Name" value={name} onChangeText={setName}
47
53
  className="min-w-0 rounded-md border border-border bg-background px-3 py-2 text-foreground" />
48
54
  <TextInput accessibilityLabel="Amount" value={text} onChangeText={setText} onSubmitEditing={apply}
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The display device's screen (ADR-085 U5, d4, d8, #705): enter the till's code and a name, show the check code while
3
+ * the cashier confirms, then the sale through `CustomerDisplayScreen`. Props only; the app passes
4
+ * `useDisplayClient(client)` and wires `onClaim` and `onCancel` to the same `DisplayClient`.
5
+ */
6
+ import { useState, type JSX } from 'react';
7
+ import { View } from 'react-native';
8
+ import type { DisplayClientError, DisplayClientPhase, DisplayState } from '@tallyui/pos';
9
+ import { cn } from '@tallyui/theme';
10
+ import { Button } from '../ui/button';
11
+ import { Input } from '../ui/input';
12
+ import { Loader } from '../ui/loader';
13
+ import { Text } from '../ui/text';
14
+ import { CustomerDisplayScreen } from './customer-display-screen';
15
+
16
+ export interface CustomerDisplayPairingProps {
17
+ /** `useDisplayClient(client)`. */
18
+ client: { phase: DisplayClientPhase; state: DisplayState };
19
+ onClaim: (code: string, displayName: string) => void;
20
+ onCancel: () => void;
21
+ /** The name field's starting value, e.g. the last name used; default "Customer display". */
22
+ defaultName?: string;
23
+ className?: string;
24
+ }
25
+
26
+ const DISPLAY_ERRORS: Record<DisplayClientError, string> = {
27
+ claim_refused: "That code didn't work. Check it on the till and try again.",
28
+ collect_refused: 'The till declined, or the code expired. Enter a new code.',
29
+ forgotten: 'This display was removed from its till. Enter a new code to pair it again.',
30
+ network: "Can't reach the store. Check the connection and try again.",
31
+ server: "The store couldn't finish that. Try again.",
32
+ };
33
+
34
+ /** Enter-code and claiming; it unmounts once the display waits or pairs, so a later enter-code starts with an empty code. */
35
+ function CodeForm({ claiming, error, defaultName, onClaim }: {
36
+ claiming: boolean; error?: DisplayClientError; defaultName: string; onClaim: CustomerDisplayPairingProps['onClaim'];
37
+ }): JSX.Element {
38
+ const [code, setCode] = useState('');
39
+ const [name, setName] = useState(defaultName);
40
+ const ready = code.trim() !== '' && name.trim() !== '';
41
+ return (
42
+ <View className="w-full max-w-md gap-4">
43
+ <Text className="text-2xl font-semibold text-foreground">Pair with a till</Text>
44
+ <View className="gap-1">
45
+ <Text nativeID="display-code-label" className="text-sm font-medium text-foreground">Code</Text>
46
+ <Input disabled={claiming} className="h-14">
47
+ <Input.Field
48
+ testID="display-code" accessibilityLabelledBy="display-code-label" value={code} onChangeText={setCode}
49
+ keyboardType="number-pad" autoFocus className="text-2xl tabular-nums"
50
+ />
51
+ </Input>
52
+ </View>
53
+ <View className="gap-1">
54
+ <Text nativeID="display-name-label" className="text-sm font-medium text-foreground">Display name</Text>
55
+ <Input disabled={claiming} className="h-11">
56
+ <Input.Field testID="display-name" accessibilityLabelledBy="display-name-label" value={name} onChangeText={setName} />
57
+ </Input>
58
+ </View>
59
+ {error && <Text testID="pairing-error" className="text-sm text-destructive">{DISPLAY_ERRORS[error]}</Text>}
60
+ <Button
61
+ testID="display-pair" size="lg" disabled={claiming || !ready} onPress={() => onClaim(code.trim(), name.trim())}
62
+ >
63
+ {claiming ? <Loader size="sm" /> : null}
64
+ <Text>Pair</Text>
65
+ </Button>
66
+ <Text className="text-sm text-muted-foreground">
67
+ Ask the cashier for a code: Settings › Customer display › Pair a display on the till.
68
+ </Text>
69
+ </View>
70
+ );
71
+ }
72
+
73
+ export function CustomerDisplayPairing({
74
+ client, onClaim, onCancel, defaultName = 'Customer display', className,
75
+ }: CustomerDisplayPairingProps): JSX.Element {
76
+ const { phase, state } = client;
77
+ if (phase.phase === 'paired') {
78
+ return (
79
+ <View testID="display-paired" className={cn('relative flex-1', className)}>
80
+ <CustomerDisplayScreen state={state} />
81
+ {/* Inside the screen's own padding at the top corner, clear of the cart and the totals. */}
82
+ {!phase.online && (
83
+ <View testID="display-offline" style={{ pointerEvents: 'none' }} className="absolute right-2 top-2 rounded-md bg-muted px-2 py-1">
84
+ <Text className="text-xs text-muted-foreground">Offline</Text>
85
+ </View>
86
+ )}
87
+ </View>
88
+ );
89
+ }
90
+ return (
91
+ <View className={cn('flex-1 items-center justify-center bg-background p-6', className)}>
92
+ {phase.phase === 'starting' ? <Loader testID="display-starting" size="lg" /> : null}
93
+ {phase.phase === 'enter-code' || phase.phase === 'claiming' ? (
94
+ <CodeForm
95
+ claiming={phase.phase === 'claiming'} error={phase.phase === 'enter-code' ? phase.error : undefined}
96
+ defaultName={defaultName} onClaim={onClaim}
97
+ />
98
+ ) : null}
99
+ {phase.phase === 'waiting' ? (
100
+ <View className="w-full max-w-md items-center gap-4">
101
+ <Text className="text-lg font-medium text-foreground">Check code</Text>
102
+ <Text testID="display-check-code" className="text-6xl font-bold tabular-nums text-foreground">{phase.checkCode}</Text>
103
+ <Text className="text-center text-sm text-muted-foreground">
104
+ Make sure the till shows the same code, then the cashier confirms.
105
+ </Text>
106
+ <Button testID="display-cancel" variant="outline" size="lg" onPress={onCancel}><Text>Cancel</Text></Button>
107
+ </View>
108
+ ) : null}
109
+ </View>
110
+ );
111
+ }
package/src/sale/index.ts CHANGED
@@ -16,3 +16,4 @@ export { ParkedSales, type ParkedSalesProps } from './parked-sales';
16
16
  export { OpenSaleTabs, type OpenSaleTabsProps } from './open-sale-tabs';
17
17
  export { ProductFilterBar, DEFAULT_PRODUCT_FILTERS, PRODUCT_FILTER_CHIPS, type ProductFilterBarProps, type ProductFilterChip, type ProductFilters } from './product-filter-bar';
18
18
  export { CustomerDisplayScreen } from './customer-display-screen';
19
+ export { CustomerDisplayPairing, type CustomerDisplayPairingProps } from './customer-display-pairing';
@@ -38,13 +38,19 @@ export interface LinePopoverProps {
38
38
  quickDiscounts?: readonly number[];
39
39
  /** The trigger's text classes (the cell's alignment and tone). */
40
40
  textClassName?: string;
41
+ /** Price only: the regular unit price in minor units; shown struck through above the value when it is above `value`. */
42
+ regularValue?: number;
43
+ /** Buttons drawn in the open panel above Apply / Cancel, e.g. the cart line's Discount and Remove. Pressing one closes
44
+ * the popover, then calls its `onPress`. `destructive` draws it in the destructive colour. */
45
+ actions?: ReadonlyArray<{ id: string; label: string; onPress: () => void; destructive?: boolean }>;
41
46
  }
42
47
 
43
48
  /**
44
49
  * A cart line's quantity or price that opens v2's keypad: the cashier types (or picks a quick discount),
45
50
  * Apply writes through `onApply`, and Cancel, Escape or a press outside close without writing.
46
51
  */
47
- export function LinePopover({ kind, lineName, currency, value, onApply, quickDiscounts, textClassName }: LinePopoverProps) {
52
+ export function LinePopover({ kind, lineName, currency, value, onApply, quickDiscounts, textClassName, regularValue,
53
+ actions }: LinePopoverProps) {
48
54
  const [open, setOpen] = useState(false);
49
55
  // v2's entry: the typed buffer (`.` as its separator), or the lit quick key, a percentage off `value`.
50
56
  const [entry, setEntry] = useState<{ buffer: string; percent?: number }>({ buffer: '' });
@@ -54,6 +60,7 @@ export function LinePopover({ kind, lineName, currency, value, onApply, quickDis
54
60
  const places = price ? minorUnitDigits(currency) : 0;
55
61
  const format = (amount: number) => price ? formatMoney({ amount, currency }) ?? '—' : String(amount);
56
62
  const keys = price ? quickKeys(quickDiscounts) : [];
63
+ const regular = price && regularValue !== undefined && regularValue > value ? format(regularValue) : null;
57
64
  const { buffer, percent } = entry;
58
65
  // A lone `0.` is not typing, so a stray tap never zeroes the line (v2's draftPrice); a typed 0 quantity writes nothing.
59
66
  const typed = buffer === '0.' ? '' : buffer.replace(/\.$/, '');
@@ -102,6 +109,8 @@ export function LinePopover({ kind, lineName, currency, value, onApply, quickDis
102
109
  <Panel onKey={onKey}>
103
110
  <Text nativeID={titleId} className="font-semibold text-popover-foreground">{title}</Text>
104
111
  <View className="items-end">
112
+ {regular ? <Text accessibilityLabel={`Regular price ${regular}`} style={{ textDecorationLine: 'line-through' }}
113
+ className="text-sm tabular-nums text-muted-foreground line-through">{regular}</Text> : null}
105
114
  {percent !== undefined ? <Text className="text-sm text-muted-foreground">{`${format(value)} −${percent}%`}</Text> : null}
106
115
  <Text testID={`${kind}-popover-value`} numberOfLines={1} className="text-2xl font-semibold tabular-nums text-popover-foreground">
107
116
  {buffer || format(typeof draft === 'number' ? draft : value)}</Text>
@@ -109,6 +118,13 @@ export function LinePopover({ kind, lineName, currency, value, onApply, quickDis
109
118
  {keys.length ? <QuickDiscountKeys keys={keys} percent={percent} onPress={quick} /> : null}
110
119
  <Keypad testID={`${kind}-popover-keypad`} rows={rows} onPress={press} />
111
120
  {error ? <Text accessibilityRole="alert" className="text-destructive">{error}</Text> : null}
121
+ {actions?.length ? <View className="flex-row flex-wrap gap-2">
122
+ {actions.map((action) => <Pressable key={action.id} testID={`${kind}-popover-action-${action.id}`}
123
+ accessibilityRole="button" accessibilityLabel={`${action.label} ${lineName}`}
124
+ onPress={() => { setOpen(false); action.onPress(); }} className={`${button} bg-card`}>
125
+ <Text className={action.destructive ? 'text-destructive' : 'text-foreground'}>{action.label}</Text>
126
+ </Pressable>)}
127
+ </View> : null}
112
128
  <View className="flex-row gap-2">
113
129
  <Pressable testID={`${kind}-popover-apply`} accessibilityRole="button" onPress={apply} className={`${button} bg-primary`}>
114
130
  <Text className="font-semibold text-primary-foreground">Apply</Text></Pressable>
@@ -6,4 +6,4 @@ export function orderReference(order: { id: string; serverRefs?: { displayId?: s
6
6
  }
7
7
 
8
8
  /** The receipt and Orders say this under a note that went below order.create 7 (ADR-083 condition 2). */
9
- export const NOTE_NOT_SENT = "The note couldn't be sent to the store.";
9
+ export const NOTE_NOT_SENT = "The customer note couldn't be sent to the store.";
@@ -113,7 +113,7 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
113
113
  {order.payments.map((payment) => <Text key={payment.id} className="text-muted-foreground">
114
114
  {`${payment.method === 'cash' ? 'Cash' : 'Card terminal'} ${formatMoney({ amount: payment.amountMinor, currency: order.currency })}${payment.reference ? ` · ${payment.reference}` : ''}`}
115
115
  </Text>)}
116
- {order.note ? <Text testID={`order-note-${order.id}`} className="text-foreground">{`Note: ${order.note}`}</Text> : null}
116
+ {order.note ? <Text testID={`order-note-${order.id}`} className="text-foreground">{`Customer note: ${order.note}`}</Text> : null}
117
117
  </View> : null}
118
118
  {stuckEntry ? <Text className="text-destructive">
119
119
  {/* The same words for any reason, with no reason code; the hour as the status line has it (numeric, #245). */}
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Settings › Customer display (ADR-085 U5, d4, d5, d11, d13): the till's paired displays, pairing one with a code and
3
+ * its "wants to pair" check (#705), and forgetting one. Props only; the app passes `useTillPairing(pairing)` and
4
+ * `useTillDisplays(service)` and wires the callbacks to the same `TillPairing`.
5
+ */
6
+ import { useRef, type JSX } from 'react';
7
+ import { View } from 'react-native';
8
+ import type { PairingError, PairingPhase, TillDisplayEntry, TillDisplayStatus } from '@tallyui/pos';
9
+ import { cn } from '@tallyui/theme';
10
+ import {
11
+ AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter,
12
+ AlertDialogTitle, AlertDialogTrigger,
13
+ } from '../ui/alert-dialog';
14
+ import { Button } from '../ui/button';
15
+ import { Loader } from '../ui/loader';
16
+ import { Text } from '../ui/text';
17
+ import { SettingsGroup } from './settings-group';
18
+
19
+ export interface CustomerDisplaySettingsProps {
20
+ /** `useTillPairing(pairing)`. */
21
+ pairing: { phase: PairingPhase; forgetError: PairingError | null };
22
+ /** `useTillDisplays(service)`. */
23
+ displays: { status: TillDisplayStatus; displays: readonly TillDisplayEntry[] };
24
+ onStartPairing: () => void;
25
+ onConfirm: (claimId: string) => void;
26
+ onDecline: (claimId: string) => void;
27
+ onCancelPairing: () => void;
28
+ onForget: (displayId: string) => void;
29
+ /** Formats the code's expiry; default: the device's locale, hours and minutes. */
30
+ formatTime?: (iso: string) => string;
31
+ className?: string;
32
+ }
33
+
34
+ const PAIRING_ERRORS: Record<PairingError, string> = {
35
+ forbidden: 'Sign in as a cashier who can pair customer displays.',
36
+ limit: 'Too many pairing attempts. Try again in a few minutes.',
37
+ expired: 'The code expired. Start again for a new code.',
38
+ not_found: 'That display is no longer waiting. Ask it to enter the code again.',
39
+ network: "Can't reach the store. Check the connection and try again.",
40
+ server: "The store couldn't finish that. Try again.",
41
+ };
42
+
43
+ const STATUS_LINES: Partial<Record<TillDisplayStatus, string>> = {
44
+ offline: "Can't reach the store. Open displays keep showing the sale; new connections wait.",
45
+ paused: 'Sign in as a cashier who can pair customer displays.',
46
+ };
47
+
48
+ type CodePhase = Extract<PairingPhase, { phase: 'code' }>;
49
+
50
+ const defaultFormatTime = (iso: string) => new Date(iso).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
51
+
52
+ function stateOf({ display, link }: TillDisplayEntry): string {
53
+ if (link === 'open') return 'Connected';
54
+ if (link === 'connecting') return 'Connecting…';
55
+ return display.connected ? 'Waiting for the display' : 'Offline';
56
+ }
57
+
58
+ function DisplayRow({ entry, onForget }: { entry: TillDisplayEntry; onForget: (displayId: string) => void }): JSX.Element {
59
+ const { displayId, name } = entry.display;
60
+ return (
61
+ <View testID={`display-${displayId}`} className="flex-row items-center gap-3 px-4 py-3">
62
+ <View className="flex-1 gap-0.5">
63
+ <Text className="text-sm font-medium text-foreground">{name}</Text>
64
+ <Text testID={`display-state-${displayId}`} className="text-xs text-muted-foreground">{stateOf(entry)}</Text>
65
+ </View>
66
+ <AlertDialog>
67
+ <AlertDialogTrigger asChild>
68
+ <Button testID={`forget-${displayId}`} variant="outline" className="min-h-11"><Text>Forget</Text></Button>
69
+ </AlertDialogTrigger>
70
+ <AlertDialogContent>
71
+ <AlertDialogTitle>{`Forget ${name}?`}</AlertDialogTitle>
72
+ <AlertDialogDescription>It will need a new code to pair again.</AlertDialogDescription>
73
+ <AlertDialogFooter>
74
+ <AlertDialogCancel asChild>
75
+ <Button testID={`forget-cancel-${displayId}`} variant="outline" className="min-h-11"><Text>Cancel</Text></Button>
76
+ </AlertDialogCancel>
77
+ <AlertDialogAction asChild>
78
+ <Button testID={`forget-confirm-${displayId}`} variant="destructive" className="min-h-11" onPress={() => onForget(displayId)}>
79
+ <Text>Forget</Text>
80
+ </Button>
81
+ </AlertDialogAction>
82
+ </AlertDialogFooter>
83
+ </AlertDialogContent>
84
+ </AlertDialog>
85
+ </View>
86
+ );
87
+ }
88
+
89
+ export function CustomerDisplaySettings({
90
+ pairing, displays, onStartPairing, onConfirm, onDecline, onCancelPairing, onForget, formatTime = defaultFormatTime, className,
91
+ }: CustomerDisplaySettingsProps): JSX.Element {
92
+ const { phase, forgetError } = pairing;
93
+ // `confirming` carries only the claim id, so the code and its claims stay on screen from the last `code` phase.
94
+ const lastCode = useRef<CodePhase | null>(null);
95
+ if (phase.phase === 'code') lastCode.current = phase;
96
+ else if (phase.phase !== 'confirming') lastCode.current = null;
97
+ const shown = phase.phase === 'code' ? phase : phase.phase === 'confirming' ? lastCode.current : null;
98
+ const busy = phase.phase === 'confirming';
99
+ const statusLine = STATUS_LINES[displays.status];
100
+
101
+ return (
102
+ <View className={cn('gap-6', className)}>
103
+ {statusLine && <Text testID="customer-display-status" className="px-4 text-sm text-muted-foreground">{statusLine}</Text>}
104
+
105
+ <SettingsGroup title="Paired displays">
106
+ {displays.displays.length === 0
107
+ ? <Text className="px-4 py-3 text-sm text-muted-foreground">No displays paired yet.</Text>
108
+ : displays.displays.map((entry) => <DisplayRow key={entry.display.displayId} entry={entry} onForget={onForget} />)}
109
+ {forgetError && (
110
+ <Text testID="forget-error" className="px-4 py-3 text-sm text-destructive">{PAIRING_ERRORS[forgetError]}</Text>
111
+ )}
112
+ </SettingsGroup>
113
+
114
+ <SettingsGroup title="Pair a display">
115
+ {shown ? (
116
+ <View className="gap-4 p-4">
117
+ <View className="items-center gap-1">
118
+ <Text testID="pairing-code" className="text-4xl font-bold tabular-nums text-foreground">{shown.code}</Text>
119
+ <Text className="text-center text-sm text-muted-foreground">
120
+ {`Enter this code on the display. Expires at ${formatTime(shown.expiresAt)}.`}
121
+ </Text>
122
+ </View>
123
+ {shown.claims.length === 0 ? (
124
+ <Text className="text-center text-sm text-muted-foreground">Waiting for a display…</Text>
125
+ ) : (
126
+ <View className="gap-2">
127
+ <Text className="text-sm text-muted-foreground">Confirm only if the display shows the same check code.</Text>
128
+ {shown.claims.map(({ claimId, displayName, checkCode }) => (
129
+ <View key={claimId} testID={`claim-${claimId}`} className="gap-3 rounded-md border border-border p-3 sm:flex-row sm:items-center">
130
+ <View className="flex-1 gap-1">
131
+ <Text className="text-sm text-foreground">{`${displayName} wants to pair. Check code`}</Text>
132
+ <Text testID={`check-${claimId}`} className="text-3xl font-bold tabular-nums text-foreground">{checkCode}</Text>
133
+ </View>
134
+ <View className="flex-row gap-2">
135
+ <Button testID={`decline-${claimId}`} variant="outline" className="min-h-11" disabled={busy} onPress={() => onDecline(claimId)}>
136
+ <Text>Decline</Text>
137
+ </Button>
138
+ <Button testID={`confirm-${claimId}`} className="min-h-11" disabled={busy} onPress={() => onConfirm(claimId)}>
139
+ {phase.phase === 'confirming' && phase.claimId === claimId ?<Loader size="sm" /> : null}
140
+ <Text>Confirm</Text>
141
+ </Button>
142
+ </View>
143
+ </View>
144
+ ))}
145
+ </View>
146
+ )}
147
+ <Button testID="pairing-cancel" variant="outline" className="min-h-11" onPress={onCancelPairing}><Text>Cancel</Text></Button>
148
+ </View>
149
+ ) : (
150
+ <View className="gap-3 p-4">
151
+ {phase.phase === 'idle' && phase.error && (
152
+ <Text testID="pairing-error" className="text-sm text-destructive">{PAIRING_ERRORS[phase.error]}</Text>
153
+ )}
154
+ <Button testID="pairing-start" className="min-h-11" disabled={phase.phase !== 'idle'} onPress={onStartPairing}>
155
+ {phase.phase === 'idle' ? null : <Loader size="sm" />}
156
+ <Text>Pair a display</Text>
157
+ </Button>
158
+ </View>
159
+ )}
160
+ </SettingsGroup>
161
+ </View>
162
+ );
163
+ }
@@ -2,3 +2,5 @@ export { SettingsRow, type SettingsRowProps } from './settings-row';
2
2
  export { SettingsGroup, type SettingsGroupProps } from './settings-group';
3
3
  export { ConnectorStatus, type ConnectorStatusProps, type ConnectionStatus } from './connector-status';
4
4
  export { DisplaySettings, type DisplaySettingsProps } from './display-settings';
5
+ export { TaxCalculationSettings, type TaxCalculationSettingsProps } from './tax-calculation-settings';
6
+ export { CustomerDisplaySettings, type CustomerDisplaySettingsProps } from './customer-display-settings';