This commit is contained in:
shafi54 2026-11-01 13:01:56 +05:30
parent 4de296410c
commit 2cd923eedf
9 changed files with 755 additions and 285 deletions

View file

@ -475,7 +475,7 @@ This file covers the route wrapper, `SlotLayout`, `SlotProducts` and the flash p
| SLOT-08 | happy | tap store | sets store id; route includes `slotId` and `storeId` | | SLOT-08 | happy | tap store | sets store id; route includes `slotId` and `storeId` |
| SLOT-09 | edge | change delivery slot | sets quick-delivery/slot stores; replaces URL with new slot | | SLOT-09 | edge | change delivery slot | sets quick-delivery/slot stores; replaces URL with new slot |
| SLOT-10 | edge | drawer hidden | drawer display none | | SLOT-10 | edge | drawer hidden | drawer display none |
| SLOT-11 | edge | flash layout | delivery header “Delivery in within 1 hour” and LocationBar | | SLOT-11 | edge | flash layout | delivery header + LocationBar; no store drawer |
### 8.2 Slot products ### 8.2 Slot products
@ -504,24 +504,27 @@ This file covers the route wrapper, `SlotLayout`, `SlotProducts` and the flash p
| ID | Type | Case and setup | Assertion | | ID | Type | Case and setup | Assertion |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| FLASH-01 | happy | storeId set, products pending | “Loading 1 Hr Delivery...” | | FLASH-01 | happy | products pending | “Loading 1 Hr Delivery...” |
| FLASH-02 | error | storeId set, products fail | “Failed to load 1 Hr Delivery” | | FLASH-02 | error | products fail, no cache | “Failed to load 1 Hr Delivery” |
| FLASH-03 | edge | no storeId, products pending | no loading gate; empty message | | FLASH-03 | happy | tag tabs | first tag selected; tabs keep cache order |
| FLASH-04 | happy | data | only flash-available + in-stock products | | FLASH-04 | happy | data | only flash-available + in-stock products of the tag |
| FLASH-05 | edge | store filter | only that store’s flash products | | FLASH-05 | happy | select another tag | feed swaps to that tag’s products |
| FLASH-06 | edge | search query case-insensitive substring | matching products only | | FLASH-06 | edge | search query case-insensitive substring | matching products in the active tag |
| FLASH-07 | edge | search trimmed/empty | all flash products | | FLASH-07 | edge | search trimmed/empty | every product in the tag |
| FLASH-08 | edge | no products | “No 1 Hr Delivery products available.” | | FLASH-08 | edge | tag with no eligible products | “No 1 Hr Delivery products available.” |
| FLASH-09 | happy | tap add | `addToCart(skuId,1,0)` on flash cart; alert “delivery in 1hr” | | FLASH-09 | happy | tap add | `addToCart(skuId,1,0)` on flash cart; alert “delivery in 1hr” |
| FLASH-10 | happy | tap card | custom `onProductPress` or flash product-detail route | | FLASH-10 | happy | tap card | custom `onProductPress` or flash product-detail route |
| FLASH-11 | edge | price | flash price if present, else regular | | FLASH-11 | edge | price | flash price if present, else regular |
| FLASH-12 | edge | pull refresh | products refetch | | FLASH-12 | edge | pull refresh | products refetch |
| FLASH-13 | edge | storeId 0 | `Number('')` falsy; all stores path | | FLASH-13 | edge | no tags | strip hidden; every flash product shows |
| FLASH-14 | edge | `FlashAddToCartDialog` queued product | auto-adds once; success clears; alert after 300ms | | FLASH-14 | edge | `FlashAddToCartDialog` queued product | auto-adds once; success clears; alert after 300ms |
| FLASH-15 | error | auto-add fails | dialog stays/does not clear; no success alert | | FLASH-15 | error | auto-add fails | dialog stays/does not clear; no success alert |
| FLASH-16 | edge | focus with `shouldNavigateToCart` | resets flag and pushes flash cart | | FLASH-16 | edge | focus with `shouldNavigateToCart` | resets flag and pushes flash cart |
| FLASH-17 | edge | `shouldNavigateToCart` false | no push | | FLASH-17 | edge | `shouldNavigateToCart` false | no push |
| FLASH-18 | edge | `storeId` param changes | store store updated | | FLASH-18 | edge | switch tag | client-side only; no router rewrite |
| FLASH-19 | happy | 12 products | first 9 render; Show More reveals 12; button disappears |
| FLASH-20 | happy | Shop by Store | heading + one tab per store; store 1 grid shows its flash products |
| FLASH-21 | edge | empty store | store 2 shows the empty copy; tag section unaffected |
--- ---

View file

@ -1,24 +1,14 @@
import React, { useEffect } from 'react'; import React from 'react';
import { useLocalSearchParams } from 'expo-router';
import { SlotLayout } from '@/components/SlotSpecificView'; import { SlotLayout } from '@/components/SlotSpecificView';
import TabLayoutWrapper from '@/components/TabLayoutWrapper'; import TabLayoutWrapper from '@/components/TabLayoutWrapper';
import { useSlotStore } from '@/components/stores/slotStore';
export default function FlashDeliveryProductsLayout() { export default function FlashDeliveryProductsLayout() {
const { storeId: storeIdRaw } = useLocalSearchParams();
const setStoreId = useSlotStore(state => state.setStoreId);
useEffect(() => {
setStoreId(Number(storeIdRaw));
}, [storeIdRaw, setStoreId]);
return ( return (
<TabLayoutWrapper> <TabLayoutWrapper>
<SlotLayout <SlotLayout
storeId={Number(storeIdRaw)}
baseUrl="/(drawer)/(tabs)/flash-delivery" baseUrl="/(drawer)/(tabs)/flash-delivery"
isForFlashDelivery={true} isForFlashDelivery={true}
/> />
</TabLayoutWrapper> </TabLayoutWrapper>
); );
} }

View file

