@tallyui/components 3.18.0 → 3.20.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 (60) hide show
  1. package/dist/index.d.ts +473 -37
  2. package/dist/index.js +3656 -1905
  3. package/package.json +9 -9
  4. package/src/cart/cart-columns.tsx +42 -4
  5. package/src/cart/cart-foot.tsx +2 -2
  6. package/src/cart/cart-line.tsx +42 -18
  7. package/src/cart/cart-note-input.tsx +10 -2
  8. package/src/cart/cart-panel.tsx +4 -1
  9. package/src/cart/cart-total.tsx +8 -5
  10. package/src/cart/index.ts +1 -1
  11. package/src/customer/customer-select.tsx +21 -3
  12. package/src/index.ts +27 -0
  13. package/src/input/search-input.tsx +1 -1
  14. package/src/order/index.ts +1 -0
  15. package/src/order/order-filter-bar.tsx +247 -0
  16. package/src/product/camera-scan-button.tsx +28 -0
  17. package/src/product/camera-scanner-panel.tsx +156 -0
  18. package/src/product/index.ts +5 -0
  19. package/src/product/product-table.tsx +14 -4
  20. package/src/product/scanner-viewfinder.tsx +76 -0
  21. package/src/product/variation-picker.tsx +128 -0
  22. package/src/register/register-bar.tsx +2 -6
  23. package/src/register/register-panel.tsx +47 -24
  24. package/src/register/register-side-sheet.tsx +175 -0
  25. package/src/reports/date-range-menu.tsx +109 -0
  26. package/src/reports/filters-bar.tsx +11 -21
  27. package/src/reports/hero.tsx +8 -4
  28. package/src/reports/index.ts +1 -0
  29. package/src/sale/cart.tsx +49 -10
  30. package/src/sale/catalogue.tsx +98 -21
  31. package/src/sale/charge-form.tsx +12 -6
  32. package/src/sale/customer-display-pairing.tsx +111 -0
  33. package/src/sale/index.ts +1 -0
  34. package/src/sale/line-popover.tsx +17 -1
  35. package/src/sale/order-reference.ts +1 -1
  36. package/src/sale/orders-list.tsx +1 -1
  37. package/src/settings/customer-display-settings.tsx +163 -0
  38. package/src/settings/index.ts +2 -0
  39. package/src/settings/tax-calculation-settings.tsx +97 -0
  40. package/src/shell/nav-drawer.tsx +1 -1
  41. package/src/tax/index.ts +1 -0
  42. package/src/tax/tax-based-on.tsx +196 -0
  43. package/src/ui/alert-dialog/index.tsx +1 -1
  44. package/src/ui/avatar/index.tsx +22 -4
  45. package/src/ui/button/index.tsx +1 -1
  46. package/src/ui/calendar/index.tsx +119 -0
  47. package/src/ui/calendar/month-grid.ts +40 -0
  48. package/src/ui/combobox/index.tsx +1 -1
  49. package/src/ui/dialog/index.tsx +21 -9
  50. package/src/ui/icon/chevron-down-icon.tsx +4 -0
  51. package/src/ui/icon/grip-icon.tsx +10 -0
  52. package/src/ui/icon/scan-icon.tsx +13 -0
  53. package/src/ui/icon/shopping-cart-icon.tsx +10 -0
  54. package/src/ui/icon-button/index.tsx +1 -1
  55. package/src/ui/index.ts +11 -1
  56. package/src/ui/input/index.tsx +1 -1
  57. package/src/ui/select/index.tsx +22 -4
  58. package/src/ui/slider/index.tsx +2 -2
  59. package/src/ui/switch/index.tsx +19 -8
  60. package/src/ui/textarea/index.tsx +1 -1
@@ -7,7 +7,7 @@
7
7
  import type { JSX } from 'react';
8
8
  import { Pressable, Text, View } from 'react-native';
9
9
  import { formatMoney } from '@tallyui/core';
10
- import type { SalesFigures } from '@tallyui/pos';
10
+ import { daysOf, type SalesFigures } from '@tallyui/pos';
11
11
  import { cn } from '@tallyui/theme';
12
12
  import { Card } from '../ui/card';
13
13
  import { dayLabel, type SalesFilters } from './filters-bar';
@@ -33,9 +33,13 @@ function Difference({ testID, text, diff, suffix }: { testID: string; text?: str
33
33
  );
34
34
  }
35
35
 
