@tallyui/components 3.13.0 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/index.d.ts +357 -27
  2. package/dist/index.js +2386 -1370
  3. package/package.json +9 -9
  4. package/src/cart/cart-columns.tsx +57 -0
  5. package/src/cart/cart-foot.tsx +82 -0
  6. package/src/cart/cart-line.tsx +37 -17
  7. package/src/cart/index.ts +2 -0
  8. package/src/checkout/cash-tendered.tsx +5 -7
  9. package/src/index.ts +26 -3
  10. package/src/input/index.ts +1 -0
  11. package/src/input/keypad.tsx +38 -0
  12. package/src/lib/error-text.ts +5 -0
  13. package/src/order/refund-form.tsx +2 -1
  14. package/src/product/category-tile.tsx +43 -0
  15. package/src/product/in-cart-badge.tsx +26 -0
  16. package/src/product/index.ts +2 -0
  17. package/src/register/closure-sheet.tsx +2 -1
  18. package/src/register/handover-slip.tsx +46 -0
  19. package/src/register/index.ts +2 -0
  20. package/src/register/movement-sheet.tsx +2 -1
  21. package/src/register/open-register-card.tsx +2 -1
  22. package/src/register/register-bar.tsx +57 -11
  23. package/src/register/register-column.tsx +2 -1
  24. package/src/register/register-count.tsx +30 -11
  25. package/src/register/register-panel.tsx +45 -4
  26. package/src/register/switch-confirm.tsx +102 -0
  27. package/src/sale/cart.tsx +63 -31
  28. package/src/sale/catalogue.tsx +34 -5
  29. package/src/sale/customer-display-screen.tsx +92 -0
  30. package/src/sale/index.ts +5 -2
  31. package/src/sale/line-popover.tsx +145 -0
  32. package/src/sale/parked-sales.tsx +2 -1
  33. package/src/sale/price-form.tsx +37 -4
  34. package/src/sale/product-filter-bar.tsx +58 -0
  35. package/src/sale/tender-pane.tsx +171 -0
  36. package/src/sale/tender.tsx +20 -35
  37. package/src/shell/app-shell.tsx +71 -0
  38. package/src/shell/index.ts +4 -0
  39. package/src/shell/nav-drawer.tsx +130 -0
  40. package/src/shell/nav-item.tsx +70 -0
  41. package/src/shell/nav-rail.tsx +58 -0
  42. package/src/shell/shell-context.ts +18 -0
  43. package/src/ui/icon/menu-icon.tsx +10 -0
  44. package/src/sale/split-tender.tsx +0 -81
@@ -3,10 +3,12 @@ import { Pressable, Text, View } from 'react-native';
3
3
  import { useStockOverlaid, useStockOverlayAsOf, type ProductTraits, type ProductCategory } from '@tallyui/core';
4
4
  import { catalogueEntries, findEntryByCode, searchProducts, variantPriceLabel, sortProducts, productSortValue,
5
5
  catalogueViewReducer, normalizeCatalogueViewState, resolveGridColumns, DEFAULT_CATALOGUE_VIEW_STATE,
6
- listCategories, inCategory,
7
- type CatalogueEntry, type CatalogueViewState, type CatalogueViewAction } from '@tallyui/pos';
6
+ listCategories, inCategory, cartQuantities,
7
+ type CatalogueEntry, type CatalogueViewState, type CatalogueViewAction, type CartQuantityLine } from '@tallyui/pos';
8
8
  import { ProductGrid, ProductImage, ProductPrice, ProductStockBadge, ProductTitle, ProductTable, ViewToggle, CategoryNav } from '../product';
9
9
  import { ProductVariantPicker } from '../product/product-variant-picker';
10
+ import { InCartBadge } from '../product/in-cart-badge';
11
+ import { ProductFilterBar, DEFAULT_PRODUCT_FILTERS, type ProductFilterChip, type ProductFilters } from './product-filter-bar';
10
12
  import { SearchInput } from '../input';
11
13
  import { VStack } from '../ui';
12
14
 
@@ -35,7 +37,8 @@ function laterOf(a: Date | null | undefined, b: Date | null | undefined): Date |
35
37
  }
36
38
 
