enh
This commit is contained in:
parent
2881c1ede8
commit
cfdac49def
29 changed files with 887 additions and 174 deletions
|
|
@ -14,6 +14,7 @@ import {
|
||||||
incrementRegionSlotsVersionNum,
|
incrementRegionSlotsVersionNum,
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
import { imageUploadS3 } from '@/src/lib/s3-client'
|
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 { getApiCacheKey, getCloudflareApiToken, getCloudflareZoneId, getAssetsDomain } from '@/src/lib/env-exporter'
|
||||||
import {
|
import {
|
||||||
CACHE_FILENAMES,
|
CACHE_FILENAMES,
|
||||||
|
|
@ -129,7 +130,11 @@ export async function createAllCacheFiles(regionId?: number): Promise<RegionCach
|
||||||
// Internal versions that skip cache purging (for batch operations)
|
// Internal versions that skip cache purging (for batch operations)
|
||||||
async function createProductsFileInternal(regionId: number, version: number): Promise<string> {
|
async function createProductsFileInternal(regionId: number, version: number): Promise<string> {
|
||||||
const productsData = await scaffoldProducts(regionId)
|
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 buffer = Buffer.from(jsonContent, 'utf-8')
|
||||||
const filePath = regionCacheObjectKey(
|
const filePath = regionCacheObjectKey(
|
||||||
getApiCacheKey(),
|
getApiCacheKey(),
|
||||||
|
|
|
||||||
43
apps/backend/src/lib/product-image-cache.ts
Normal file
43
apps/backend/src/lib/product-image-cache.ts
Normal file
|
|
@ -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<T extends CatalogueImages>(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
|
||||||
|
}
|
||||||
|
|
@ -65,8 +65,11 @@ async function productsVersion(admin: ApiClient): Promise<number> {
|
||||||
/**
|
/**
|
||||||
* Read the products document from the scaffold function (test route).
|
* Read the products document from the scaffold function (test route).
|
||||||
*
|
*
|
||||||
* This is the exact object the cache writer serialises, read straight from D1,
|
* This is the pre-publication object, read straight from D1 so it does not wait
|
||||||
* so it no longer waits for the CacheCreator debounce or the S3 upload.
|
* 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(
|
async function pollProducts(
|
||||||
_admin: ApiClient,
|
_admin: ApiClient,
|
||||||
|
|
|
||||||
62
apps/backend/tests/unit/product-image-cache.test.ts
Normal file
62
apps/backend/tests/unit/product-image-cache.test.ts
Normal file
|
|
@ -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])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -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-13 | edge | tag has exactly 6 products | no Show More |
|
||||||
| HOME-14 | edge | tag has 7 products | Show More; after expand all 7 |
|
| 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-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-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-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 |
|
| 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-18 | edge | clear already empty | no bump |
|
||||||
| STORE-19 | edge | region memory only | no persist |
|
| STORE-19 | edge | region memory only | no persist |
|
||||||
| STORE-20 | edge | same value written twice | map identity preserved (no subscriber wake) |
|
| 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
|
### 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-01 | happy | initializer | product store populated; slot store populated; reconcile runs |
|
||||||
| CENTRAL-02 | edge | unmount | hooks clean up/no infinite loop |
|
| 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
|
## 26. Cross-cutting acceptance rules
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,7 @@ import { useUserDetails } from "@/src/contexts/AuthContext";
|
||||||
import TabLayoutWrapper from "@/components/TabLayoutWrapper";
|
import TabLayoutWrapper from "@/components/TabLayoutWrapper";
|
||||||
import LocationBar from "@/src/components/LocationBar";
|
import LocationBar from "@/src/components/LocationBar";
|
||||||
import { useNavigationStore } from "@/src/store/navigationStore";
|
import { useNavigationStore } from "@/src/store/navigationStore";
|
||||||
|
import { useHomeTagStore } from "@/src/store/homeTagStore";
|
||||||
import NextOrderGlimpse from "@/components/NextOrderGlimpse";
|
import NextOrderGlimpse from "@/components/NextOrderGlimpse";
|
||||||
dayjs.extend(relativeTime);
|
dayjs.extend(relativeTime);
|
||||||
|
|
||||||
|
|
@ -62,19 +63,6 @@ const staticStyles = {
|
||||||
slotsListContent: { paddingBottom: 24 },
|
slotsListContent: { paddingBottom: 24 },
|
||||||
} as const;
|
} 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 RenderStore = memo(({ item }: ListItemProps) => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { setNavigatedFromHome, setSelectedStoreId } = useNavigationStore();
|
const { setNavigatedFromHome, setSelectedStoreId } = useNavigationStore();
|
||||||
|
|
@ -192,17 +180,18 @@ const SlotCard = memo(({ slot }: SlotCardProps) => {
|
||||||
|
|
||||||
interface TagTabStripProps {
|
interface TagTabStripProps {
|
||||||
dashboardTags: any[];
|
dashboardTags: any[];
|
||||||
activeTagId: number | null;
|
|
||||||
onSelectTag: (id: number) => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fixed, horizontally scrollable tab strip (plain ScrollView — no nesting,
|
// Fixed, horizontally scrollable tab strip (plain ScrollView — no nesting,
|
||||||
// so it scrolls reliably on Android). Sits OUTSIDE the vertical FlatList.
|
// so it scrolls reliably on Android). Sits OUTSIDE the vertical FlatList.
|
||||||
const TagTabStrip = memo(({
|
const TagTabStrip = memo(({
|
||||||
dashboardTags,
|
dashboardTags,
|
||||||
activeTagId,
|
|
||||||
onSelectTag,
|
|
||||||
}: TagTabStripProps) => {
|
}: 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<any>(null);
|
const scrollRef = useRef<any>(null);
|
||||||
const positions = useRef<number[]>([]);
|
const positions = useRef<number[]>([]);
|
||||||
|
|
||||||
|
|
@ -243,7 +232,7 @@ const TagTabStrip = memo(({
|
||||||
onLayout={(e: any) => {
|
onLayout={(e: any) => {
|
||||||
positions.current[i] = e.nativeEvent.layout.x;
|
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`}
|
style={tw`h-12 px-3 justify-center`}
|
||||||
activeOpacity={0.7}
|
activeOpacity={0.7}
|
||||||
>
|
>
|
||||||
|
|
@ -278,10 +267,7 @@ const TagTabStrip = memo(({
|
||||||
|
|
||||||
interface TagSceneProps {
|
interface TagSceneProps {
|
||||||
dashboardTags: any[];
|
dashboardTags: any[];
|
||||||
activeTagId: number | null;
|
|
||||||
productsByTagId: Record<number, any[]>;
|
productsByTagId: Record<number, any[]>;
|
||||||
expandedByTagId: Record<number, boolean>;
|
|
||||||
onToggleExpand: (tagId: number) => void;
|
|
||||||
onProductPress: (id: number) => void;
|
onProductPress: (id: number) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -289,17 +275,21 @@ interface TagSceneProps {
|
||||||
// scrolls with the page.
|
// scrolls with the page.
|
||||||
const TagScene = memo(({
|
const TagScene = memo(({
|
||||||
dashboardTags,
|
dashboardTags,
|
||||||
activeTagId,
|
|
||||||
productsByTagId,
|
productsByTagId,
|
||||||
expandedByTagId,
|
|
||||||
onToggleExpand,
|
|
||||||
onProductPress,
|
onProductPress,
|
||||||
}: TagSceneProps) => {
|
}: 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;
|
if (tagId == null) return null;
|
||||||
|
|
||||||
const products = productsByTagId[tagId] || [];
|
const products = productsByTagId[tagId] || [];
|
||||||
const expanded = !!expandedByTagId[tagId];
|
|
||||||
const visible = expanded ? products : products.slice(0, 6);
|
const visible = expanded ? products : products.slice(0, 6);
|
||||||
const hasMore = products.length > 6 && !expanded;
|
const hasMore = products.length > 6 && !expanded;
|
||||||
|
|
||||||
|
|
@ -323,7 +313,7 @@ const TagScene = memo(({
|
||||||
testID={`tag-show-more-${tagId}`}
|
testID={`tag-show-more-${tagId}`}
|
||||||
style={tw`self-center mt-1 mb-2 px-5 py-2.5 rounded-full bg-brand500 shadow-sm`}
|
style={tw`self-center mt-1 mb-2 px-5 py-2.5 rounded-full bg-brand500 shadow-sm`}
|
||||||
activeOpacity={0.85}
|
activeOpacity={0.85}
|
||||||
onPress={() => onToggleExpand(tagId)}
|
onPress={() => expandTag(tagId)}
|
||||||
>
|
>
|
||||||
<MyText style={tw`text-white text-sm font-semibold`}>Show More</MyText>
|
<MyText style={tw`text-white text-sm font-semibold`}>Show More</MyText>
|
||||||
</MyTouchableOpacity>
|
</MyTouchableOpacity>
|
||||||
|
|
@ -375,20 +365,18 @@ const ProductItem = memo(({ item, onPress }: ProductItemProps) => {
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
interface ListHeaderProps extends TagSceneProps {
|
interface ListHeaderProps {
|
||||||
onSelectTag: (id: number) => void;
|
dashboardTags: any[];
|
||||||
|
productsByTagId: Record<number, any[]>;
|
||||||
|
onProductPress: (id: number) => void;
|
||||||
storesData: any;
|
storesData: any;
|
||||||
sortedSlots: any[];
|
sortedSlots: any[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const ListHeader = memo(({
|
const ListHeader = memo(({
|
||||||
dashboardTags,
|
dashboardTags,
|
||||||
activeTagId,
|
|
||||||
productsByTagId,
|
productsByTagId,
|
||||||
expandedByTagId,
|
|
||||||
onToggleExpand,
|
|
||||||
onProductPress,
|
onProductPress,
|
||||||
onSelectTag,
|
|
||||||
storesData,
|
storesData,
|
||||||
sortedSlots,
|
sortedSlots,
|
||||||
}: ListHeaderProps) => {
|
}: ListHeaderProps) => {
|
||||||
|
|
@ -402,11 +390,7 @@ const ListHeader = memo(({
|
||||||
<NextOrderGlimpse />
|
<NextOrderGlimpse />
|
||||||
</View>
|
</View>
|
||||||
{dashboardTags.length > 0 && (
|
{dashboardTags.length > 0 && (
|
||||||
<TagTabStrip
|
<TagTabStrip dashboardTags={dashboardTags} />
|
||||||
dashboardTags={dashboardTags}
|
|
||||||
activeTagId={activeTagId}
|
|
||||||
onSelectTag={onSelectTag}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
{dashboardTags.length > 0 && (
|
{dashboardTags.length > 0 && (
|
||||||
<View
|
<View
|
||||||
|
|
@ -417,10 +401,7 @@ const ListHeader = memo(({
|
||||||
>
|
>
|
||||||
<TagScene
|
<TagScene
|
||||||
dashboardTags={dashboardTags}
|
dashboardTags={dashboardTags}
|
||||||
activeTagId={activeTagId}
|
|
||||||
productsByTagId={productsByTagId}
|
productsByTagId={productsByTagId}
|
||||||
expandedByTagId={expandedByTagId}
|
|
||||||
onToggleExpand={onToggleExpand}
|
|
||||||
onProductPress={onProductPress}
|
onProductPress={onProductPress}
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
|
|
@ -520,16 +501,51 @@ export default function Dashboard() {
|
||||||
const { data: storesData, refetch: refetchStores } = useStores();
|
const { data: storesData, refetch: refetchStores } = useStores();
|
||||||
const { data: slotsData } = useSlots();
|
const { data: slotsData } = useSlots();
|
||||||
|
|
||||||
const products = productsData?.products || [];
|
// Single source of truth for the catalogue: `products` and `dashboardTags`
|
||||||
const dashboardTags = productsData?.tags || [];
|
// 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<number | null>(null);
|
// Hoisted: the old version rebuilt this Map once per tag.
|
||||||
const activeTagId = selectedTagId ?? dashboardTags[0]?.id ?? null;
|
const productById = new Map<number, any>();
|
||||||
const [expandedByTagId, setExpandedByTagId] = useState<Record<number, boolean>>({});
|
for (const product of products) {
|
||||||
const handleToggleExpand = useCallback((tagId: number) => {
|
productById.set(product.id, product);
|
||||||
setExpandedByTagId((prev) => ({ ...prev, [tagId]: true }));
|
}
|
||||||
}, []);
|
|
||||||
|
|
||||||
|
const map: Record<number, any[]> = {};
|
||||||
|
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<number>();
|
||||||
|
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(() => {
|
React.useEffect(() => {
|
||||||
if (products.length === 0) {
|
if (products.length === 0) {
|
||||||
|
|
@ -555,7 +571,7 @@ export default function Dashboard() {
|
||||||
setDisplayedProducts(allSorted)
|
setDisplayedProducts(allSorted)
|
||||||
setVisibleCount(21)
|
setVisibleCount(21)
|
||||||
setHasMore(allSorted.length > 21)
|
setHasMore(allSorted.length > 21)
|
||||||
}, [productsData, productSlotsMap]);
|
}, [products, productSlotsMap]);
|
||||||
|
|
||||||
const handleShowMore = useCallback(() => {
|
const handleShowMore = useCallback(() => {
|
||||||
setVisibleCount((prev) => {
|
setVisibleCount((prev) => {
|
||||||
|
|
@ -577,35 +593,6 @@ export default function Dashboard() {
|
||||||
});
|
});
|
||||||
}, [slotsData]);
|
}, [slotsData]);
|
||||||
|
|
||||||
const productsByTagId = useMemo(() => {
|
|
||||||
const map: Record<number, any[]> = {};
|
|
||||||
for (const tag of dashboardTags) {
|
|
||||||
const productById = new Map<number, any>();
|
|
||||||
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 () => {
|
const handleRefresh = useCallback(async () => {
|
||||||
setIsRefreshing(true);
|
setIsRefreshing(true);
|
||||||
try {
|
try {
|
||||||
|
|
@ -647,30 +634,26 @@ export default function Dashboard() {
|
||||||
// <Image style={{ width: 150, height: 235 }} source={{ uri: item.images[0]}} />
|
// <Image style={{ width: 150, height: 235 }} source={{ uri: item.images[0]}} />
|
||||||
), [handleProductPress]);
|
), [handleProductPress]);
|
||||||
|
|
||||||
const pageTint = activeTagId == null ? '#FFFFFF' : getTagColor(activeTagId).pageBg;
|
// The page background stays white (the per-tag tint was never enabled).
|
||||||
const pageTintStyle = useMemo(() => [
|
const pageTintStyle = useMemo(() => [
|
||||||
tw`flex-1`,
|
tw`flex-1`,
|
||||||
{ backgroundColor: '#FFFFFF' }
|
{ backgroundColor: '#FFFFFF' }
|
||||||
], [pageTint]);
|
], []);
|
||||||
|
|
||||||
const searchBarContainerStyle = useMemo(() => [
|
const searchBarContainerStyle = useMemo(() => [
|
||||||
tw`w-full px-4 pt-4 pb-0`,
|
tw`w-full px-4 pt-4 pb-0`,
|
||||||
{ backgroundColor: '#FFFFFF' }
|
{ backgroundColor: '#FFFFFF' }
|
||||||
], [pageTint]);
|
], []);
|
||||||
|
|
||||||
const listHeader = useMemo(() => (
|
const listHeader = useMemo(() => (
|
||||||
<ListHeader
|
<ListHeader
|
||||||
dashboardTags={dashboardTags}
|
dashboardTags={dashboardTags}
|
||||||
activeTagId={activeTagId}
|
|
||||||
productsByTagId={productsByTagId}
|
productsByTagId={productsByTagId}
|
||||||
expandedByTagId={expandedByTagId}
|
|
||||||
onToggleExpand={handleToggleExpand}
|
|
||||||
onProductPress={handleProductPress}
|
onProductPress={handleProductPress}
|
||||||
onSelectTag={setSelectedTagId}
|
|
||||||
storesData={storesData}
|
storesData={storesData}
|
||||||
sortedSlots={sortedSlots}
|
sortedSlots={sortedSlots}
|
||||||
/>
|
/>
|
||||||
), [dashboardTags, activeTagId, productsByTagId, expandedByTagId, handleToggleExpand, handleProductPress, storesData, sortedSlots]);
|
), [dashboardTags, productsByTagId, handleProductPress, storesData, sortedSlots]);
|
||||||
|
|
||||||
const listContentContainerStyle = useMemo(() => [
|
const listContentContainerStyle = useMemo(() => [
|
||||||
tw`pb-24`,
|
tw`pb-24`,
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,7 @@ import FirstUserWrapper from "@/components/FirstUserWrapper";
|
||||||
import HealthTestWrapper from "@/components/HealthTestWrapper";
|
import HealthTestWrapper from "@/components/HealthTestWrapper";
|
||||||
import UpdateChecker from "@/components/UpdateChecker";
|
import UpdateChecker from "@/components/UpdateChecker";
|
||||||
import CentralStoreInitializer from "@/src/components/CentralStoreInitializer";
|
import CentralStoreInitializer from "@/src/components/CentralStoreInitializer";
|
||||||
|
import ImageCacheTtl from "@/src/components/ImageCacheTtl";
|
||||||
import { RefreshProvider } from "../../../packages/ui/src/lib/refresh-context";
|
import { RefreshProvider } from "../../../packages/ui/src/lib/refresh-context";
|
||||||
import WebViewWrapper from "@/components/WebViewWrapper";
|
import WebViewWrapper from "@/components/WebViewWrapper";
|
||||||
import BackHandlerWrapper from "@/components/BackHandler";
|
import BackHandlerWrapper from "@/components/BackHandler";
|
||||||
|
|
@ -82,6 +83,7 @@ export default function RootLayout() {
|
||||||
<PaperProvider>
|
<PaperProvider>
|
||||||
<RefreshProvider queryClient={queryClient}>
|
<RefreshProvider queryClient={queryClient}>
|
||||||
<CentralStoreInitializer>
|
<CentralStoreInitializer>
|
||||||
|
<ImageCacheTtl />
|
||||||
<BackHandlerWrapper />
|
<BackHandlerWrapper />
|
||||||
<RenderCommitProbe>
|
<RenderCommitProbe>
|
||||||
<Stack screenOptions={{ headerShown: false }} />
|
<Stack screenOptions={{ headerShown: false }} />
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,6 @@ import {
|
||||||
import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier';
|
import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier';
|
||||||
import { useCartStore } from '@/src/store/cartStore';
|
import { useCartStore } from '@/src/store/cartStore';
|
||||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
||||||
import { Image as RnImage } from 'react-native'
|
|
||||||
import { useRenderProbe } from '@/src/lib/render-probe'
|
import { useRenderProbe } from '@/src/lib/render-probe'
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -185,22 +184,24 @@ const ProductCard: React.FC<ProductCardProps> = ({
|
||||||
activeOpacity={0.9}
|
activeOpacity={0.9}
|
||||||
>
|
>
|
||||||
<View style={tw`relative`}>
|
<View style={tw`relative`}>
|
||||||
<RnImage
|
<Image
|
||||||
source={{ uri: imageUri }}
|
source={imageUri ?? null}
|
||||||
// source={{uri: 'https://pub-6bf1fbc4048a4cbaa533ddbb13bf9de6.r2.dev/product-images/1763796113884-0'}}
|
style={{ width: "100%", height: isHero ? itemWidth * 0.82 : itemWidth }}
|
||||||
style={{ width: "100%", height: isHero ? itemWidth * 0.82 : itemWidth, resizeMode: "cover" }}
|
contentFit="cover"
|
||||||
|
cachePolicy="memory-disk"
|
||||||
|
// Tells expo-image this view belongs to a list row, so a recycled
|
||||||
|
// cell releases the previous product's bitmap instead of keeping it
|
||||||
|
// in memory.
|
||||||
|
recyclingKey={item.id != null ? String(item.id) : undefined}
|
||||||
|
transition={0}
|
||||||
onLoadStart={() => {
|
onLoadStart={() => {
|
||||||
setImageStatus('loading')
|
setImageStatus('loading')
|
||||||
setImageError(null)
|
setImageError(null)
|
||||||
}}
|
}}
|
||||||
// onLoadEnd={() => {
|
|
||||||
// setImageError('loading stopped indefinitely')
|
|
||||||
//
|
|
||||||
// }}
|
|
||||||
onLoad={() => setImageStatus('loaded')}
|
onLoad={() => setImageStatus('loaded')}
|
||||||
onError={(event) => {
|
onError={(event) => {
|
||||||
setImageStatus('error')
|
setImageStatus('error')
|
||||||
setImageError( 'Image failed to load')
|
setImageError(event?.error || 'Image failed to load')
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,11 @@
|
||||||
"shafi-dev": {
|
"shafi-dev": {
|
||||||
"distribution": "internal",
|
"distribution": "internal",
|
||||||
"channel": "shafi-dev",
|
"channel": "shafi-dev",
|
||||||
"autoIncrement": true
|
"autoIncrement": true,
|
||||||
|
"android": {
|
||||||
|
"buildType": "apk",
|
||||||
|
"gradleCommand": ":app:assembleRelease -PreactNativeArchitectures=arm64-v8a -Pandroid.enableProguardInReleaseBuilds=true"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"production": {
|
"production": {
|
||||||
"autoIncrement": true,
|
"autoIncrement": true,
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
import { useCallback } from 'react';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
||||||
|
|
||||||
|
|
@ -6,19 +7,21 @@ export function useProductSlotIdentifier() {
|
||||||
const slots = useCentralSlotStore((state) => state.slots);
|
const slots = useCentralSlotStore((state) => state.slots);
|
||||||
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
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;
|
if (!slots?.length) return null;
|
||||||
|
|
||||||
const now = dayjs();
|
const now = dayjs();
|
||||||
const productInfo = productSlotsMap[productId];
|
const productInfo = productSlotsMap[productId];
|
||||||
|
|
||||||
if (!productInfo?.slots?.length) return null;
|
if (!productInfo?.slots?.length) return null;
|
||||||
|
|
||||||
// Find slots that contain this product and have future delivery time
|
// Find slots that contain this product and have future delivery time
|
||||||
const availableSlots = productInfo.slots.filter((slot: any) =>
|
const availableSlots = productInfo.slots.filter((slot: any) =>
|
||||||
dayjs(slot.deliveryTime).isAfter(now)
|
dayjs(slot.deliveryTime).isAfter(now)
|
||||||
);
|
);
|
||||||
|
|
||||||
if (availableSlots.length === 0) return null;
|
if (availableSlots.length === 0) return null;
|
||||||
|
|
||||||
// Return earliest slot ID (sorted by delivery time)
|
// Return earliest slot ID (sorted by delivery time)
|
||||||
|
|
@ -27,7 +30,7 @@ export function useProductSlotIdentifier() {
|
||||||
)[0];
|
)[0];
|
||||||
|
|
||||||
return earliestSlot.id;
|
return earliestSlot.id;
|
||||||
};
|
}, [slots, productSlotsMap]);
|
||||||
|
|
||||||
return { getQuickestSlot, productSlotsMap };
|
return { getQuickestSlot, productSlotsMap };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
50
apps/user-ui/src/components/ImageCacheTtl.tsx
Normal file
50
apps/user-ui/src/components/ImageCacheTtl.tsx
Normal file
|
|
@ -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<void> {
|
||||||
|
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
|
||||||
|
}
|
||||||
41
apps/user-ui/src/lib/image-cache-meta.ts
Normal file
41
apps/user-ui/src/lib/image-cache-meta.ts
Normal file
|
|
@ -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<number | null> {
|
||||||
|
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<void> {
|
||||||
|
const uri = timestampFileUri()
|
||||||
|
if (!uri) return
|
||||||
|
await FileSystem.writeAsStringAsync(uri, String(timestamp))
|
||||||
|
}
|
||||||
32
apps/user-ui/src/lib/image-cache-ttl.ts
Normal file
32
apps/user-ui/src/lib/image-cache-ttl.ts
Normal file
|
|
@ -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
|
||||||
|
}
|
||||||
|
|
@ -10,6 +10,7 @@ import { useCentralProductStore } from '@/src/store/centralProductStore'
|
||||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
||||||
import { useSlotStore } from '@/components/stores/slotStore'
|
import { useSlotStore } from '@/components/stores/slotStore'
|
||||||
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
||||||
|
import { useHomeTagStore } from '@/src/store/homeTagStore'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The one and only way to change the browsing region.
|
* The one and only way to change the browsing region.
|
||||||
|
|
@ -53,6 +54,10 @@ export async function confirmRegionSwitch(
|
||||||
useFlashCartStore.getState().clearAddedFlashProduct()
|
useFlashCartStore.getState().clearAddedFlashProduct()
|
||||||
useFlashNavigationStore.getState().reset()
|
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.
|
// 3. Drop cached regional catalog/slot snapshots so they cannot leak across.
|
||||||
const productStore = useCentralProductStore.getState()
|
const productStore = useCentralProductStore.getState()
|
||||||
productStore.setProducts([])
|
productStore.setProducts([])
|
||||||
|
|
|
||||||
|
|
@ -52,10 +52,10 @@ export function useRenderProbe(label: string) {
|
||||||
ts: now,
|
ts: now,
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(
|
// console.log(
|
||||||
`[render-probe] component=${label} renders=${summary.renders}/${summary.elapsed}ms ` +
|
// `[render-probe] component=${label} renders=${summary.renders}/${summary.elapsed}ms ` +
|
||||||
`(~${summary.perSecond}/s)${suspicious}`
|
// `(~${summary.perSecond}/s)${suspicious}`
|
||||||
)
|
// )
|
||||||
|
|
||||||
fetch(PROBE_ENDPOINT, {
|
fetch(PROBE_ENDPOINT, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|
@ -109,10 +109,10 @@ export default function RenderCommitProbe({ children }: { children: React.ReactN
|
||||||
ts: now,
|
ts: now,
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(
|
// console.log(
|
||||||
`[render-probe] path=${summary.path} commits=${summary.commits}/${summary.elapsed}ms ` +
|
// `[render-probe] path=${summary.path} commits=${summary.commits}/${summary.elapsed}ms ` +
|
||||||
`(~${summary.perSecond}/s) last=${summary.phase} ${summary.duration}ms${suspicious}`
|
// `(~${summary.perSecond}/s) last=${summary.phase} ${summary.duration}ms${suspicious}`
|
||||||
)
|
// )
|
||||||
|
|
||||||
fetch(PROBE_ENDPOINT, {
|
fetch(PROBE_ENDPOINT, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|
|
||||||
38
apps/user-ui/src/store/homeTagStore.ts
Normal file
38
apps/user-ui/src/store/homeTagStore.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { create } from 'zustand'
|
||||||
|
|
||||||
|
interface HomeTagState {
|
||||||
|
/** User-picked tag; null means "first dashboard tag". */
|
||||||
|
selectedTagId: number | null
|
||||||
|
expandedByTagId: Record<number, boolean>
|
||||||
|
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<HomeTagState>((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: {} }),
|
||||||
|
}))
|
||||||
|
|
@ -25,6 +25,7 @@ import { useRegionStore } from '@/src/store/regionStore'
|
||||||
import { useLocationStore } from '@/src/store/locationStore'
|
import { useLocationStore } from '@/src/store/locationStore'
|
||||||
import { useSlotStore } from '@/components/stores/slotStore'
|
import { useSlotStore } from '@/components/stores/slotStore'
|
||||||
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
||||||
|
import { useHomeTagStore } from '@/src/store/homeTagStore'
|
||||||
|
|
||||||
export function resetStores() {
|
export function resetStores() {
|
||||||
useAppStore.setState({ hideTabsNav: {} })
|
useAppStore.setState({ hideTabsNav: {} })
|
||||||
|
|
@ -54,6 +55,7 @@ export function resetStores() {
|
||||||
})
|
})
|
||||||
useSlotStore.setState({ slotId: undefined, storeId: undefined })
|
useSlotStore.setState({ slotId: undefined, storeId: undefined })
|
||||||
useFlashNavigationStore.setState({ shouldNavigateToCart: false })
|
useFlashNavigationStore.setState({ shouldNavigateToCart: false })
|
||||||
|
useHomeTagStore.setState({ selectedTagId: null, expandedByTagId: {} })
|
||||||
useLocationStore.getState().stop()
|
useLocationStore.getState().stop()
|
||||||
useLocationStore.setState({ coords: null, status: 'idle', error: null })
|
useLocationStore.setState({ coords: null, status: 'idle', error: null })
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -68,6 +68,7 @@ module.exports = {
|
||||||
'^expo-router$': '<rootDir>/mocks/native/expo-router.tsx',
|
'^expo-router$': '<rootDir>/mocks/native/expo-router.tsx',
|
||||||
'^expo-router/(.*)$': '<rootDir>/mocks/native/expo-router.tsx',
|
'^expo-router/(.*)$': '<rootDir>/mocks/native/expo-router.tsx',
|
||||||
'^expo-image$': '<rootDir>/mocks/native/common.tsx',
|
'^expo-image$': '<rootDir>/mocks/native/common.tsx',
|
||||||
|
'^expo-file-system$': '<rootDir>/mocks/native/common.tsx',
|
||||||
'^expo-linear-gradient$': '<rootDir>/mocks/native/common.tsx',
|
'^expo-linear-gradient$': '<rootDir>/mocks/native/common.tsx',
|
||||||
'^expo-blur$': '<rootDir>/mocks/native/common.tsx',
|
'^expo-blur$': '<rootDir>/mocks/native/common.tsx',
|
||||||
'^expo-status-bar$': '<rootDir>/mocks/native/common.tsx',
|
'^expo-status-bar$': '<rootDir>/mocks/native/common.tsx',
|
||||||
|
|
|
||||||
58
apps/user-ui/tests/lib/image-cache-meta.test.ts
Normal file
58
apps/user-ui/tests/lib/image-cache-meta.test.ts
Normal file
|
|
@ -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')
|
||||||
|
})
|
||||||
|
})
|
||||||
98
apps/user-ui/tests/lib/image-cache-ttl.test.tsx
Normal file
98
apps/user-ui/tests/lib/image-cache-ttl.test.tsx
Normal file
|
|
@ -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(<ImageCacheTtl />)
|
||||||
|
|
||||||
|
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(<ImageCacheTtl />)
|
||||||
|
|
||||||
|
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(<ImageCacheTtl />)
|
||||||
|
|
||||||
|
await waitFor(() => expect(clearDiskCache).toHaveBeenCalledTimes(1))
|
||||||
|
expect(writeClearedAt).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
view.unmount()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -21,6 +21,7 @@ import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
||||||
import { useRegionStore } from '@/src/store/regionStore'
|
import { useRegionStore } from '@/src/store/regionStore'
|
||||||
import { useSlotStore } from '@/components/stores/slotStore'
|
import { useSlotStore } from '@/components/stores/slotStore'
|
||||||
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
||||||
|
import { useHomeTagStore } from '@/src/store/homeTagStore'
|
||||||
import {
|
import {
|
||||||
AVAILABILITY,
|
AVAILABILITY,
|
||||||
MERGED_PRODUCTS,
|
MERGED_PRODUCTS,
|
||||||
|
|
@ -60,6 +61,27 @@ describe('stores', () => {
|
||||||
expect(useAppStore.getState().hideTabsNav).toBe(hidden)
|
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', () => {
|
it('STORE-02: addressStore selects and clears an address id', () => {
|
||||||
useAddressStore.getState().setSelectedAddressId(11)
|
useAddressStore.getState().setSelectedAddressId(11)
|
||||||
expect(useAddressStore.getState().selectedAddressId).toBe(11)
|
expect(useAddressStore.getState().selectedAddressId).toBe(11)
|
||||||
|
|
|
||||||
|
|
@ -9,14 +9,27 @@ import * as React from 'react'
|
||||||
import { View } from 'react-native'
|
import { View } from 'react-native'
|
||||||
|
|
||||||
/* expo-image */
|
/* expo-image */
|
||||||
export const Image = ({ testID, source, ...props }: any) =>
|
const ImageComponent = ({ testID, source, ...props }: any) =>
|
||||||
React.createElement(View, {
|
React.createElement(View, {
|
||||||
...props,
|
...props,
|
||||||
testID: testID ?? 'expo-image',
|
testID: testID ?? 'expo-image',
|
||||||
accessibilityLabel: typeof source === 'object' ? source?.uri : undefined,
|
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
|
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 */
|
/* expo-linear-gradient */
|
||||||
export const LinearGradient = ({ children, testID, ...props }: any) =>
|
export const LinearGradient = ({ children, testID, ...props }: any) =>
|
||||||
React.createElement(View, { ...props, testID: testID ?? 'linear-gradient' }, children)
|
React.createElement(View, { ...props, testID: testID ?? 'linear-gradient' }, children)
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,6 @@ import * as React from 'react'
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
DeviceEventEmitter,
|
DeviceEventEmitter,
|
||||||
Image,
|
|
||||||
Linking,
|
Linking,
|
||||||
SectionList,
|
SectionList,
|
||||||
StyleSheet,
|
StyleSheet,
|
||||||
|
|
@ -485,14 +484,13 @@ describe('Home (HOME)', () => {
|
||||||
expect(idsFrom(getAllByTestId(/^tag-product-/), 'tag-product-')).toEqual([5, 2])
|
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 () => {
|
it('HOME-16: duplicate ids in a tag productIds are rendered once', async () => {
|
||||||
// Current gap: productsByTagId maps productIds without de-duplicating, so a
|
|
||||||
// repeated id renders the card twice. Pinned until the map deduplicates.
|
|
||||||
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts([2, 2, 5])]))
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts([2, 2, 5])]))
|
||||||
const { getAllByTestId } = await renderHome()
|
const { getAllByTestId } = await renderHome()
|
||||||
|
|
||||||
expect(getAllByTestId('tag-product-2')).toHaveLength(2)
|
// The first occurrence keeps its curated position; the repeat is dropped.
|
||||||
expect(getAllByTestId(/^tag-product-/)).toHaveLength(3)
|
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 () => {
|
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 { getByTestId } = await renderHome()
|
||||||
|
|
||||||
const card = within(getByTestId('product-item-2'))
|
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()
|
expect(card.getByText('Image failed to load')).toBeTruthy()
|
||||||
})
|
})
|
||||||
|
|
|
||||||
BIN
apps/user-ui/user-ui-shafi-dev-arm.apk
Normal file
BIN
apps/user-ui/user-ui-shafi-dev-arm.apk
Normal file
Binary file not shown.
|
|
@ -10,6 +10,7 @@ import { useCentralProductStore } from './stores/central-product-store'
|
||||||
import { useCentralSlotStore } from './stores/central-slot-store'
|
import { useCentralSlotStore } from './stores/central-slot-store'
|
||||||
import { useSlotStore } from './stores/slot-store'
|
import { useSlotStore } from './stores/slot-store'
|
||||||
import { useFlashNavigationStore } from './stores/flash-navigation-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.
|
* The one and only way to change the browsing region.
|
||||||
|
|
@ -50,6 +51,10 @@ export async function confirmRegionSwitch(
|
||||||
useFlashCartStore.getState().setAddedFlashProduct(null)
|
useFlashCartStore.getState().setAddedFlashProduct(null)
|
||||||
useFlashNavigationStore.getState().setShouldNavigateToCart(false)
|
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.
|
// 3. Drop cached regional catalog/slot snapshots so they cannot leak across.
|
||||||
const productStore = useCentralProductStore.getState()
|
const productStore = useCentralProductStore.getState()
|
||||||
productStore.setProducts([])
|
productStore.setProducts([])
|
||||||
|
|
|
||||||
34
apps/web-ui/src/lib/stores/home-tag-store.ts
Normal file
34
apps/web-ui/src/lib/stores/home-tag-store.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
import { create } from 'zustand'
|
||||||
|
|
||||||
|
interface HomeTagState {
|
||||||
|
/** User-picked tag; null means "first dashboard tag". */
|
||||||
|
selectedTagId: number | null
|
||||||
|
expandedByTagId: Record<number, boolean>
|
||||||
|
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<HomeTagState>((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: {} }),
|
||||||
|
}))
|
||||||
|
|
@ -14,6 +14,7 @@ import { AppLayout } from '../components/AppLayout'
|
||||||
import { ProductCard } from '../components/ProductCard'
|
import { ProductCard } from '../components/ProductCard'
|
||||||
import AddToCartDialog from '../components/AddToCartDialog'
|
import AddToCartDialog from '../components/AddToCartDialog'
|
||||||
import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier'
|
import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier'
|
||||||
|
import { useHomeTagStore } from '../lib/stores/home-tag-store'
|
||||||
import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores'
|
import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores'
|
||||||
import { Store, ImageOff, Loader2, Clock, Truck } from 'lucide-react'
|
import { Store, ImageOff, Loader2, Clock, Truck } from 'lucide-react'
|
||||||
|
|
||||||
|
|
@ -102,17 +103,56 @@ function HomePage() {
|
||||||
|
|
||||||
const stores = storesData?.stores || []
|
const stores = storesData?.stores || []
|
||||||
// const banners = bannersData?.banners || []
|
// const banners = bannersData?.banners || []
|
||||||
const allProducts = productsData?.products || []
|
|
||||||
const slots = slotsData?.slots || []
|
const slots = slotsData?.slots || []
|
||||||
|
|
||||||
// Explore Products tabs — tags in tagsOrder, products in per-tag sortOrder
|
// Single source of truth for the catalogue (mirrors user-ui home): the tags,
|
||||||
const dashboardTags = productsData?.tags || []
|
// the full product list and the per-tag rows all come out of one memo.
|
||||||
const [selectedTagId, setSelectedTagId] = useState<number | null>(null)
|
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<number, any>()
|
||||||
|
for (const product of allProducts) {
|
||||||
|
productById.set(product.id, product)
|
||||||
|
}
|
||||||
|
|
||||||
|
const map: Record<number, any[]> = {}
|
||||||
|
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<number>()
|
||||||
|
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 activeTagId = selectedTagId ?? dashboardTags[0]?.id ?? null
|
||||||
const [expandedByTagId, setExpandedByTagId] = useState<Record<number, boolean>>({})
|
const expandedByTagId = useHomeTagStore((state) => state.expandedByTagId)
|
||||||
const handleToggleExpand = (tagId: number) => {
|
const expandTag = useHomeTagStore((state) => state.expandTag)
|
||||||
setExpandedByTagId((prev) => ({ ...prev, [tagId]: true }))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Auto-scroll the active tab into view (matches user-ui tab behavior)
|
// Auto-scroll the active tab into view (matches user-ui tab behavior)
|
||||||
const tabsScrollRef = useRef<HTMLDivElement>(null)
|
const tabsScrollRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
@ -129,44 +169,6 @@ function HomePage() {
|
||||||
}
|
}
|
||||||
}, [activeTabIndex])
|
}, [activeTabIndex])
|
||||||
|
|
||||||
const productsByTagId = useMemo(() => {
|
|
||||||
const map: Record<number, any[]> = {}
|
|
||||||
for (const tag of dashboardTags) {
|
|
||||||
const productById = new Map<number, any>()
|
|
||||||
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] || []) : []
|
const activeTagProducts = activeTagId != null ? (productsByTagId[activeTagId] || []) : []
|
||||||
|
|
||||||
// Sort products: in-stock first, then by slot availability
|
// Sort products: in-stock first, then by slot availability
|
||||||
|
|
@ -184,7 +186,7 @@ function HomePage() {
|
||||||
if (!aOutOfStock && bOutOfStock) return -1
|
if (!aOutOfStock && bOutOfStock) return -1
|
||||||
return 0
|
return 0
|
||||||
})
|
})
|
||||||
}, [productsData, productSlotsMap])
|
}, [allProducts, productSlotsMap, getQuickestSlot])
|
||||||
|
|
||||||
// Load-more model for All Products (matches user-ui: 21 at a time)
|
// Load-more model for All Products (matches user-ui: 21 at a time)
|
||||||
const [visibleCount, setVisibleCount] = useState(21)
|
const [visibleCount, setVisibleCount] = useState(21)
|
||||||
|
|
@ -296,7 +298,7 @@ function HomePage() {
|
||||||
ref={(el) => {
|
ref={(el) => {
|
||||||
tabPositions.current[i] = el?.offsetLeft ?? 0
|
tabPositions.current[i] = el?.offsetLeft ?? 0
|
||||||
}}
|
}}
|
||||||
onClick={() => setSelectedTagId(tag.id)}
|
onClick={() => selectTag(tag.id)}
|
||||||
className="shrink-0 cursor-pointer px-3 py-2"
|
className="shrink-0 cursor-pointer px-3 py-2"
|
||||||
>
|
>
|
||||||
<span
|
<span
|
||||||
|
|
@ -337,7 +339,7 @@ function HomePage() {
|
||||||
{activeTagProducts.length > 6 && !expandedByTagId[activeTagId] && (
|
{activeTagProducts.length > 6 && !expandedByTagId[activeTagId] && (
|
||||||
<div className="mt-4 flex justify-center">
|
<div className="mt-4 flex justify-center">
|
||||||
<button
|
<button
|
||||||
onClick={() => handleToggleExpand(activeTagId)}
|
onClick={() => expandTag(activeTagId)}
|
||||||
className="rounded-full bg-brand-500 px-6 py-2.5 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-brand-600"
|
className="rounded-full bg-brand-500 px-6 py-2.5 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-brand-600"
|
||||||
>
|
>
|
||||||
Show More
|
Show More
|
||||||
|
|
|
||||||
183
change-log.txt
183
change-log.txt
|
|
@ -170,3 +170,186 @@ was rebuilt on every render (re-attaching the platform control).
|
||||||
+ FLASH-25: a pull keeps the spinner up until the refresh settles.
|
+ FLASH-25: a pull keeps the spinner up until the refresh settles.
|
||||||
+ HIDE-04: re-render does not rewrite the store.
|
+ HIDE-04: re-render does not rewrite the store.
|
||||||
+ STORE-20: same-value write keeps the map identity.
|
+ STORE-20: same-value write keeps the map identity.
|
||||||
|
|
||||||
|
[2026-11-01 14:24:07 IST] user-ui: arm64-only Android profile for personal device builds.
|
||||||
|
|
||||||
|
--- apps/user-ui/eas.json
|
||||||
|
+ "shafi-dev-arm64": internal distribution, channel shafi-dev, buildType apk,
|
||||||
|
gradleCommand ":app:assembleRelease -PreactNativeArchitectures=arm64-v8a".
|
||||||
|
Same JS/OTA channel as shafi-dev; the APK simply carries only arm64-v8a native
|
||||||
|
libs instead of all four ABIs (that is most of the 80 MB universal APK).
|
||||||
|
~ shafi-dev left untouched (universal APK for emulators / 32-bit testers).
|
||||||
|
|
||||||
|
[2026-11-01 14:31:37 IST] user-ui: shafi-dev now builds arm64-only + R8 (was universal APK).
|
||||||
|
|
||||||
|
Measured on the device (Play install, v1.2.0): base.apk 38.4 MB (dex 29.6 MB,
|
||||||
|
assets 3.9, res 2.7) + split arm64 libs 19.0 MB + density/langs 0.4 => 57.8 MB
|
||||||
|
installed. The local universal APK carries the same bytes plus three unused ABI
|
||||||
|
sets (x86, x86_64, armeabi-v7a), which is the 80 MB.
|
||||||
|
|
||||||
|
--- apps/user-ui/eas.json
|
||||||
|
~ shafi-dev: explicit buildType apk; gradleCommand
|
||||||
|
":app:assembleRelease -PreactNativeArchitectures=arm64-v8a
|
||||||
|
-Pandroid.enableProguardInReleaseBuilds=true".
|
||||||
|
-PreactNativeArchitectures drops the three unused ABIs, and the ProGuard
|
||||||
|
property turns on R8 + resource shrinking for this profile only (the template
|
||||||
|
reads it via findProperty, so production is untouched).
|
||||||
|
- shafi-dev-arm64 removed: redundant now that shafi-dev is arm64-only.
|
||||||
|
|
||||||
|
[2026-11-01 14:53:35 IST] Home: catalogue memo is the single source for products, tags and products-by-tag.
|
||||||
|
|
||||||
|
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
|
||||||
|
~ Removed `products = productsData?.products || []`, `dashboardTags =
|
||||||
|
productsData?.tags || []` and the separate `productsByTagId` memo. One memo
|
||||||
|
now returns { dashboardTags, products, productsByTagId } and all three are
|
||||||
|
read from it.
|
||||||
|
~ productById Map hoisted out of the per-tag loop (it was rebuilt once per tag).
|
||||||
|
~ Duplicate ids in tag.productIds are skipped (first occurrence wins), so a
|
||||||
|
repeated id renders one card instead of two.
|
||||||
|
~ displayedProducts effect deps use the memo's `products`.
|
||||||
|
--- apps/user-ui/hooks/useProductSlotIdentifier.ts
|
||||||
|
~ getQuickestSlot wrapped in useCallback with [slots, productSlotsMap]. It was
|
||||||
|
a new function every render, which made the catalogue memo recompute on every
|
||||||
|
render (and defeated its useMemo).
|
||||||
|
--- apps/web-ui/src/routes/home.index.tsx
|
||||||
|
~ Same restructure: one memo returns { dashboardTags, allProducts,
|
||||||
|
productsByTagId }, dedupe + hoisted productById, and the dead `extra` branch
|
||||||
|
removed (its filter can never match: orderedIds is built from productIds).
|
||||||
|
--- apps/user-ui/tests/pages/home.test.tsx
|
||||||
|
~ HOME-16 rewritten: duplicate ids in a tag now render once (was pinning the
|
||||||
|
bug).
|
||||||
|
--- apps/user-ui/JEST-TEST-CASES.md
|
||||||
|
~ HOME-16 catalogue row updated.
|
||||||
|
|
||||||
|
[2026-11-01 15:10:50 IST] Home tag selection/expansion moved to a zustand store so a tap stops re-rendering the whole page.
|
||||||
|
|
||||||
|
Selecting a tag used to set Dashboard state, which re-rendered Dashboard, rebuilt
|
||||||
|
ListHeader and rebuilt the SectionList `sections` literal, re-rendering every
|
||||||
|
visible main-list ProductCard as well. The selection now lives outside React
|
||||||
|
state; only the tab strip and the active tag scene subscribe.
|
||||||
|
|
||||||
|
--- apps/user-ui/src/store/homeTagStore.ts (new)
|
||||||
|
+ selectedTagId + expandedByTagId + selectTag/expandTag/resetHomeTags.
|
||||||
|
+ Writes are no-ops when unchanged (same guard as appStore.setHideTabsNavKey)
|
||||||
|
so re-selecting the active tag does not wake subscribers.
|
||||||
|
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
|
||||||
|
~ Removed Dashboard's selectedTagId/expandedByTagId state, activeTagId,
|
||||||
|
handleToggleExpand and the dead pageTint (both styles hardcoded #FFFFFF, so
|
||||||
|
getTagColor/TAG_COLORS had no visible effect).
|
||||||
|
~ TagTabStrip and TagScene subscribe to useHomeTagStore directly; their
|
||||||
|
activeTagId/onSelectTag/expandedByTagId/onToggleExpand props are gone.
|
||||||
|
~ ListHeader no longer receives or forwards selection props.
|
||||||
|
~ listHeader memo deps drop activeTagId/expandedByTagId/handleToggleExpand, so
|
||||||
|
Dashboard no longer produces a new header element on a tag tap.
|
||||||
|
--- apps/user-ui/src/lib/region-switch.ts
|
||||||
|
+ resetHomeTags() on region switch: tag ids are region-scoped.
|
||||||
|
--- apps/user-ui/tests/helpers/reset.ts
|
||||||
|
+ reset the home tag store between cases.
|
||||||
|
--- apps/user-ui/tests/lib/stores.test.ts
|
||||||
|
+ STORE-21: selecting the active tag again keeps store identity.
|
||||||
|
+ STORE-22: resetHomeTags clears selection and expansion.
|
||||||
|
--- apps/user-ui/JEST-TEST-CASES.md
|
||||||
|
~ rows for STORE-21/22.
|
||||||
|
--- apps/web-ui/src/lib/stores/home-tag-store.ts (new)
|
||||||
|
+ Same store, mirrored.
|
||||||
|
--- apps/web-ui/src/routes/home.index.tsx
|
||||||
|
~ selection/expansion read from the store (the web page is one component, so it
|
||||||
|
still subscribes; behaviour matches user-ui).
|
||||||
|
--- apps/web-ui/src/lib/region-switch.ts
|
||||||
|
+ resetHomeTags() on region switch.
|
||||||
|
|
||||||
|
[2026-11-01 17:53:16 IST] user-ui: ProductCard images move from RN Image (Fresco) to expo-image.
|
||||||
|
|
||||||
|
Diagnosed from the device onError payload:
|
||||||
|
"Pool hard cap violation? Hard cap = 301989888 Used size = 301156264 Free
|
||||||
|
size = 0 Request size = 4259840" — Fresco's bitmap pool (288 MiB) was full, so
|
||||||
|
valid images failed to decode. Live catalogue check: 148/149 image URLs return
|
||||||
|
200 image/*; the one 404 is product 84's ref missing the product-images/ prefix.
|
||||||
|
Source images are 1024-1600px, i.e. 4-10 MB decoded at source vs ~0.35 MB at
|
||||||
|
card size.
|
||||||
|
|
||||||
|
--- apps/user-ui/components/ProductCard.tsx
|
||||||
|
~ <RnImage> replaced with expo-image <Image> (already imported, used by every
|
||||||
|
other image surface in the app): contentFit="cover", cachePolicy="memory-disk",
|
||||||
|
recyclingKey=item.id, transition={0}. Glide downsamples to the view size and
|
||||||
|
bounds its caches instead of holding full-size bitmaps in Fresco's pool.
|
||||||
|
~ resizeMode moved out of the style object into contentFit (style resizeMode is
|
||||||
|
not a valid RN style).
|
||||||
|
~ onError now surfaces event.error (was discarded, always "Image failed to
|
||||||
|
load"). Remove the now-unused `Image as RnImage` import.
|
||||||
|
--- apps/user-ui/tests/pages/home.test.tsx
|
||||||
|
~ HOME-38 fires the error on the expo-image mock (testID "expo-image") instead
|
||||||
|
of an RN Image instance.
|
||||||
|
|
||||||
|
[2026-11-01 18:07:16 IST] product-images: generated 1000px copies of the 147 oversized catalogue images (nothing uploaded).
|
||||||
|
|
||||||
|
--- product-images/resized/ (new, untracked)
|
||||||
|
+ one resized copy per row of needs-edit.csv; max side 1000, aspect preserved,
|
||||||
|
JPEG re-encoded at quality 70, PNG kept as PNG. Originals untouched.
|
||||||
|
--- product-images/resized-report.csv (new, untracked)
|
||||||
|
+ per file: old/new dimensions, old/new bytes, old/new decoded MB, delta.
|
||||||
|
- R2 bucket, products.json and DB were not modified.
|
||||||
|
|
||||||
|
[2026-11-01 18:26:30 IST] product-images: 800px pass generated and uploaded over the live keys (prod bucket).
|
||||||
|
|
||||||
|
--- product-images/resized-800/ (new, untracked)
|
||||||
|
+ every referenced catalogue image with max side > 800 resized to 800px
|
||||||
|
(JPEG q70, PNG kept as PNG). Originals left untouched in product-images/.
|
||||||
|
--- product-images/resized-800-report.csv (new, untracked)
|
||||||
|
+ per file: old/new dimensions, bytes and decoded MB.
|
||||||
|
--- R2 (bucket meatfarmer, prefix product-images/)
|
||||||
|
~ the same keys were overwritten with the 800px files; Content-Type preserved
|
||||||
|
per output format. Cloudflare cache purged for every replaced URL.
|
||||||
|
- No DB rows, products.json or version numbers changed.
|
||||||
|
|
||||||
|
[2026-11-01 18:37:42 IST] products.json: append a static cache-busting query to image URLs.
|
||||||
|
|
||||||
|
Client image caches are keyed by URL and the R2 object keys never change, so
|
||||||
|
replaced files were invisible to phones that had cached the old bytes. The
|
||||||
|
generated catalogue now appends ?random=1 to every product image URL and tag
|
||||||
|
imageUrl. Static by design: a per-request value would defeat caching.
|
||||||
|
|
||||||
|
--- apps/backend/src/lib/product-image-cache.ts (new)
|
||||||
|
+ PRODUCT_IMAGE_CACHE_BUST = 'random=1', withImageCacheBust(url) (handles a URL
|
||||||
|
that already has a query) and applyImageCacheBust(catalogue), which rewrites
|
||||||
|
product images and tag imageUrl only.
|
||||||
|
--- apps/backend/src/lib/cloud_cache.ts
|
||||||
|
~ createProductsFileInternal applies applyImageCacheBust before serialising, so
|
||||||
|
only the published products.json carries the query; the admin summary endpoint
|
||||||
|
and the test snapshot controller keep raw URLs.
|
||||||
|
--- apps/backend/tests/unit/product-image-cache.test.ts (new)
|
||||||
|
+ unit coverage for plain URLs, URLs with a query, empty values, the
|
||||||
|
product/tag mapping and input immutability.
|
||||||
|
--- docs/jobs-to-be-added.txt
|
||||||
|
+ job to roll the same asset version out to the remaining image surfaces.
|
||||||
|
|
||||||
|
[2026-11-01 19:03:33 IST] user-ui: enforce a 3-day TTL on the expo-image disk cache.
|
||||||
|
|
||||||
|
expo-image has no per-entry TTL (cachePolicy is only none/disk/memory/memory-disk;
|
||||||
|
the underlying Glide/SDWebImage caches are LRU, no expiry). It does expose
|
||||||
|
Image.clearDiskCache(), so the cache is cleared when the stored timestamp is
|
||||||
|
older than 3 days, checked on mount and whenever the app returns to the
|
||||||
|
foreground. Results in a maximum age of 3 days for any cached image.
|
||||||
|
|
||||||
|
--- apps/user-ui/src/lib/image-cache-ttl.ts (new)
|
||||||
|
+ IMAGE_CACHE_TTL_MS (3 days), IMAGE_CACHE_CLEARED_AT_KEY and
|
||||||
|
shouldClearImageCache(lastClearedAt, now) (null/invalid/future timestamps
|
||||||
|
clear).
|
||||||
|
--- apps/user-ui/src/lib/image-cache-meta.ts (new)
|
||||||
|
+ timestamp persisted in a plain file under expo-file-system's documentDirectory
|
||||||
|
(expo-file-system is a dependency of expo). No SecureStore / StorageService.
|
||||||
|
--- apps/user-ui/src/components/ImageCacheTtl.tsx (new)
|
||||||
|
+ one-shot guard, reads the file timestamp, calls Image.clearDiskCache() only
|
||||||
|
when expired, writes the new timestamp when the clear reports success. Errors
|
||||||
|
never block startup.
|
||||||
|
--- apps/user-ui/app/_layout.tsx
|
||||||
|
+ mount <ImageCacheTtl /> inside CentralStoreInitializer.
|
||||||
|
--- apps/user-ui/tests/mocks/native/common.tsx + tests/jest.config.js
|
||||||
|
+ expo-image mock gains clearDiskCache/clearMemoryCache/prefetch jest.fn
|
||||||
|
statics; expo-file-system is mapped to the same shim.
|
||||||
|
--- apps/user-ui/tests/lib/image-cache-ttl.test.tsx (new)
|
||||||
|
+ IMGCACHE-01..07: helper boundaries, component clear/skip and failed-clear.
|
||||||
|
--- apps/user-ui/tests/lib/image-cache-meta.test.ts (new)
|
||||||
|
+ IMGCACHE-08..10: missing/corrupt file and the write path.
|
||||||
|
--- apps/user-ui/JEST-TEST-CASES.md
|
||||||
|
+ rows for IMGCACHE-01..10.
|
||||||
|
|
|
||||||
|
|
@ -4,4 +4,12 @@ three months. If no, replace it with a placeholder product and delet the actual
|
||||||
2. Job to remove expired coupons.
|
2. Job to remove expired coupons.
|
||||||
3. Job to remove unclaimed expired reserve coupons.
|
3. Job to remove unclaimed expired reserve coupons.
|
||||||
4. Job to clear outdated slots
|
4. Job to clear outdated slots
|
||||||
5. Remove the is vaguely backfilled column from addresses table.
|
5. Remove the is vaguely backfilled column from addresses table.
|
||||||
|
6. Image URL cache-busting rollout. products.json generation now appends a
|
||||||
|
7. static `?random=1` to product image URLs and tag imageUrl (see
|
||||||
|
createProductsFileInternal). Roll the same versioned query out to the remaining
|
||||||
|
image surfaces: product detail API, stores + store detail, banners
|
||||||
|
(banner-store), tags (product-tag-store) and review images. Move the value into
|
||||||
|
a shared ASSET_VERSION constant and bump it whenever image files change; also
|
||||||
|
bump products_version_num so clients fetch the new catalogue file.
|
||||||
|
8. Job to clean expired slots' json files.
|
||||||
Loading…
Add table
Reference in a new issue