959 lines
33 KiB
TypeScript
959 lines
33 KiB
TypeScript
import React, { useState } from 'react';
|
|
import { Drawer } from 'expo-router/drawer';
|
|
import { DrawerContentComponentProps } from '@react-navigation/drawer';
|
|
import { View, ScrollView, Alert, Dimensions, RefreshControl } from 'react-native';
|
|
import { Image } from 'expo-image';
|
|
import { useRouter, usePathname, Slot } from 'expo-router';
|
|
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
|
import { tw, theme, MyText, MyTouchableOpacity, MyFlatList, AppContainer, MiniQuantifier, SearchBar } from 'common-ui';
|
|
import { trpc } from '@/src/trpc-client';
|
|
import { useStores, useSlots } from '@/src/hooks/prominent-api-hooks';
|
|
import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore';
|
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
|
import { useCentralProductStore } from '@/src/store/centralProductStore';
|
|
import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks';
|
|
import { useHideTabNav } from '@/src/hooks/useHideTabNav';
|
|
import CartIcon from '@/components/icons/CartIcon';
|
|
import ProductCard from '@/components/ProductCard';
|
|
import { useSlotStore } from '@/components/stores/slotStore';
|
|
import { useFlashTabStore } from '@/src/store/flashTabStore';
|
|
|
|
import { LinearGradient } from 'expo-linear-gradient';
|
|
import FloatingCartBar from '@/components/floating-cart-bar';
|
|
import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector';
|
|
import dayjs from 'dayjs';
|
|
|
|
const { width: screenWidth } = Dimensions.get("window");
|
|
const drawerWidth = 85; // From layout drawerStyle
|
|
const itemWidth = (screenWidth - drawerWidth - 48) / 2; // Account for drawer width
|
|
|
|
interface SlotLayoutProps extends SlotProductsProps {
|
|
isForFlashDelivery?: boolean;
|
|
}
|
|
|
|
function CustomDrawerContent(baseUrl: string, drawerProps: DrawerContentComponentProps, slotIdParent?: number, storeIdParent?: number) {
|
|
const router = useRouter();
|
|
const pathname = usePathname();
|
|
const { data: storesData } = useStores();
|
|
const setStoreId = useSlotStore(state => state.setStoreId);
|
|
|
|
const { slotId, storeId } = useSlotStore();
|
|
|
|
// Get current pathname to determine active item
|
|
const currentPath = pathname;
|
|
// Check if we are on the main 'quick-delivery' page (All products)
|
|
// const isAllActive = !currentPath.includes('/store/');
|
|
const isAllActive = isNaN(storeId as number);
|
|
|
|
|
|
const allSlotsUrl = `${baseUrl}${slotId ? `?slotId=${slotId}` : ''}`;
|
|
|
|
return (
|
|
<View style={tw`flex-1 bg-gray-50 px-2 border-r border-gray-200`}>
|
|
<ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={tw`pb-20`}>
|
|
<View style={tw`flex-col gap-3`}>
|
|
{/* All Products Item */}
|
|
<MyTouchableOpacity
|
|
style={[
|
|
tw`items-center w-full mb-2 rounded-2xl overflow-hidden`,
|
|
isAllActive ? tw`shadow-lg` : tw``
|
|
]}
|
|
onPress={() => {
|
|
router.replace(allSlotsUrl as any);
|
|
}}
|
|
activeOpacity={0.8}
|
|
>
|
|
{isAllActive ? (
|
|
<LinearGradient
|
|
colors={[theme.colors.brand400, theme.colors.brand600]}
|
|
style={tw`w-full p-3 items-center`}
|
|
start={{ x: 0, y: 0 }}
|
|
end={{ x: 1, y: 1 }}
|
|
>
|
|
<View style={tw`w-10 h-10 rounded-full items-center justify-center bg-white/20 mb-1 border border-white/30`}>
|
|
<MaterialIcons name="grid-view" size={20} color="white" />
|
|
</View>
|
|
<MyText style={tw`text-[10px] font-bold text-white text-center`}>
|
|
ALL
|
|
</MyText>
|
|
</LinearGradient>
|
|
) : (
|
|
<View style={tw`w-full p-3 items-center bg-white border border-gray-100 rounded-2xl`}>
|
|
<View style={tw`w-10 h-10 rounded-full items-center justify-center bg-gray-50 mb-1`}>
|
|
<MaterialIcons name="grid-view" size={20} color="#6B7280" />
|
|
</View>
|
|
<MyText style={tw`text-[10px] font-medium text-gray-500 text-center`}>
|
|
ALL
|
|
</MyText>
|
|
</View>
|
|
)}
|
|
</MyTouchableOpacity>
|
|
|
|
<View style={tw`h-[1px] bg-gray-200 my-1 mx-2`} />
|
|
|
|
{/* Store Items */}
|
|
{storesData?.stores?.map(store => {
|
|
// Check if this specific store is active
|
|
|
|
const isStoreActive = storeId === store.id;
|
|
// const isStoreActive = currentPath.includes(`/store/${store.id}`);
|
|
|
|
return (
|
|
<MyTouchableOpacity
|
|
key={store.id}
|
|
style={[
|
|
tw`items-center w-full mb-3 rounded-2xl overflow-hidden`,
|
|
isStoreActive ? tw`shadow-lg` : tw``
|
|
]}
|
|
onPress={() => {
|
|
setStoreId(store.id);
|
|
const targetUrl = `${baseUrl}${slotId ? `?slotId=${slotId}&storeId=${store.id}` : `?storeId=${store.id}`}`;
|
|
|
|
router.replace(targetUrl as any);
|
|
}}
|
|
activeOpacity={0.8}
|
|
>
|
|
{isStoreActive ? (
|
|
<LinearGradient
|
|
colors={[theme.colors.brand400, theme.colors.brand600]}
|
|
style={tw`w-full p-2 py-3 items-center`}
|
|
start={{ x: 0, y: 0 }}
|
|
end={{ x: 1, y: 1 }}
|
|
>
|
|
<View style={tw`w-12 h-12 rounded-full items-center justify-center bg-white border-2 border-white mb-2 shadow-sm overflow-hidden`}>
|
|
{store.signedImageUrl ? (
|
|
<Image
|
|
source={{ uri: store.signedImageUrl }}
|
|
style={tw`w-12 h-12 rounded-full`}
|
|
resizeMode="cover"
|
|
/>
|
|
) : (
|
|
<MaterialIcons name="storefront" size={24} color={theme.colors.brand500} />
|
|
)}
|
|
</View>
|
|
<MyText style={tw`text-[10px] font-bold text-white text-center w-full leading-tight`} numberOfLines={2}>
|
|
{store.name.replace(/^The\s+/i, '')}
|
|
</MyText>
|
|
|
|
{/* Active Pip/Indicator */}
|
|
<View style={tw`absolute right-0 top-0 bottom-0 w-1 bg-white/30`} />
|
|
</LinearGradient>
|
|
) : (
|
|
<View style={tw`w-full p-2 py-3 items-center bg-white border border-gray-100 rounded-2xl`}>
|
|
<View style={tw`w-12 h-12 rounded-full items-center justify-center bg-gray-50 mb-2 border border-gray-100 overflow-hidden`}>
|
|
{store.signedImageUrl ? (
|
|
<Image
|
|
source={{ uri: store.signedImageUrl }}
|
|
style={tw`w-12 h-12 rounded-full`}
|
|
resizeMode="cover"
|
|
/>
|
|
) : (
|
|
<MaterialIcons name="storefront" size={24} color="#9CA3AF" />
|
|
)}
|
|
</View>
|
|
<MyText style={tw`text-[10px] font-medium text-gray-500 text-center w-full leading-tight`} numberOfLines={2}>
|
|
{store.name.replace(/^The\s+/i, '')}
|
|
</MyText>
|
|
</View>
|
|
)}
|
|
</MyTouchableOpacity>
|
|
);
|
|
}) || (
|
|
<MyText style={tw`text-xs text-gray-400 text-center py-4`}>Loading...</MyText>
|
|
)}
|
|
</View>
|
|
</ScrollView>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
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) {
|
|
const router = useRouter();
|
|
|
|
// const { slotId: paramsSlotId } = useLocalSearchParams();
|
|
const isDrawerHidden = useQuickDeliveryStore(state => state.isDrawerHidden);
|
|
const setSelectedSlotId = useQuickDeliveryStore(state => state.setSelectedSlotId);
|
|
const setSlotId = useSlotStore(state => state.setSlotId);
|
|
|
|
const handleSlotChange = (newSlotId: number) => {
|
|
setSelectedSlotId(newSlotId);
|
|
setSlotId(newSlotId);
|
|
router.replace(`${baseUrl}?slotId=${newSlotId}` as any);
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<View
|
|
style={[
|
|
tw`w-full bg-white`,
|
|
isForFlashDelivery ? tw`pb-1` : tw`flex-row px-4 py-2 mb-1`,
|
|
]}
|
|
>
|
|
<QuickDeliveryAddressSelector
|
|
slotId={Number(slotId)}
|
|
onSlotChange={handleSlotChange}
|
|
isForFlashDelivery={isForFlashDelivery}
|
|
/>
|
|
</View>
|
|
{/* Flash delivery has no store rail: the tag tabs live in the products
|
|
screen and this layout only renders the child route. */}
|
|
{isForFlashDelivery ? (
|
|
<View style={tw`flex-1 bg-white`}>
|
|
<Slot />
|
|
</View>
|
|
) : (
|
|
<Drawer
|
|
drawerContent={(props) => CustomDrawerContent(baseUrl, props, slotId, storeId)}
|
|
screenOptions={{
|
|
headerShown: false,
|
|
drawerType: 'permanent',
|
|
drawerStyle: {
|
|
width: 85,
|
|
...(isDrawerHidden && { display: 'none' }),
|
|
},
|
|
headerStyle: {
|
|
// width: 220,
|
|
backgroundColor: 'white',
|
|
},
|
|
headerShadowVisible: false,
|
|
}}
|
|
>
|
|
</Drawer>
|
|
)}
|
|
|
|
{/* <FloatingCartBar /> */}
|
|
<View style={tw`absolute bottom-2 left-4 right-4`}>
|
|
<FloatingCartBar isFlashDelivery={isForFlashDelivery} />
|
|
{/* <View style={tw`h-12 w-full bg-green-600`}></View> */}
|
|
</View>
|
|
</>
|
|
);
|
|
}
|
|
|
|
const formatQuantity = (quantity: number, unit: string): { value: string; display: string } => {
|
|
if (unit?.toLowerCase() === 'kg' && quantity < 1) {
|
|
return { value: `${Math.round(quantity * 1000)} g`, display: `${Math.round(quantity * 1000)}g` };
|
|
}
|
|
return { value: `${quantity} ${unit}(s)`, display: `${quantity}${unit}` };
|
|
};
|
|
|
|
const CompactProductCard = ({
|
|
item,
|
|
handleAddToCart,
|
|
onPress,
|
|
cartType = "regular",
|
|
}: {
|
|
item: any;
|
|
handleAddToCart: (productId: number) => void;
|
|
onPress?: () => void;
|
|
cartType?: "regular" | "flash";
|
|
}) => {
|
|
|
|
// Cart management for miniView
|
|
const { data: cartData } = useGetCart({}, cartType);
|
|
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
|
const updateCartItem = useUpdateCartItem({
|
|
showSuccessAlert: false,
|
|
showErrorAlert: false,
|
|
refetchCart: true,
|
|
}, cartType);
|
|
const removeFromCart = useRemoveFromCart({
|
|
showSuccessAlert: false,
|
|
showErrorAlert: false,
|
|
refetchCart: true,
|
|
}, cartType);
|
|
|
|
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({ itemId: cartItem.id });
|
|
} else if (newQuantity === 1 && !cartItem) {
|
|
handleAddToCart(item.id);
|
|
} else if (cartItem) {
|
|
updateCartItem.mutate({ itemId: cartItem.id, quantity: newQuantity });
|
|
}
|
|
};
|
|
|
|
return (
|
|
<View testID={`${cartType === "flash" ? "flash-product" : "slot-product"}-${item.id}`}>
|
|
<MyTouchableOpacity
|
|
testID="compact-product-card"
|
|
style={[
|
|
tw`bg-white rounded-lg shadow-sm mb-2 overflow-hidden border border-gray-100`,
|
|
{ width: itemWidth },
|
|
]}
|
|
onPress={onPress}
|
|
activeOpacity={0.9}
|
|
>
|
|
<View style={tw`relative`}>
|
|
<Image
|
|
source={{ uri: item.images?.[0] }}
|
|
style={{ width: "100%", height: itemWidth, resizeMode: "cover" }}
|
|
/>
|
|
{isOutOfStock && (
|
|
<View style={tw`absolute inset-0 bg-black/30 items-center justify-center`}>
|
|
<MyText style={tw`text-white text-xs font-bold`}>Out of Stock</MyText>
|
|
</View>
|
|
)}
|
|
<View testID={`${cartType === "flash" ? "flash-add" : "slot-add"}-${item.id}`} style={tw`absolute bottom-2 right-2`}>
|
|
{quantity > 0 ? (
|
|
<MiniQuantifier
|
|
value={quantity}
|
|
onChange={handleQuantityChange}
|
|
step={item.incrementStep}
|
|
showUnits={true}
|
|
// unit={item.unitNotation}
|
|
/>
|
|
) : (
|
|
<MyTouchableOpacity
|
|
testID="compact-card-add"
|
|
style={tw`w-8 h-8 rounded-full bg-white items-center justify-center shadow-md`}
|
|
onPress={() => handleQuantityChange(1)}
|
|
activeOpacity={0.8}
|
|
>
|
|
<CartIcon focused={false} size={16} color="#2E90FA" />
|
|
</MyTouchableOpacity>
|
|
)}
|
|
</View>
|
|
</View>
|
|
|
|
<View style={tw`p-2`}>
|
|
<MyText style={tw`text-gray-900 font-medium text-xs mb-1`} numberOfLines={2}>
|
|
{item.name}
|
|
</MyText>
|
|
|
|
<View style={tw`flex-row items-center justify-between`}>
|
|
<View style={tw`flex-row items-baseline flex-wrap`}>
|
|
<MyText style={tw`text-brand500 font-bold text-sm`}>₹{cartType === "flash" ? (item.flashPrice ?? item.price) : item.price}</MyText>
|
|
{item.marketPrice && Number(item.marketPrice) > Number(item.price) && (
|
|
<MyText style={tw`text-gray-400 text-xs ml-1 line-through`}>₹{item.marketPrice}</MyText>
|
|
)}
|
|
{item.productType !== 'combo' && (
|
|
<MyText style={tw`text-gray-600 text-xs ml-1`}>Quantity: <MyText style={tw`text-[#f81260] font-semibold`}>{item.unit || item.unitNotation}</MyText></MyText>
|
|
)}
|
|
</View>
|
|
</View>
|
|
</View>
|
|
|
|
</MyTouchableOpacity>
|
|
</View>
|
|
);
|
|
};
|
|
|
|
interface SlotProductsProps {
|
|
slotId?: number;
|
|
storeId?: number;
|
|
baseUrl: string;
|
|
}
|
|
|
|
export function SlotProducts({ slotId:slotIdParent, storeId:storeIdParent, baseUrl, }: SlotProductsProps) {
|
|
useHideTabNav('quick_delivery');
|
|
const [isLoadingDialogOpen, setIsLoadingDialogOpen] = React.useState(false);
|
|
const router = useRouter();
|
|
const slotId = slotIdParent;
|
|
const storeId = storeIdParent;
|
|
const storeIdNum = storeId;
|
|
|
|
const { data: slotsData, isLoading: slotsLoading, error: slotsError } = useSlots();
|
|
const { productsById } = useCentralProductStore();
|
|
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
|
|
|
// Find the specific slot from cached data
|
|
const slot = slotsData?.slots?.find(s => s.id === slotId);
|
|
|
|
const { addToCart = () => { } } = useAddToCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, "regular") || {};
|
|
|
|
const handleAddToCart = (productId: number) => {
|
|
setIsLoadingDialogOpen(true);
|
|
const item = filteredProducts.find((p) => p.id === productId);
|
|
const deliveryTime = slot?.deliveryTime ? dayjs(slot.deliveryTime).format('ddd, DD MMM • h:mm A') : '';
|
|
addToCart(productId, 1, slotId || 0, () => {
|
|
setIsLoadingDialogOpen(false);
|
|
if (item) {
|
|
Alert.alert('Added to Cart', `Added ${item.name} for delivery at ${deliveryTime}`);
|
|
}
|
|
});
|
|
};
|
|
|
|
if (slotsLoading) {
|
|
return (
|
|
<AppContainer>
|
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
|
<MyText style={tw`text-gray-500 font-medium`}>Loading slot delivery...</MyText>
|
|
</View>
|
|
</AppContainer>
|
|
);
|
|
}
|
|
|
|
if (slotsError) {
|
|
return (
|
|
<AppContainer>
|
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
|
<MaterialIcons name="error-outline" size={48} color="#D84343" />
|
|
<MyText style={tw`text-gray-900 text-lg font-bold mt-4`}>Oops!</MyText>
|
|
<MyText style={tw`text-gray-500 mt-2`}>Failed to load slot delivery</MyText>
|
|
</View>
|
|
</AppContainer>
|
|
);
|
|
}
|
|
|
|
if (!slot) {
|
|
return (
|
|
<AppContainer>
|
|
<View style={tw`flex-1 justify-center items-center`}>
|
|
<MyText style={tw`text-2xl font-bold text-gray-900 mb-4`}>Quick Delivery</MyText>
|
|
<MyText style={tw`text-gray-600`}>No delivery slot available.</MyText>
|
|
</View>
|
|
</AppContainer>
|
|
);
|
|
}
|
|
|
|
// Get product details from central store using slot product IDs
|
|
// Filter: 1) Must exist in productsById, 2) Must not be out of stock (from slots data)
|
|
const slotProducts = slot.products
|
|
?.map(p => productsById[p.id])
|
|
?.filter((product): product is NonNullable<typeof product> => product !== null && product !== undefined)
|
|
?.filter(product => !productSlotsMap[product.id]?.isOutOfStock) || [];
|
|
|
|
const filteredProducts = storeIdNum
|
|
? slotProducts.filter(p => p.storeId === storeIdNum)
|
|
: slotProducts;
|
|
|
|
return (
|
|
<View testID="slot-detail-page" style={tw`flex-1`}>
|
|
<MyFlatList
|
|
data={filteredProducts}
|
|
numColumns={2}
|
|
renderItem={({ item }) => (
|
|
<CompactProductCard
|
|
item={item}
|
|
handleAddToCart={handleAddToCart}
|
|
onPress={() => router.push(`/(drawer)/(tabs)/home/product-detail/${item.id}`)}
|
|
cartType="regular"
|
|
/>
|
|
)}
|
|
keyExtractor={(item, index) => index.toString()}
|
|
columnWrapperStyle={{ gap: 16, justifyContent: 'flex-start' }}
|
|
contentContainerStyle={[tw`pb-24 px-4`, { gap: 16 }]}
|
|
onRefresh={() => {}}
|
|
ListEmptyComponent={
|
|
storeIdNum ? (
|
|
<View style={tw`items-center justify-center py-10`}>
|
|
<MyText style={tw`text-gray-400 font-medium`}>No products from this store in this slot.</MyText>
|
|
</View>
|
|
) : null
|
|
}
|
|
/>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
interface FlashDeliveryProductsProps {
|
|
baseUrl: string;
|
|
onProductPress?: (productId: number) => void;
|
|
}
|
|
|
|
// 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;
|
|
|
|
interface FlashTabItem {
|
|
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: FlashTabItem[], picked: number | null): number | null {
|
|
if (picked != null && items.some((item) => item.id === picked)) return picked;
|
|
return items[0]?.id ?? null;
|
|
}
|
|
|
|
/**
|
|
* Tag strip. Reads the selection straight from the store, so a tap does not
|
|
* re-render the page, and receives a memoised `items` array so its memo holds.
|
|
*/
|
|
const FlashTagStrip = React.memo(({ items }: { items: FlashTabItem[] }) => {
|
|
const selectedTagId = useFlashTabStore((state) => state.selectedTagId);
|
|
const selectTag = useFlashTabStore((state) => state.selectTag);
|
|
|
|
return (
|
|
<FlashTabStrip
|
|
testID="flash-tag-strip"
|
|
tabTestIDPrefix="flash-tag-tab"
|
|
items={items}
|
|
activeId={resolveActiveId(items, selectedTagId)}
|
|
onSelect={selectTag}
|
|
/>
|
|
);
|
|
});
|
|
FlashTagStrip.displayName = 'FlashTagStrip';
|
|
|
|
const FlashStoreStrip = React.memo(({ items }: { items: FlashTabItem[] }) => {
|
|
const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId);
|
|
const selectStore = useFlashTabStore((state) => state.selectStore);
|
|
|
|
return (
|
|
<FlashTabStrip
|
|
testID="flash-store-strip"
|
|
tabTestIDPrefix="flash-store-tab"
|
|
items={items}
|
|
activeId={resolveActiveId(items, selectedStoreId)}
|
|
onSelect={selectStore}
|
|
/>
|
|
);
|
|
});
|
|
FlashStoreStrip.displayName = 'FlashStoreStrip';
|
|
|
|
/** Search box. Owns the store subscription so typing never re-renders the page. */
|
|
const FlashSearchBar = React.memo(() => {
|
|
const searchQuery = useFlashTabStore((state) => state.searchQuery);
|
|
const setSearchQuery = useFlashTabStore((state) => state.setSearchQuery);
|
|
|
|
return (
|
|
<SearchBar
|
|
testID="flash-product-search"
|
|
value={searchQuery}
|
|
onChangeText={setSearchQuery}
|
|
placeholder="Search products..."
|
|
/>
|
|
);
|
|
});
|
|
FlashSearchBar.displayName = 'FlashSearchBar';
|
|
|
|
interface FlashProductItemProps {
|
|
item: any;
|
|
onPress: (productId: number) => void;
|
|
}
|
|
|
|
/** One card. `onPress` is derived from the id so the parent's handler identity
|
|
* is the only prop that matters. */
|
|
const FlashProductItem = React.memo(({ item, onPress }: FlashProductItemProps) => {
|
|
const handlePress = React.useCallback(() => onPress(item.id), [item.id, onPress]);
|
|
|
|
return (
|
|
<View style={tw`mb-3`}>
|
|
<ProductCard
|
|
item={item}
|
|
itemWidth={flashItemWidth}
|
|
cartType="flash"
|
|
variant="hero"
|
|
miniView
|
|
showDeliveryInfo={false}
|
|
useAddToCartDialog={false}
|
|
onPress={handlePress}
|
|
/>
|
|
</View>
|
|
);
|
|
});
|
|
FlashProductItem.displayName = 'FlashProductItem';
|
|
|
|
interface FlashProductGridProps {
|
|
products: any[];
|
|
onProductPress: (productId: number) => void;
|
|
gridTestID: string;
|
|
showMoreTestID: string;
|
|
}
|
|
|
|
/**
|
|
* 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.
|
|
* The search value lives in the store, so only the grids wake on typing.
|
|
*/
|
|
const FlashProductGrid = React.memo(({
|
|
products,
|
|
onProductPress,
|
|
gridTestID,
|
|
showMoreTestID,
|
|
}: FlashProductGridProps) => {
|
|
const searchQuery = useFlashTabStore((state) => state.searchQuery);
|
|
const trimmedQuery = searchQuery.trim().toLowerCase();
|
|
|
|
const filtered = React.useMemo(() => {
|
|
if (!trimmedQuery) return products;
|
|
return products.filter((product: any) =>
|
|
product.name?.toLowerCase().includes(trimmedQuery)
|
|
);
|
|
}, [products, trimmedQuery]);
|
|
|
|
const [visibleCount, setVisibleCount] = React.useState(FLASH_PAGE_SIZE);
|
|
// Adjust during render, not in an effect: an effect would paint the new
|
|
// results with the previous count and then reset, costing a second render.
|
|
const [lastQuery, setLastQuery] = React.useState(trimmedQuery);
|
|
if (lastQuery !== trimmedQuery) {
|
|
setLastQuery(trimmedQuery);
|
|
setVisibleCount(FLASH_PAGE_SIZE);
|
|
}
|
|
|
|
const visible = filtered.length > visibleCount ? filtered.slice(0, visibleCount) : filtered;
|
|
|
|
if (filtered.length === 0) {
|
|
return (
|
|
<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>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<View testID={gridTestID} style={tw`flex-row flex-wrap justify-between`}>
|
|
{visible.map((product: any) => (
|
|
<FlashProductItem key={product.id} item={product} onPress={onProductPress} />
|
|
))}
|
|
</View>
|
|
{filtered.length > visibleCount && (
|
|
<View style={tw`items-center py-4`}>
|
|
<MyTouchableOpacity
|
|
testID={showMoreTestID}
|
|
style={tw`px-6 py-3 rounded-full bg-brand500 shadow-sm`}
|
|
activeOpacity={0.85}
|
|
onPress={() => setVisibleCount((count) => count + FLASH_PAGE_SIZE)}
|
|
>
|
|
<MyText style={tw`text-white text-sm font-semibold`}>Show More</MyText>
|
|
</MyTouchableOpacity>
|
|
</View>
|
|
)}
|
|
</>
|
|
);
|
|
});
|
|
FlashProductGrid.displayName = 'FlashProductGrid';
|
|
|
|
interface FlashTagSectionProps {
|
|
tagItems: FlashTabItem[];
|
|
tagIds: number[];
|
|
productsByTagId: Record<number, any[]>;
|
|
/** With no tags configured the section lists every flash product. */
|
|
fallbackProducts: any[];
|
|
onProductPress: (productId: number) => void;
|
|
}
|
|
|
|
/** Tag strip + its grid. Only this section re-renders when a tag is picked. */
|
|
const FlashTagSection = React.memo(({
|
|
tagItems,
|
|
tagIds,
|
|
productsByTagId,
|
|
fallbackProducts,
|
|
onProductPress,
|
|
}: 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] ?? [];
|
|
|
|
return (
|
|
<>
|
|
<FlashTagStrip items={tagItems} />
|
|
<View testID="flash-tag-section" style={tw`px-4`}>
|
|
<FlashProductGrid
|
|
key={tagId ?? 'all'}
|
|
products={products}
|
|
onProductPress={onProductPress}
|
|
gridTestID="flash-tag-grid"
|
|
showMoreTestID="flash-products-show-more"
|
|
/>
|
|
</View>
|
|
</>
|
|
);
|
|
});
|
|
FlashTagSection.displayName = 'FlashTagSection';
|
|
|
|
interface FlashStoreSectionProps {
|
|
storeItems: FlashTabItem[];
|
|
storeIds: number[];
|
|
productsByStoreId: Record<number, any[]>;
|
|
onProductPress: (productId: number) => void;
|
|
}
|
|
|
|
/** "Shop by Store" heading, its strip and grid. Picking a store wakes only this. */
|
|
const FlashStoreSection = React.memo(({
|
|
storeItems,
|
|
storeIds,
|
|
productsByStoreId,
|
|
onProductPress,
|
|
}: FlashStoreSectionProps) => {
|
|
const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId);
|
|
const storeId =
|
|
selectedStoreId != null && storeIds.includes(selectedStoreId)
|
|
? selectedStoreId
|
|
: storeIds[0] ?? null;
|
|
|
|
return (
|
|
<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>
|
|
<FlashStoreStrip items={storeItems} />
|
|
<View style={tw`px-4`}>
|
|
<FlashProductGrid
|
|
key={storeId ?? 'all'}
|
|
products={productsByStoreId[storeId ?? -1] ?? []}
|
|
onProductPress={onProductPress}
|
|
gridTestID="flash-store-grid"
|
|
showMoreTestID="flash-store-show-more"
|
|
/>
|
|
</View>
|
|
</View>
|
|
);
|
|
});
|
|
FlashStoreSection.displayName = 'FlashStoreSection';
|
|
|
|
export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsProps) {
|
|
useHideTabNav('quick_delivery');
|
|
// Owned by the user's pull, not by React Query: `isFetching` is true for every
|
|
// background fetch (remount-after-stale, invalidation, version bump), which
|
|
// made the pull-to-refresh spinner pop up on its own.
|
|
const [isRefreshing, setIsRefreshing] = useState(false);
|
|
const router = useRouter();
|
|
|
|
const products = useCentralProductStore((state) => state.products);
|
|
const catalogueTags = useCentralProductStore((state) => state.tags);
|
|
const isProductsLoading = useCentralProductStore((state) => state.isLoading);
|
|
const productsError = useCentralProductStore((state) => state.error);
|
|
const refetchProducts = useCentralProductStore((state) => state.refetchProducts);
|
|
const { data: storesData, refetch: refetchStores } = useStores();
|
|
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
|
|
|
// Single memo for the flash catalogue. Tabs, per-tab rows and per-store rows
|
|
// are derived together so the screen never holds two views of the same
|
|
// payload that can drift apart. Picking a tab no longer touches any of it.
|
|
const {
|
|
tagItems,
|
|
tagIds,
|
|
productsByTagId,
|
|
storeItems,
|
|
storeIds,
|
|
productsByStoreId,
|
|
flashProducts,
|
|
} = React.useMemo(() => {
|
|
const stores = storesData?.stores || [];
|
|
|
|
const flashProducts = products.filter((product: any) => {
|
|
const info = productSlotsMap[product.id];
|
|
return info?.isFlashAvailable && !info?.isOutOfStock;
|
|
});
|
|
|
|
const flashProductIds = new Set<number>(flashProducts.map((product: any) => product.id));
|
|
const flashStoreIds = new Set<number>(flashProducts.map((product: any) => product.storeId));
|
|
|
|
// A tab only exists if it has at least one in-stock flash product; empty
|
|
// tags and stores are not shown at all.
|
|
const tagTabs = catalogueTags.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] = flashProducts.filter((product: any) => ids.has(product.id));
|
|
}
|
|
|
|
const productsByStoreId: Record<number, any[]> = {};
|
|
for (const store of storeTabs) {
|
|
productsByStoreId[store.id] = flashProducts.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,
|
|
flashProducts,
|
|
};
|
|
}, [products, catalogueTags, storesData, productSlotsMap]);
|
|
|
|
// Stable so FlashProductItem/FlashProductGrid memos survive a re-render.
|
|
const handleProductPress = React.useCallback(
|
|
(productId: number) => {
|
|
if (onProductPress) {
|
|
onProductPress(productId);
|
|
} else {
|
|
router.push(`/(drawer)/(tabs)/flash-delivery/product-detail/${productId}`);
|
|
}
|
|
},
|
|
[onProductPress, router]
|
|
);
|
|
|
|
const handleRefresh = React.useCallback(async () => {
|
|
setIsRefreshing(true);
|
|
try {
|
|
await Promise.all([refetchProducts?.(), refetchStores()]);
|
|
} finally {
|
|
setIsRefreshing(false);
|
|
}
|
|
}, [refetchProducts, refetchStores]);
|
|
|
|
// Memoised so the platform control is not rebuilt on every render.
|
|
const refreshControl = React.useMemo(
|
|
() => (
|
|
<RefreshControl
|
|
refreshing={isRefreshing}
|
|
onRefresh={handleRefresh}
|
|
tintColor={theme.colors.brand500}
|
|
colors={[theme.colors.brand500]}
|
|
/>
|
|
),
|
|
[isRefreshing, handleRefresh]
|
|
);
|
|
|
|
if (isProductsLoading) {
|
|
return (
|
|
<AppContainer>
|
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
|
<MyText style={tw`text-gray-500 font-medium`}>Loading 1 Hr Delivery...</MyText>
|
|
</View>
|
|
</AppContainer>
|
|
);
|
|
}
|
|
|
|
if (productsError && products.length === 0) {
|
|
return (
|
|
<AppContainer>
|
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
|
<MaterialIcons name="error-outline" size={48} color="#D84343" />
|
|
<MyText style={tw`text-gray-900 text-lg font-bold mt-4`}>Oops!</MyText>
|
|
<MyText style={tw`text-gray-500 mt-2`}>Failed to load 1 Hr Delivery</MyText>
|
|
</View>
|
|
</AppContainer>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<ScrollView
|
|
style={tw`flex-1 bg-white`}
|
|
contentContainerStyle={tw`pb-24`}
|
|
refreshControl={refreshControl}
|
|
>
|
|
<View style={tw`px-4 pt-2`}>
|
|
<FlashSearchBar />
|
|
</View>
|
|
|
|
{/* Tag section — tabs scroll with the page, not sticky. */}
|
|
<FlashTagSection
|
|
tagItems={tagItems}
|
|
tagIds={tagIds}
|
|
productsByTagId={productsByTagId}
|
|
fallbackProducts={flashProducts}
|
|
onProductPress={handleProductPress}
|
|
/>
|
|
|
|
{/* Shop by Store — one tab per store. */}
|
|
{storeIds.length > 0 && (
|
|
<FlashStoreSection
|
|
storeItems={storeItems}
|
|
storeIds={storeIds}
|
|
productsByStoreId={productsByStoreId}
|
|
onProductPress={handleProductPress}
|
|
/>
|
|
)}
|
|
</ScrollView>
|
|
);
|
|
}
|