37
39
  export function Catalogue<Doc>({ products, traits, currency, onSelect, statusText, statusAccessory, lastSyncedAt, loading, pullError, lastStockCheckAt, hour12, minCodeLength,
38
- viewState, defaultViewState, loadViewState, saveViewState, onViewStateError, onStateChange, showViewToggle = false, items, onQueryChange, showCategoryNav = false, categories, pickAnyOptions = false }: {
40
+ viewState, defaultViewState, loadViewState, saveViewState, onViewStateError, onStateChange, showViewToggle = false, items, onQueryChange, showCategoryNav = false, categories, pickAnyOptions = false,
41
+ cartLines, showFilterBar = false, filterChips = ['inStock'], filters: filtersProp, onFiltersChange }: {
39
42
  products: Doc[];
40
43
  traits: ProductTraits<Doc>;
41
44
  currency: string;
@@ -85,6 +88,16 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
85
88
  onQueryChange?: (query: string) => void;
86
89
  /** Ask for a value for each of a variant's local "Any" option groups before onSelect (#495); set it only when the store accepts order.create version 6. */
87
90
  pickAnyOptions?: boolean;
91
+ /** The open sale's lines (e.g. useSale's order.lineItems); each grid tile shows its product's summed quantity. */
92
+ cartLines?: readonly CartQuantityLine[];
93
+ /** Show v2's filter chips under the search box. Default false. */
94
+ showFilterBar?: boolean;
95
+ /** Which chips the bar shows. Default ['inStock'], the one Catalogue applies itself. */
96
+ filterChips?: readonly ProductFilterChip[];
97
+ /** Controlled filters; changes are reported through onFiltersChange. */
98
+ filters?: ProductFilters;
99
+ /** The cashier's next filters (requested filters when controlled). */
100
+ onFiltersChange?: (filters: ProductFilters) => void;
88
101
  }) {
89
102
  const [initial] = useState<{
90
103
  state: CatalogueViewState; loaded?: CatalogueViewState; pending?: Promise<unknown>; failed?: boolean; error?: unknown;
@@ -130,6 +143,14 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
130
143
  }
131
144
  }
132
145
 
146
+ const [internalFilters, setInternalFilters] = useState(DEFAULT_PRODUCT_FILTERS);
147
+ const filters = filtersProp ?? internalFilters;
148
+ function changeFilters(next: ProductFilters) {
149
+ if (filtersProp === undefined) setInternalFilters(next);
150
+ onFiltersChange?.(next);
151
+ }
152
+ const quantities = useMemo(() => cartQuantities(cartLines ?? []), [cartLines]);
153
+
133
154
  const isLoading = loading ?? (lastSyncedAt === null && pullError == null);
134
155
  // Idempotent (the adapter's overlay returns just the fields the stock map sets), so an app that already
135
156
  // merges the overlay itself keeps working, and can drop its own merge.
@@ -148,12 +169,16 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
148
169
  const [width, setWidth] = useState(0);
149
170
  const columns = resolveGridColumns(state.gridColumns, width);
150
171
  const entries = useMemo(() => catalogueEntries(shown, traits, { currency }), [shown, traits, currency]);
172
+ // v2's In Stock pill is stock_status 'instock', so it drops backorders too; a stock the backend did not report stays.
173
+ const stockFiltered = showFilterBar && filters.inStock;
151
174
  const results = useMemo(() => {
152
175
  if (items !== undefined) return suppliedItems;
153
- const filtered = searchProducts(activeCategory
176
+ const matched = searchProducts(activeCategory
154
177
  ? shown.filter((doc) => inCategory(doc, activeCategory.id, traits)) : shown, query, traits);
178
+ const filtered = stockFiltered
179
+ ? matched.filter((doc) => !['out_of_stock', 'backorder'].includes(traits.getStock(doc).status)) : matched;
155
180
  return state.sort ? sortProducts(filtered, state.sort, (doc, field) => productSortValue(doc, field, traits, { currency })) : filtered;
156
- }, [items, suppliedItems, shown, query, traits, state.sort, currency, showCategoryNav, activeCategory]);
181
+ }, [items, suppliedItems, shown, query, traits, state.sort, currency, showCategoryNav, activeCategory, stockFiltered]);
157
182
  const choices = useMemo(() => (chooserId === null ? []
158
183
  : entries.filter((entry) => traits.getId(entry.product) === chooserId)), [entries, chooserId, traits]);
159
184
  // A product that leaves the catalogue (a resync, or no longer sellable) closes its chooser.
@@ -197,6 +222,7 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
197
222
 
198
223
  const emptyState = <Text className="mt-10 text-center text-sm text-muted-foreground">
199
224
  {query.trim() ? `No products match "${query.trim()}".` : activeCategory ? `No products in ${activeCategory.name}.`
225
+ : stockFiltered && items === undefined && shown.length > 0 ? 'No products in stock.'
200
226
  : isLoading ? 'Loading products…' : 'No products yet.'}
201
227
  </Text>;
202
228
 
@@ -209,6 +235,7 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
209
235
  const entry = findEntryByCode(entries, query);
210
236
  if (entry) { select(entry); setQuery(''); }
211
237
  }} />
