499 lines
16 KiB
TypeScript
499 lines
16 KiB
TypeScript
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
|
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
import { MiniQuantifier } from 'web-components'
|
|
import { useAllProducts, useStores } from '../hooks/prominent-api-hooks'
|
|
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
|
import { useCentralSlotStore } from '../lib/stores/central-slot-store'
|
|
import { useFlashTabStore } from '../lib/stores/flash-tab-store'
|
|
import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks'
|
|
import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores'
|
|
import { usePopulateCentralProductStore } from '../hooks/usePopulateCentralProductStore'
|
|
import { AppLayout } from '../components/AppLayout'
|
|
import { Zap, ShoppingCart } from 'lucide-react'
|
|
import type { CompactProductCardProps } from '@packages/shared'
|
|
|
|
export const Route = createFileRoute('/flash')({
|
|
component: FlashDeliveryPage,
|
|
})
|
|
|
|
// Three rows of three at a time, like the home catalog.
|
|
const PAGE_SIZE = 9
|
|
|
|
const GRID_CLASS =
|
|
'grid grid-cols-3 gap-3 sm:gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5'
|
|
const STRIP_CLASS =
|
|
'scrollbar-hide -mx-4 mb-5 flex gap-1 overflow-x-auto px-4 md:mx-0 md:px-0'
|
|
|
|
interface TabItem {
|
|
id: number
|
|
label: string
|
|
}
|
|
|
|
/** Active tab, resolved the way the page always did: the picked id while it
|
|
* still exists in this region's catalogue, otherwise the first tab. */
|
|
function resolveActiveId(items: TabItem[], picked: number | null): number | null {
|
|
if (picked != null && items.some((item) => item.id === picked)) return picked
|
|
return items[0]?.id ?? null
|
|
}
|
|
|
|
/**
|
|
* Tag tabs. Reads the selection from the store, so a tap re-renders only this
|
|
* strip and the tag grid — mirroring the native FlashTagStrip/TagScene split.
|
|
*/
|
|
const FlashTagStrip = memo(({ items }: { items: TabItem[] }) => {
|
|
const selectedTagId = useFlashTabStore((state) => state.selectedTagId)
|
|
const selectTag = useFlashTabStore((state) => state.selectTag)
|
|
|
|
const scrollRef = useRef<HTMLDivElement>(null)
|
|
const positions = useRef<number[]>([])
|
|
const activeId = resolveActiveId(items, selectedTagId)
|
|
const index = Math.max(
|
|
0,
|
|
items.findIndex((item) => item.id === activeId)
|
|
)
|
|
|
|
useEffect(() => {
|
|
const x = positions.current[index]
|
|
if (x != null) {
|
|
scrollRef.current?.scrollTo({ left: Math.max(0, x - 16), behavior: 'smooth' })
|
|
}
|
|
}, [index])
|
|
|
|
if (items.length === 0) return null
|
|
|
|
return (
|
|
<div ref={scrollRef} className={STRIP_CLASS}>
|
|
{items.map((item, i) => {
|
|
const active = item.id === activeId
|
|
return (
|
|
<button
|
|
key={item.id}
|
|
ref={(el) => {
|
|
positions.current[i] = el?.offsetLeft ?? 0
|
|
}}
|
|
onClick={() => selectTag(item.id)}
|
|
className="shrink-0 cursor-pointer px-3 py-2"
|
|
>
|
|
<span
|
|
className={`block text-sm font-bold ${
|
|
active ? 'text-flash-600' : 'text-gray-500'
|
|
}`}
|
|
>
|
|
{item.label}
|
|
</span>
|
|
<span
|
|
className={`mt-1 block h-1 rounded-full ${
|
|
active ? 'bg-flash-500' : 'bg-transparent'
|
|
}`}
|
|
/>
|
|
</button>
|
|
)
|
|
})}
|
|
</div>
|
|
)
|
|
})
|
|
FlashTagStrip.displayName = 'FlashTagStrip'
|
|
|
|
const FlashStoreStrip = memo(({ items }: { items: TabItem[] }) => {
|
|
const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId)
|
|
const selectStore = useFlashTabStore((state) => state.selectStore)
|
|
|
|
const activeId = resolveActiveId(items, selectedStoreId)
|
|
|
|
if (items.length === 0) return null
|
|
|
|
return (
|
|
<div className={STRIP_CLASS}>
|
|
{items.map((item) => {
|
|
const active = item.id === activeId
|
|
return (
|
|
<button
|
|
key={item.id}
|
|
onClick={() => selectStore(item.id)}
|
|
className="shrink-0 cursor-pointer px-3 py-2"
|
|
>
|
|
<span
|
|
className={`block text-sm font-bold ${
|
|
active ? 'text-flash-600' : 'text-gray-500'
|
|
}`}
|
|
>
|
|
{item.label}
|
|
</span>
|
|
<span
|
|
className={`mt-1 block h-1 rounded-full ${
|
|
active ? 'bg-flash-500' : 'bg-transparent'
|
|
}`}
|
|
/>
|
|
</button>
|
|
)
|
|
})}
|
|
</div>
|
|
)
|
|
})
|
|
FlashStoreStrip.displayName = 'FlashStoreStrip'
|
|
|
|
/** One card. Navigation is derived from the id so the parent handler identity
|
|
* is the only prop that can invalidate the memo. */
|
|
const FlashProductItem = memo(
|
|
({ item, onAddToCart }: { item: any; onAddToCart: (productId: number) => void }) => {
|
|
const navigate = useNavigate()
|
|
const handlePress = useCallback(() => {
|
|
navigate({ to: '/flash/product/$id', params: { id: String(item.id) } })
|
|
}, [navigate, item.id])
|
|
|
|
return (
|
|
<CompactProductCard item={item} handleAddToCart={onAddToCart} onPress={handlePress} />
|
|
)
|
|
}
|
|
)
|
|
FlashProductItem.displayName = 'FlashProductItem'
|
|
|
|
interface FlashProductGridProps {
|
|
products: any[]
|
|
onAddToCart: (productId: number) => void
|
|
}
|
|
|
|
/**
|
|
* One paged grid. Owns its visible count and is keyed by the active tab, so a
|
|
* tab switch resets the page size on the first render instead of in an effect.
|
|
*/
|
|
const FlashProductGrid = memo(({ products, onAddToCart }: FlashProductGridProps) => {
|
|
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE)
|
|
const visible = products.length > visibleCount ? products.slice(0, visibleCount) : products
|
|
|
|
if (products.length === 0) {
|
|
return (
|
|
<div className="py-10 text-center">
|
|
<p className="font-medium text-gray-400">No flash delivery products available.</p>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<div className={GRID_CLASS}>
|
|
{visible.map((product: any) => (
|
|
<FlashProductItem key={product.id} item={product} onAddToCart={onAddToCart} />
|
|
))}
|
|
</div>
|
|
|
|
{products.length > visibleCount && (
|
|
<div className="mt-6 flex justify-center">
|
|
<button
|
|
type="button"
|
|
onClick={() => setVisibleCount((count) => count + PAGE_SIZE)}
|
|
className="cursor-pointer rounded-full bg-flash-500 px-6 py-3 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-flash-600"
|
|
>
|
|
Show More
|
|
</button>
|
|
</div>
|
|
)}
|
|
</>
|
|
)
|
|
})
|
|
FlashProductGrid.displayName = 'FlashProductGrid'
|
|
|
|
interface FlashTagSectionProps {
|
|
tagItems: TabItem[]
|
|
tagIds: number[]
|
|
productsByTagId: Record<number, any[]>
|
|
/** With no tags configured the section lists every flash product. */
|
|
fallbackProducts: any[]
|
|
onAddToCart: (productId: number) => void
|
|
}
|
|
|
|
const FlashTagSection = memo(
|
|
({
|
|
tagItems,
|
|
tagIds,
|
|
productsByTagId,
|
|
fallbackProducts,
|
|
onAddToCart,
|
|
}: FlashTagSectionProps) => {
|
|
const selectedTagId = useFlashTabStore((state) => state.selectedTagId)
|
|
const tagId =
|
|
selectedTagId != null && tagIds.includes(selectedTagId)
|
|
? selectedTagId
|
|
: tagIds[0] ?? null
|
|
const products = tagId == null ? fallbackProducts : productsByTagId[tagId] ?? []
|
|
const label = tagItems.find((item) => item.id === tagId)?.label ?? 'All Products'
|
|
|
|
return (
|
|
<>
|
|
<FlashTagStrip items={tagItems} />
|
|
|
|
<div className="mb-4 flex items-center justify-between">
|
|
<p className="text-lg font-extrabold text-gray-900">{label}</p>
|
|
<p className="text-sm text-gray-500">{products.length} items</p>
|
|
</div>
|
|
|
|
<FlashProductGrid
|
|
key={tagId ?? 'all'}
|
|
products={products}
|
|
onAddToCart={onAddToCart}
|
|
/>
|
|
</>
|
|
)
|
|
}
|
|
)
|
|
FlashTagSection.displayName = 'FlashTagSection'
|
|
|
|
interface FlashStoreSectionProps {
|
|
storeItems: TabItem[]
|
|
storeIds: number[]
|
|
productsByStoreId: Record<number, any[]>
|
|
onAddToCart: (productId: number) => void
|
|
}
|
|
|
|
const FlashStoreSection = memo(
|
|
({ storeItems, storeIds, productsByStoreId, onAddToCart }: FlashStoreSectionProps) => {
|
|
const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId)
|
|
const storeId =
|
|
selectedStoreId != null && storeIds.includes(selectedStoreId)
|
|
? selectedStoreId
|
|
: storeIds[0] ?? null
|
|
const products = productsByStoreId[storeId ?? -1] ?? []
|
|
|
|
return (
|
|
<div className="mt-10">
|
|
<div className="mb-2 flex items-center justify-between">
|
|
<p className="text-lg font-extrabold text-gray-900">Shop by Store</p>
|
|
<p className="text-sm text-gray-500">{products.length} items</p>
|
|
</div>
|
|
|
|
<FlashStoreStrip items={storeItems} />
|
|
|
|
<FlashProductGrid
|
|
key={storeId ?? 'all'}
|
|
products={products}
|
|
onAddToCart={onAddToCart}
|
|
/>
|
|
</div>
|
|
)
|
|
}
|
|
)
|
|
FlashStoreSection.displayName = 'FlashStoreSection'
|
|
|
|
function FlashDeliveryPage() {
|
|
// Populate central stores so flash-eligible products resolve on direct load
|
|
usePopulateCentralStores()
|
|
usePopulateCentralProductStore()
|
|
|
|
const { data: productsData } = useAllProducts()
|
|
const { data: storesData } = useStores()
|
|
const { productsById } = useCentralProductStore()
|
|
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)
|
|
|
|
const addToCart = useAddToCart('flash')
|
|
const { data: cartData } = useGetCart('flash')
|
|
|
|
// Single memo for the flash catalogue: tabs and per-tab rows are derived
|
|
// together so the page never holds two views of the same payload. Picking a
|
|
// tab no longer touches any of it.
|
|
const {
|
|
tagItems,
|
|
tagIds,
|
|
productsByTagId,
|
|
storeItems,
|
|
storeIds,
|
|
productsByStoreId,
|
|
allFlashProducts,
|
|
} = useMemo(() => {
|
|
const tags = productsData?.tags || []
|
|
const stores = storesData?.stores || []
|
|
|
|
const allFlashProducts = Object.values(productsById).filter(
|
|
(product: any) =>
|
|
product &&
|
|
productSlotsMap[product.id]?.isFlashAvailable &&
|
|
!productSlotsMap[product.id]?.isOutOfStock
|
|
)
|
|
|
|
const flashProductIds = new Set<number>(allFlashProducts.map((p: any) => p.id))
|
|
const flashStoreIds = new Set<number>(allFlashProducts.map((p: any) => p.storeId))
|
|
|
|
// A tab only exists when it has at least one in-stock flash product.
|
|
const tagTabs = tags.filter((tag: any) =>
|
|
((tag.productIds || []) as number[]).some((id) => flashProductIds.has(id))
|
|
)
|
|
const storeTabs = stores.filter((store: any) => flashStoreIds.has(store.id))
|
|
|
|
const productsByTagId: Record<number, any[]> = {}
|
|
for (const tag of tagTabs) {
|
|
const ids = new Set<number>((tag.productIds || []) as number[])
|
|
productsByTagId[tag.id] = allFlashProducts.filter((product: any) =>
|
|
ids.has(product.id)
|
|
)
|
|
}
|
|
|
|
const productsByStoreId: Record<number, any[]> = {}
|
|
for (const store of storeTabs) {
|
|
productsByStoreId[store.id] = allFlashProducts.filter(
|
|
(product: any) => product.storeId === store.id
|
|
)
|
|
}
|
|
|
|
return {
|
|
tagItems: tagTabs.map((tag: any) => ({ id: tag.id, label: tag.tagName })),
|
|
tagIds: tagTabs.map((tag: any) => tag.id),
|
|
productsByTagId,
|
|
storeItems: storeTabs.map((store: any) => ({
|
|
id: store.id,
|
|
label: store.name.replace(/^The\s+/i, ''),
|
|
})),
|
|
storeIds: storeTabs.map((store: any) => store.id),
|
|
productsByStoreId,
|
|
allFlashProducts,
|
|
}
|
|
}, [productsData, storesData, productsById, productSlotsMap])
|
|
|
|
// Stable so FlashProductItem memos survive a section re-render.
|
|
const handleAddToCart = useCallback(
|
|
(productId: number) => {
|
|
const item = allFlashProducts.find((p: any) => p.id === productId)
|
|
addToCart.mutate(
|
|
{ skuId: productId, quantity: 1, storeId: item?.storeId ?? 0 },
|
|
{
|
|
onSuccess: () => {
|
|
alert(`Added ${item?.name || 'item'} for 1 Hr Delivery`)
|
|
},
|
|
}
|
|
)
|
|
},
|
|
[addToCart, allFlashProducts]
|
|
)
|
|
|
|
return (
|
|
<AppLayout isFlashDelivery={true}>
|
|
<div className="min-h-screen bg-gray-50">
|
|
{/* Page header */}
|
|
<div className="border-b border-gray-200 bg-white">
|
|
<div className="mx-auto flex w-full max-w-7xl items-center gap-2 px-4 py-5 md:px-8">
|
|
<Zap className="h-6 w-6 text-flash-500" fill="currentColor" />
|
|
<div>
|
|
<p className="text-[11px] font-black uppercase tracking-[0.22em] text-flash-500">
|
|
Express Counter
|
|
</p>
|
|
<h1 className="display-2 text-gray-900">Delivery within 1 hour</h1>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="mx-auto w-full max-w-7xl px-4 py-6 pb-32 md:px-8 md:pb-16">
|
|
{/* Info Banner */}
|
|
<div className="mb-4 rounded-xl border border-yellow-200 bg-yellow-50 p-3">
|
|
<p className="text-sm text-yellow-800">
|
|
Get these products delivered within 1 hour! Only available for select items.
|
|
</p>
|
|
</div>
|
|
|
|
{/* Tag tabs — same model as the home page tabs */}
|
|
<FlashTagSection
|
|
tagItems={tagItems}
|
|
tagIds={tagIds}
|
|
productsByTagId={productsByTagId}
|
|
fallbackProducts={allFlashProducts}
|
|
onAddToCart={handleAddToCart}
|
|
/>
|
|
|
|
{storeIds.length > 0 && (
|
|
<FlashStoreSection
|
|
storeItems={storeItems}
|
|
storeIds={storeIds}
|
|
productsByStoreId={productsByStoreId}
|
|
onAddToCart={handleAddToCart}
|
|
/>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</AppLayout>
|
|
)
|
|
}
|
|
|
|
// Memoised: identical to the native ProductCard change — an unmemoised card
|
|
// re-runs its cart hooks for every sibling whenever its section re-renders.
|
|
const CompactProductCard = memo(function CompactProductCard({
|
|
item,
|
|
handleAddToCart,
|
|
onPress,
|
|
}: CompactProductCardProps) {
|
|
const { data: cartData } = useGetCart('flash');
|
|
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
|
const updateCartItem = useUpdateCartItem('flash');
|
|
const removeFromCart = useRemoveFromCart('flash');
|
|
|
|
const cartItem = cartData?.items?.find(
|
|
(cartItem: any) => cartItem.skuId === item.id,
|
|
);
|
|
const quantity = cartItem?.quantity || 0;
|
|
const isOutOfStock = productSlotsMap[item.id]?.isOutOfStock;
|
|
|
|
const handleQuantityChange = (newQuantity: number) => {
|
|
if (newQuantity === 0 && cartItem) {
|
|
removeFromCart.mutate(cartItem.id);
|
|
} else if (newQuantity === 1 && !cartItem) {
|
|
handleAddToCart(item.id);
|
|
} else if (cartItem) {
|
|
updateCartItem.mutate({ skuId: cartItem.skuId, quantity: newQuantity });
|
|
}
|
|
};
|
|
|
|
const price = item.flashPrice ?? item.price
|
|
|
|
return (
|
|
<div
|
|
onClick={onPress}
|
|
className="group overflow-hidden rounded-xl border border-gray-200 bg-white transition-all hover:border-flash-300 hover:shadow-md"
|
|
>
|
|
<div className="relative">
|
|
<img
|
|
src={item.images?.[0]}
|
|
alt={item.name}
|
|
className="aspect-square w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]"
|
|
/>
|
|
{isOutOfStock && (
|
|
<div className="absolute inset-0 flex items-center justify-center bg-gray-900/40">
|
|
<p className="text-xs font-bold text-white">Out of Stock</p>
|
|
</div>
|
|
)}
|
|
<div className="absolute bottom-2 right-2">
|
|
{quantity > 0 ? (
|
|
<MiniQuantifier
|
|
value={quantity}
|
|
setValue={handleQuantityChange}
|
|
step={item.incrementStep}
|
|
/>
|
|
) : (
|
|
<div
|
|
className="flex h-9 w-9 items-center justify-center rounded-full bg-white shadow-md transition-colors hover:bg-flash-25"
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
handleQuantityChange(1);
|
|
}}
|
|
>
|
|
<ShoppingCart className="h-4 w-4 text-flash-500" />
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="p-3">
|
|
<p className="mb-1 line-clamp-2 text-xs font-bold text-gray-900">{item.name}</p>
|
|
|
|
<div className="flex flex-wrap items-baseline gap-x-1.5">
|
|
<p className="text-sm font-extrabold text-flash-500">₹{price}</p>
|
|
{item.marketPrice && Number(item.marketPrice) > Number(item.price) && (
|
|
<p className="text-[11px] text-gray-400 line-through">
|
|
₹{item.marketPrice}
|
|
</p>
|
|
)}
|
|
</div>
|
|
<p className="mt-0.5 text-[11px] text-gray-500">
|
|
<span className="font-semibold text-flash-500">
|
|
{item.unitNotation || item.unit}
|
|
</span>
|
|
</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
})
|