Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
315 lines
14 KiB
TypeScript
315 lines
14 KiB
TypeScript
'use client'
|
|
|
|
import { useMemo, useRef, useState } from 'react'
|
|
import { ScanBarcode } from 'lucide-react'
|
|
import type { PosEventProduct } from '@/app/lib/types'
|
|
import { useMoney } from '@/app/pos/currency'
|
|
import { useScanKeyCapture } from '@/app/lib/useScanKeyCapture'
|
|
import { Button } from '@/app/components/ui/button'
|
|
import { Input } from '@/app/components/ui/input'
|
|
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/app/components/ui/dialog'
|
|
import { cn } from '@/app/lib/utils'
|
|
import { useT } from '@/app/lib/i18n/MessagesProvider'
|
|
|
|
// POS product picker (redesign-pos-sale-flow, BABYBOO-38): tap a tile to add one unit; quantities are
|
|
// reduced from the cart. At least 4 tiles per row from the lg breakpoint. The search box narrows by
|
|
// name, product code, or scan code (from SKU variant barcodes), and Enter on an exact scan match adds
|
|
// it, so a barcode scanner that ends with Enter adds the item. A product sold out at this counter
|
|
// reads "Order in" and is addable only when the sale is a Pick up or Deliver (`allowOrderIn`).
|
|
// Rows sharing a productCode show as one tile that opens a variant picker (group-pos-variants); exact
|
|
// scan matches and single rows keep their own tile.
|
|
|
|
interface ProductGridProps {
|
|
products: PosEventProduct[]
|
|
cartQtyByPricingId: Record<string, number>
|
|
onAdd: (product: PosEventProduct) => void
|
|
/** True for a Pick up or Deliver sale: sold-out products can then be ordered in. */
|
|
allowOrderIn: boolean
|
|
}
|
|
|
|
function resolveCategory(product: PosEventProduct): string {
|
|
return product.category == null || product.category === '' ? 'Other' : product.category
|
|
}
|
|
|
|
function buildCategoryButtons(products: PosEventProduct[]): string[] {
|
|
const seen = new Set<string>()
|
|
let hasOther = false
|
|
for (const p of products) {
|
|
const cat = resolveCategory(p)
|
|
if (cat === 'Other') hasOther = true
|
|
else seen.add(cat)
|
|
}
|
|
return ['All', ...seen, ...(hasOther ? ['Other'] : [])]
|
|
}
|
|
|
|
const STOCK_TEXT: Record<string, string> = { IN_STOCK: 'PosInStock', SOLD_OUT: 'PosOrderIn', PRE_ORDER: 'PosPreOrder' }
|
|
|
|
function ProductImage({ id, src, alt, soldOut }: { id: string; src?: string | null; alt: string; soldOut: boolean }) {
|
|
const t = useT()
|
|
const [failed, setFailed] = useState(false)
|
|
const dim = soldOut ? ' grayscale opacity-60' : ''
|
|
if (!src || failed) {
|
|
return (
|
|
<span
|
|
data-testid={`product-image-${id}`}
|
|
className={`flex aspect-[4/3] w-full items-center justify-center rounded-md bg-muted text-xs text-muted-foreground${dim}`}
|
|
>
|
|
{t('CatNoImage')}
|
|
</span>
|
|
)
|
|
}
|
|
return (
|
|
// eslint-disable-next-line @next/next/no-img-element -- remote drive URLs; no next/image remotePatterns configured
|
|
<img
|
|
data-testid={`product-image-${id}`}
|
|
src={src}
|
|
alt={alt}
|
|
loading="lazy"
|
|
onError={() => setFailed(true)}
|
|
className={`aspect-[4/3] w-full rounded-md bg-card object-contain${dim}`}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export function ProductGrid({ products, cartQtyByPricingId, onAdd, allowOrderIn }: ProductGridProps) {
|
|
const t = useT()
|
|
const money = useMoney()
|
|
const [activeCategory, setActiveCategory] = useState('All')
|
|
const [query, setQuery] = useState('')
|
|
const [message, setMessage] = useState<{ code: string; params?: Record<string, string> } | null>(null)
|
|
const [openGroup, setOpenGroup] = useState<string | null>(null)
|
|
const searchRef = useRef<HTMLInputElement>(null)
|
|
|
|
useScanKeyCapture((key) => {
|
|
const el = searchRef.current
|
|
const allSelected = !!el?.value && el.selectionStart === 0 && el.selectionEnd === el.value.length
|
|
setQuery((q) => (allSelected ? key : q + key))
|
|
setMessage(null)
|
|
el?.focus()
|
|
})
|
|
|
|
const canAdd = (p: PosEventProduct) => p.availability !== 'SOLD_OUT' || allowOrderIn
|
|
const q = query.trim().toLowerCase()
|
|
|
|
const scanMatches = (p: PosEventProduct) => (p.scanCodes ?? []).some(c => c.toLowerCase() === q) || (p.productCode ?? '').toLowerCase() === q
|
|
|
|
const visibleProducts = products.filter((p) => {
|
|
// An exact scan match shows whatever category tab is active, so several matches are always there to tap.
|
|
if (q && scanMatches(p)) return true
|
|
if (activeCategory !== 'All' && resolveCategory(p) !== activeCategory) return false
|
|
return !q || p.label.toLowerCase().includes(q) || (p.productCode ?? '').toLowerCase().includes(q) || scanMatches(p)
|
|
})
|
|
|
|
const rowsByCode = useMemo(() => {
|
|
const map = new Map<string, PosEventProduct[]>()
|
|
for (const p of products) if (p.productCode) map.set(p.productCode, [...(map.get(p.productCode) ?? []), p])
|
|
return map
|
|
}, [products])
|
|
|
|
// Group visible rows by productCode (first-appearance order); scan matches and code-less rows stay single.
|
|
// A search surfacing one variant still shows the whole group, so any sibling can be picked.
|
|
const tiles: PosEventProduct[][] = []
|
|
const seenCodes = new Set<string>()
|
|
for (const p of visibleProducts) {
|
|
const code = p.productCode
|
|
if (!code || (q && scanMatches(p))) {
|
|
tiles.push([p])
|
|
} else if (!seenCodes.has(code)) {
|
|
seenCodes.add(code)
|
|
tiles.push((rowsByCode.get(code) ?? [p]).filter(r => !(q && scanMatches(r))))
|
|
}
|
|
}
|
|
const dialogRows = openGroup ? rowsByCode.get(openGroup) ?? [] : []
|
|
const dialogName = dialogRows[0] ? (dialogRows[0].productName || dialogRows[0].label) : ''
|
|
|
|
const exactMatch = q ? products.filter(scanMatches) : []
|
|
|
|
function onSearchKey(e: React.KeyboardEvent<HTMLInputElement>) {
|
|
if (e.key !== 'Enter') return
|
|
e.preventDefault()
|
|
if (exactMatch.length === 1 && canAdd(exactMatch[0])) {
|
|
onAdd(exactMatch[0])
|
|
setQuery('')
|
|
setMessage(null)
|
|
searchRef.current?.focus()
|
|
} else if (exactMatch.length === 1 && !canAdd(exactMatch[0])) {
|
|
setMessage({ code: 'PosSoldOutHere', params: { name: exactMatch[0].label } })
|
|
searchRef.current?.select()
|
|
} else if (exactMatch.length === 0 && visibleProducts.length === 0) {
|
|
setMessage({ code: 'PosNoProductMatches', params: { query: query.trim() } })
|
|
searchRef.current?.select()
|
|
}
|
|
}
|
|
|
|
function onQueryChange(e: React.ChangeEvent<HTMLInputElement>) {
|
|
setQuery(e.target.value)
|
|
setMessage(null)
|
|
}
|
|
|
|
function onTileClick(product: PosEventProduct) {
|
|
onAdd(product)
|
|
searchRef.current?.focus()
|
|
}
|
|
|
|
function stockLabel(p: PosEventProduct) {
|
|
return p.availability ? t(STOCK_TEXT[p.availability]) : undefined
|
|
}
|
|
|
|
function renderGroup(rows: PosEventProduct[]) {
|
|
const code = rows[0].productCode as string
|
|
const name = rows[0].productName || rows[0].label
|
|
const qty = rows.reduce((sum, r) => sum + (cartQtyByPricingId[r.pPricingId] ?? 0), 0)
|
|
const prices = rows.map(r => r.unitPrice)
|
|
const min = Math.min(...prices)
|
|
const max = Math.max(...prices)
|
|
const allOut = rows.every(r => !canAdd(r))
|
|
return (
|
|
<li key={`group-${code}`} data-testid={`product-group-${code}`} data-in-cart={qty > 0 ? 'true' : 'false'}>
|
|
<button
|
|
type="button"
|
|
aria-label={t('PosChooseVariantAria', { name })}
|
|
onClick={() => setOpenGroup(code)}
|
|
className={cn(
|
|
'relative flex h-full w-full flex-col gap-1.5 rounded-lg border bg-card p-2.5 text-left transition-colors hover:border-primary/60',
|
|
qty > 0 && 'border-primary bg-primary/5',
|
|
)}
|
|
>
|
|
<ProductImage id={`group-${code}`} src={rows.find(r => r.imageUrl)?.imageUrl} alt={name} soldOut={allOut} />
|
|
{qty > 0 && (
|
|
<span className="absolute right-2 top-2 flex h-6 min-w-6 items-center justify-center rounded-full bg-primary px-1.5 text-xs text-primary-foreground tabular-nums">
|
|
{qty}
|
|
</span>
|
|
)}
|
|
<span title={name} className="line-clamp-2 min-h-[2.5rem] text-sm font-medium leading-5">{name}</span>
|
|
<span className="text-xs text-muted-foreground">{code}</span>
|
|
<span className="mt-auto flex flex-wrap items-baseline justify-between gap-x-2">
|
|
<span className="whitespace-nowrap font-semibold tabular-nums">{min === max ? money(min) : t('PosPriceRange', { min: money(min), max: money(max) })}</span>
|
|
<span className={cn('whitespace-nowrap text-xs', allOut ? 'font-medium text-primary' : 'text-muted-foreground')}>
|
|
{t(allOut ? 'PosOrderIn' : 'PosVariantOptions', { count: rows.length })}
|
|
</span>
|
|
</span>
|
|
</button>
|
|
</li>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<div className="flex flex-col gap-3">
|
|
<div className="relative">
|
|
<ScanBarcode aria-hidden="true" className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
|
<Input
|
|
ref={searchRef}
|
|
type="search"
|
|
aria-label={t('PosScanSearch')}
|
|
placeholder={t('PosScanSearch')}
|
|
value={query}
|
|
onChange={onQueryChange}
|
|
onKeyDown={onSearchKey}
|
|
className="h-11 pl-9"
|
|
/>
|
|
{message && <p role="status" aria-live="polite" className="text-sm text-destructive">{t(message.code, message.params)}</p>}
|
|
</div>
|
|
|
|
<div role="group" aria-label={t('PosCategories')} className="flex flex-wrap gap-2">
|
|
{buildCategoryButtons(products).map((cat) => (
|
|
<Button
|
|
key={cat}
|
|
type="button"
|
|
size="sm"
|
|
className="rounded-full"
|
|
variant={activeCategory === cat ? 'default' : 'outline'}
|
|
aria-pressed={activeCategory === cat}
|
|
onClick={() => setActiveCategory(cat)}
|
|
>
|
|
{cat === 'All' ? t('All') : cat === 'Other' ? t('PosCategoryOther') : cat}
|
|
</Button>
|
|
))}
|
|
</div>
|
|
|
|
<ul aria-label={t('PosProductsAria')} className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 2xl:grid-cols-5">
|
|
{tiles.map((rows) => {
|
|
if (rows.length > 1) return renderGroup(rows)
|
|
const product = rows[0]
|
|
const qty = cartQtyByPricingId[product.pPricingId] ?? 0
|
|
const soldOut = product.availability === 'SOLD_OUT'
|
|
const stock = stockLabel(product)
|
|
return (
|
|
<li key={product.pPricingId} data-testid={`product-card-${product.pPricingId}`} data-in-cart={qty > 0 ? 'true' : 'false'}>
|
|
<button
|
|
type="button"
|
|
aria-label={t(soldOut ? 'PosAddProductOrderInAria' : 'PosAddProductAria', { name: product.label, price: money(product.unitPrice) })}
|
|
disabled={!canAdd(product)}
|
|
onClick={() => onTileClick(product)}
|
|
className={cn(
|
|
'relative flex h-full w-full flex-col gap-1.5 rounded-lg border bg-card p-2.5 text-left transition-colors hover:border-primary/60 disabled:cursor-not-allowed disabled:opacity-60',
|
|
qty > 0 && 'border-primary bg-primary/5',
|
|
)}
|
|
>
|
|
<ProductImage id={product.pPricingId} src={product.imageUrl} alt={product.label} soldOut={soldOut} />
|
|
{qty > 0 && (
|
|
<span
|
|
data-testid={`product-qty-${product.pPricingId}`}
|
|
className="absolute right-2 top-2 flex h-6 min-w-6 items-center justify-center rounded-full bg-primary px-1.5 text-xs text-primary-foreground tabular-nums"
|
|
>
|
|
{qty}
|
|
</span>
|
|
)}
|
|
<span title={product.label} className="line-clamp-2 min-h-[2.5rem] text-sm font-medium leading-5">
|
|
{product.label}
|
|
</span>
|
|
{product.productCode && <span className="text-xs text-muted-foreground">{product.productCode}</span>}
|
|
<span className="mt-auto flex flex-wrap items-baseline justify-between gap-x-2">
|
|
<span className="whitespace-nowrap font-semibold tabular-nums">{money(product.unitPrice)}</span>
|
|
{stock && (
|
|
<span className={cn('whitespace-nowrap text-xs', soldOut ? 'font-medium text-primary' : 'text-muted-foreground')}>{stock}</span>
|
|
)}
|
|
</span>
|
|
</button>
|
|
</li>
|
|
)
|
|
})}
|
|
</ul>
|
|
|
|
<Dialog open={dialogRows.length > 0} onOpenChange={(open) => { if (!open) setOpenGroup(null) }}>
|
|
{/* Back to the scan box, not the tile, so the next barcode scan lands in the search. */}
|
|
<DialogContent aria-describedby={undefined} onCloseAutoFocus={(e) => { e.preventDefault(); searchRef.current?.focus() }}>
|
|
<DialogHeader>
|
|
<DialogTitle>{dialogName}</DialogTitle>
|
|
</DialogHeader>
|
|
<div className="flex max-h-[60vh] flex-col gap-2 overflow-y-auto">
|
|
{dialogRows.map((row) => {
|
|
const qty = cartQtyByPricingId[row.pPricingId] ?? 0
|
|
const soldOut = row.availability === 'SOLD_OUT'
|
|
const stock = stockLabel(row)
|
|
const name = row.variantName || row.label
|
|
return (
|
|
<button
|
|
key={row.pPricingId}
|
|
type="button"
|
|
aria-label={t(soldOut ? 'PosAddProductOrderInAria' : 'PosAddProductAria', { name, price: money(row.unitPrice) })}
|
|
disabled={!canAdd(row)}
|
|
onClick={() => onAdd(row)}
|
|
className={cn(
|
|
'flex min-h-12 w-full items-center justify-between gap-3 rounded-lg border bg-card px-3 py-2 text-left transition-colors hover:border-primary/60 disabled:cursor-not-allowed disabled:opacity-60',
|
|
qty > 0 && 'border-primary bg-primary/5',
|
|
)}
|
|
>
|
|
<span className="text-sm font-medium">{name}</span>
|
|
<span className="flex items-center gap-3">
|
|
{stock && <span className={cn('whitespace-nowrap text-xs', soldOut ? 'font-medium text-primary' : 'text-muted-foreground')}>{stock}</span>}
|
|
<span className="whitespace-nowrap font-semibold tabular-nums">{money(row.unitPrice)}</span>
|
|
{qty > 0 && (
|
|
<span className="flex h-6 min-w-6 items-center justify-center rounded-full bg-primary px-1.5 text-xs text-primary-foreground tabular-nums">{qty}</span>
|
|
)}
|
|
</span>
|
|
</button>
|
|
)
|
|
})}
|
|
</div>
|
|
<DialogFooter showCloseButton />
|
|
</DialogContent>
|
|
</Dialog>
|
|
</div>
|
|
)
|
|
}
|