diff --git a/apps/backend/src/lib/cloud_cache.ts b/apps/backend/src/lib/cloud_cache.ts index d1c45cf..478e892 100644 --- a/apps/backend/src/lib/cloud_cache.ts +++ b/apps/backend/src/lib/cloud_cache.ts @@ -14,6 +14,7 @@ import { incrementRegionSlotsVersionNum, } from '@/src/dbService' import { imageUploadS3 } from '@/src/lib/s3-client' +import { applyImageCacheBust } from '@/src/lib/product-image-cache' import { getApiCacheKey, getCloudflareApiToken, getCloudflareZoneId, getAssetsDomain } from '@/src/lib/env-exporter' import { CACHE_FILENAMES, @@ -129,7 +130,11 @@ export async function createAllCacheFiles(regionId?: number): Promise { const productsData = await scaffoldProducts(regionId) - const jsonContent = JSON.stringify(productsData, null, 2) + + // Only the published catalogue carries the cache-busting query: the admin + // endpoint and the test snapshot controller keep the raw asset URLs. + const catalogue = applyImageCacheBust(productsData) + const jsonContent = JSON.stringify(catalogue, null, 2) const buffer = Buffer.from(jsonContent, 'utf-8') const filePath = regionCacheObjectKey( getApiCacheKey(), diff --git a/apps/backend/src/lib/product-image-cache.ts b/apps/backend/src/lib/product-image-cache.ts new file mode 100644 index 0000000..d1451f9 --- /dev/null +++ b/apps/backend/src/lib/product-image-cache.ts @@ -0,0 +1,43 @@ +/** + * Cache-busting for published catalogue images. + * + * Clients (Fresco/Glide/expo-image) key their disk caches on the URL, and R2 + * object keys are permanent: replacing a file under the same key is invisible + * to anyone who already cached the old bytes. `products.json` therefore appends + * a static query so the replaced file gets a new client cache key. + * + * Keep it STATIC. A per-request random value would defeat caching entirely and + * make every card mount re-download its image. Bump the value when the image + * files change. + */ +export const PRODUCT_IMAGE_CACHE_BUST = 'random=1' + +/** Append the cache-busting query to a public asset URL. */ +export function withImageCacheBust(url: string): string { + if (!url) return url + return `${url}${url.includes('?') ? '&' : '?'}${PRODUCT_IMAGE_CACHE_BUST}` +} + +interface CatalogueImages { + products: Array<{ images: string[] }> + tags: Array<{ imageUrl: string | null }> +} + +/** + * Apply the cache-busting query to every image URL carried by the published + * products document (product images and tag images). Everything else is passed + * through untouched. + */ +export function applyImageCacheBust(catalogue: T): T { + return { + ...catalogue, + products: catalogue.products.map((product) => ({ + ...product, + images: (product.images || []).map(withImageCacheBust), + })), + tags: catalogue.tags.map((tag) => ({ + ...tag, + imageUrl: tag.imageUrl ? withImageCacheBust(tag.imageUrl) : tag.imageUrl, + })), + } as T +} diff --git a/apps/backend/tests/api/cache-products.test.ts b/apps/backend/tests/api/cache-products.test.ts index 09ced52..308c88f 100644 --- a/apps/backend/tests/api/cache-products.test.ts +++ b/apps/backend/tests/api/cache-products.test.ts @@ -65,8 +65,11 @@ async function productsVersion(admin: ApiClient): Promise { /** * Read the products document from the scaffold function (test route). * - * This is the exact object the cache writer serialises, read straight from D1, - * so it no longer waits for the CacheCreator debounce or the S3 upload. + * This is the pre-publication object, read straight from D1 so it does not wait + * for the CacheCreator debounce or the S3 upload. The cache writer serialises it + * after applying the image cache-busting query + * (`src/lib/product-image-cache.ts`), so image URLs here deliberately lack the + * `?random=1` suffix. */ async function pollProducts( _admin: ApiClient, diff --git a/apps/backend/tests/unit/product-image-cache.test.ts b/apps/backend/tests/unit/product-image-cache.test.ts new file mode 100644 index 0000000..7d9439e --- /dev/null +++ b/apps/backend/tests/unit/product-image-cache.test.ts @@ -0,0 +1,62 @@ +/** + * Unit tests for the published-catalogue image cache-busting helper + * (`src/lib/product-image-cache.ts`). + * + * Clients key their image disk caches by URL and the R2 object keys never + * change, so the published `products.json` has to carry a different URL after + * an image file is replaced. The value is static on purpose; these tests pin + * that contract so nobody swaps in a per-request random. + */ +import { + PRODUCT_IMAGE_CACHE_BUST, + applyImageCacheBust, + withImageCacheBust, +} from '@/src/lib/product-image-cache' + +const URL = 'https://assets.freshyo.in/product-images/1768718685357-0' + +describe('products.json image cache busting', () => { + it('appends the static query to a plain URL', () => { + expect(withImageCacheBust(URL)).toBe(`${URL}?${PRODUCT_IMAGE_CACHE_BUST}`) + }) + + it('uses & when the URL already carries a query', () => { + expect(withImageCacheBust(`${URL}?foo=1`)).toBe( + `${URL}?foo=1&${PRODUCT_IMAGE_CACHE_BUST}` + ) + }) + + it('leaves an empty URL alone', () => { + expect(withImageCacheBust('')).toBe('') + }) + + it('rewrites product images and tag imageUrl, leaving everything else untouched', () => { + const catalogue = { + count: 1, + products: [{ id: 7, name: 'Coconut', images: [URL, `${URL}?foo=1`] }], + tags: [ + { id: 1, tagName: 'Popular', imageUrl: 'https://assets.freshyo.in/tags/1.png' }, + { id: 2, tagName: 'No image', imageUrl: null }, + ], + } + + const published = applyImageCacheBust(catalogue) + + expect(published.count).toBe(1) + expect(published.products[0].name).toBe('Coconut') + expect(published.products[0].images).toEqual([ + `${URL}?${PRODUCT_IMAGE_CACHE_BUST}`, + `${URL}?foo=1&${PRODUCT_IMAGE_CACHE_BUST}`, + ]) + expect(published.tags[0].imageUrl).toBe( + `https://assets.freshyo.in/tags/1.png?${PRODUCT_IMAGE_CACHE_BUST}` + ) + expect(published.tags[1].imageUrl).toBeNull() + }) + + it('does not mutate the input catalogue', () => { + const catalogue = { products: [{ images: [URL] }], tags: [{ imageUrl: null }] } + applyImageCacheBust(catalogue) + expect(catalogue.products[0].images).toEqual([URL]) + }) +}) diff --git a/apps/user-ui/JEST-TEST-CASES.md b/apps/user-ui/JEST-TEST-CASES.md index cef539f..9d63f43 100644 --- a/apps/user-ui/JEST-TEST-CASES.md +++ b/apps/user-ui/JEST-TEST-CASES.md @@ -301,7 +301,7 @@ Mock `useAllProducts` via `common.essentialConsts` + versioned `products.json` a | HOME-13 | edge | tag has exactly 6 products | no Show More | | HOME-14 | edge | tag has 7 products | Show More; after expand all 7 | | HOME-15 | edge | admin order `productIds` `[5,2]` | cards render in that order | -| HOME-16 | edge | duplicate IDs in tag `productIds` | product rendered once (map semantics) | +| HOME-16 | edge | duplicate IDs in tag `productIds` | first occurrence kept, repeat dropped (one card) | | HOME-17 | edge | unknown ID in tag `productIds` | skipped; no crash | | HOME-18 | edge | out-of-stock product in tag | pushed to the end, admin order preserved within groups | | HOME-19 | edge | `isSlotsLoaded` false and product has no slot | not marked out of stock yet | @@ -1598,6 +1598,8 @@ Covered by HOME-81..98, plus: | STORE-18 | edge | clear already empty | no bump | | STORE-19 | edge | region memory only | no persist | | STORE-20 | edge | same value written twice | map identity preserved (no subscriber wake) | +| STORE-21 | edge | tag selected twice | store identity preserved (no subscriber wake) | +| STORE-22 | edge | resetHomeTags | selection null and expansion empty | ### App helpers @@ -1640,6 +1642,21 @@ Covered by HOME-81..98, plus: | CENTRAL-01 | happy | initializer | product store populated; slot store populated; reconcile runs | | CENTRAL-02 | edge | unmount | hooks clean up/no infinite loop | +### Image cache TTL — `tests/lib/image-cache-ttl.test.tsx` and `image-cache-meta.test.ts` + +| ID | Type | Case and setup | Assertion | +| --- | --- | --- | --- | +| IMGCACHE-01 | edge | missing / zero / NaN timestamp | clears | +| IMGCACHE-02 | edge | younger than 3 days | no clear | +| IMGCACHE-03 | edge | exactly 3 days / older | clears | +| IMGCACHE-04 | edge | future timestamp (clock skew) | clears | +| IMGCACHE-05 | happy | expired on mount | `clearDiskCache` called; timestamp refreshed | +| IMGCACHE-06 | edge | fresh on mount | `clearDiskCache` not called | +| IMGCACHE-07 | error | `clearDiskCache` resolves false | timestamp not written (retries) | +| IMGCACHE-08 | edge | timestamp file missing | reads null | +| IMGCACHE-09 | edge | valid / corrupt / unreadable file | number / null / null | +| IMGCACHE-10 | happy | write timestamp | documentDirectory path + string value | + --- ## 26. Cross-cutting acceptance rules diff --git a/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx b/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx index c53363b..0536451 100755 --- a/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx @@ -30,6 +30,7 @@ import { useUserDetails } from "@/src/contexts/AuthContext"; import TabLayoutWrapper from "@/components/TabLayoutWrapper"; import LocationBar from "@/src/components/LocationBar"; import { useNavigationStore } from "@/src/store/navigationStore"; +import { useHomeTagStore } from "@/src/store/homeTagStore"; import NextOrderGlimpse from "@/components/NextOrderGlimpse"; dayjs.extend(relativeTime); @@ -62,19 +63,6 @@ const staticStyles = { slotsListContent: { paddingBottom: 24 }, } as const; -const TAG_COLORS = [ - { pageBg: '#FFF8F9', bg: '#FFF1F2', border: '#FECDD3', text: '#9F1239', dot: '#E11D48' }, // rose - { pageBg: '#FFFCF1', bg: '#FFFBEB', border: '#FDE68A', text: '#92400E', dot: '#D97706' }, // amber - { pageBg: '#F6FEF9', bg: '#F0FDF4', border: '#BBF7D0', text: '#166534', dot: '#16A34A' }, // green - { pageBg: '#F5FAFF', bg: '#EFF6FF', border: '#BFDBFE', text: '#1E3A8A', dot: '#2563EB' }, // blue - { pageBg: '#FAF8FF', bg: '#F5F3FF', border: '#DDD6FE', text: '#5B21B6', dot: '#7C3AED' }, // violet - { pageBg: '#FFF9F2', bg: '#FFF7ED', border: '#FFD6B0', text: '#9A3412', dot: '#EA580C' }, // orange - { pageBg: '#F3FEFF', bg: '#ECFEFF', border: '#A5F3FC', text: '#155E75', dot: '#0891B2' }, // cyan - { pageBg: '#FFF7FB', bg: '#FDF2F8', border: '#FBCFE8', text: '#9D174D', dot: '#DB2777' }, // pink -]; - -const getTagColor = (id: number) => TAG_COLORS[id % TAG_COLORS.length]; - const RenderStore = memo(({ item }: ListItemProps) => { const router = useRouter(); const { setNavigatedFromHome, setSelectedStoreId } = useNavigationStore(); @@ -192,17 +180,18 @@ const SlotCard = memo(({ slot }: SlotCardProps) => { interface TagTabStripProps { dashboardTags: any[]; - activeTagId: number | null; - onSelectTag: (id: number) => void; } // Fixed, horizontally scrollable tab strip (plain ScrollView — no nesting, // so it scrolls reliably on Android). Sits OUTSIDE the vertical FlatList. const TagTabStrip = memo(({ dashboardTags, - activeTagId, - onSelectTag, }: TagTabStripProps) => { + // Selection is read here, not in Dashboard: a tap must not re-render the + // page (see homeTagStore). + const selectedTagId = useHomeTagStore((state) => state.selectedTagId); + const selectTag = useHomeTagStore((state) => state.selectTag); + const activeTagId = selectedTagId ?? dashboardTags[0]?.id ?? null; const scrollRef = useRef(null); const positions = useRef([]); @@ -243,7 +232,7 @@ const TagTabStrip = memo(({ onLayout={(e: any) => { positions.current[i] = e.nativeEvent.layout.x; }} - onPress={() => onSelectTag(Number(route.key))} + onPress={() => selectTag(Number(route.key))} style={tw`h-12 px-3 justify-center`} activeOpacity={0.7} > @@ -278,10 +267,7 @@ const TagTabStrip = memo(({ interface TagSceneProps { dashboardTags: any[]; - activeTagId: number | null; productsByTagId: Record; - expandedByTagId: Record; - onToggleExpand: (tagId: number) => void; onProductPress: (id: number) => void; } @@ -289,17 +275,21 @@ interface TagSceneProps { // scrolls with the page. const TagScene = memo(({ dashboardTags, - activeTagId, productsByTagId, - expandedByTagId, - onToggleExpand, onProductPress, }: TagSceneProps) => { - const tagId = activeTagId ?? dashboardTags[0]?.id ?? null; + const selectedTagId = useHomeTagStore((state) => state.selectedTagId); + const tagId = selectedTagId ?? dashboardTags[0]?.id ?? null; + // One boolean selector per tag, so expanding another tag does not re-render + // this scene (or anything above it). + const expanded = useHomeTagStore((state) => + tagId == null ? false : !!state.expandedByTagId[tagId] + ); + const expandTag = useHomeTagStore((state) => state.expandTag); + if (tagId == null) return null; const products = productsByTagId[tagId] || []; - const expanded = !!expandedByTagId[tagId]; const visible = expanded ? products : products.slice(0, 6); const hasMore = products.length > 6 && !expanded; @@ -323,7 +313,7 @@ const TagScene = memo(({ testID={`tag-show-more-${tagId}`} style={tw`self-center mt-1 mb-2 px-5 py-2.5 rounded-full bg-brand500 shadow-sm`} activeOpacity={0.85} - onPress={() => onToggleExpand(tagId)} + onPress={() => expandTag(tagId)} > Show More @@ -375,20 +365,18 @@ const ProductItem = memo(({ item, onPress }: ProductItemProps) => { ); }); -interface ListHeaderProps extends TagSceneProps { - onSelectTag: (id: number) => void; +interface ListHeaderProps { + dashboardTags: any[]; + productsByTagId: Record; + onProductPress: (id: number) => void; storesData: any; sortedSlots: any[]; } const ListHeader = memo(({ dashboardTags, - activeTagId, productsByTagId, - expandedByTagId, - onToggleExpand, onProductPress, - onSelectTag, storesData, sortedSlots, }: ListHeaderProps) => { @@ -402,11 +390,7 @@ const ListHeader = memo(({ {dashboardTags.length > 0 && ( - + )} {dashboardTags.length > 0 && ( @@ -520,16 +501,51 @@ export default function Dashboard() { const { data: storesData, refetch: refetchStores } = useStores(); const { data: slotsData } = useSlots(); - const products = productsData?.products || []; - const dashboardTags = productsData?.tags || []; + // Single source of truth for the catalogue: `products` and `dashboardTags` + // come out of this memo together with the per-tag rows, so the screen never + // holds two views of the same payload that can drift apart. + const { dashboardTags, products, productsByTagId } = useMemo(() => { + const dashboardTags = productsData?.tags ?? []; + const products = productsData?.products ?? []; - const [selectedTagId, setSelectedTagId] = useState(null); - const activeTagId = selectedTagId ?? dashboardTags[0]?.id ?? null; - const [expandedByTagId, setExpandedByTagId] = useState>({}); - const handleToggleExpand = useCallback((tagId: number) => { - setExpandedByTagId((prev) => ({ ...prev, [tagId]: true })); - }, []); + // Hoisted: the old version rebuilt this Map once per tag. + const productById = new Map(); + for (const product of products) { + productById.set(product.id, product); + } + const map: Record = {}; + for (const tag of dashboardTags) { + // Respect the admin-curated order — tag.productIds is already ordered by + // the tag's sortOrder (backend reorders it when building the cache). + // Unknown ids are skipped and a repeated id only renders once. + const ordered: any[] = []; + const seen = new Set(); + for (const id of tag.productIds || []) { + if (seen.has(id)) continue; + seen.add(id); + const product = productById.get(id); + if (product) ordered.push(product); + } + + // Out-of-stock items are pushed to the end, preserving their relative order. + const inStock: any[] = []; + const outOfStock: any[] = []; + for (const product of ordered) { + const isOut = + Boolean(productSlotsMap[product.id]?.isOutOfStock) || + (isSlotsLoaded && !getQuickestSlot(product.id)); + if (isOut) outOfStock.push(product); + else inStock.push(product); + } + map[tag.id] = [...inStock, ...outOfStock]; + } + + return { dashboardTags, products, productsByTagId: map }; + }, [productsData, productSlotsMap, isSlotsLoaded, getQuickestSlot]); + + // Tag selection/expansion live in homeTagStore (subscribed by TagTabStrip and + // TagScene), so a tap does not re-render Dashboard or rebuild the list below. React.useEffect(() => { if (products.length === 0) { @@ -555,7 +571,7 @@ export default function Dashboard() { setDisplayedProducts(allSorted) setVisibleCount(21) setHasMore(allSorted.length > 21) - }, [productsData, productSlotsMap]); + }, [products, productSlotsMap]); const handleShowMore = useCallback(() => { setVisibleCount((prev) => { @@ -577,35 +593,6 @@ export default function Dashboard() { }); }, [slotsData]); - const productsByTagId = useMemo(() => { - const map: Record = {}; - for (const tag of dashboardTags) { - const productById = new Map(); - for (const product of products) { - productById.set(product.id, product); - } - - // Respect the admin-curated order — tag.productIds is already ordered by - // the tag's sortOrder (backend reorders it when building the cache). - // Out-of-stock items are pushed to the end, preserving their relative order. - const ordered = (tag.productIds || []) - .map((id: number) => productById.get(id)) - .filter(Boolean) as any[]; - - const inStock: any[] = []; - const outOfStock: any[] = []; - for (const product of ordered) { - const isOut = - Boolean(productSlotsMap[product.id]?.isOutOfStock) || - (isSlotsLoaded && !getQuickestSlot(product.id)); - if (isOut) outOfStock.push(product); - else inStock.push(product); - } - map[tag.id] = [...inStock, ...outOfStock]; - } - return map; - }, [dashboardTags, products, productSlotsMap, getQuickestSlot, isSlotsLoaded]); - const handleRefresh = useCallback(async () => { setIsRefreshing(true); try { @@ -647,30 +634,26 @@ export default function Dashboard() { // ), [handleProductPress]); - const pageTint = activeTagId == null ? '#FFFFFF' : getTagColor(activeTagId).pageBg; + // The page background stays white (the per-tag tint was never enabled). const pageTintStyle = useMemo(() => [ tw`flex-1`, { backgroundColor: '#FFFFFF' } - ], [pageTint]); + ], []); const searchBarContainerStyle = useMemo(() => [ tw`w-full px-4 pt-4 pb-0`, { backgroundColor: '#FFFFFF' } - ], [pageTint]); + ], []); const listHeader = useMemo(() => ( - ), [dashboardTags, activeTagId, productsByTagId, expandedByTagId, handleToggleExpand, handleProductPress, storesData, sortedSlots]); + ), [dashboardTags, productsByTagId, handleProductPress, storesData, sortedSlots]); const listContentContainerStyle = useMemo(() => [ tw`pb-24`, diff --git a/apps/user-ui/app/_layout.tsx b/apps/user-ui/app/_layout.tsx index fb2c819..edaffb9 100755 --- a/apps/user-ui/app/_layout.tsx +++ b/apps/user-ui/app/_layout.tsx @@ -22,6 +22,7 @@ import FirstUserWrapper from "@/components/FirstUserWrapper"; import HealthTestWrapper from "@/components/HealthTestWrapper"; import UpdateChecker from "@/components/UpdateChecker"; import CentralStoreInitializer from "@/src/components/CentralStoreInitializer"; +import ImageCacheTtl from "@/src/components/ImageCacheTtl"; import { RefreshProvider } from "../../../packages/ui/src/lib/refresh-context"; import WebViewWrapper from "@/components/WebViewWrapper"; import BackHandlerWrapper from "@/components/BackHandler"; @@ -82,6 +83,7 @@ export default function RootLayout() { + diff --git a/apps/user-ui/components/ProductCard.tsx b/apps/user-ui/components/ProductCard.tsx index 333521f..546fed8 100644 --- a/apps/user-ui/components/ProductCard.tsx +++ b/apps/user-ui/components/ProductCard.tsx @@ -15,7 +15,6 @@ import { import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier'; import { useCartStore } from '@/src/store/cartStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; -import { Image as RnImage } from 'react-native' import { useRenderProbe } from '@/src/lib/render-probe' @@ -185,22 +184,24 @@ const ProductCard: React.FC = ({ activeOpacity={0.9} > - { setImageStatus('loading') setImageError(null) }} - // onLoadEnd={() => { - // setImageError('loading stopped indefinitely') - // - // }} onLoad={() => setImageStatus('loaded')} onError={(event) => { setImageStatus('error') - setImageError( 'Image failed to load') + setImageError(event?.error || 'Image failed to load') }} /> diff --git a/apps/user-ui/eas.json b/apps/user-ui/eas.json index 98353ed..172de20 100755 --- a/apps/user-ui/eas.json +++ b/apps/user-ui/eas.json @@ -21,7 +21,11 @@ "shafi-dev": { "distribution": "internal", "channel": "shafi-dev", - "autoIncrement": true + "autoIncrement": true, + "android": { + "buildType": "apk", + "gradleCommand": ":app:assembleRelease -PreactNativeArchitectures=arm64-v8a -Pandroid.enableProguardInReleaseBuilds=true" + } }, "production": { "autoIncrement": true, diff --git a/apps/user-ui/hooks/useProductSlotIdentifier.ts b/apps/user-ui/hooks/useProductSlotIdentifier.ts index 69b29ea..275e4f9 100644 --- a/apps/user-ui/hooks/useProductSlotIdentifier.ts +++ b/apps/user-ui/hooks/useProductSlotIdentifier.ts @@ -1,3 +1,4 @@ +import { useCallback } from 'react'; import dayjs from 'dayjs'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; @@ -6,19 +7,21 @@ export function useProductSlotIdentifier() { const slots = useCentralSlotStore((state) => state.slots); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); - const getQuickestSlot = (productId: number): number | null => { + // Memoised: a fresh function every render invalidates every memo that lists + // it as a dependency (the home catalogue map included), so it never settles. + const getQuickestSlot = useCallback((productId: number): number | null => { if (!slots?.length) return null; - + const now = dayjs(); const productInfo = productSlotsMap[productId]; - + if (!productInfo?.slots?.length) return null; - + // Find slots that contain this product and have future delivery time const availableSlots = productInfo.slots.filter((slot: any) => dayjs(slot.deliveryTime).isAfter(now) ); - + if (availableSlots.length === 0) return null; // Return earliest slot ID (sorted by delivery time) @@ -27,7 +30,7 @@ export function useProductSlotIdentifier() { )[0]; return earliestSlot.id; - }; + }, [slots, productSlotsMap]); return { getQuickestSlot, productSlotsMap }; } diff --git a/apps/user-ui/src/components/ImageCacheTtl.tsx b/apps/user-ui/src/components/ImageCacheTtl.tsx new file mode 100644 index 0000000..4d016ee --- /dev/null +++ b/apps/user-ui/src/components/ImageCacheTtl.tsx @@ -0,0 +1,50 @@ +import * as React from 'react' +import { AppState } from 'react-native' +import { Image } from 'expo-image' +import { + readImageCacheClearedAt, + writeImageCacheClearedAt, +} from '@/src/lib/image-cache-meta' +import { shouldClearImageCache } from '@/src/lib/image-cache-ttl' + +// One clear at a time: the mount effect and a foreground transition can race. +let clearing = false + +async function clearDiskCacheIfExpired(): Promise { + if (clearing) return + clearing = true + try { + const lastClearedAt = await readImageCacheClearedAt() + if (!shouldClearImageCache(lastClearedAt)) return + + // Resolves false on web / when the activity is gone; keep the old timestamp + // in that case so the next foreground retries instead of waiting 3 days. + const cleared = await Image.clearDiskCache() + if (cleared !== false) { + await writeImageCacheClearedAt(Date.now()) + } + } catch { + // Cache maintenance must never block startup. + } finally { + clearing = false + } +} + +/** + * Keeps expo-image's disk cache at most three days old. Mounted once at the + * root; re-checks whenever the app returns to the foreground (the app can stay + * in memory for weeks without a cold start). + */ +export default function ImageCacheTtl() { + React.useEffect(() => { + void clearDiskCacheIfExpired() + + const subscription = AppState.addEventListener('change', (state) => { + if (state === 'active') void clearDiskCacheIfExpired() + }) + + return () => subscription.remove() + }, []) + + return null +} diff --git a/apps/user-ui/src/lib/image-cache-meta.ts b/apps/user-ui/src/lib/image-cache-meta.ts new file mode 100644 index 0000000..700c4bd --- /dev/null +++ b/apps/user-ui/src/lib/image-cache-meta.ts @@ -0,0 +1,41 @@ +import * as FileSystem from 'expo-file-system' +import { IMAGE_CACHE_CLEARED_AT_KEY } from '@/src/lib/image-cache-ttl' + +/** + * Plain-file persistence for the image cache TTL timestamp. + * + * Deliberately not StorageServiceCasual: that writes to expo-secure-store, and + * a cache-maintenance timestamp is not a secret. expo-file-system ships as a + * dependency of `expo`, so no extra package is needed. + * + * The document directory survives app restarts and updates (but not a + * reinstall, which also clears the image cache — exactly what we want). + */ +function timestampFileUri(): string | null { + if (!FileSystem.documentDirectory) return null + return `${FileSystem.documentDirectory}${IMAGE_CACHE_CLEARED_AT_KEY}` +} + +/** Epoch ms of the last successful disk-cache clear, or null when unknown. */ +export async function readImageCacheClearedAt(): Promise { + const uri = timestampFileUri() + if (!uri) return null + + try { + const info = await FileSystem.getInfoAsync(uri) + if (!info.exists) return null + + const raw = await FileSystem.readAsStringAsync(uri) + const parsed = Number(raw) + return Number.isFinite(parsed) ? parsed : null + } catch { + return null + } +} + +/** Persist the last successful clear. Throws so the caller can retry later. */ +export async function writeImageCacheClearedAt(timestamp: number): Promise { + const uri = timestampFileUri() + if (!uri) return + await FileSystem.writeAsStringAsync(uri, String(timestamp)) +} diff --git a/apps/user-ui/src/lib/image-cache-ttl.ts b/apps/user-ui/src/lib/image-cache-ttl.ts new file mode 100644 index 0000000..7adfcd8 --- /dev/null +++ b/apps/user-ui/src/lib/image-cache-ttl.ts @@ -0,0 +1,32 @@ +/** + * TTL for expo-image's persistent disk cache. + * + * expo-image has no per-entry expiry (cachePolicy is only none/disk/memory/ + * memory-disk, and the native caches are LRU), so the only way to bound the age + * of a cached image is to clear the disk cache periodically. Clearing every + * three days makes three days the maximum age of any cached image. + */ +export const IMAGE_CACHE_TTL_MS = 3 * 24 * 60 * 60 * 1000 + +/** StorageServiceCasual key holding the epoch ms of the last successful clear. */ +export const IMAGE_CACHE_CLEARED_AT_KEY = 'image_cache_cleared_at' + +/** + * True when the disk cache is due for a clear. A missing, invalid or future + * timestamp (clock skew) clears too: we cannot prove the cache is fresh. + */ +export function shouldClearImageCache( + lastClearedAt: number | null, + now: number = Date.now() +): boolean { + if ( + lastClearedAt == null || + !Number.isFinite(lastClearedAt) || + lastClearedAt <= 0 || + lastClearedAt > now + ) { + return true + } + + return now - lastClearedAt >= IMAGE_CACHE_TTL_MS +} diff --git a/apps/user-ui/src/lib/region-switch.ts b/apps/user-ui/src/lib/region-switch.ts index e9aa79c..b1d7c85 100644 --- a/apps/user-ui/src/lib/region-switch.ts +++ b/apps/user-ui/src/lib/region-switch.ts @@ -10,6 +10,7 @@ import { useCentralProductStore } from '@/src/store/centralProductStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useSlotStore } from '@/components/stores/slotStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' +import { useHomeTagStore } from '@/src/store/homeTagStore' /** * The one and only way to change the browsing region. @@ -53,6 +54,10 @@ export async function confirmRegionSwitch( useFlashCartStore.getState().clearAddedFlashProduct() useFlashNavigationStore.getState().reset() + // Tag ids belong to the outgoing region; a stale selection would point at a + // tag the new catalog does not have. + useHomeTagStore.getState().resetHomeTags() + // 3. Drop cached regional catalog/slot snapshots so they cannot leak across. const productStore = useCentralProductStore.getState() productStore.setProducts([]) diff --git a/apps/user-ui/src/lib/render-probe.tsx b/apps/user-ui/src/lib/render-probe.tsx index 8e76c44..945bfaa 100644 --- a/apps/user-ui/src/lib/render-probe.tsx +++ b/apps/user-ui/src/lib/render-probe.tsx @@ -52,10 +52,10 @@ export function useRenderProbe(label: string) { ts: now, } - console.log( - `[render-probe] component=${label} renders=${summary.renders}/${summary.elapsed}ms ` + - `(~${summary.perSecond}/s)${suspicious}` - ) + // console.log( + // `[render-probe] component=${label} renders=${summary.renders}/${summary.elapsed}ms ` + + // `(~${summary.perSecond}/s)${suspicious}` + // ) fetch(PROBE_ENDPOINT, { method: 'POST', @@ -109,10 +109,10 @@ export default function RenderCommitProbe({ children }: { children: React.ReactN ts: now, } - console.log( - `[render-probe] path=${summary.path} commits=${summary.commits}/${summary.elapsed}ms ` + - `(~${summary.perSecond}/s) last=${summary.phase} ${summary.duration}ms${suspicious}` - ) + // console.log( + // `[render-probe] path=${summary.path} commits=${summary.commits}/${summary.elapsed}ms ` + + // `(~${summary.perSecond}/s) last=${summary.phase} ${summary.duration}ms${suspicious}` + // ) fetch(PROBE_ENDPOINT, { method: 'POST', diff --git a/apps/user-ui/src/store/homeTagStore.ts b/apps/user-ui/src/store/homeTagStore.ts new file mode 100644 index 0000000..8631266 --- /dev/null +++ b/apps/user-ui/src/store/homeTagStore.ts @@ -0,0 +1,38 @@ +import { create } from 'zustand' + +interface HomeTagState { + /** User-picked tag; null means "first dashboard tag". */ + selectedTagId: number | null + expandedByTagId: Record + selectTag: (tagId: number) => void + expandTag: (tagId: number) => void + resetHomeTags: () => void +} + +/** + * Home tag selection lives outside Dashboard on purpose: while it was local + * state, every tap re-rendered Dashboard, which rebuilt ListHeader and the + * SectionList rows, re-rendering the whole page. Only TagTabStrip and TagScene + * subscribe here, so a tap updates just those two. + */ +export const useHomeTagStore = create((set) => ({ + selectedTagId: null, + expandedByTagId: {}, + + // No-op when unchanged: re-selecting the active tag must not wake + // subscribers (same guard as appStore.setHideTabsNavKey). + selectTag: (tagId) => + set((state) => + state.selectedTagId === tagId ? state : { selectedTagId: tagId } + ), + + expandTag: (tagId) => + set((state) => + state.expandedByTagId[tagId] + ? state + : { expandedByTagId: { ...state.expandedByTagId, [tagId]: true } } + ), + + // Tag ids are region-scoped, so a region switch has to drop both. + resetHomeTags: () => set({ selectedTagId: null, expandedByTagId: {} }), +})) diff --git a/apps/user-ui/tests/helpers/reset.ts b/apps/user-ui/tests/helpers/reset.ts index dd0cc74..6ddb26f 100644 --- a/apps/user-ui/tests/helpers/reset.ts +++ b/apps/user-ui/tests/helpers/reset.ts @@ -25,6 +25,7 @@ import { useRegionStore } from '@/src/store/regionStore' import { useLocationStore } from '@/src/store/locationStore' import { useSlotStore } from '@/components/stores/slotStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' +import { useHomeTagStore } from '@/src/store/homeTagStore' export function resetStores() { useAppStore.setState({ hideTabsNav: {} }) @@ -54,6 +55,7 @@ export function resetStores() { }) useSlotStore.setState({ slotId: undefined, storeId: undefined }) useFlashNavigationStore.setState({ shouldNavigateToCart: false }) + useHomeTagStore.setState({ selectedTagId: null, expandedByTagId: {} }) useLocationStore.getState().stop() useLocationStore.setState({ coords: null, status: 'idle', error: null }) } diff --git a/apps/user-ui/tests/jest.config.js b/apps/user-ui/tests/jest.config.js index e254804..b4d6e4e 100644 --- a/apps/user-ui/tests/jest.config.js +++ b/apps/user-ui/tests/jest.config.js @@ -68,6 +68,7 @@ module.exports = { '^expo-router$': '/mocks/native/expo-router.tsx', '^expo-router/(.*)$': '/mocks/native/expo-router.tsx', '^expo-image$': '/mocks/native/common.tsx', + '^expo-file-system$': '/mocks/native/common.tsx', '^expo-linear-gradient$': '/mocks/native/common.tsx', '^expo-blur$': '/mocks/native/common.tsx', '^expo-status-bar$': '/mocks/native/common.tsx', diff --git a/apps/user-ui/tests/lib/image-cache-meta.test.ts b/apps/user-ui/tests/lib/image-cache-meta.test.ts new file mode 100644 index 0000000..a648e55 --- /dev/null +++ b/apps/user-ui/tests/lib/image-cache-meta.test.ts @@ -0,0 +1,58 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * IMGCACHE-08..10 — the plain-file timestamp used by the 3-day image cache TTL. + * + * expo-file-system is mocked; this pins the read/write contract and the + * fallbacks (missing file, corrupt content) without touching native storage. + */ +import * as FileSystem from 'expo-file-system' +import { + readImageCacheClearedAt, + writeImageCacheClearedAt, +} from '@/src/lib/image-cache-meta' +import { IMAGE_CACHE_CLEARED_AT_KEY } from '@/src/lib/image-cache-ttl' + +jest.mock('expo-file-system', () => ({ + documentDirectory: 'file:///documents/', + getInfoAsync: jest.fn(), + readAsStringAsync: jest.fn(), + writeAsStringAsync: jest.fn(async () => undefined), +})) + +const getInfoAsync = FileSystem.getInfoAsync as unknown as jest.Mock +const readAsStringAsync = FileSystem.readAsStringAsync as unknown as jest.Mock +const writeAsStringAsync = FileSystem.writeAsStringAsync as unknown as jest.Mock + +const FILE_URI = `file:///documents/${IMAGE_CACHE_CLEARED_AT_KEY}` + +describe('image cache timestamp file', () => { + beforeEach(() => { + jest.clearAllMocks() + }) + + it('IMGCACHE-08: a missing file reads as null', async () => { + getInfoAsync.mockResolvedValue({ exists: false }) + + await expect(readImageCacheClearedAt()).resolves.toBeNull() + expect(readAsStringAsync).not.toHaveBeenCalled() + }) + + it('IMGCACHE-09: valid content parses and corrupt content reads as null', async () => { + getInfoAsync.mockResolvedValue({ exists: true }) + + readAsStringAsync.mockResolvedValueOnce('1700000000000') + await expect(readImageCacheClearedAt()).resolves.toBe(1700000000000) + + readAsStringAsync.mockResolvedValueOnce('not-a-number') + await expect(readImageCacheClearedAt()).resolves.toBeNull() + + readAsStringAsync.mockRejectedValueOnce(new Error('io')) + await expect(readImageCacheClearedAt()).resolves.toBeNull() + }) + + it('IMGCACHE-10: writing stores the timestamp under the document directory', async () => { + await writeImageCacheClearedAt(1700000000123) + + expect(writeAsStringAsync).toHaveBeenCalledWith(FILE_URI, '1700000000123') + }) +}) diff --git a/apps/user-ui/tests/lib/image-cache-ttl.test.tsx b/apps/user-ui/tests/lib/image-cache-ttl.test.tsx new file mode 100644 index 0000000..0fb5555 --- /dev/null +++ b/apps/user-ui/tests/lib/image-cache-ttl.test.tsx @@ -0,0 +1,98 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * IMGCACHE-01..07 — the 3-day TTL for expo-image's disk cache. + * + * Helper boundaries (01..04) and the mounted component (05..07). The timestamp + * file helper is mocked here; its own file-system plumbing is covered in + * `image-cache-meta.test.ts`. + */ +import * as React from 'react' +import { render, waitFor } from '@testing-library/react-native' +import { Image } from 'expo-image' + +import ImageCacheTtl from '@/src/components/ImageCacheTtl' +import { IMAGE_CACHE_TTL_MS, shouldClearImageCache } from '@/src/lib/image-cache-ttl' +import { + readImageCacheClearedAt, + writeImageCacheClearedAt, +} from '@/src/lib/image-cache-meta' + +import { resetAllMocks } from '../helpers/reset' + +jest.mock('@/src/lib/image-cache-meta', () => ({ + readImageCacheClearedAt: jest.fn(), + writeImageCacheClearedAt: jest.fn(async () => undefined), +})) + +const readClearedAt = readImageCacheClearedAt as unknown as jest.Mock +const writeClearedAt = writeImageCacheClearedAt as unknown as jest.Mock +const clearDiskCache = Image.clearDiskCache as unknown as jest.Mock + +describe('image cache TTL', () => { + beforeEach(() => { + resetAllMocks() + readClearedAt.mockReset() + writeClearedAt.mockReset() + writeClearedAt.mockResolvedValue(undefined) + }) + + it('IMGCACHE-01: a missing, zero or invalid timestamp clears', () => { + expect(shouldClearImageCache(null)).toBe(true) + expect(shouldClearImageCache(0)).toBe(true) + expect(shouldClearImageCache(Number.NaN)).toBe(true) + }) + + it('IMGCACHE-02: a timestamp younger than three days keeps the cache', () => { + const now = Date.now() + expect(shouldClearImageCache(now - IMAGE_CACHE_TTL_MS + 1, now)).toBe(false) + expect(shouldClearImageCache(now - 1000, now)).toBe(false) + }) + + it('IMGCACHE-03: exactly three days (or older) clears', () => { + const now = Date.now() + expect(shouldClearImageCache(now - IMAGE_CACHE_TTL_MS, now)).toBe(true) + expect(shouldClearImageCache(now - IMAGE_CACHE_TTL_MS - 1000, now)).toBe(true) + }) + + it('IMGCACHE-04: a future timestamp (clock skew) clears', () => { + const now = Date.now() + expect(shouldClearImageCache(now + 60_000, now)).toBe(true) + }) + + it('IMGCACHE-05: an expired cache is cleared and the timestamp is refreshed', async () => { + readClearedAt.mockResolvedValue(Date.now() - IMAGE_CACHE_TTL_MS - 1000) + + const view = render() + + await waitFor(() => expect(clearDiskCache).toHaveBeenCalledTimes(1)) + await waitFor(() => expect(writeClearedAt).toHaveBeenCalledTimes(1)) + expect(writeClearedAt.mock.calls[0][0]).toBeGreaterThan(Date.now() - 5000) + + view.unmount() + }) + + it('IMGCACHE-06: a fresh cache is left alone', async () => { + readClearedAt.mockResolvedValue(Date.now() - 1000) + + const view = render() + + await waitFor(() => expect(readClearedAt).toHaveBeenCalled()) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(clearDiskCache).not.toHaveBeenCalled() + expect(writeClearedAt).not.toHaveBeenCalled() + + view.unmount() + }) + + it('IMGCACHE-07: a failed clear does not persist a timestamp (retries next time)', async () => { + readClearedAt.mockResolvedValue(null) + clearDiskCache.mockResolvedValueOnce(false) + + const view = render() + + await waitFor(() => expect(clearDiskCache).toHaveBeenCalledTimes(1)) + expect(writeClearedAt).not.toHaveBeenCalled() + + view.unmount() + }) +}) diff --git a/apps/user-ui/tests/lib/stores.test.ts b/apps/user-ui/tests/lib/stores.test.ts index f723278..d65be8b 100644 --- a/apps/user-ui/tests/lib/stores.test.ts +++ b/apps/user-ui/tests/lib/stores.test.ts @@ -21,6 +21,7 @@ import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useRegionStore } from '@/src/store/regionStore' import { useSlotStore } from '@/components/stores/slotStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' +import { useHomeTagStore } from '@/src/store/homeTagStore' import { AVAILABILITY, MERGED_PRODUCTS, @@ -60,6 +61,27 @@ describe('stores', () => { expect(useAppStore.getState().hideTabsNav).toBe(hidden) }) + it('STORE-21: re-selecting the active tag keeps the store identity', () => { + useHomeTagStore.getState().selectTag(5) + const before = useHomeTagStore.getState() + + useHomeTagStore.getState().selectTag(5) + + // Same state object, so TagTabStrip/TagScene are not woken. + expect(useHomeTagStore.getState()).toBe(before) + }) + + it('STORE-22: resetHomeTags clears the selection and every expansion', () => { + useHomeTagStore.getState().selectTag(5) + useHomeTagStore.getState().expandTag(5) + useHomeTagStore.getState().expandTag(9) + + useHomeTagStore.getState().resetHomeTags() + + expect(useHomeTagStore.getState().selectedTagId).toBeNull() + expect(useHomeTagStore.getState().expandedByTagId).toEqual({}) + }) + it('STORE-02: addressStore selects and clears an address id', () => { useAddressStore.getState().setSelectedAddressId(11) expect(useAddressStore.getState().selectedAddressId).toBe(11) diff --git a/apps/user-ui/tests/mocks/native/common.tsx b/apps/user-ui/tests/mocks/native/common.tsx index f2e26d6..a566018 100644 --- a/apps/user-ui/tests/mocks/native/common.tsx +++ b/apps/user-ui/tests/mocks/native/common.tsx @@ -9,14 +9,27 @@ import * as React from 'react' import { View } from 'react-native' /* expo-image */ -export const Image = ({ testID, source, ...props }: any) => +const ImageComponent = ({ testID, source, ...props }: any) => React.createElement(View, { ...props, testID: testID ?? 'expo-image', accessibilityLabel: typeof source === 'object' ? source?.uri : undefined, }) + +export const Image = Object.assign(ImageComponent, { + clearDiskCache: jest.fn(async () => true), + clearMemoryCache: jest.fn(async () => true), + prefetch: jest.fn(async () => true), +}) export const ImageBackground = Image +/* expo-file-system */ +export const documentDirectory = 'file:///documents/' +export const getInfoAsync = jest.fn(async () => ({ exists: false })) +export const readAsStringAsync = jest.fn(async () => '') +export const writeAsStringAsync = jest.fn(async () => undefined) +export const deleteAsync = jest.fn(async () => undefined) + /* expo-linear-gradient */ export const LinearGradient = ({ children, testID, ...props }: any) => React.createElement(View, { ...props, testID: testID ?? 'linear-gradient' }, children) diff --git a/apps/user-ui/tests/pages/home.test.tsx b/apps/user-ui/tests/pages/home.test.tsx index 2bd0b1b..bf8d672 100644 --- a/apps/user-ui/tests/pages/home.test.tsx +++ b/apps/user-ui/tests/pages/home.test.tsx @@ -16,7 +16,6 @@ import * as React from 'react' import { Alert, DeviceEventEmitter, - Image, Linking, SectionList, StyleSheet, @@ -485,14 +484,13 @@ describe('Home (HOME)', () => { expect(idsFrom(getAllByTestId(/^tag-product-/), 'tag-product-')).toEqual([5, 2]) }) - it('HOME-16: duplicate ids in a tag productIds are rendered once (current: map keeps them)', async () => { - // Current gap: productsByTagId maps productIds without de-duplicating, so a - // repeated id renders the card twice. Pinned until the map deduplicates. + it('HOME-16: duplicate ids in a tag productIds are rendered once', async () => { setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts([2, 2, 5])])) const { getAllByTestId } = await renderHome() - expect(getAllByTestId('tag-product-2')).toHaveLength(2) - expect(getAllByTestId(/^tag-product-/)).toHaveLength(3) + // The first occurrence keeps its curated position; the repeat is dropped. + expect(getAllByTestId('tag-product-2')).toHaveLength(1) + expect(idsFrom(getAllByTestId(/^tag-product-/), 'tag-product-')).toEqual([2, 5]) }) it('HOME-17: an unknown id in a tag productIds is skipped', async () => { @@ -724,7 +722,7 @@ describe('Home (HOME)', () => { const { getByTestId } = await renderHome() const card = within(getByTestId('product-item-2')) - fireEvent(card.UNSAFE_getByType(Image), 'error') + fireEvent(card.getByTestId('expo-image'), 'error') expect(card.getByText('Image failed to load')).toBeTruthy() }) diff --git a/apps/user-ui/user-ui-shafi-dev-arm.apk b/apps/user-ui/user-ui-shafi-dev-arm.apk new file mode 100644 index 0000000..7dc48cb Binary files /dev/null and b/apps/user-ui/user-ui-shafi-dev-arm.apk differ diff --git a/apps/web-ui/src/lib/region-switch.ts b/apps/web-ui/src/lib/region-switch.ts index c351fbb..14ee7f6 100644 --- a/apps/web-ui/src/lib/region-switch.ts +++ b/apps/web-ui/src/lib/region-switch.ts @@ -10,6 +10,7 @@ import { useCentralProductStore } from './stores/central-product-store' import { useCentralSlotStore } from './stores/central-slot-store' import { useSlotStore } from './stores/slot-store' import { useFlashNavigationStore } from './stores/flash-navigation-store' +import { useHomeTagStore } from './stores/home-tag-store' /** * The one and only way to change the browsing region. @@ -50,6 +51,10 @@ export async function confirmRegionSwitch( useFlashCartStore.getState().setAddedFlashProduct(null) useFlashNavigationStore.getState().setShouldNavigateToCart(false) + // Tag ids belong to the outgoing region; a stale selection would point at a + // tag the new catalog does not have. + useHomeTagStore.getState().resetHomeTags() + // 3. Drop cached regional catalog/slot snapshots so they cannot leak across. const productStore = useCentralProductStore.getState() productStore.setProducts([]) diff --git a/apps/web-ui/src/lib/stores/home-tag-store.ts b/apps/web-ui/src/lib/stores/home-tag-store.ts new file mode 100644 index 0000000..5f58ee8 --- /dev/null +++ b/apps/web-ui/src/lib/stores/home-tag-store.ts @@ -0,0 +1,34 @@ +import { create } from 'zustand' + +interface HomeTagState { + /** User-picked tag; null means "first dashboard tag". */ + selectedTagId: number | null + expandedByTagId: Record + selectTag: (tagId: number) => void + expandTag: (tagId: number) => void + resetHomeTags: () => void +} + +/** + * Mirrors apps/user-ui/src/store/homeTagStore.ts. The web home is a single + * component, so it subscribes to the selection directly; the store still keeps + * the state shape and reset behaviour identical to the native app. + */ +export const useHomeTagStore = create((set) => ({ + selectedTagId: null, + expandedByTagId: {}, + + selectTag: (tagId) => + set((state) => + state.selectedTagId === tagId ? state : { selectedTagId: tagId } + ), + + expandTag: (tagId) => + set((state) => + state.expandedByTagId[tagId] + ? state + : { expandedByTagId: { ...state.expandedByTagId, [tagId]: true } } + ), + + resetHomeTags: () => set({ selectedTagId: null, expandedByTagId: {} }), +})) diff --git a/apps/web-ui/src/routes/home.index.tsx b/apps/web-ui/src/routes/home.index.tsx index 6391ac6..7e0d294 100644 --- a/apps/web-ui/src/routes/home.index.tsx +++ b/apps/web-ui/src/routes/home.index.tsx @@ -14,6 +14,7 @@ import { AppLayout } from '../components/AppLayout' import { ProductCard } from '../components/ProductCard' import AddToCartDialog from '../components/AddToCartDialog' import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier' +import { useHomeTagStore } from '../lib/stores/home-tag-store' import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores' import { Store, ImageOff, Loader2, Clock, Truck } from 'lucide-react' @@ -102,17 +103,56 @@ function HomePage() { const stores = storesData?.stores || [] // const banners = bannersData?.banners || [] - const allProducts = productsData?.products || [] const slots = slotsData?.slots || [] - // Explore Products tabs — tags in tagsOrder, products in per-tag sortOrder - const dashboardTags = productsData?.tags || [] - const [selectedTagId, setSelectedTagId] = useState(null) + // Single source of truth for the catalogue (mirrors user-ui home): the tags, + // the full product list and the per-tag rows all come out of one memo. + const { dashboardTags, allProducts, productsByTagId } = useMemo(() => { + const dashboardTags = productsData?.tags || [] + const allProducts = productsData?.products || [] + + // Hoisted: the old version rebuilt this Map once per tag. + const productById = new Map() + for (const product of allProducts) { + productById.set(product.id, product) + } + + const map: Record = {} + for (const tag of dashboardTags) { + // tag.productIds is already in the admin-curated order (backend sorts by + // sortOrder). Unknown ids are skipped, and a repeated id renders once. + const ordered: any[] = [] + const seen = new Set() + for (const id of tag.productIds || []) { + if (seen.has(id)) continue + seen.add(id) + const product = productById.get(id) + if (product) ordered.push(product) + } + + const inStock: any[] = [] + const outOfStock: any[] = [] + for (const product of ordered) { + const isOutOfStock = + Boolean(productSlotsMap[product.id]?.isOutOfStock) || !getQuickestSlot(product.id) + if (isOutOfStock) outOfStock.push(product) + else inStock.push(product) + } + + map[tag.id] = [...inStock, ...outOfStock] + } + + return { dashboardTags, allProducts, productsByTagId: map } + }, [productsData, productSlotsMap, getQuickestSlot]) + + // Explore Products tabs — tags in tagsOrder, products in per-tag sortOrder. + // Selection/expansion live in the shared store (mirrors user-ui) so the state + // shape and reset behaviour match the native app. + const selectedTagId = useHomeTagStore((state) => state.selectedTagId) + const selectTag = useHomeTagStore((state) => state.selectTag) const activeTagId = selectedTagId ?? dashboardTags[0]?.id ?? null - const [expandedByTagId, setExpandedByTagId] = useState>({}) - const handleToggleExpand = (tagId: number) => { - setExpandedByTagId((prev) => ({ ...prev, [tagId]: true })) - } + const expandedByTagId = useHomeTagStore((state) => state.expandedByTagId) + const expandTag = useHomeTagStore((state) => state.expandTag) // Auto-scroll the active tab into view (matches user-ui tab behavior) const tabsScrollRef = useRef(null) @@ -129,44 +169,6 @@ function HomePage() { } }, [activeTabIndex]) - const productsByTagId = useMemo(() => { - const map: Record = {} - for (const tag of dashboardTags) { - const productById = new Map() - for (const product of allProducts) { - productById.set(product.id, product) - } - - // tag.productIds is already in the admin-curated order (backend sorts by sortOrder). - const orderedIds = (tag.productIds || []).filter((id: number) => productById.has(id)) - const ordered: any[] = [] - const rest: any[] = [] - for (const id of orderedIds) { - const product = productById.get(id) - const isOutOfStock = Boolean(productSlotsMap[id]?.isOutOfStock) || !getQuickestSlot(id) - if (isOutOfStock) rest.push(product) - else ordered.push(product) - } - - // Products in the tag's productIds but not in the curated order (added later) — availability sort. - const seen = new Set(orderedIds) - const extra = allProducts - .filter((product: any) => (tag.productIds?.includes(product.id) ?? false) && !seen.has(product.id)) - .sort((a: any, b: any) => { - const slotA = getQuickestSlot(a.id) - const slotB = getQuickestSlot(b.id) - const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || !slotA - const bOutOfStock = Boolean(productSlotsMap[b.id]?.isOutOfStock) || !slotB - if (aOutOfStock && !bOutOfStock) return 1 - if (!aOutOfStock && bOutOfStock) return -1 - return 0 - }) - - map[tag.id] = [...ordered, ...rest, ...extra] - } - return map - }, [dashboardTags, allProducts, getQuickestSlot, productSlotsMap]) - const activeTagProducts = activeTagId != null ? (productsByTagId[activeTagId] || []) : [] // Sort products: in-stock first, then by slot availability @@ -184,7 +186,7 @@ function HomePage() { if (!aOutOfStock && bOutOfStock) return -1 return 0 }) - }, [productsData, productSlotsMap]) + }, [allProducts, productSlotsMap, getQuickestSlot]) // Load-more model for All Products (matches user-ui: 21 at a time) const [visibleCount, setVisibleCount] = useState(21) @@ -296,7 +298,7 @@ function HomePage() { ref={(el) => { tabPositions.current[i] = el?.offsetLeft ?? 0 }} - onClick={() => setSelectedTagId(tag.id)} + onClick={() => selectTag(tag.id)} className="shrink-0 cursor-pointer px-3 py-2" > 6 && !expandedByTagId[activeTagId] && (