36
+ /** A custom range compares as pos `comparisonRange` does by day count: a day, a week (up to 7) or a month. */
37
+ const customDays = (filters: SalesFilters) => (filters.preset === 'custom' ? daysOf(filters.range).length : 0);
38
+
36
39
  function compareLabel(filters: SalesFilters): string {
37
- if (filters.preset === 'thisWeek' || filters.preset === 'lastWeek') return 'vs the week before';
38
- if (filters.preset === 'thisMonth' || filters.preset === 'lastMonth') return 'vs the month before';
40
+ const days = customDays(filters);
41
+ if (filters.preset === 'thisWeek' || filters.preset === 'lastWeek' || (days > 1 && days <= 7)) return 'vs the week before';
42
+ if (filters.preset === 'thisMonth' || filters.preset === 'lastMonth' || days > 7) return 'vs the month before';
39
43
  if (filters.compare === 'previous') return 'vs yesterday';
40
44
  const weekday = new Intl.DateTimeFormat('en-GB', { weekday: 'long', timeZone: 'UTC' }).format(new Date(`${filters.range.from}T00:00:00Z`));
41
45
  return `vs last ${weekday}`;
@@ -56,7 +60,7 @@ export function SalesHero({ figures, filters, onFiltersChange, currency }: Sales
56
60
  const compareSeries = figures.comparison?.series ?? [];
57
61
  const max = Math.max(0, ...series.map((point) => point.grossMinor), ...compareSeries.map((point) => point.grossMinor));
58
62
  const height = (gross: number) => `${max > 0 ? (Math.max(0, gross) / max) * 100 : 0}%` as const;
59
- const oneDay = filters.preset === 'today' || filters.preset === 'yesterday';
63
+ const oneDay = filters.preset === 'today' || filters.preset === 'yesterday' || customDays(filters) === 1;
60
64
 
61
65
  return (
62
66
  <Card testID="sales-hero" className="gap-4 p-4">
@@ -2,3 +2,4 @@ export { SalesRoom, type SalesRoomProps } from './sales-room';
2
2
  export { SalesHero, type SalesHeroProps } from './hero';
3
3
  export { SalesCards, type SalesCardsProps, type SalesCardId } from './cards';
4
4
  export { SalesFiltersBar, type SalesFiltersBarProps, type SalesFilters, type SalesOption } from './filters-bar';
5
+ export { DateRangeMenu, type DateRangeMenuProps } from './date-range-menu';
package/src/sale/cart.tsx CHANGED
@@ -5,13 +5,17 @@ import { buildReceiptData } from '@tallyui/pos';
5
5
  import type { useSale } from '@tallyui/pos';
6
6
  import { CartColumnHeads, CartFoot, CartLine, CartLineActions, CartPanel, CartTotal, type CartFootAction } from '../cart';
7
7
  import { cartShowsPrice } from '../cart/cart-columns';
8
+ import type { CartColumnSettings } from '../cart/cart-columns';
8
9
  import { DiscountChips, DiscountForm } from './discount-form';
9
10
  import { PriceForm } from './price-form';
10
11
  import { ChargeForm } from './charge-form';
11
12
  import { LinePopover } from './line-popover';
13
+ import { ShoppingCartIcon } from '../ui';
12
14
 
13
15
  /** `taxLabel` names each tax row; VAT isn't universal, so a platform passes its own (medusapos passes `VAT ${rate}%`). */
14
- export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10000}%`, canEditPrice = false, onPriceChange, quickDiscounts, taxClasses, afterSubtotal, couponDiscountMinor, orderActions = true, checkout, lineEditor = 'inline' }:
16
+ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10000}%`, canEditPrice = false, onPriceChange, quickDiscounts, taxClasses, afterSubtotal, showTotal = true, couponDiscountMinor, orderActions = true, checkout, lineEditor = 'inline',
17
+ columns,
18
+ emptyIcon = <ShoppingCartIcon size={48} />, emptyText = 'Tap a product to start a sale' }:
15
19
  { sale: ReturnType<typeof useSale>; taxLabel?: (ratePpm: number) => string;
16
20
  taxClasses?: ReadonlyArray<{ id: string; label: string }>;
17
21
  /** Shows a Price action on each line. Pass the till's own permission; the control isn't shown without it. */
@@ -22,6 +26,8 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
22
26
  quickDiscounts?: readonly number[];
23
27
  /** Rows under the totals' Subtotal, e.g. the platform's coupon chips (passed to CartTotal). */
24
28
  afterSubtotal?: ReactNode;
29
+ /** Draws the totals' Total row. Pass `false` for v2's cart, where the total is on the Checkout button (`checkout`). Default `true`. */
30
+ showTotal?: boolean;
25
31
  /** The coupon amount the app itemises in `afterSubtotal` (e.g. Σ `order.display.coupons`), in integer minor units of
26
32
  * the order's currency, in the display mode. When given, the Discount row shows the other discounts only (the
27
33
  * totals' discount minus this) and is hidden when they come to 0. Absent: the Discount row is the whole discount. */
@@ -33,10 +39,22 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
33
39
  * ⋮ menu lists `actions`. Absent: the Cash and Card terminal row. */
34
40
  checkout?: { onCheckout: () => void; actions?: readonly CartFootAction[] };
35
41
  /** `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. */
42
+ * cells/price.tsx), the price one with the quick-discount keys and the struck regular price. Popover mode draws no
43
+ * button row under the line: Discount, Price (narrow cart) and Remove are in the quantity popover, Discount in the
44
+ * price popover. Default `inline`: the − / + buttons and Price form. */
37
45
  lineEditor?: 'inline' | 'popover';
46
+ /** v2's Cart Settings › Columns: which columns show, a Split link under a quantity above 1 (`quantity.split`) and the
47
+ * SKU under the name (`name.sku`). The defaults are today's cart: Qty, Item, Price (folding as before) and Total. */
48
+ columns?: CartColumnSettings;
49
+ /** The empty cart's icon, centred above `emptyText` and hidden from screen readers. Default: v2's cart icon in the
50
+ * muted colour. Pass `null` for no icon. */
51
+ emptyIcon?: ReactNode;
52
+ /** The empty cart's line. Default: v2's "Tap a product to start a sale". */
53
+ emptyText?: string;
38
54
  }) {
39
55
  const { order } = sale;
56
+ // v2's empty cart: an icon and a line, no heads and no foot. A fee or shipping row alone keeps the cart.
57
+ const empty = !order.lineItems.length && !order.fees?.length && !order.shipping?.length;
40
58
  const money = (amount: number) => ({ amount, currency: order.currency });
41
59
  // order.display's figures (TallyUI ADR-063), with its tax split by rate; never app arithmetic (medusapos ADR 0008).
42
60
  const { totals } = buildReceiptData(order, { storeName: '' });
@@ -46,6 +64,12 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
46
64
  const display = (lineId: string) => order.display.lines.find((line) => line.lineId === lineId)!;
47
65
  const orderAmounts = order.discounts.length === 1
48
66
  ? [{ discountId: order.discounts[0].id, amountMinor: order.display.orderDiscountMinor }] : [];
67
+ // A line's Split refusal, shown under that line until its next split or another line's split attempt.
68
+ const [splitError, setSplitError] = useState<{ lineId: string; message: string } | null>(null);
69
+ const split = (lineId: string) => {
70
+ const refused = sale.splitLine(lineId);
71
+ setSplitError(refused === null ? null : { lineId, message: refused });
72
+ };
49
73
  // One open form: a line's discount or price, the order's discount (lineId null), or a charge.
50
74
  const [form, setForm] = useState<{ type: 'discount'; lineId: string | null } | { type: 'price'; lineId: string } | { type: 'charge' } | null>(null);
51
75
  const chargesOffered = (sale.capabilities?.orderCreate ?? 0) >= 5;
@@ -72,12 +96,20 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
72
96
  <CartLine name={line.name} attributes={line.attributes} quantity={line.quantity} unitPrice={money(line.unitPriceMinor)}
73
97
  regularUnitPrice={line.regularUnitPriceMinor === undefined ? undefined : money(line.regularUnitPriceMinor)}
74
98
  lineTotal={money(display(line.id).amountMinor)} showPrice={showPrice}
99
+ columns={columns} sku={line.sku} imageUrl={line.imageUrl} onSplit={() => split(line.id)}
75
100
  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}