238
+ {showFilterBar ? <ProductFilterBar value={filters} onChange={changeFilters} chips={filterChips} /> : null}
212
239
  {(statusText || statusAccessory || showViewToggle) ? (
213
240
  <View testID="catalogue-status-row" className="flex-row items-center gap-2">
214
241
  {statusText ? <Text className="flex-1 text-xs text-muted-foreground" numberOfLines={statusAccessory ? 1 : undefined}>
@@ -265,6 +292,8 @@ export function Catalogue<Doc>({ products, traits, currency, onSelect, statusTex
265
292
  <ProductPrice doc={product} />
266
293
  <ProductStockBadge doc={product} showAsOf={false} className="self-center" />
267
294
  </VStack>
295
+ <InCartBadge count={quantities.get(traits.getId(product)) ?? 0} className="absolute right-2 top-2"
296
+ testID={`in-cart-${traits.getId(product)}`} />
268
297
  </Pressable>
269
298
  )}
270
299
  emptyState={emptyState} />}
@@ -0,0 +1,92 @@
1
+ import type { ReactNode } from 'react';
2
+ import { Image, ScrollView, Text, View } from 'react-native';
3
+ import { formatMoney } from '@tallyui/core';
4
+ import type { DisplayPayment, DisplayState, ReceiptData } from '@tallyui/pos';
5
+
6
+ // English copy from WCPOS v2's display (Pro packages/display/src/sample-snapshot.json); config.i18n overrides it.
7
+ const COPY = {
8
+ welcome: 'Welcome', your_items: 'Your items', items_appear_here: 'Your items will appear here', subtotal: 'Subtotal',
9
+ discount: 'Discount', total_tax: 'Tax', included_tax: 'Tax included', total: 'Total', paid_so_far: 'Paid so far',
10
+ present_card: 'Please present your card', approved: 'Approved', declined: 'Declined',
11
+ try_another_card: 'Please try another card or ask staff', paid_in_full: 'Paid in full', change: 'Change',
12
+ thank_you: 'Thank you',
13
+ };
14
+
15
+ const CARD = { started: 'bg-primary', approved: 'bg-success', complete: 'bg-success', declined: 'bg-destructive' };
16
+ const CARD_TEXT = { started: 'text-primary-foreground', approved: 'text-success-foreground',
17
+ complete: 'text-success-foreground', declined: 'text-destructive-foreground' };
18
+
19
+ /**
20
+ * What the customer sees on the second screen, laid out as WCPOS v2's default "Ledger" display
21
+ * (Pro templates/display.html): idle shows the store; cart and payment show the items on the left and a panel on the
22
+ * right with the totals, or the payment card.
23
+ */
24
+ export function CustomerDisplayScreen({ state }: { state: DisplayState }) {
25
+ const { config, view } = state;
26
+ const t = (key: keyof typeof COPY) => config?.i18n[key] ?? COPY[key];
27
+ if (view.screen === 'idle') {
28
+ const logo = config?.store.logo;
29
+ return <View testID="customer-display-idle" className="flex-1 items-center justify-center gap-6 bg-primary p-8">
30
+ {logo ? <Image source={{ uri: logo }} accessibilityLabel={config.store.name} resizeMode="contain" style={{ width: 320, height: 180 }} />
31
+ : <Text className="text-5xl font-bold text-primary-foreground">{config?.store.name ?? ''}</Text>}
32
+ <Text className="text-2xl text-primary-foreground">{t('welcome')}</Text>
33
+ </View>;
34
+ }
35
+ const { receipt } = view.cart;
36
+ const money = (amount: number) => formatMoney({ amount, currency: receipt.currency }, config?.store.locale) ?? '';
37
+ const row = (label: string, amount: string, key?: string) => <View key={key} className="flex-row justify-between gap-4 py-1">
38
+ <Text className="text-lg text-muted-foreground">{label}</Text><Text className="text-lg text-muted-foreground">{amount}</Text>
39
+ </View>;
40
+ const total = <View className="mt-3 flex-row items-baseline justify-between gap-4 border-t-2 border-foreground pt-4">
41
+ <Text className="text-base font-semibold uppercase text-foreground">{t('total')}</Text>
42
+ <Text className="text-4xl font-bold text-foreground">{money(receipt.totals.totalMinor)}</Text>
43
+ </View>;
44
+ return <View testID={`customer-display-${view.screen}`} className="flex-1 flex-col bg-card sm:flex-row">
45
+ <ScrollView className="flex-1" contentContainerClassName="p-8 sm:p-12">
46
+ <Text className="mb-5 text-sm font-semibold uppercase text-muted-foreground">{t('your_items')}</Text>
47
+ {receipt.lineItems.length === 0 ? <Text className="py-8 text-center text-xl text-muted-foreground">{t('items_appear_here')}</Text> : null}
48
+ {receipt.lineItems.map((line, index) => <View key={index} className="flex-row items-baseline gap-4 border-b border-border py-4">
49
+ <Text className="w-14 text-xl text-muted-foreground">{`${line.quantity} ×`}</Text>
50
+ <View className="flex-1">
51
+ <Text className="text-xl font-semibold text-foreground">{line.name}</Text>
52
+ {Object.entries(line.attributes ?? {}).map(([name, value]) => <Text key={name} className="text-base text-muted-foreground">{`${name}: ${value}`}</Text>)}
53
+ </View>
54
+ <Text className="text-xl font-semibold text-foreground">{money(line.displayAmountMinor)}</Text>
55
+ </View>)}
56
+ </ScrollView>
57
+ <View className="justify-end border-t border-border p-8 sm:w-96 sm:border-l sm:border-t-0">
58
+ <Text className="mb-auto text-lg font-bold text-foreground">{config?.store.name ?? receipt.header.storeName}</Text>
59
+ {view.screen === 'cart' ? <View>
60
+ {row(t('subtotal'), money(receipt.totals.subtotalMinor))}
61
+ {receipt.fees.map((charge, index) => row(charge.name, money(charge.amountMinor), `fee-${index}`))}
62
+ {receipt.shipping.map((charge, index) => row(charge.name, money(charge.amountMinor), `shipping-${index}`))}
63
+ {receipt.totals.discountMinor > 0 ? row(t('discount'), `-${money(receipt.totals.discountMinor)}`) : null}
64
+ {receipt.totals.taxMinor > 0 ? row(t(receipt.totals.taxInclusive ? 'included_tax' : 'total_tax'), money(receipt.totals.taxMinor)) : null}
65
+ {total}
66
+ </View> : <PaymentCard receipt={receipt} payment={view.payment} money={money} t={t}>{total}</PaymentCard>}
67
+ </View>
68
+ </View>;
69
+ }
70
+
71
+ function PaymentCard({ receipt, payment, money, t, children }: {
72
+ receipt: ReceiptData; payment: DisplayPayment; money: (amount: number) => string; t: (key: keyof typeof COPY) => string;
73
+ children: ReactNode;
74
+ }) {
75
+ const paid = receipt.payments.reduce((sum, { amountMinor }) => sum + amountMinor, 0);
76
+ const due = Math.max(0, receipt.totals.totalMinor - paid);
77
+ const complete = payment.state === 'complete';
78
+ const title = { started: t('present_card'), approved: t('approved'), declined: t('declined'), complete: t('paid_in_full') }[payment.state];
79
+ const message = complete ? t('thank_you') : payment.message ?? (payment.state === 'declined' ? t('try_another_card') : undefined);
80
+ const text = CARD_TEXT[payment.state];
81
+ return <View className="gap-4">
82
+ {complete ? null : <View>{children}{paid > 0 ? <View className="flex-row justify-between py-1">
83
+ <Text className="text-lg text-success">{t('paid_so_far')}</Text><Text className="text-lg text-success">{money(paid)}</Text>
84
+ </View> : null}</View>}
85
+ <View className={`gap-2 rounded-xl p-6 ${CARD[payment.state]}`}>
86
+ <Text className={`text-sm font-semibold uppercase ${text}`}>{title}</Text>
87
+ <Text className={`text-4xl font-bold ${text}`}>{money(complete ? receipt.totals.totalMinor : payment.leg?.amountMinor ?? due)}</Text>
88
+ {complete && receipt.changeDueMinor > 0 ? <Text className={`text-lg ${text}`}>{`${t('change')} ${money(receipt.changeDueMinor)}`}</Text> : null}
89
+ {message ? <Text className={`text-lg ${text}`}>{message}</Text> : null}
90
+ </View>
91
+ </View>;
92
+ }
package/src/sale/index.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  export { Cart } from './cart';
2
2
  export { CartBar } from './cart-bar';
3
- export { Tender } from './tender';
4
- export { SplitTender } from './split-tender';
3
+ export { Tender, SplitTender } from './tender';
4
+ export { TenderPane, type TenderPaneProps } from './tender-pane';
5
5
  export { DiscountForm, DiscountChips, parseDiscount, discountLabel } from './discount-form';
6
6
  export { PriceForm, parsePrice } from './price-form';
7
+ export { LinePopover, type LinePopoverProps } from './line-popover';
7
8
  export { ChargeForm, type ChargeFormProps } from './charge-form';
8
9
  export { Catalogue, formatStockSyncTime } from './catalogue';
9
10
  export { Receipt } from './receipt';
@@ -13,3 +14,5 @@ export { SyncStatus } from './sync-status';
13
14
  export { OrdersList, type OrderHistoryRow } from './orders-list';
14
15
  export { ParkedSales, type ParkedSalesProps } from './parked-sales';
15
16
  export { OpenSaleTabs, type OpenSaleTabsProps } from './open-sale-tabs';
17
+ export { ProductFilterBar, DEFAULT_PRODUCT_FILTERS, PRODUCT_FILTER_CHIPS, type ProductFilterBarProps, type ProductFilterChip, type ProductFilters } from './product-filter-bar';
18
+ export { CustomerDisplayScreen } from './customer-display-screen';
@@ -0,0 +1,145 @@
1
+ // Port of WCPOS v2 (monorepo main) packages/components/src/quantity-keypad/ and price-keypad/ (index.tsx and
2
+ // reducer.ts), lib/decimal-entry.ts and keypad/index.tsx's decimalRow, as the cart cells open them
3
+ // (packages/core/src/screens/main/pos/cart/cells/quantity-keypad.tsx and cells/price.tsx); MIT, WCPOS.
4
+ import { useEffect, useId, useRef, useState, type ReactNode, type RefObject } from 'react';
5
+ import { Platform, Pressable, StyleSheet, Text, View } from 'react-native';
6
+ import { formatMoney, minorUnitDigits } from '@tallyui/core';
7
+ import { Popover } from '@tallyui/primitives';
8
+ import { cn } from '@tallyui/theme';
9
+ import { DIGIT_ROWS, Keypad, type KeypadKey } from '../input/keypad';
10
+ import { lessPercent, parsePrice, QuickDiscountKeys, quickKeys } from './price-form';
11
+
12
+ /** nav-drawer.tsx's focus targets. */
13
+ const FOCUSABLE = 'button, [href], input, [tabindex]:not([tabindex="-1"])';
14
+ const BACKSPACE: KeypadKey = { name: 'backspace', label: 'Delete last digit', text: '⌫' };
15
+ const button = 'min-h-11 flex-1 items-center justify-center rounded-md border border-border px-3 py-2';
16
+
17
+ /** v2's typeDecimal: `.` once and only with places, a digit past the places refused, a lone 0 replaced. */
18
+ function typeDecimal(buffer: string, key: string, places: number): string {
19
+ if (key === 'backspace') return buffer.slice(0, -1);
20
+ if (key === 'decimal') return places > 0 && !buffer.includes('.') ? `${buffer || '0'}.` : buffer;
21
+ if (!/^[0-9]$/.test(key)) return buffer;
22
+ const point = buffer.indexOf('.');
23
+ if (point >= 0) return buffer.length - point > places ? buffer : buffer + key;
24
+ return buffer === '0' ? key : buffer + key;
25
+ }
26
+
27
+ export interface LinePopoverProps {
28
+ /** `quantity` takes whole numbers only, with no decimal key (decimal quantities need an ADR first, TallyUI#486). */
29
+ kind: 'quantity' | 'price';
30
+ lineName: string;
31
+ /** The order's currency: the price's format and its decimal places. */
32
+ currency: string;
33
+ /** The stored quantity, or the unit price in integer minor units. */
34
+ value: number;
35
+ /** Writes the new value; returns a refusal to show, or null once applied. */
36
+ onApply: (value: number) => string | null;
37
+ /** Price only: v2's quick-discount keys, the first three valid percentages (as PriceForm's). */
38
+ quickDiscounts?: readonly number[];
39
+ /** The trigger's text classes (the cell's alignment and tone). */
40
+ textClassName?: string;
41
+ }
42
+
43
+ /**
44
+ * A cart line's quantity or price that opens v2's keypad: the cashier types (or picks a quick discount),
45
+ * Apply writes through `onApply`, and Cancel, Escape or a press outside close without writing.
46
+ */
47
+ export function LinePopover({ kind, lineName, currency, value, onApply, quickDiscounts, textClassName }: LinePopoverProps) {
48
+ const [open, setOpen] = useState(false);
49
+ // v2's entry: the typed buffer (`.` as its separator), or the lit quick key, a percentage off `value`.
50
+ const [entry, setEntry] = useState<{ buffer: string; percent?: number }>({ buffer: '' });
51
+ const [error, setError] = useState<string | null>(null);
52
+ const titleId = useId();
53
+ const price = kind === 'price';
54
+ const places = price ? minorUnitDigits(currency) : 0;
55
+ const format = (amount: number) => price ? formatMoney({ amount, currency }) ?? '—' : String(amount);
56
+ const keys = price ? quickKeys(quickDiscounts) : [];
57
+ const { buffer, percent } = entry;
58
+ // A lone `0.` is not typing, so a stray tap never zeroes the line (v2's draftPrice); a typed 0 quantity writes nothing.
59
+ const typed = buffer === '0.' ? '' : buffer.replace(/\.$/, '');
60
+ const draft = !price ? (Number.parseInt(typed, 10) > 0 ? Number.parseInt(typed, 10) : undefined)
61
+ : percent !== undefined ? lessPercent(value, percent) : typed ? parsePrice(typed, currency) : undefined;
62
+ const title = `${price ? 'Price' : 'Quantity'} for ${lineName}`;
63
+ const rows = [...DIGIT_ROWS, places
64
+ ? [{ name: 'decimal', label: 'Decimal point', text: '.' }, { name: '0', label: '0' }, BACKSPACE]
65
+ : [{ name: '0', label: '0', span: 2 }, BACKSPACE]];
66
+
67
+ const openChange = (next: boolean) => {
68
+ if (next) { setEntry({ buffer: '' }); setError(null); }
69
+ setOpen(next);
70
+ };
71
+ const press = (name: string) => {
72
+ setEntry((now) => ({ buffer: typeDecimal(now.percent === undefined ? now.buffer : '', name, places) }));
73
+ setError(null);
74
+ };
75
+ const quick = (key: number) => {
76
+ setEntry((now) => (now.percent === key ? { buffer: '' } : { buffer: '', percent: key }));
77
+ setError(null);
78
+ };
79
+ function apply() {
80
+ if (draft === undefined || draft === value) return setOpen(false);
81
+ const refused = typeof draft === 'string' ? draft : onApply(draft);
82
+ setError(refused);
83
+ if (refused === null) setOpen(false);
84
+ }
85
+ const onKey = (key: string) => {
86
+ if (key === 'Escape') setOpen(false);
87
+ else if (/^[0-9]$/.test(key)) press(key);
88
+ else if (key === 'Backspace') press('backspace');
89
+ else if ((key === '.' || key === ',') && places) press('decimal');
90
+ };
91
+
92
+ return <Popover.Root open={open} onOpenChange={openChange}>
93
+ <Popover.Trigger testID={`${kind}-popover-trigger`} accessibilityLabel={`Edit ${kind} of ${lineName}`}
94
+ className="min-h-11 justify-center rounded-md px-1">
95
+ <Text className={cn('text-sm tabular-nums text-foreground', textClassName)}>{format(value)}</Text>
96
+ </Popover.Trigger>
97
+ <Popover.Portal>
98
+ <Popover.Overlay style={StyleSheet.absoluteFill} />
99
+ <Popover.Content testID={`${kind}-popover`} align={price ? 'end' : 'start'} sideOffset={4}
100
+ aria-labelledby={titleId} aria-describedby={undefined}
101
+ className="w-64 rounded-md border border-border bg-popover p-4 shadow-md">
102
+ <Panel onKey={onKey}>
103
+ <Text nativeID={titleId} className="font-semibold text-popover-foreground">{title}</Text>
104
+ <View className="items-end">
105
+ {percent !== undefined ? <Text className="text-sm text-muted-foreground">{`${format(value)} −${percent}%`}</Text> : null}
106
+ <Text testID={`${kind}-popover-value`} numberOfLines={1} className="text-2xl font-semibold tabular-nums text-popover-foreground">
107
+ {buffer || format(typeof draft === 'number' ? draft : value)}</Text>
108
+ </View>
109
+ {keys.length ? <QuickDiscountKeys keys={keys} percent={percent} onPress={quick} /> : null}
110
+ <Keypad testID={`${kind}-popover-keypad`} rows={rows} onPress={press} />
111
+ {error ? <Text accessibilityRole="alert" className="text-destructive">{error}</Text> : null}
112
+ <View className="flex-row gap-2">
113
+ <Pressable testID={`${kind}-popover-apply`} accessibilityRole="button" onPress={apply} className={`${button} bg-primary`}>
114
+ <Text className="font-semibold text-primary-foreground">Apply</Text></Pressable>
115
+ <Pressable testID={`${kind}-popover-cancel`} accessibilityRole="button" onPress={() => setOpen(false)} className={`${button} bg-card`}>
116
+ <Text className="text-foreground">Cancel</Text></Pressable>
117
+ </View>
118
+ </Panel>
119
+ </Popover.Content>
120
+ </Popover.Portal>
121
+ </Popover.Root>;
122
+ }
123
+
124
+ /** The open panel. Web: focus moves into it and back to where it was on close; keys go to `onKey` (nav-drawer's pattern). */
125
+ function Panel({ onKey, children }: { onKey: (key: string) => void; children: ReactNode }) {
126
+ const panel = useRef<View>(null);
127
+ useKeys(panel, onKey);
128
+ return <View ref={panel} className="gap-3">{children}</View>;
129
+ }
130
+
131
+ function useKeys(panel: RefObject<View | null>, onKey: (key: string) => void) {
132
+ const latest = useRef(onKey);
133
+ latest.current = onKey;
134
+ useEffect(() => {
135
+ if (Platform.OS !== 'web' || typeof document === 'undefined') return;
136
+ const previous = document.activeElement as HTMLElement | null;
137
+ (panel.current as unknown as HTMLElement | null)?.querySelector<HTMLElement>(FOCUSABLE)?.focus();
138
+ const onKeyDown = (event: KeyboardEvent) => latest.current(event.key);
139
+ document.addEventListener('keydown', onKeyDown);
140
+ return () => {
141
+ document.removeEventListener('keydown', onKeyDown);
142
+ previous?.focus?.();
143
+ };
144
+ }, [panel]);
145
+ }
@@ -2,6 +2,7 @@ import { useState, type JSX } from 'react';
2
2
  import { ScrollView, useWindowDimensions, View } from 'react-native';
3
3
  import { formatMoney } from '@tallyui/core';
4
4
  import type { ParkedOrderSummary, useSale } from '@tallyui/pos';
5
+ import { errorText } from '../lib/error-text';
5
6
  import { Button } from '../ui/button';
6
7
  import { Dialog, DialogClose, DialogContent, DialogTitle } from '../ui/dialog';
7
8
  import { IconButton } from '../ui/icon-button';
@@ -33,7 +34,7 @@ export function ParkedSales({ sale, parked, onDiscard, onPark, onResume, currenc
33
34
  try {
34
35
  await action();
35
36
  } catch (e) {
36
- setError(String(e));
37
+ setError(errorText(e));
37
38
  }
38
39
  };
39
40
 
@@ -15,26 +15,59 @@ export function parsePrice(text: string, currency: string): number | string {
15
15
  }
16
16
 
17
17
  const button = 'rounded-md border border-border px-3 py-2 min-h-11 items-center justify-center';
18
+ /** v2's price keypad draws three quick keys (`QUICK_KEYS`, WCPOS `components/src/price-keypad/index.tsx`). */
19
+ const QUICK_KEYS = 3;
20
+
21
+ /** `currentMinor` less `percent` (to two places), half up at the minor unit, as v2's `draftPrice` rounds. */
22
+ export const lessPercent = (currentMinor: number, percent: number) =>
23
+ Math.round(currentMinor * (10000 - Math.round(percent * 100)) / 10000);
24
+
25
+ /** The quick keys drawn: the first three valid percentages (0 < n ≤ 100). */
26
+ export const quickKeys = (list: readonly number[] = []) => list.filter((n) => Number.isFinite(n) && n > 0 && n <= 100).slice(0, QUICK_KEYS);
27
+
28
+ /** v2's quick-discount key row; `percent` is the lit key. Shared by PriceForm and LinePopover. */
29
+ export function QuickDiscountKeys({ keys, percent, onPress }: { keys: readonly number[]; percent?: number; onPress: (key: number) => void }) {
30
+ return <View testID="price-quick-discounts" className="flex-row gap-2">
31
+ {keys.map((key) => <Pressable key={key} testID={`price-discount-${key}`} accessibilityRole="button"
32
+ accessibilityLabel={`Discount (${key}%)`} accessibilityState={{ selected: key === percent }}
33
+ aria-selected={key === percent} onPress={() => onPress(key)}
34
+ className={`${button} flex-1 ${key === percent ? 'bg-primary' : 'bg-card'}`}>
35
+ <Text className={key === percent ? 'text-primary-foreground' : 'text-foreground'}>{`−${key}%`}</Text>
36
+ </Pressable>)}
37
+ </View>;
38
+ }
18
39
 
19
40
  /** `onApply` returns a refusal to show inline, or null once applied. */
20
- export function PriceForm({ lineName, currency, currentMinor, onApply, onClose }: {
41
+ export function PriceForm({ lineName, currency, currentMinor, onApply, onClose, quickDiscounts = [] }: {
21
42
  lineName: string; currency: string; currentMinor: number;
22
43
  onApply: (amountMinor: number, reason?: string) => string | null; onClose: () => void;
44
+ /** Percentages off the current price, as v2's price-keypad keys; the first three valid ones (0 < n ≤ 100) are drawn. */
45
+ quickDiscounts?: readonly number[];
23
46
  }): JSX.Element {
24
47
  const [text, setText] = useState('');
25
48
  const [reason, setReason] = useState('');
26
49
  const [error, setError] = useState<string | null>(null);
50
+ // The lit key (v2's reducer): pressing it again puts the current price back; typing starts over.
51
+ const [percent, setPercent] = useState<number | undefined>();
52
+ const keys = quickKeys(quickDiscounts);
27
53
  const title = `Price for ${lineName}`;
54
+ const current = formatMoney({ amount: currentMinor, currency });
55
+ const draft = percent === undefined ? undefined : lessPercent(currentMinor, percent);
28
56
  function apply() {
29
- const parsed = parsePrice(text, currency);
57
+ const parsed = draft ?? parsePrice(text, currency);
30
58
  const refused = typeof parsed === 'string' ? parsed : onApply(parsed, reason.trim() || undefined);
31
59
  setError(refused);
32
60
  if (refused === null) onClose();
33
61
  }
34
62
  return <View testID="price-form" role="group" accessibilityLabel={title} className="gap-2 px-3 py-2">
35
63
  <Text className="font-semibold text-foreground">{title}</Text>
36
- <Text className="text-muted-foreground">{formatMoney({ amount: currentMinor, currency })}</Text>
37
- <TextInput testID="price-input" accessibilityLabel="Price value" value={text} onChangeText={setText}
64
+ {draft === undefined ? <Text className="text-muted-foreground">{current}</Text>
65
+ : <Text testID="price-quick-draft" className="text-muted-foreground">
66
+ {`${current} −${percent}% → ${formatMoney({ amount: draft, currency })}`}</Text>}
67
+ {keys.length ? <QuickDiscountKeys keys={keys} percent={percent}
68
+ onPress={(key) => { setPercent(key === percent ? undefined : key); setText(''); setError(null); }} /> : null}
69
+ <TextInput testID="price-input" accessibilityLabel="Price value" value={text}
70
+ onChangeText={(next) => { setText(next); setPercent(undefined); }}
38
71
  onSubmitEditing={apply} inputMode="decimal" placeholder={currency}
39
72
  className="min-w-0 rounded-md border border-border bg-background px-3 py-2 text-foreground" />
40
73
  <TextInput testID="price-reason" accessibilityLabel="Reason (optional)" placeholder="Reason (optional)"
@@ -0,0 +1,58 @@
1
+ import { Pressable, ScrollView, Text, View } from 'react-native';
2
+ import { cn } from '@tallyui/theme';
3
+ import { XIcon } from '../ui/icon/x-icon';
4
+
5
+ // v2's built-in pills, in its order: packages/core/src/screens/main/pos/products/filter-bar/filter-bar-layout.ts
6
+ // `BUILT_IN_PILL_IDS` (MIT, WCPOS).
7
+ export type ProductFilterChip = 'inStock' | 'featured' | 'onSale' | 'category' | 'tag' | 'brand';
8
+ type ToggleChip = 'inStock' | 'featured' | 'onSale';
9
+ type TermChip = 'category' | 'tag' | 'brand';
10
+
11
+ export interface ProductFilters { inStock: boolean; featured: boolean; onSale: boolean }
12
+
13
+ /** In Stock starts on, as v2's `stock_status: 'instock'` does while "show out-of-stock products" is off (its default). */
14
+ export const DEFAULT_PRODUCT_FILTERS: ProductFilters = { inStock: true, featured: false, onSale: false };
15
+ export const PRODUCT_FILTER_CHIPS: readonly ProductFilterChip[] = ['inStock', 'featured', 'onSale', 'category', 'tag', 'brand'];
16
+
17
+ const LABELS: Record<ProductFilterChip, string> = {
18
+ inStock: 'In Stock', featured: 'Featured', onSale: 'On Sale', category: 'Category', tag: 'Tag', brand: 'Brand',
19
+ };
20
+
21
+ export interface ProductFilterBarProps {
22
+ value: ProductFilters;
23
+ onChange: (next: ProductFilters) => void;
24
+ /** Which chips to show, in this order. Default PRODUCT_FILTER_CHIPS. */
25
+ chips?: readonly ProductFilterChip[];
26
+ /** Opens the app's term picker; the category, tag and brand chips render only when it is given. */
27
+ onTermPress?: (chip: TermChip) => void;
28
+ className?: string;
29
+ }
30
+
31
+ function isToggle(chip: ProductFilterChip): chip is ToggleChip {
32
+ return chip === 'inStock' || chip === 'featured' || chip === 'onSale';
33
+ }
34
+
35
+ /**
36
+ * v2's always-on filter chips above the product grid: In Stock, Featured and On Sale toggle; Category, Tag
37
+ * and Brand open the app's term picker. Ported from WCPOS v2 `FilterBar`,
38
+ * packages/core/src/screens/main/pos/products/filter-bar/filter-bar.tsx (MIT, WCPOS).
39
+ */
40
+ export function ProductFilterBar({ value, onChange, chips = PRODUCT_FILTER_CHIPS, onTermPress, className }: ProductFilterBarProps) {
41
+ const shown = chips.filter((chip) => isToggle(chip) || onTermPress);
42
+ return (
43
+ <ScrollView horizontal showsHorizontalScrollIndicator={false} className={className} contentContainerClassName="flex-row gap-2">
44
+ {shown.map((chip) => {
45
+ const on = isToggle(chip) && value[chip];
46
+ return (
47
+ <Pressable key={chip} testID={`filter-chip-${chip}`} role="button" aria-pressed={isToggle(chip) ? on : undefined}
48
+ onPress={() => (isToggle(chip) ? onChange({ ...value, [chip]: !value[chip] }) : onTermPress?.(chip))}
49
+ className={cn('min-h-11 flex-row items-center gap-1.5 rounded-full border px-3',
50
+ on ? 'border-primary/30 bg-primary/10' : 'border-border bg-card')}>
51
+ <Text className={cn('text-sm', on ? 'text-primary' : 'text-foreground')}>{LABELS[chip]}</Text>
52
+ {on && chip === 'inStock' ? <View className="text-primary"><XIcon size={14} /></View> : null}
53
+ </Pressable>
54
+ );
55
+ })}
56
+ </ScrollView>
57
+ );
58
+ }