@ -1,8 +1,7 @@
import React, { useEffect } from 'react'; import React from 'react';
import { useLocalSearchParams, useRouter } from 'expo-router'; import { useRouter } from 'expo-router';
import { View, Alert } from 'react-native'; import { View, Alert } from 'react-native';
import { FlashDeliveryProducts } from '@/components/SlotSpecificView'; import { FlashDeliveryProducts } from '@/components/SlotSpecificView';
import { useSlotStore } from '@/components/stores/slotStore';
import FlashDeliveryNote from '@/components/FlashDeliveryNote'; import FlashDeliveryNote from '@/components/FlashDeliveryNote';
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'; import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore';
import { useFocusEffect } from '@react-navigation/native'; import { useFocusEffect } from '@react-navigation/native';
@ -56,15 +55,9 @@ const FlashAddToCartDialog = () => {
}; };
export default function FlashDeliveryView() { export default function FlashDeliveryView() {
const { storeId } = useLocalSearchParams<{ storeId?: string }>();
const setStoreId = useSlotStore(state => state.setStoreId);
const router = useRouter(); const router = useRouter();
const { shouldNavigateToCart, reset } = useFlashNavigationStore(); const { shouldNavigateToCart, reset } = useFlashNavigationStore();
useEffect(() => {
setStoreId(Number(storeId));
}, [storeId, setStoreId]);
useFocusEffect( useFocusEffect(
React.useCallback(() => { React.useCallback(() => {
if (shouldNavigateToCart) { if (shouldNavigateToCart) {
@ -82,7 +75,6 @@ export default function FlashDeliveryView() {
<> <>
<FlashDeliveryNote /> <FlashDeliveryNote />
<FlashDeliveryProducts <FlashDeliveryProducts
storeId={Number(storeId)}
baseUrl="/(drawer)/(tabs)/flash-delivery" baseUrl="/(drawer)/(tabs)/flash-delivery"
onProductPress={handleProductPress} onProductPress={handleProductPress}
/> />

View file

@ -29,6 +29,8 @@ interface ProductCardProps {
nullIfNotAvailable?: boolean; nullIfNotAvailable?: boolean;
containerComp?: React.ComponentType<any> | React.JSXElementConstructor<any>; containerComp?: React.ComponentType<any> | React.JSXElementConstructor<any>;
useAddToCartDialog?: boolean; useAddToCartDialog?: boolean;
/** Which cart this card reads and writes. Flash skips scheduled-slot logic. */
cartType?: 'regular' | 'flash';
} }
const formatQuantity = (quantity: number, unit: string): { value: string; display: string } => { const formatQuantity = (quantity: number, unit: string): { value: string; display: string } => {
@ -48,9 +50,11 @@ const ProductCard: React.FC<ProductCardProps> = ({
nullIfNotAvailable = false, nullIfNotAvailable = false,
containerComp: ContainerComp = React.Fragment, containerComp: ContainerComp = React.Fragment,
useAddToCartDialog = false, useAddToCartDialog = false,
cartType = 'regular',
}) => { }) => {
useRenderProbe('component:ProductCard') useRenderProbe('component:ProductCard')
const isHero = variant === 'hero'; const isHero = variant === 'hero';
const isFlash = cartType === 'flash';
const imageUri = item.images?.[0] const imageUri = item.images?.[0]
const [imageStatus, setImageStatus] = React.useState<'loading' | 'loaded' | 'error'>('loading') const [imageStatus, setImageStatus] = React.useState<'loading' | 'loaded' | 'error'>('loading')
const [imageError, setImageError] = React.useState<string | null>(null) const [imageError, setImageError] = React.useState<string | null>(null)
@ -63,24 +67,24 @@ const ProductCard: React.FC<ProductCardProps> = ({
return () => clearInterval(intervalId) return () => clearInterval(intervalId)
}, []) }, [])
const { data: cartData } = useGetCart(); const { data: cartData } = useGetCart({}, cartType);
const { getQuickestSlot } = useProductSlotIdentifier(); const { getQuickestSlot } = useProductSlotIdentifier();
const { setAddedToCartProduct } = useCartStore(); const { setAddedToCartProduct } = useCartStore();
const updateCartItem = useUpdateCartItem({ const updateCartItem = useUpdateCartItem({
showSuccessAlert: false, showSuccessAlert: false,
showErrorAlert: false, showErrorAlert: false,
refetchCart: true, refetchCart: true,
}); }, cartType);
const removeFromCart = useRemoveFromCart({ const removeFromCart = useRemoveFromCart({
showSuccessAlert: false, showSuccessAlert: false,
showErrorAlert: false, showErrorAlert: false,
refetchCart: true, refetchCart: true,
}); }, cartType);
const { addToCart = () => {} } = useAddToCart({ const { addToCart = () => {} } = useAddToCart({
showSuccessAlert: false, showSuccessAlert: false,
showErrorAlert: false, showErrorAlert: false,
refetchCart: true, refetchCart: true,
}) || {}; }, cartType) || {};
// Find current quantity from cart data // Find current quantity from cart data
const cartItem = cartData?.items?.find((cartItem: any) => cartItem.skuId === item.id); const cartItem = cartData?.items?.find((cartItem: any) => cartItem.skuId === item.id);
@ -121,8 +125,14 @@ const ProductCard: React.FC<ProductCardProps> = ({
const productSlotInfo = productSlotsMap[item.id]; const productSlotInfo = productSlotsMap[item.id];
const isOutOfStockFromSlots = productSlotInfo?.isOutOfStock; const isOutOfStockFromSlots = productSlotInfo?.isOutOfStock;
const isSlotsLoaded = useCentralSlotStore((state) => state.isSlotsLoaded); const isSlotsLoaded = useCentralSlotStore((state) => state.isSlotsLoaded);
// Don't treat "no slot yet" as out of stock while slot data is still loading // Don't treat "no slot yet" as out of stock while slot data is still loading.
const displayIsOutOfStock = isOutOfStockFromSlots || (isSlotsLoaded && !slotId); // Flash has no scheduled slot at all, so only the explicit flag counts.
const displayIsOutOfStock = isFlash
? Boolean(isOutOfStockFromSlots)
: isOutOfStockFromSlots || (isSlotsLoaded && !slotId);
// Flash products carry their own promo price.
const displayPrice = isFlash ? item.flashPrice ?? item.price : item.price;
// if(item.name.startsWith('Mutton Curry Cut')) { // if(item.name.startsWith('Mutton Curry Cut')) {
// console.log({slotId, displayIsOutOfStock}) // console.log({slotId, displayIsOutOfStock})
@ -139,6 +149,12 @@ const ProductCard: React.FC<ProductCardProps> = ({
} else if (newQuantity === 0 && cartItem) { } else if (newQuantity === 0 && cartItem) {
removeFromCart.mutate({ itemId: cartItem.id }); removeFromCart.mutate({ itemId: cartItem.id });
} else if (newQuantity === 1 && !cartItem) { } else if (newQuantity === 1 && !cartItem) {
if (isFlash) {
addToCart(item.id, 1, 0, () => {
Alert.alert('Added to Cart', `Added ${item.name} for delivery in 1hr`);
});
return;
}
const slotId = getQuickestSlot(item.id); const slotId = getQuickestSlot(item.id);
if (!slotId) { if (!slotId) {
Alert.alert("Error", "No available delivery slot for this product"); Alert.alert("Error", "No available delivery slot for this product");
@ -227,8 +243,8 @@ const ProductCard: React.FC<ProductCardProps> = ({
</MyText> </MyText>
<View style={isHero ? tw`flex-row items-baseline mb-1` : tw`flex-row items-baseline mb-2`}> <View style={isHero ? tw`flex-row items-baseline mb-1` : tw`flex-row items-baseline mb-2`}>
<MyText style={isHero ? tw`text-brand500 font-bold text-sm` : tw`text-brand500 font-bold text-base`}>₹{item.price}</MyText> <MyText style={isHero ? tw`text-brand500 font-bold text-sm` : tw`text-brand500 font-bold text-base`}>₹{displayPrice}</MyText>
{item.marketPrice && Number(item.marketPrice) > Number(item.price) && ( {item.marketPrice && Number(item.marketPrice) > Number(displayPrice) && (
<MyText style={isHero ? tw`text-gray-400 text-[10px] ml-1.5 line-through` : tw`text-gray-400 text-xs ml-2 line-through`}>₹{item.marketPrice}</MyText> <MyText style={isHero ? tw`text-gray-400 text-[10px] ml-1.5 line-through` : tw`text-gray-400 text-xs ml-2 line-through`}>₹{item.marketPrice}</MyText>
)} )}
</View> </View>
@ -238,7 +254,7 @@ const ProductCard: React.FC<ProductCardProps> = ({
)} )}
</View> </View>
{showDeliveryInfo && displayDeliveryDate && ( {showDeliveryInfo && !isFlash && displayDeliveryDate && (
<View style={tw`flex-row items-center bg-brand50 px-2 py-1.5 rounded-lg self-start mb-2 border border-brand100`}> <View style={tw`flex-row items-center bg-brand50 px-2 py-1.5 rounded-lg self-start mb-2 border border-brand100`}>
<MaterialIcons name="local-shipping" size={12} color="#2E90FA" /> <MaterialIcons name="local-shipping" size={12} color="#2E90FA" />
<MyText style={tw`text-[10px] text-brand700 ml-1.5 font-bold`}> <MyText style={tw`text-[10px] text-brand700 ml-1.5 font-bold`}>

View file

@ -1,20 +1,20 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Drawer } from 'expo-router/drawer'; import { Drawer } from 'expo-router/drawer';
import { DrawerContentComponentProps } from '@react-navigation/drawer'; import { DrawerContentComponentProps } from '@react-navigation/drawer';
import { View, ScrollView, Alert, Dimensions } from 'react-native'; import { View, ScrollView, Alert, Dimensions, RefreshControl } from 'react-native';
import { Image } from 'expo-image'; import { Image } from 'expo-image';
import { useRouter, usePathname } from 'expo-router'; import { useRouter, usePathname, Slot } from 'expo-router';
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { tw, theme, MyText, MyTouchableOpacity, MyFlatList, AppContainer, MiniQuantifier, SearchBar } from 'common-ui'; import { tw, theme, MyText, MyTouchableOpacity, MyFlatList, AppContainer, MiniQuantifier, SearchBar } from 'common-ui';
import { trpc } from '@/src/trpc-client'; import { trpc } from '@/src/trpc-client';
import { useAllProducts, useStores, useSlots } from '@/src/hooks/prominent-api-hooks'; import { useAllProducts, useStores, useSlots } from '@/src/hooks/prominent-api-hooks';
import { AllProductsApiType } from '@backend/trpc/router';
import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore'; import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore';
import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { useCentralProductStore } from '@/src/store/centralProductStore'; import { useCentralProductStore } from '@/src/store/centralProductStore';
import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks'; import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks';
import { useHideTabNav } from '@/src/hooks/useHideTabNav'; import { useHideTabNav } from '@/src/hooks/useHideTabNav';
import CartIcon from '@/components/icons/CartIcon'; import CartIcon from '@/components/icons/CartIcon';
import ProductCard from '@/components/ProductCard';
import { useSlotStore } from '@/components/stores/slotStore'; import { useSlotStore } from '@/components/stores/slotStore';
import { LinearGradient } from 'expo-linear-gradient'; import { LinearGradient } from 'expo-linear-gradient';
@ -166,6 +166,98 @@ function CustomDrawerContent(baseUrl: string, drawerProps: DrawerContentComponen
); );
} }
interface FlashTabStripProps {
items: { id: number; label: string }[];
activeId: number | null;
onSelect: (id: number) => void;
testID: string;
tabTestIDPrefix: string;
}
/**
* Horizontally scrollable tab strip used by the 1 Hr Delivery page for both the
* tag section and "Shop by Store".
*
* Same mechanics as the home page's TagTabStrip (plain ScrollView so Android
* scrolls reliably, active tab auto-scrolled into view). It lives inside the
* page's vertical ScrollView, so it scrolls away with the content.
*/
const FlashTabStrip = React.memo(({
items,
activeId,
onSelect,
testID,
tabTestIDPrefix,
}: FlashTabStripProps) => {
const scrollRef = React.useRef<any>(null);
const positions = React.useRef<number[]>([]);
const index = React.useMemo(() => {
const idx = items.findIndex((item) => item.id === activeId);
return idx < 0 ? 0 : idx;
}, [items, activeId]);
React.useEffect(() => {
const x = positions.current[index];
if (x != null) {
scrollRef.current?.scrollTo({ x: Math.max(0, x - 16), animated: true });
}
}, [index]);
if (items.length === 0) return null;
return (
<ScrollView
ref={scrollRef}
horizontal
testID={testID}
showsHorizontalScrollIndicator={false}
style={[tw`bg-white`, { flexGrow: 0, height: 48 }]}
contentContainerStyle={tw`px-2 items-center`}
>
{items.map((item, i) => {
const isActive = i === index;
return (
<MyTouchableOpacity
key={item.id}
testID={`${tabTestIDPrefix}-${item.id}`}
onLayout={(e: any) => {
positions.current[i] = e.nativeEvent.layout.x;
}}
onPress={() => onSelect(item.id)}
style={tw`h-12 px-3 justify-center`}
activeOpacity={0.7}
>
<View style={tw`items-center justify-center`}>
<MyText
style={[
tw`text-sm font-bold`,
isActive
? { color: theme.colors.brand600 }
: { color: '#64748B' },
]}
>
{item.label}
</MyText>
<View
style={[
tw`h-1 rounded-full mt-1 self-stretch`,
{
backgroundColor: isActive
? theme.colors.brand500
: 'transparent',
},
]}
/>
</View>
</MyTouchableOpacity>
);
})}
</ScrollView>
);
});
FlashTabStrip.displayName = 'FlashTabStrip';
export function SlotLayout({ slotId, storeId, baseUrl, isForFlashDelivery }: SlotLayoutProps) { export function SlotLayout({ slotId, storeId, baseUrl, isForFlashDelivery }: SlotLayoutProps) {
const router = useRouter(); const router = useRouter();
@ -194,23 +286,31 @@ export function SlotLayout({ slotId, storeId, baseUrl, isForFlashDelivery }: Slo
isForFlashDelivery={isForFlashDelivery} isForFlashDelivery={isForFlashDelivery}
/> />
</View> </View>
<Drawer {/* Flash delivery has no store rail: the tag tabs live in the products
drawerContent={(props) => CustomDrawerContent(baseUrl, props, slotId, storeId)} screen and this layout only renders the child route. */}
screenOptions={{ {isForFlashDelivery ? (
headerShown: false, <View style={tw`flex-1 bg-white`}>
drawerType: 'permanent', <Slot />
drawerStyle: { </View>
width: 85, ) : (
...(isDrawerHidden && { display: 'none' }), <Drawer
}, drawerContent={(props) => CustomDrawerContent(baseUrl, props, slotId, storeId)}
headerStyle: { screenOptions={{
// width: 220, headerShown: false,
backgroundColor: 'white', drawerType: 'permanent',
}, drawerStyle: {
headerShadowVisible: false, width: 85,
}} ...(isDrawerHidden && { display: 'none' }),
> },
</Drawer> headerStyle: {
// width: 220,
backgroundColor: 'white',
},
headerShadowVisible: false,
}}
>
</Drawer>
)}
{/* <FloatingCartBar /> */} {/* <FloatingCartBar /> */}
<View style={tw`absolute bottom-2 left-4 right-4`}> <View style={tw`absolute bottom-2 left-4 right-4`}>
@ -443,36 +543,136 @@ export function SlotProducts({ slotId:slotIdParent, storeId:storeIdParent, baseU
} }
interface FlashDeliveryProductsProps { interface FlashDeliveryProductsProps {
storeId?: number;
baseUrl: string; baseUrl: string;
onProductPress?: (productId: number) => void; onProductPress?: (productId: number) => void;
} }
export function FlashDeliveryProducts({ storeId:storeIdParent, baseUrl, onProductPress }: FlashDeliveryProductsProps) { // 16px page margin + two 8px gaps leaves each of the three cards this wide.
const flashItemWidth = (screenWidth - 48) / 3;
// Three rows per page, like the home catalog.
const FLASH_PAGE_SIZE = 9;
export function FlashDeliveryProducts({ baseUrl, onProductPress }: FlashDeliveryProductsProps) {
useHideTabNav('quick_delivery'); useHideTabNav('quick_delivery');
const [isLoadingDialogOpen, setIsLoadingDialogOpen] = React.useState(false);
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
const [selectedTagId, setSelectedTagId] = useState<number | null>(null);
const [selectedStoreId, setSelectedStoreId] = useState<number | null>(null);
const [tagVisibleCount, setTagVisibleCount] = useState(FLASH_PAGE_SIZE);
const [storeVisibleCount, setStoreVisibleCount] = useState(FLASH_PAGE_SIZE);
const router = useRouter(); const router = useRouter();
const storeId = storeIdParent;
const storeIdNum = storeId;
const productsQuery = useAllProducts(); const productsQuery = useAllProducts();
const { data: storesData, refetch: refetchStores } = useStores();
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
const { addToCart = () => { } } = useAddToCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, "flash") || {}; const tags = productsQuery?.data?.tags || [];
// First tag is the default, matching the home page.
const activeTagId = selectedTagId ?? tags[0]?.id ?? null;
const handleAddToCart = (productId: number) => { const stores = storesData?.stores || [];
setIsLoadingDialogOpen(true); // Every store gets a tab; the first is the default.
const item = flashProducts.find((p: any) => p.id === productId); const activeStoreId = selectedStoreId ?? stores[0]?.id ?? null;
addToCart(productId, 1, 0, () => {
setIsLoadingDialogOpen(false);
if (item) {
Alert.alert('Added to Cart', `Added ${item.name} for delivery in 1hr`);
}
});
};
if (storeIdNum && productsQuery?.isLoading) { const trimmedQuery = searchQuery.trim().toLowerCase();
const tagProductIds = React.useMemo(() => {
const tag = tags.find((t: any) => t.id === activeTagId);
return new Set<number>((tag?.productIds || []) as number[]);
}, [tags, activeTagId]);
const flashProducts = React.useMemo(() => {
const products = productsQuery?.data?.products || [];
return products.filter((p: any) => {
const info = productSlotsMap[p.id];
return info?.isFlashAvailable && !info?.isOutOfStock;
});
}, [productsQuery?.data?.products, productSlotsMap]);
const matchesSearch = React.useCallback(
(product: any) =>
!trimmedQuery || product.name?.toLowerCase().includes(trimmedQuery),
[trimmedQuery]
);
const tagProducts = React.useMemo(
() =>
flashProducts.filter(
(product: any) =>
(activeTagId == null || tagProductIds.has(product.id)) &&
matchesSearch(product)
),
[flashProducts, activeTagId, tagProductIds, matchesSearch]
);
const storeProducts = React.useMemo(
() =>
flashProducts.filter(
(product: any) =>
(activeStoreId == null || product.storeId === activeStoreId) &&
matchesSearch(product)
),
[flashProducts, activeStoreId, matchesSearch]
);
// Each section pages independently; a tab or search change starts over.
React.useEffect(() => {
setTagVisibleCount(FLASH_PAGE_SIZE);
}, [activeTagId, trimmedQuery]);
React.useEffect(() => {
setStoreVisibleCount(FLASH_PAGE_SIZE);
}, [activeStoreId, trimmedQuery]);
const visibleTagProducts = tagProducts.slice(0, tagVisibleCount);
const visibleStoreProducts = storeProducts.slice(0, storeVisibleCount);
const renderProduct = (item: any) => (
<View key={item.id} style={tw`mb-3`}>
<ProductCard
item={item}
itemWidth={flashItemWidth}
cartType="flash"
variant="hero"
miniView
showDeliveryInfo={false}
useAddToCartDialog={false}
onPress={() => {
if (onProductPress) {
onProductPress(item.id);
} else {
router.push(`/(drawer)/(tabs)/flash-delivery/product-detail/${item.id}`);
}
}}
/>
</View>
);
const renderGrid = (products: any[], testID: string) => (
<View testID={testID} style={tw`flex-row flex-wrap justify-between`}>
{products.map(renderProduct)}
</View>
);
const renderShowMore = (testID: string, onPress: () => void) => (
<View style={tw`items-center py-4`}>
<MyTouchableOpacity
testID={testID}
style={tw`px-6 py-3 rounded-full bg-brand500 shadow-sm`}
activeOpacity={0.85}
onPress={onPress}
>
<MyText style={tw`text-white text-sm font-semibold`}>Show More</MyText>
</MyTouchableOpacity>
</View>
);
const renderEmpty = () => (
<View style={tw`items-center justify-center py-10`}>
<MyText style={tw`text-gray-400 font-medium`}>No 1 Hr Delivery products available.</MyText>
</View>
);
if (productsQuery?.isLoading) {
return ( return (
<AppContainer> <AppContainer>
<View style={tw`flex-1 justify-center items-center bg-gray-50`}> <View style={tw`flex-1 justify-center items-center bg-gray-50`}>
@ -482,7 +682,7 @@ export function FlashDeliveryProducts({ storeId:storeIdParent, baseUrl, onProduc
); );
} }
if (storeIdNum && productsQuery?.error) { if (productsQuery?.error && !productsQuery?.data) {
return ( return (
<AppContainer> <AppContainer>
<View style={tw`flex-1 justify-center items-center bg-gray-50`}> <View style={tw`flex-1 justify-center items-center bg-gray-50`}>
@ -494,72 +694,78 @@ export function FlashDeliveryProducts({ storeId:storeIdParent, baseUrl, onProduc
); );
} }
// Filter products to only include those eligible for flash delivery
let flashProducts: AllProductsApiType['products'][number][] = [];
if (storeIdNum) {
// Filter by store, flash availability, and stock status
flashProducts = productsQuery?.data?.products?.filter(p => {
const productInfo = productSlotsMap[p.id];
return p.storeId === storeIdNum &&
productInfo?.isFlashAvailable &&
!productInfo?.isOutOfStock;
}) || [];
} else {
// Show all flash-available products that are in stock
flashProducts = productsQuery?.data?.products?.filter(p => {
const productInfo = productSlotsMap[p.id];
return productInfo?.isFlashAvailable &&
!productInfo?.isOutOfStock;
}) || [];
}
// Apply search filter (searches within this store's products only)
const trimmedQuery = searchQuery.trim().toLowerCase();
if (trimmedQuery) {
flashProducts = flashProducts.filter(p =>
p.name?.toLowerCase().includes(trimmedQuery)
);
}
return ( return (
<View style={tw`flex-1`}> <ScrollView
<MyFlatList style={tw`flex-1 bg-white`}
data={flashProducts} contentContainerStyle={tw`pb-24`}
numColumns={2} refreshControl={
ListHeaderComponent={ <RefreshControl
<View style={tw`px-4 pt-2`}> refreshing={productsQuery.isFetching}
<SearchBar onRefresh={() => {
testID="flash-product-search" productsQuery.refetch();
value={searchQuery} refetchStores();
onChangeText={setSearchQuery} }}
placeholder="Search products in this store..." tintColor={theme.colors.brand500}
/> colors={[theme.colors.brand500]}
</View> />
} }
renderItem={({ item }) => ( >
<CompactProductCard <View style={tw`px-4 pt-2`}>
item={item} <SearchBar
handleAddToCart={handleAddToCart} testID="flash-product-search"
onPress={() => { value={searchQuery}
if (onProductPress) { onChangeText={setSearchQuery}
onProductPress(item.id); placeholder="Search products..."
} else { />
router.push(`/(drawer)/(tabs)/flash-delivery/product-detail/${item.id}`); </View>
}
}} {/* Tag section — tabs scroll with the page, not sticky. */}
cartType="flash" <FlashTabStrip
/> testID="flash-tag-strip"
)} tabTestIDPrefix="flash-tag-tab"
keyExtractor={(item, index) => index.toString()} items={tags.map((tag: any) => ({ id: tag.id, label: tag.tagName }))}
columnWrapperStyle={{ gap: 16, justifyContent: 'flex-start' }} activeId={activeTagId}
contentContainerStyle={[tw`pb-24 px-4`, { gap: 16 }]} onSelect={setSelectedTagId}
onRefresh={() => productsQuery.refetch()}
ListEmptyComponent={
<View style={tw`items-center justify-center py-10`}>
<MyText style={tw`text-gray-400 font-medium`}>No 1 Hr Delivery products available.</MyText>
</View>
}
/> />
</View> <View testID="flash-tag-section" style={tw`px-4`}>
{tagProducts.length > 0
? renderGrid(visibleTagProducts, 'flash-tag-grid')
: renderEmpty()}
{tagProducts.length > tagVisibleCount &&
renderShowMore('flash-products-show-more', () =>
setTagVisibleCount((count) => count + FLASH_PAGE_SIZE)
)}
</View>
{/* Shop by Store — one tab per store. */}
{stores.length > 0 && (
<View testID="flash-store-section" style={tw`mt-8`}>
<View style={tw`px-4 mb-2`}>
<MyText style={tw`text-2xl font-extrabold text-gray-900 tracking-tight`}>
Shop by Store
</MyText>
</View>
<FlashTabStrip
testID="flash-store-strip"
tabTestIDPrefix="flash-store-tab"
items={stores.map((store: any) => ({
id: store.id,
label: store.name.replace(/^The\s+/i, ''),
}))}
activeId={activeStoreId}
onSelect={setSelectedStoreId}
/>
<View style={tw`px-4`}>
{storeProducts.length > 0
? renderGrid(visibleStoreProducts, 'flash-store-grid')
: renderEmpty()}
{storeProducts.length > storeVisibleCount &&
renderShowMore('flash-store-show-more', () =>
setStoreVisibleCount((count) => count + FLASH_PAGE_SIZE)
)}
</View>
</View>
)}
</ScrollView>
); );
} }

View file

@ -1,32 +1,27 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
/** /**
* Catalogue section 8.3 — Flash products (`tests/pages/flash-products.test.tsx`, * Catalogue section 8.3 — Flash products (`tests/pages/flash-products.test.tsx`,
* FLASH-01..18). * FLASH-01..21).
* *
* The page is `flash-delivery/(products)/index.tsx` plus `FlashDeliveryProducts` * The page is `flash-delivery/(products)/index.tsx` plus `FlashDeliveryProducts`
* in `components/SlotSpecificView.tsx`. Product eligibility comes from the * in `components/SlotSpecificView.tsx`. The screen has two independently paged
* central slot store (`isFlashAvailable` / `isOutOfStock`) and the catalogue from * sections: products by tag (tabs mirror the home page order) and products by
* the CDN products document, so both are seeded per case. * store ("Shop by Store", one tab per store).
*/ */
import * as React from 'react' import * as React from 'react'
import { Alert, RefreshControl } from 'react-native' import { Alert, RefreshControl } from 'react-native'
import { act, fireEvent, waitFor } from '@testing-library/react-native' import { act, fireEvent, waitFor, within } from '@testing-library/react-native'
import { QueryClient } from '@tanstack/react-query' import { QueryClient } from '@tanstack/react-query'
import { StorageServiceCasual } from 'common-ui' import { StorageServiceCasual } from 'common-ui'
import FlashDeliveryView from '@/app/(drawer)/(tabs)/flash-delivery/(products)/index' import FlashDeliveryView from '@/app/(drawer)/(tabs)/flash-delivery/(products)/index'
import { useSlotStore } from '@/components/stores/slotStore'
import { useFlashCartStore } from '@/src/store/flashCartStore' import { useFlashCartStore } from '@/src/store/flashCartStore'
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { import { flush, renderWithProviders, seedBoot } from '../helpers/test-utils'
flush,
renderWithProviders,
seedBoot,
} from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { router, __setParams } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
import { jsonCallsFor, setJsonError, setJsonPending, setJsonResponse } from '../mocks/fetch-json' import { jsonCallsFor, setJsonError, setJsonPending, setJsonResponse } from '../mocks/fetch-json'
import { __snapshot } from '../mocks/secure-store-mock' import { __snapshot } from '../mocks/secure-store-mock'
import { import {
@ -35,11 +30,13 @@ import {
PRODUCT_AVAILABILITY, PRODUCT_AVAILABILITY,
PRODUCTS_RESPONSE, PRODUCTS_RESPONSE,
SLOTS, SLOTS,
TAGS,
productsCacheUrl, productsCacheUrl,
} from '../fixtures' } from '../fixtures'
const FLASH_CART_ROUTE = '/(drawer)/(tabs)/flash-delivery/(cart)/cart' const FLASH_CART_ROUTE = '/(drawer)/(tabs)/flash-delivery/(cart)/cart'
const SEARCH_INPUT = 'flash-product-search-input' const SEARCH_INPUT = 'flash-product-search-input'
const EMPTY_COPY = 'No 1 Hr Delivery products available.'
type AvailabilityEntry = (typeof AVAILABILITY)[number] type AvailabilityEntry = (typeof AVAILABILITY)[number]
@ -55,25 +52,25 @@ function seedFlashAvailability(entries: any[]) {
useCentralSlotStore.getState().setSlotsData(SLOTS as any, PRODUCT_AVAILABILITY as any, entries as any) useCentralSlotStore.getState().setSlotsData(SLOTS as any, PRODUCT_AVAILABILITY as any, entries as any)
} }
/** Product catalogue with per-id store overrides (the store filter reads this doc). */ /** Replace the cache's tag document (tabs and per-tag product ids). */
function seedProductsInStores(stores: Record<number, number>) { function seedTags(tags: any[]) {
setJsonResponse(productsCacheUrl(), { setJsonResponse(productsCacheUrl(), { ...PRODUCTS_RESPONSE, tags })
...PRODUCTS_RESPONSE,
products: PRODUCTS_RESPONSE.products.map((product) =>
stores[product.id] ? { ...product, storeId: stores[product.id] } : product
),
})
} }
async function load() { async function load() {
await flush(3) await flush(3)
} }
function renderFlash(params: Record<string, any> = {}, queryClient?: QueryClient) { function renderFlash(queryClient?: QueryClient) {
__setParams(params)
return renderWithProviders(<FlashDeliveryView />, { auth: false, queryClient }) return renderWithProviders(<FlashDeliveryView />, { auth: false, queryClient })
} }
type FlashView = ReturnType<typeof renderFlash>
/** Product assertions are scoped: both sections can show the same card. */
const tagSection = (view: FlashView) => within(view.getByTestId('flash-tag-section'))
const storeSection = (view: FlashView) => within(view.getByTestId('flash-store-section'))
/** /**
* Flash cart mutations otherwise schedule React Query's 5-minute GC timer, which * Flash cart mutations otherwise schedule React Query's 5-minute GC timer, which
* keeps the jest process alive long after the run has finished. * keeps the jest process alive long after the run has finished.
@ -98,18 +95,18 @@ describe('Flash products (FLASH)', () => {
seedBoot() seedBoot()
}) })
it('FLASH-01: with a storeId a pending request shows the flash loading state', async () => { it('FLASH-01: a pending products request shows the flash loading state', async () => {
setJsonPending(productsCacheUrl()) setJsonPending(productsCacheUrl())
const { getByText } = renderFlash({ storeId: '1' }) const { getByText } = renderFlash()
await load() await load()
expect(getByText('Loading 1 Hr Delivery...')).toBeTruthy() expect(getByText('Loading 1 Hr Delivery...')).toBeTruthy()
}) })
it('FLASH-02: with a storeId a failed request shows the flash failure state', async () => { it('FLASH-02: a failed request with no cache shows the flash failure state', async () => {
setJsonError(productsCacheUrl(), new Error('offline')) setJsonError(productsCacheUrl(), new Error('offline'))
const { getByText } = renderFlash({ storeId: '1' }) const { getByText } = renderFlash()
await load() await load()
@ -117,85 +114,118 @@ describe('Flash products (FLASH)', () => {
expect(getByText('Failed to load 1 Hr Delivery')).toBeTruthy() expect(getByText('Failed to load 1 Hr Delivery')).toBeTruthy()
}) })
it('FLASH-03: without a storeId there is no loading gate, just the empty copy', async () => { it('FLASH-03: the first tag is selected and the tabs keep the cache order', async () => {
setJsonPending(productsCacheUrl())
const { getByText, queryByText } = renderFlash()
await load()
expect(queryByText('Loading 1 Hr Delivery...')).toBeNull()
expect(getByText('No 1 Hr Delivery products available.')).toBeTruthy()
})
it('FLASH-04: only flash-available, in-stock products are listed', async () => {
seedFlashAvailability( seedFlashAvailability(
availabilityWith({ availabilityWith({
2: { isFlashAvailable: true, isOutOfStock: true }, 2: { isFlashAvailable: true },
5: { isFlashAvailable: true }, 5: { isFlashAvailable: true },
}) })
) )
const { getByText, queryByText } = renderFlash({ storeId: '1' }) const view = renderFlash()
await load() await load()
expect(getByText('Paneer')).toBeTruthy() expect(view.getByTestId('flash-tag-strip')).toBeTruthy()
expect(getByText('Cucumber')).toBeTruthy() expect(view.getByTestId('flash-tag-tab-1')).toBeTruthy()
expect(view.getByTestId('flash-tag-tab-2')).toBeTruthy()
expect(view.getByTestId('flash-tag-tab-3')).toBeTruthy()
// Chicken is tag 1, so its product shows and Vegetables stays out of it.
expect(tagSection(view).getByText('Chicken Breast')).toBeTruthy()
expect(tagSection(view).queryByText('Cucumber')).toBeNull()
})
it('FLASH-04: the active tag keeps only flash-available, in-stock products', async () => {
seedFlashAvailability(
availabilityWith({
2: { isFlashAvailable: true },
6: { isFlashAvailable: true, isOutOfStock: true },
9: { isFlashAvailable: true },
})
)
const view = renderFlash()
await load()
const grid = tagSection(view)
expect(grid.getByText('Chicken Breast')).toBeTruthy()
expect(grid.getByText('No Image Item')).toBeTruthy()
// Flash available but out of stock. // Flash available but out of stock.
expect(queryByText('Chicken Breast')).toBeNull() expect(grid.queryByText('Mutton')).toBeNull()
expect(queryByText('Mutton')).toBeNull()
}) })
it('FLASH-05: a storeId keeps only that store\'s flash products', async () => { it('FLASH-05: selecting another tab swaps the feed to that tag', async () => {
seedProductsInStores({ 5: 2 }) seedFlashAvailability(
seedFlashAvailability(availabilityWith({ 5: { isFlashAvailable: true } })) availabilityWith({
const { getByText, queryByText } = renderFlash({ storeId: '1' }) 2: { isFlashAvailable: true },
5: { isFlashAvailable: true },
})
)
const view = renderFlash()
await load()
expect(tagSection(view).getByText('Chicken Breast')).toBeTruthy()
fireEvent.press(view.getByTestId('flash-tag-tab-2'))
expect(tagSection(view).getByText('Cucumber')).toBeTruthy()
expect(tagSection(view).queryByText('Chicken Breast')).toBeNull()
})
it('FLASH-06: the search box filters case-insensitively within the tag', async () => {
seedFlashAvailability(
availabilityWith({
2: { isFlashAvailable: true },
5: { isFlashAvailable: true },
})
)
const view = renderFlash()
await load()
fireEvent.press(view.getByTestId('flash-tag-tab-2'))
fireEvent.changeText(view.getByTestId(SEARCH_INPUT), 'cuc')
expect(tagSection(view).getByText('Cucumber')).toBeTruthy()
fireEvent.changeText(view.getByTestId(SEARCH_INPUT), 'chick')
expect(tagSection(view).getByText(EMPTY_COPY)).toBeTruthy()
})
it('FLASH-07: a whitespace-only search keeps every product in the tag', async () => {
seedFlashAvailability(
availabilityWith({
2: { isFlashAvailable: true },
9: { isFlashAvailable: true },
})
)
const view = renderFlash()
await load() await load()
expect(getByText('Paneer')).toBeTruthy() fireEvent.changeText(view.getByTestId(SEARCH_INPUT), ' ')
expect(queryByText('Cucumber')).toBeNull()
expect(tagSection(view).getByText('Chicken Breast')).toBeTruthy()
expect(tagSection(view).getByText('No Image Item')).toBeTruthy()
}) })
it('FLASH-06: the search box filters case-insensitively on a substring', async () => { it('FLASH-08: a tag with no eligible products shows the flash empty copy', async () => {
seedFlashAvailability(availabilityWith({ 5: { isFlashAvailable: true } })) seedFlashAvailability(availabilityWith({ 2: { isFlashAvailable: true } }))
const { getByTestId, getByText, queryByText } = renderFlash() const view = renderFlash()
await load() await load()
expect(getByText('Paneer')).toBeTruthy() fireEvent.press(view.getByTestId('flash-tag-tab-3'))
fireEvent.changeText(getByTestId(SEARCH_INPUT), 'cuc') expect(tagSection(view).getByText(EMPTY_COPY)).toBeTruthy()
expect(getByText('Cucumber')).toBeTruthy()
expect(queryByText('Paneer')).toBeNull()
})
it('FLASH-07: a whitespace-only search keeps every flash product', async () => {
seedFlashAvailability(availabilityWith({ 5: { isFlashAvailable: true } }))
const { getByTestId, getByText } = renderFlash()
await load()
fireEvent.changeText(getByTestId(SEARCH_INPUT), ' ')
expect(getByText('Cucumber')).toBeTruthy()
expect(getByText('Paneer')).toBeTruthy()
})
it('FLASH-08: no eligible products shows the flash empty copy', async () => {
setJsonResponse(productsCacheUrl(), { products: [], count: 0, tags: [] })
const { getByText } = renderFlash({ storeId: '1' })
await load()
expect(getByText('No 1 Hr Delivery products available.')).toBeTruthy()
}) })
it('FLASH-09: tapping add writes to the flash cart and alerts for 1hr delivery', async () => { it('FLASH-09: tapping add writes to the flash cart and alerts for 1hr delivery', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
const { getAllByTestId } = renderFlash({ storeId: '1' }, createMutationQueryClient()) seedTags([{ ...TAGS[0], productIds: [8] }])
seedFlashAvailability(availabilityWith({ 8: { isFlashAvailable: true } }))
const view = renderFlash(createMutationQueryClient())
await load() await load()
fireEvent.press(getAllByTestId('compact-card-add')[0]) fireEvent.press(tagSection(view).getAllByTestId('add-to-cart-icon')[0])
await waitFor(() => await waitFor(() =>
expect(JSON.parse(__snapshot().flash_cart_items ?? '[]')).toHaveLength(1) expect(JSON.parse(__snapshot().flash_cart_items ?? '[]')).toHaveLength(1)
@ -212,10 +242,12 @@ describe('Flash products (FLASH)', () => {
}) })
it('FLASH-10: tapping a card pushes the flash product-detail route', async () => { it('FLASH-10: tapping a card pushes the flash product-detail route', async () => {
const { getAllByTestId } = renderFlash({ storeId: '1' }) seedTags([{ ...TAGS[0], productIds: [8] }])
seedFlashAvailability(availabilityWith({ 8: { isFlashAvailable: true } }))
const view = renderFlash()
await load() await load()
fireEvent.press(getAllByTestId('compact-product-card')[0]) fireEvent.press(tagSection(view).getAllByTestId('product-card')[0])
expect(router.push).toHaveBeenCalledWith( expect(router.push).toHaveBeenCalledWith(
'/(drawer)/(tabs)/flash-delivery/product-detail/8' '/(drawer)/(tabs)/flash-delivery/product-detail/8'
@ -223,45 +255,48 @@ describe('Flash products (FLASH)', () => {
}) })
it('FLASH-11: the card uses the flash price when present and the regular one otherwise', async () => { it('FLASH-11: the card uses the flash price when present and the regular one otherwise', async () => {
seedFlashAvailability(availabilityWith({ 5: { isFlashAvailable: true } })) seedTags([{ ...TAGS[0], productIds: [5, 8] }])
const { getByText } = renderFlash() seedFlashAvailability(
availabilityWith({ 5: { isFlashAvailable: true }, 8: { isFlashAvailable: true } })
)
const view = renderFlash()
await load() await load()
// P_FLASH (8): price 90, flashPrice 75. P_CUCUMBER (5): price 15, no flash price. // P_FLASH (8): price 90, flashPrice 75. P_CUCUMBER (5): price 15, no flash price.
expect(getByText('₹75')).toBeTruthy() expect(tagSection(view).getByText('₹75')).toBeTruthy()
expect(getByText('₹15')).toBeTruthy() expect(tagSection(view).getByText('₹15')).toBeTruthy()
}) })
it('FLASH-12: pull to refresh refetches the products document', async () => { it('FLASH-12: pull to refresh refetches the products document', async () => {
const { UNSAFE_getAllByType } = renderFlash({ storeId: '1' }) const view = renderFlash()
await load() await load()
const before = jsonCallsFor(productsCacheUrl()).length const before = jsonCallsFor(productsCacheUrl()).length
await act(async () => { await act(async () => {
UNSAFE_getAllByType(RefreshControl)[0].props.onRefresh() view.UNSAFE_getAllByType(RefreshControl)[0].props.onRefresh()
}) })
await flush(3) await flush(3)
expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(before) expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(before)
}) })
it('FLASH-13: a storeId of 0 is falsy and falls back to the all-stores list', async () => { it('FLASH-13: without tags the strip is hidden and every flash product shows', async () => {
seedProductsInStores({ 5: 2 }) seedTags([])
seedFlashAvailability(availabilityWith({ 5: { isFlashAvailable: true } })) seedFlashAvailability(availabilityWith({ 8: { isFlashAvailable: true } }))
const { getByText } = renderFlash({ storeId: '' }) const view = renderFlash()
await load() await load()
expect(getByText('Paneer')).toBeTruthy() expect(view.queryByTestId('flash-tag-strip')).toBeNull()
expect(getByText('Cucumber')).toBeTruthy() expect(tagSection(view).getByText('Paneer')).toBeTruthy()
}) })
it('FLASH-14: a queued flash product is auto-added once and alerts after 300ms', async () => { it('FLASH-14: a queued flash product is auto-added once and alerts after 300ms', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
useFlashCartStore.getState().setAddedFlashProduct({ productId: 8, product: P_FLASH }) useFlashCartStore.getState().setAddedFlashProduct({ productId: 8, product: P_FLASH })
renderFlash({ storeId: '1' }, createMutationQueryClient()) renderFlash(createMutationQueryClient())
await load() await load()
await waitFor(() => expect(useFlashCartStore.getState().addedFlashProduct).toBeNull()) await waitFor(() => expect(useFlashCartStore.getState().addedFlashProduct).toBeNull())
@ -293,7 +328,7 @@ describe('Flash products (FLASH)', () => {
}) })
useFlashCartStore.getState().setAddedFlashProduct({ productId: 8, product: P_FLASH }) useFlashCartStore.getState().setAddedFlashProduct({ productId: 8, product: P_FLASH })
renderFlash({ storeId: '1' }, createMutationQueryClient()) renderFlash(createMutationQueryClient())
await load() await load()
expect(useFlashCartStore.getState().addedFlashProduct).not.toBeNull() expect(useFlashCartStore.getState().addedFlashProduct).not.toBeNull()
@ -305,7 +340,7 @@ describe('Flash products (FLASH)', () => {
it('FLASH-16: focusing with shouldNavigateToCart resets the flag and pushes the flash cart', async () => { it('FLASH-16: focusing with shouldNavigateToCart resets the flag and pushes the flash cart', async () => {
useFlashNavigationStore.setState({ shouldNavigateToCart: true }) useFlashNavigationStore.setState({ shouldNavigateToCart: true })
renderFlash({ storeId: '1' }) renderFlash()
await load() await load()
expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(false) expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(false)
@ -313,21 +348,98 @@ describe('Flash products (FLASH)', () => {
}) })
it('FLASH-17: without shouldNavigateToCart the page does not push the cart', async () => { it('FLASH-17: without shouldNavigateToCart the page does not push the cart', async () => {
renderFlash({ storeId: '1' }) renderFlash()
await load() await load()
expect(router.push).not.toHaveBeenCalledWith(FLASH_CART_ROUTE) expect(router.push).not.toHaveBeenCalledWith(FLASH_CART_ROUTE)
}) })
it('FLASH-18: a changed storeId param updates the slot store', async () => { it('FLASH-18: switching tags stays client-side and never rewrites the route', async () => {
__setParams({ storeId: '1' }) seedFlashAvailability(
const { rerender } = renderWithProviders(<FlashDeliveryView />, { auth: false }) availabilityWith({
2: { isFlashAvailable: true },
5: { isFlashAvailable: true },
})
)
const view = renderFlash()
await load() await load()
expect(useSlotStore.getState().storeId).toBe(1)
__setParams({ storeId: '2' }) fireEvent.press(view.getByTestId('flash-tag-tab-2'))
rerender(<FlashDeliveryView />)
expect(useSlotStore.getState().storeId).toBe(2) expect(router.replace).not.toHaveBeenCalled()
expect(router.push).not.toHaveBeenCalled()
})
it('FLASH-19: nine products render first and Show More reveals the rest', async () => {
const generated = Array.from({ length: 12 }, (_, index) => ({
...P_FLASH,
id: 800 + index,
name: `Flash ${index + 1}`,
}))
setJsonResponse(productsCacheUrl(), {
products: generated,
count: generated.length,
tags: [{ ...TAGS[0], productIds: generated.map((product) => product.id) }],
})
seedFlashAvailability(
generated.map((product) => ({
id: product.id,
price: 90,
marketPrice: 100,
flashPrice: 75,
isFlashAvailable: true,
isOutOfStock: false,
isSuspended: false,
isOffer: false,
}))
)
const view = renderFlash()
await load()
expect(tagSection(view).getAllByTestId('product-card')).toHaveLength(9)
fireEvent.press(view.getByTestId('flash-products-show-more'))
expect(tagSection(view).getAllByTestId('product-card')).toHaveLength(12)
expect(view.queryByTestId('flash-products-show-more')).toBeNull()
})
it('FLASH-20: Shop by Store gives every store a tab and shows that store\'s products', async () => {
seedFlashAvailability(
availabilityWith({
2: { isFlashAvailable: true },
5: { isFlashAvailable: true },
})
)
const view = renderFlash()
await load()
expect(view.getByText('Shop by Store')).toBeTruthy()
expect(view.getByTestId('flash-store-strip')).toBeTruthy()
expect(view.getByTestId('flash-store-tab-1')).toBeTruthy()
expect(view.getByTestId('flash-store-tab-2')).toBeTruthy()
// Both fixtures belong to store 1.
expect(storeSection(view).getByText('Chicken Breast')).toBeTruthy()
expect(storeSection(view).getByText('Cucumber')).toBeTruthy()
})
it('FLASH-21: a store with no flash products shows the empty copy in its section only', async () => {
seedFlashAvailability(
availabilityWith({
2: { isFlashAvailable: true },
5: { isFlashAvailable: true },
})
)
const view = renderFlash()
await load()
fireEvent.press(view.getByTestId('flash-store-tab-2'))
expect(storeSection(view).getByText(EMPTY_COPY)).toBeTruthy()
// The tag section is unaffected.
expect(tagSection(view).getByText('Chicken Breast')).toBeTruthy()
}) })
}) })

View file

@ -235,7 +235,7 @@ describe('Slot view (SLOT)', () => {
expect((globalThis as any).__drawerProps.screenOptions.drawerStyle.display).toBe('none') expect((globalThis as any).__drawerProps.screenOptions.drawerStyle.display).toBe('none')
}) })
it('SLOT-11: the flash layout shows the 1 hour header and the location bar', async () => { it('SLOT-11: the flash layout shows the header, the location bar and no store drawer', async () => {
const { getByTestId, getByText } = renderWithProviders(<FlashProductsLayout />, { const { getByTestId, getByText } = renderWithProviders(<FlashProductsLayout />, {
auth: false, auth: false,
}) })
@ -244,6 +244,8 @@ describe('Slot view (SLOT)', () => {
expect(getByText('Delivery in within 1 hour')).toBeTruthy() expect(getByText('Delivery in within 1 hour')).toBeTruthy()
expect(getByTestId('location-bar')).toBeTruthy() expect(getByTestId('location-bar')).toBeTruthy()
// Store selection moved to tag tabs inside the products screen.
expect((globalThis as any).__drawerProps).toBeUndefined()
}) })
it('SLOT-12: pending slots show the slot loading state', async () => { it('SLOT-12: pending slots show the slot loading state', async () => {

View file

@ -15,6 +15,9 @@ export const Route = createFileRoute('/flash')({
component: FlashDeliveryPage, component: FlashDeliveryPage,
}) })
// Three rows of three at a time, like the home catalog.
const PAGE_SIZE = 9
function FlashDeliveryPage() { function FlashDeliveryPage() {
const navigate = useNavigate() const navigate = useNavigate()
@ -22,36 +25,32 @@ function FlashDeliveryPage() {
usePopulateCentralStores() usePopulateCentralStores()
usePopulateCentralProductStore() usePopulateCentralProductStore()
const { data: productsData } = useAllProducts()
const { data: storesData } = useStores() const { data: storesData } = useStores()
const { productsById } = useCentralProductStore() const { productsById } = useCentralProductStore()
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap) const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)
const tags = productsData?.tags || []
const stores = storesData?.stores || [] const stores = storesData?.stores || []
const addToCart = useAddToCart('flash') const addToCart = useAddToCart('flash')
const { data: cartData } = useGetCart('flash') const { data: cartData } = useGetCart('flash')
// Store tabs — one tab per store (same model as home's category tabs) // Tag tabs — same order and default as the home page.
const storesWithFlash = useMemo(() => { const [selectedTagId, setSelectedTagId] = useState<number | null>(null)
return stores.filter((store: any) => const activeTagId = selectedTagId ?? tags[0]?.id ?? null
Object.values(productsById).some( const activeTag = tags.find((tag: any) => tag.id === activeTagId) || null
(p: any) => const tagProductIds = useMemo(
p?.storeId === store.id && () => new Set<number>((activeTag?.productIds || []) as number[]),
productSlotsMap[p.id]?.isFlashAvailable && [activeTag]
!productSlotsMap[p.id]?.isOutOfStock )
)
)
}, [stores, productsById, productSlotsMap])
const [selectedStoreId, setSelectedStoreId] = useState<number | null>(null) // Auto-scroll the active tag into view
const activeStoreId = selectedStoreId ?? storesWithFlash[0]?.id ?? null
// Auto-scroll the active store tab into view (matches user-ui tab behavior)
const tabsScrollRef = useRef<HTMLDivElement>(null) const tabsScrollRef = useRef<HTMLDivElement>(null)
const tabPositions = useRef<number[]>([]) const tabPositions = useRef<number[]>([])
const activeTabIndex = Math.max( const activeTabIndex = Math.max(
0, 0,
storesWithFlash.findIndex((s: any) => s.id === activeStoreId) tags.findIndex((tag: any) => tag.id === activeTagId)
) )
useEffect(() => { useEffect(() => {
@ -71,16 +70,36 @@ function FlashDeliveryPage() {
) )
}, [productsById, productSlotsMap]) }, [productsById, productSlotsMap])
// Products to show: active store's flash items, or all flash items when no stores // Products to show: the active tag's flash items, or everything when no
// tags are configured.
const filteredProducts = useMemo(() => { const filteredProducts = useMemo(() => {
if (activeStoreId != null) { if (activeTagId == null) return allFlashProducts
return allFlashProducts.filter((p: any) => p.storeId === activeStoreId) return allFlashProducts.filter((p: any) => tagProductIds.has(p.id))
} }, [activeTagId, allFlashProducts, tagProductIds])
return allFlashProducts
// Home's pattern: a page at a time, with a Show More button.
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE)
useEffect(() => {
setVisibleCount(PAGE_SIZE)
}, [activeTagId])
const visibleProducts = filteredProducts.slice(0, visibleCount)
// Shop by Store — every store gets a tab, first selected by default.
const [selectedStoreId, setSelectedStoreId] = useState<number | null>(null)
const activeStoreId = selectedStoreId ?? stores[0]?.id ?? null
const storeProducts = useMemo(() => {
if (activeStoreId == null) return allFlashProducts
return allFlashProducts.filter((p: any) => p.storeId === activeStoreId)
}, [activeStoreId, allFlashProducts]) }, [activeStoreId, allFlashProducts])
const [storeVisibleCount, setStoreVisibleCount] = useState(PAGE_SIZE)
useEffect(() => {
setStoreVisibleCount(PAGE_SIZE)
}, [activeStoreId])
const visibleStoreProducts = storeProducts.slice(0, storeVisibleCount)
const handleAddToCart = (productId: number) => { const handleAddToCart = (productId: number) => {
const item = filteredProducts.find((p: any) => p.id === productId) const item = allFlashProducts.find((p: any) => p.id === productId)
addToCart.mutate( addToCart.mutate(
{ skuId: productId, quantity: 1, storeId: item?.storeId ?? 0 }, { skuId: productId, quantity: 1, storeId: item?.storeId ?? 0 },
{ {
@ -115,21 +134,21 @@ function FlashDeliveryPage() {
</p> </p>
</div> </div>
{/* Store tabs — same model as home page tabs */} {/* Tag tabs — same model as the home page tabs */}
{storesWithFlash.length > 0 && ( {tags.length > 0 && (
<div <div
ref={tabsScrollRef} ref={tabsScrollRef}
className="scrollbar-hide -mx-4 mb-5 flex gap-1 overflow-x-auto px-4 md:mx-0 md:px-0" className="scrollbar-hide -mx-4 mb-5 flex gap-1 overflow-x-auto px-4 md:mx-0 md:px-0"
> >
{storesWithFlash.map((store: any, i: number) => { {tags.map((tag: any, i: number) => {
const active = activeStoreId === store.id const active = activeTagId === tag.id
return ( return (
<button <button
key={store.id} key={tag.id}
ref={(el) => { ref={(el) => {
tabPositions.current[i] = el?.offsetLeft ?? 0 tabPositions.current[i] = el?.offsetLeft ?? 0
}} }}
onClick={() => setSelectedStoreId(store.id)} onClick={() => setSelectedTagId(tag.id)}
className="shrink-0 cursor-pointer px-3 py-2" className="shrink-0 cursor-pointer px-3 py-2"
> >
<span <span
@ -137,7 +156,7 @@ function FlashDeliveryPage() {
active ? 'text-flash-600' : 'text-gray-500' active ? 'text-flash-600' : 'text-gray-500'
}`} }`}
> >
{store.name.replace(/^The\s+/i, '')} {tag.tagName}
</span> </span>
<span <span
className={`mt-1 block h-1 rounded-full ${ className={`mt-1 block h-1 rounded-full ${
@ -152,10 +171,7 @@ function FlashDeliveryPage() {
<div className="mb-4 flex items-center justify-between"> <div className="mb-4 flex items-center justify-between">
<p className="text-lg font-extrabold text-gray-900"> <p className="text-lg font-extrabold text-gray-900">
{activeStoreId != null {activeTag?.tagName ?? 'All Products'}
? stores.find((s: any) => s.id === activeStoreId)?.name.replace(/^The\s+/i, '') ||
'Store Products'
: 'All Products'}
</p> </p>
<p className="text-sm text-gray-500"> <p className="text-sm text-gray-500">
{filteredProducts.length} items {filteredProducts.length} items
@ -163,7 +179,7 @@ function FlashDeliveryPage() {
</div> </div>
<div className="grid grid-cols-3 gap-3 sm:gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5"> <div className="grid grid-cols-3 gap-3 sm:gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
{filteredProducts.map((product: any) => ( {visibleProducts.map((product: any) => (
<CompactProductCard <CompactProductCard
key={product.id} key={product.id}
item={product} item={product}
@ -178,6 +194,18 @@ function FlashDeliveryPage() {
))} ))}
</div> </div>
{filteredProducts.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>
)}
{filteredProducts.length === 0 && ( {filteredProducts.length === 0 && (
<div className="py-10 text-center"> <div className="py-10 text-center">
<p className="font-medium text-gray-400"> <p className="font-medium text-gray-400">
@ -185,6 +213,78 @@ function FlashDeliveryPage() {
</p> </p>
</div> </div>
)} )}
{stores.length > 0 && (
<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">{storeProducts.length} items</p>
</div>
{/* Store tabs — one per store, scrolled by the page itself */}
<div className="scrollbar-hide -mx-4 mb-5 flex gap-1 overflow-x-auto px-4 md:mx-0 md:px-0">
{stores.map((store: any) => {
const active = activeStoreId === store.id
return (
<button
key={store.id}
onClick={() => setSelectedStoreId(store.id)}
className="shrink-0 cursor-pointer px-3 py-2"
>
<span
className={`block text-sm font-bold ${
active ? 'text-flash-600' : 'text-gray-500'
}`}
>
{store.name.replace(/^The\s+/i, '')}
</span>
<span
className={`mt-1 block h-1 rounded-full ${
active ? 'bg-flash-500' : 'bg-transparent'
}`}
/>
</button>
)
})}
</div>
<div className="grid grid-cols-3 gap-3 sm:gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
{visibleStoreProducts.map((product: any) => (
<CompactProductCard
key={product.id}
item={product}
handleAddToCart={handleAddToCart}
onPress={() =>
navigate({
to: '/flash/product/$id',
params: { id: String(product.id) },
})
}
/>
))}
</div>
{storeProducts.length > storeVisibleCount && (
<div className="mt-6 flex justify-center">
<button
type="button"
onClick={() => setStoreVisibleCount((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>
)}
{storeProducts.length === 0 && (
<div className="py-10 text-center">
<p className="font-medium text-gray-400">
No flash delivery products available.
</p>
</div>
)}
</div>
)}
</div> </div>
</div> </div>
</AppLayout> </AppLayout>

View file

@ -93,3 +93,52 @@ No data, paging, or card changes.
~ Grid gap-5 (20px) -> gap-2 (8px); px-4 page margin unchanged. ~ Grid gap-5 (20px) -> gap-2 (8px); px-4 page margin unchanged.
Three cards now fill the row, matching the All Available Products grid. Three cards now fill the row, matching the All Available Products grid.
Web offers page already uses a 12px grid gap (gap-3), so no web change. Web offers page already uses a 12px grid gap (gap-3), so no web change.
[2026-11-01 12:51:23 IST] Flash delivery: tag tabs instead of the store drawer, 3-up hero grid.
--- apps/user-ui/components/ProductCard.tsx
+ cartType?: 'regular' | 'flash' (default regular). Flash reads/writes the flash
cart, prices flashPrice ?? price, adds with slotId 0 and the 1hr alert, and
skips scheduled-slot out-of-stock/delivery badges. Regular call sites unchanged.
--- apps/user-ui/components/SlotSpecificView.tsx
+ FlashTagStrip: horizontal, fixed strip copied from home's TagTabStrip mechanics.
~ SlotLayout: isForFlashDelivery renders selector + strip + <Slot/>; the
scheduled view keeps its Drawer untouched.
~ FlashDeliveryProducts: tags from useAllProducts (first tag default), filter by
tag.productIds then search, numColumns 3, width (sw-48)/3, columnGap 8,
rowGap 12, ProductCard hero cards. Store filtering/loading gates removed.
--- apps/user-ui/app/(drawer)/(tabs)/flash-delivery/(products)/index.tsx
--- apps/user-ui/app/(drawer)/(tabs)/flash-delivery/(products)/_layout.tsx
~ storeId param no longer read or written; route shape unchanged.
--- apps/web-ui/src/routes/flash.tsx
~ Store tabs -> tag tabs (same order, first default); store filtering removed;
cart storeId still taken from the product.
--- tests
~ flash-products store cases rewritten for tags; slot-view flash asserts no
drawer; JEST-TEST-CASES rows updated.
[2026-11-01 12:56:02 IST] Flash delivery: page the tag feed 9 at a time with Show More.
--- apps/user-ui/components/SlotSpecificView.tsx
+ FLASH_PAGE_SIZE = 9; visibleCount state, reset on tag/search change; grid renders
the first 9, footer Show More adds 9 (home's pattern). testID flash-products-show-more.
--- apps/web-ui/src/routes/flash.tsx
~ Same 9-at-a-time paging with a Show More button; reset on tag change.
--- apps/user-ui/tests/pages/flash-products.test.tsx
+ FLASH-19: nine products render, Show More reveals the rest.
--- apps/user-ui/JEST-TEST-CASES.md
+ FLASH-19 row.
[2026-11-01 12:59:05 IST] Flash delivery: scroll-away tabs + a "Shop by Store" tab section.
--- apps/user-ui/components/SlotSpecificView.tsx
~ FlashTagStrip generalised to FlashTabStrip (items + testID prefix); reused for
tags and stores.
~ FlashDeliveryProducts becomes a ScrollView: search, tag strip, tag grid (9 +
Show More), then "Shop by Store" heading, store strip, store grid (9 + Show
More). Both strips scroll with the page; paging resets per section on
tab/search change. Search filters both grids. Every store gets a tab.
--- apps/web-ui/src/routes/flash.tsx
~ Same two sections, store tabs below the tag grid, independent 9-item paging.
--- tests
~ Product assertions scoped to the tag grid; new store-section cases.