101
+ value={line.quantity} onApply={(quantity) => { sale.setQuantity(line.id, quantity); return null; }} actions={[
102
+ ...(!pricePopover ? [{ id: 'discount', label: 'Discount', onPress: () => setForm({ type: 'discount', lineId: line.id }) }] : []),
103
+ ...(canEditPrice && !pricePopover ? [{ id: 'price', label: 'Price', onPress: () => setForm({ type: 'price', lineId: line.id }) }] : []),
104
+ { id: 'remove', label: 'Remove', destructive: true, onPress: () => sale.remove(line.id) },
105
+ ]} /> : undefined}
77
106
  priceSlot={pricePopover ? <LinePopover kind="price" lineName={line.name} currency={order.currency} value={line.unitPriceMinor}
107
+ regularValue={line.regularUnitPriceMinor} actions={[{ id: 'discount', label: 'Discount', onPress: () => setForm({ type: 'discount', lineId: line.id }) }]}
78
108
  quickDiscounts={quickDiscounts} textClassName="text-right text-muted-foreground" onApply={(amount) => applyPrice(line, amount)} /> : undefined} />
109
+ {splitError?.lineId === line.id ? <Text accessibilityRole="alert" testID="cart-line-split-error"
110
+ className="px-3 text-sm text-destructive">{splitError.message}</Text> : null}
79
111
  <DiscountChips discounts={line.discounts} amounts={display(line.id).discounts} currency={order.currency} onRemove={sale.removeDiscount} />
80
- <CartLineActions actions={[
112
+ {lineEditor === 'inline' ? <CartLineActions actions={[
81
113
  { id: 'discount', label: 'Discount', color: 'text-primary', onPress: () => setForm({ type: 'discount', lineId: line.id }) },
82
114
  ...(canEditPrice && !pricePopover ? [{ id: 'price', label: 'Price', color: 'text-primary', onPress: () => setForm({ type: 'price', lineId: line.id }) }] : []),
83
115
  ]}>
@@ -89,16 +121,23 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
89
121
  <Pressable accessibilityRole="button" accessibilityLabel={`Remove ${line.name}`}
90
122
  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
123
  </View>
92
- </CartLineActions>
124
+ </CartLineActions> : null}
93
125
  {discountForm(line.id, `Discount on ${line.name}`)}
94
126
  {canEditPrice && !pricePopover && form?.type === 'price' && form.lineId === line.id ? <PriceForm key={line.id} lineName={line.name}
95
127
  currency={order.currency} currentMinor={line.unitPriceMinor} quickDiscounts={quickDiscounts} onClose={() => setForm(null)}
96
128
  onApply={(amount, reason) => applyPrice(line, amount, reason)} /> : null}
97
129
  </>;
98
130
  return <View dataSet={{ print: 'hide' }} className="flex-1 min-h-0" onLayout={(event) => setCartWidth(event.nativeEvent.layout.width)}>
99
- <CartColumnHeads showPrice={showPrice} />
131
+ {empty ? null : <CartColumnHeads showPrice={showPrice} columns={columns} />}
100
132
  <CartPanel items={order.lineItems} renderItem={renderItem}
101
- emptyState={<Text testID="cart-empty" className="px-3 py-2 text-muted-foreground">Scan or tap a product to start a sale.</Text>}
133
+ footerClassName="px-2 py-2"
134
+ emptyState={empty ? <View testID="cart-empty" className="flex-1 items-center justify-center gap-3 px-3 py-6">
135
+ {emptyIcon === null ? null : <View aria-hidden accessibilityElementsHidden importantForAccessibility="no-hide-descendants"
136
+ className="text-muted-foreground">{emptyIcon}</View>}
137
+ <Text testID="cart-empty-text" className="text-center text-muted-foreground">{emptyText}</Text>
138
+ {/* The footer is gone, so a resume or coupon message on an empty cart shows here. */}
139
+ {sale.error ? <Text accessibilityRole="alert" className="text-destructive">{sale.error}</Text> : null}
140
+ </View> : undefined}
102
141
  afterItems={<>
103
142
  {(['fees', 'shipping'] as const).map((kind) => order[kind]?.map((charge, index) =>
104
143
  <View key={charge.id} testID={`cart-${kind === 'fees' ? 'fee' : 'shipping'}-${index}`} className="flex-row items-center gap-3 px-3 py-2">
@@ -128,11 +167,11 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
128
167
  className="self-start rounded-md border border-border bg-card px-4 py-2 min-h-11 justify-center">
129
168
  <Text className="text-foreground">Add charge</Text></Pressable> : null}
130
169
  </View> : null}</>}
131
- footer={<View testID="cart-footer" className="gap-3 pb-4">
170
+ footer={empty ? undefined : <View testID="cart-footer" className="gap-2">
132
171
  {/* Exclusive: subtotal − discount + tax = total. Inclusive: subtotal − discount = total, the tax "incl.", not added. */}
133
- <CartTotal subtotal={money(totals.subtotalMinor)} total={money(totals.totalMinor)}
172
+ <CartTotal className="px-0 py-0" subtotal={money(totals.subtotalMinor)} total={money(totals.totalMinor)}
134
173
  discount={money(couponDiscountMinor === undefined ? totals.discountMinor : Math.max(0, totals.discountMinor - couponDiscountMinor))}
135
- taxLines={taxRows} taxInclusive={totals.taxInclusive} afterSubtotal={afterSubtotal} />
174
+ taxLines={taxRows} taxInclusive={totals.taxInclusive} afterSubtotal={afterSubtotal} showTotal={showTotal} />
136
175
  {sale.error ? <Text accessibilityRole="alert" className="text-destructive">{sale.error}</Text> : null}
137
176
  {checkout ? <CartFoot total={money(totals.totalMinor)} onCheckout={checkout.onCheckout} actions={checkout.actions}
138
177
  disabled={!order.lineItems.length} /> : <View className="flex-row gap-3">
@@ -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). */}