Compare commits

...

2 commits

Author SHA1 Message Date
shafi54
d5a4d373ef enh 2026-10-25 10:38:54 +05:30
shafi54
ad6b525748 enh 2026-10-25 10:30:05 +05:30
36 changed files with 2430 additions and 344 deletions

View file

@ -272,7 +272,7 @@ export default function OrderDetails() {
</MyText>
{order.isFlashDelivery && (
<MyText style={tw`text-[9px] font-bold text-amber-600 mt-0.5`}>
⚡ 30-Min
⚡ 1-Hour
</MyText>
)}
</View>

View file

@ -274,7 +274,7 @@ function OrderDetails() {
</MyText>
{order.isFlashDelivery && (
<MyText className="mt-0.5 block text-[9px] font-bold text-amber-600">
⚡ 30-Min
⚡ 1-Hour
</MyText>
)}
</div>

View file

@ -335,6 +335,7 @@ availability ${assetsDomain}regions/${regionId}/av-${availability_version_n
| CACHE-22 | edge | global constants update | refreshed KV reflects new version/store URLs |
| CACHE-23 | edge | missing assets domain/cache key env | payload null/empty; cache tests should fail with actionable message |
| CACHE-24 | edge | bound deleted and recreated | old KV key removed; new bound does not serve stale payload |
| CACHE-115 | happy | `essentialUrls` in API + KV | products/stores/banners/essential-consts under the cache key; availability/slots outside it; store template substitutes |
### 4.2 products.json
@ -436,6 +437,7 @@ availability ${assetsDomain}regions/${regionId}/av-${availability_version_n
| CACHE-96 | edge | essential-consts lag | slots/availability versions may lag live; test only numeric/stable fields |
| CACHE-97 | edge | bound/region identity | match effective bound used to build |
| CACHE-98 | edge | webview fields in file | null/closable (file build uses default host) |
| CACHE-116 | happy | `essentialUrls` in the file | matches the file's own version fields; availability/slots outside the cache key |
### 4.7 Cross-file invariants

File diff suppressed because it is too large Load diff

View file

@ -15,31 +15,20 @@ import {
} from '@/src/dbService'
import { imageUploadS3 } from '@/src/lib/s3-client'
import { getApiCacheKey, getCloudflareApiToken, getCloudflareZoneId, getAssetsDomain } from '@/src/lib/env-exporter'
import { CACHE_FILENAMES } from '@packages/shared'
import {
CACHE_FILENAMES,
availabilityCacheUrl,
availabilityObjectKey,
regionCacheObjectKey,
regionCacheUrl,
slotsCacheUrl,
slotsObjectKey,
storeDetailCacheUrl,
storeDetailObjectKey,
} from '@packages/shared'
import { retryWithExponentialBackoff } from '@/src/lib/retry'
import { refreshGenKvForRegion } from '@/src/lib/gen-store'
const buildRegionCachePath = (regionId: number, version: number, filename: string) =>
`regions/${regionId}/v-${version}/${filename}`
const buildRegionAvailabilityPath = (regionId: number, version: number) =>
`regions/${regionId}/av-${version}/${CACHE_FILENAMES.availability}`
const buildRegionSlotsPath = (regionId: number, version: number) =>
`regions/${regionId}/slots/v-${version}/${CACHE_FILENAMES.slots}`
function constructRegionCacheUrl(regionId: number, filename: string, version: number): string {
return `${getAssetsDomain()}${getApiCacheKey()}/${buildRegionCachePath(regionId, version, filename)}`
}
function constructRegionAvailabilityUrl(regionId: number, version: number): string {
return `${getAssetsDomain()}${buildRegionAvailabilityPath(regionId, version)}`
}
function constructRegionSlotsUrl(regionId: number, version: number): string {
return `${getAssetsDomain()}${buildRegionSlotsPath(regionId, version)}`
}
export interface RegionCacheFilesResult {
regionId: number
cacheVersion: number
@ -56,38 +45,46 @@ export async function createRegionCacheFiles(regionId: number): Promise<RegionCa
console.log(`Starting creation of cache files for region ${regionId}...`)
const cacheVersion = await incrementRegionCacheVersion(regionId)
// Bump the other two counters BEFORE any file is built: `essential-consts.json`
// (and the KV mirror) reads the region's version rows, so it must see the same
// versions the files are about to be written under.
const availabilityVersion = await incrementRegionAvailabilityVersionNum(regionId)
const slotsVersion = await incrementRegionSlotsVersionNum(regionId)
// Create all per-region cache files in parallel
const [
productsKey,
essentialConstsKey,
storesKey,
slotsVersion,
availabilityVersion,
bannersKey,
individualStoreKeys,
] = await Promise.all([
createProductsFileInternal(regionId, cacheVersion),
createEssentialConstsFileInternal(regionId, cacheVersion),
createStoresFileInternal(regionId, cacheVersion),
createSlotsCacheFile(regionId, false),
createAvailabilityCacheFile(regionId, false),
createBannersFileInternal(regionId, cacheVersion),
createAllStoresFilesInternal(regionId, cacheVersion),
// Side effects only; their versions were hoisted above.
createSlotsCacheFile(regionId, false, slotsVersion),
createAvailabilityCacheFile(regionId, false, availabilityVersion),
])
const stores = await getStoresSummary(regionId)
const assetsDomain = getAssetsDomain()
const apiCacheKey = getApiCacheKey()
// Collect all per-region URLs for batch cache purge
const urls = [
constructRegionCacheUrl(regionId, CACHE_FILENAMES.products, cacheVersion),
constructRegionCacheUrl(regionId, CACHE_FILENAMES.essentialConsts, cacheVersion),
constructRegionCacheUrl(regionId, CACHE_FILENAMES.stores, cacheVersion),
constructRegionSlotsUrl(regionId, slotsVersion),
constructRegionAvailabilityUrl(regionId, availabilityVersion),
constructRegionCacheUrl(regionId, CACHE_FILENAMES.banners, cacheVersion),
...stores.map((store) => constructRegionCacheUrl(regionId, `stores/${store.id}.json`, cacheVersion)),
]
regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, CACHE_FILENAMES.products),
regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, CACHE_FILENAMES.essentialConsts),
regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, CACHE_FILENAMES.stores),
slotsCacheUrl(assetsDomain, regionId, slotsVersion),
availabilityCacheUrl(assetsDomain, regionId, availabilityVersion),
regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, CACHE_FILENAMES.banners),
...stores.map((store) =>
storeDetailCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, store.id)
),
].filter((url) => url.length > 0)
// Purge all caches in one batch with retry
try {
@ -134,7 +131,12 @@ async function createProductsFileInternal(regionId: number, version: number): Pr
const productsData = await scaffoldProducts(regionId)
const jsonContent = JSON.stringify(productsData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
const filePath = `${getApiCacheKey()}/${buildRegionCachePath(regionId, version, CACHE_FILENAMES.products)}`
const filePath = regionCacheObjectKey(
getApiCacheKey(),
regionId,
version,
CACHE_FILENAMES.products
)
console.log(filePath)
return await imageUploadS3(
@ -145,12 +147,16 @@ async function createProductsFileInternal(regionId: number, version: number): Pr
}
export async function createAvailabilityCacheFile(regionId: number, refresh = true): Promise<number> {
const version = await incrementRegionAvailabilityVersionNum(regionId)
export async function createAvailabilityCacheFile(
regionId: number,
refresh = true,
version?: number
): Promise<number> {
const fileVersion = version ?? (await incrementRegionAvailabilityVersionNum(regionId))
const availabilityData = await scaffoldAvailability(regionId)
const jsonContent = JSON.stringify(availabilityData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
const filePath = buildRegionAvailabilityPath(regionId, version)
const filePath = availabilityObjectKey(regionId, fileVersion)
console.log(filePath)
await imageUploadS3(
@ -161,7 +167,7 @@ export async function createAvailabilityCacheFile(regionId: number, refresh = tr
if (refresh) await refreshGenKvForRegion(regionId)
return version
return fileVersion
}
async function createEssentialConstsFileInternal(regionId: number, version: number): Promise<string> {
@ -173,7 +179,7 @@ async function createEssentialConstsFileInternal(regionId: number, version: numb
return await imageUploadS3(
buffer,
'application/json',
`${getApiCacheKey()}/${buildRegionCachePath(regionId, version, CACHE_FILENAMES.essentialConsts)}`
regionCacheObjectKey(getApiCacheKey(), regionId, version, CACHE_FILENAMES.essentialConsts)
)
}
@ -184,16 +190,20 @@ async function createStoresFileInternal(regionId: number, version: number): Prom
return await imageUploadS3(
buffer,
'application/json',
`${getApiCacheKey()}/${buildRegionCachePath(regionId, version, CACHE_FILENAMES.stores)}`
regionCacheObjectKey(getApiCacheKey(), regionId, version, CACHE_FILENAMES.stores)
)
}
export async function createSlotsCacheFile(regionId: number, refresh = true): Promise<number> {
const version = await incrementRegionSlotsVersionNum(regionId)
export async function createSlotsCacheFile(
regionId: number,
refresh = true,
version?: number
): Promise<number> {
const fileVersion = version ?? (await incrementRegionSlotsVersionNum(regionId))
const slotsData = await scaffoldSlotsWithProducts(regionId)
const jsonContent = JSON.stringify(slotsData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
const filePath = buildRegionSlotsPath(regionId, version)
const filePath = slotsObjectKey(regionId, fileVersion)
console.log(filePath)
await imageUploadS3(
@ -204,7 +214,7 @@ export async function createSlotsCacheFile(regionId: number, refresh = true): Pr
if (refresh) await refreshGenKvForRegion(regionId)
return version
return fileVersion
}
async function createBannersFileInternal(regionId: number, version: number): Promise<string> {
@ -214,7 +224,7 @@ async function createBannersFileInternal(regionId: number, version: number): Pro
return await imageUploadS3(
buffer,
'application/json',
`${getApiCacheKey()}/${buildRegionCachePath(regionId, version, CACHE_FILENAMES.banners)}`
regionCacheObjectKey(getApiCacheKey(), regionId, version, CACHE_FILENAMES.banners)
)
}
@ -230,7 +240,7 @@ async function createAllStoresFilesInternal(regionId: number, version: number):
const s3Key = await imageUploadS3(
buffer,
'application/json',
`${getApiCacheKey()}/${buildRegionCachePath(regionId, version, `stores/${store.id}.json`)}`
storeDetailObjectKey(getApiCacheKey(), regionId, version, store.id)
)
results.push(s3Key)
}

View file

@ -28,6 +28,8 @@ async function allBoundIds(): Promise<number[]> {
}
async function putBound(kv: any, boundId: number): Promise<void> {
// The scaffold payload carries `essentialUrls` alongside the version fields,
// so the KV mirror serves exactly the URLs the cache writer published.
const payload = await buildEssentialConsts(boundId)
await kv.put(genKvKeyForBound(boundId), JSON.stringify(payload))
}

View file

@ -92,6 +92,8 @@ export {
getSlotDeliverySequence,
updateSlotDeliverySequence,
staleSlotsCleanup,
SLOT_SKU_RETENTION_HOURS,
slotSkuCleanupCutoff,
// Admin - Staff User
getStaffUserByName,
getStaffUserById,

View file

@ -124,9 +124,9 @@ export const slotsRouter = router({
console.error('Failed to regenerate slots cache after slot create:', error)
})
// Cleanup stale product slot associations for THIS region only. Awaited so
// the incremental 20-slot window is not skipped when the mutation returns;
// the .catch keeps a cleanup failure from failing slot creation.
// Drop skuIds from slots delivered more than 36h ago for THIS region only.
// Awaited so the cleanup is not skipped when the mutation returns; the
// .catch keeps a cleanup failure from failing slot creation.
await staleSlotsCleanup(ctx.staffUser.regionId).catch((error) => {
console.error('Failed to cleanup stale slots:', error)
})

View file

@ -25,6 +25,7 @@ import {
} from '@/src/lib/const-store'
import { readEssentialConstsFromKv } from '@/src/lib/gen-store'
import { getAssetsDomain, getApiCacheKey } from '@/src/lib/env-exporter'
import { buildEssentialUrls } from '@packages/shared'
const polygon = turfPolygon(mbnrGeoJson.features[0].geometry.coordinates);
@ -54,6 +55,12 @@ export async function scaffoldEssentialConsts(boundId: number) {
// Flat union of global + region + bound consts (+ env + identity). Key names
// match the three tables exactly so clients read one flat object.
const productsVersionNum = pickNumber(region['products_version_num'], 0)
const availabilityVersionNum = pickNumber(region['availability_version_num'], 0)
const slotsVersionNum = pickNumber(region['slots_version_num'], 0)
const assetsDomain = getAssetsDomain()
const apiCacheKey = getApiCacheKey()
return {
// global_consts
versionNum: pickRaw(global['versionNum'], null),
@ -61,9 +68,9 @@ export async function scaffoldEssentialConsts(boundId: number) {
appStoreUrl: pickRaw(global['appStoreUrl'], null),
internalAppVersion: pickNumber(global['internalAppVersion'], 1),
// region_consts
products_version_num: pickNumber(region['products_version_num'], 0),
availability_version_num: pickNumber(region['availability_version_num'], 0),
slots_version_num: pickNumber(region['slots_version_num'], 0),
products_version_num: productsVersionNum,
availability_version_num: availabilityVersionNum,
slots_version_num: slotsVersionNum,
popularItems: pickRaw(region['popularItems'], null),
allItemsOrder: pickRaw(region['allItemsOrder'], null),
supportMobile: pickRaw(region['supportMobile'], ''),
@ -77,10 +84,22 @@ export async function scaffoldEssentialConsts(boundId: number) {
// Per bound: each bound switches flash delivery on/off independently.
isFlashDeliveryEnabled: pickBool(boundConsts['isFlashDeliveryEnabled'], false),
// env + identity
assetsDomain: getAssetsDomain(),
apiCacheKey: getApiCacheKey(),
assetsDomain,
apiCacheKey,
regionId,
boundId,
// Every cache file this region can read, built once for clients + the KV
// mirror. Empty strings mean "not configured"; clients fall back.
essentialUrls: buildEssentialUrls({
assetsDomain,
apiCacheKey,
regionId,
versions: {
products: productsVersionNum,
availability: availabilityVersionNum,
slots: slotsVersionNum,
},
}),
// stale-client notice (overridden per-request in the procedure)
webViewHtml: null,
webviewHtml: null,

View file

@ -1,5 +1,5 @@
/**
* CACHE-88..98 — `banners.json` and the versioned `essential-consts.json`
* CACHE-88..98, CACHE-116 — `banners.json` and the versioned `essential-consts.json`
* (catalogue §4.6).
*
* `banners.json` is rebuilt asynchronously with `products_version_num` (the
@ -286,4 +286,33 @@ describe('essential-consts.json (CACHE-94..98)', () => {
expect(doc.webViewHtml).toBeNull()
expect(doc.isWebviewClosable).toBe(true)
})
it('CACHE-116: the file publishes essentialUrls for its own versions', () => {
const doc = shared.essentialConsts.doc
const urls = doc.essentialUrls
expect(urls).toBeTruthy()
expect(urls.productsUrl).toBe(
`${doc.assetsDomain}${doc.apiCacheKey}/regions/${doc.regionId}/v-${doc.products_version_num}/products.json`
)
expect(urls.storesUrl).toBe(
`${doc.assetsDomain}${doc.apiCacheKey}/regions/${doc.regionId}/v-${doc.products_version_num}/stores.json`
)
expect(urls.bannersUrl).toBe(
`${doc.assetsDomain}${doc.apiCacheKey}/regions/${doc.regionId}/v-${doc.products_version_num}/banners.json`
)
expect(urls.essentialConstsUrl).toBe(
`${doc.assetsDomain}${doc.apiCacheKey}/regions/${doc.regionId}/v-${doc.products_version_num}/essential-consts.json`
)
// Availability/slots keep the existing bucket layout (outside the cache key).
expect(urls.availabilityUrl).toBe(
`${doc.assetsDomain}regions/${doc.regionId}/av-${doc.availability_version_num}/availability.json`
)
expect(urls.slotsUrl).toBe(
`${doc.assetsDomain}regions/${doc.regionId}/slots/v-${doc.slots_version_num}/slots.json`
)
expect(urls.storeDetailUrlTemplate).toBe(
`${doc.assetsDomain}${doc.apiCacheKey}/regions/${doc.regionId}/v-${doc.products_version_num}/stores/{storeId}.json`
)
})
})

View file

@ -1,5 +1,5 @@
/**
* CACHE-01..24 — essential constants (catalogue §4.1).
* CACHE-01..24, CACHE-115 — essential constants (catalogue §4.1).
*
* `common.essentialConsts({ boundId })` is served from the per-bound KV mirror
* (`readEssentialConstsFromKv`); the payload is a flat union of
@ -30,7 +30,16 @@ import {
setRegionConstant,
squareGeojson,
} from '../helpers/fixtures'
import { getEssentialConsts, productsCacheUrl } from '../helpers/cache'
import {
availabilityCacheUrl,
bannersCacheUrl,
essentialConstsCacheUrl,
getEssentialConsts,
productsCacheUrl,
slotsCacheUrl,
storeDetailCacheUrl,
storesCacheUrl,
} from '../helpers/cache'
import { TEST_BOUND_ID, TEST_OTHER_BOUND_ID, TEST_REGION_ID, TEST_OTHER_REGION_ID } from '../helpers/env'
jest.setTimeout(300_000)
@ -146,6 +155,32 @@ describe('common.essentialConsts shape (CACHE-01..05)', () => {
})
})
describe('common.essentialConsts published URLs (CACHE-115)', () => {
it('CACHE-115: essentialUrls matches the versioned CDN files (API + KV mirror)', async () => {
const consts = await getEssentialConsts(TEST_BOUND_ID)
const urls = consts.essentialUrls
expect(urls).toBeTruthy()
expect(urls!.productsUrl).toBe(productsCacheUrl(consts))
expect(urls!.storesUrl).toBe(storesCacheUrl(consts))
expect(urls!.bannersUrl).toBe(bannersCacheUrl(consts))
expect(urls!.essentialConstsUrl).toBe(essentialConstsCacheUrl(consts))
expect(urls!.availabilityUrl).toBe(availabilityCacheUrl(consts))
expect(urls!.slotsUrl).toBe(slotsCacheUrl(consts))
// The per-store file cannot be a single URL: the template is completed by
// the client with the store id.
expect(urls!.storeDetailUrlTemplate).toContain('{storeId}')
expect(urls!.storeDetailUrlTemplate.replace('{storeId}', '42')).toBe(
storeDetailCacheUrl(consts, 42)
)
// Existing bucket layout: availability/slots sit outside the api cache key.
expect(urls!.availabilityUrl).not.toContain(`/${consts.apiCacheKey}/`)
expect(urls!.slotsUrl).not.toContain(`/${consts.apiCacheKey}/`)
})
})
describe('common.essentialConsts fallbacks (CACHE-06..11)', () => {
it('CACHE-06: a missing numeric bound const falls back to 200/0/500/69', async () => {
await withBoundSettings(

View file

@ -18,6 +18,13 @@
import { apiClient, sleep } from './api'
import { staffSession } from './sessions'
import { API_BASE_URL, CACHE_POLL_INTERVAL_MS, CACHE_POLL_TIMEOUT_MS, TEST_BOUND_ID, TEST_REGION_ID } from './env'
import {
CACHE_FILENAMES,
availabilityCacheUrl as buildAvailabilityCacheUrl,
regionCacheUrl,
slotsCacheUrl as buildSlotsCacheUrl,
storeDetailCacheUrl as buildStoreDetailCacheUrl,
} from '@packages/shared'
export interface EssentialConsts {
regionId: number
@ -27,6 +34,8 @@ export interface EssentialConsts {
products_version_num: number
slots_version_num: number
availability_version_num: number
/** Published CDN URLs (absent in payloads written before this field existed). */
essentialUrls?: Record<string, string>
webviewHtml?: string | null
isWebviewClosable?: boolean
[key: string]: unknown
@ -117,38 +126,46 @@ export function versionOf(consts: EssentialConsts, kind: CacheKind): number {
return value
}
const base = (c: EssentialConsts, regionId = c.regionId) => `${c.assetsDomain}${c.apiCacheKey}/regions/${regionId}`
const baseRegion = (c: EssentialConsts, regionId?: number) => regionId ?? c.regionId
export const productsCacheUrl = (c: EssentialConsts, regionId?: number, version = versionOf(c, 'products')) =>
`${base(c, regionId)}/v-${version}/products.json`
regionCacheUrl(c.assetsDomain, c.apiCacheKey, baseRegion(c, regionId), version, CACHE_FILENAMES.products)
export const storesCacheUrl = (c: EssentialConsts, regionId?: number, version = versionOf(c, 'products')) =>
`${base(c, regionId)}/v-${version}/stores.json`
regionCacheUrl(c.assetsDomain, c.apiCacheKey, baseRegion(c, regionId), version, CACHE_FILENAMES.stores)
export const storeDetailCacheUrl = (
c: EssentialConsts,
storeId: number,
regionId?: number,
version = versionOf(c, 'products')
) => `${base(c, regionId)}/v-${version}/stores/${storeId}.json`
) =>
buildStoreDetailCacheUrl(c.assetsDomain, c.apiCacheKey, baseRegion(c, regionId), version, storeId)
export const bannersCacheUrl = (c: EssentialConsts, regionId?: number, version = versionOf(c, 'products')) =>
`${base(c, regionId)}/v-${version}/banners.json`
regionCacheUrl(c.assetsDomain, c.apiCacheKey, baseRegion(c, regionId), version, CACHE_FILENAMES.banners)
export const essentialConstsCacheUrl = (
c: EssentialConsts,
regionId?: number,
version = versionOf(c, 'products')
) => `${base(c, regionId)}/v-${version}/essential-consts.json`
) =>
regionCacheUrl(
c.assetsDomain,
c.apiCacheKey,
baseRegion(c, regionId),
version,
CACHE_FILENAMES.essentialConsts
)
export const slotsCacheUrl = (c: EssentialConsts, regionId?: number, version = versionOf(c, 'slots')) =>
`${c.assetsDomain}regions/${regionId ?? c.regionId}/slots/v-${version}/slots.json`
buildSlotsCacheUrl(c.assetsDomain, baseRegion(c, regionId), version)
export const availabilityCacheUrl = (
c: EssentialConsts,
regionId?: number,
version = versionOf(c, 'availability')
) => `${c.assetsDomain}regions/${regionId ?? c.regionId}/av-${version}/availability.json`
) => buildAvailabilityCacheUrl(c.assetsDomain, baseRegion(c, regionId), version)
/** GET a cache file and parse it; throws with the status on a non-2xx. */
export async function fetchCacheJson<T = unknown>(url: string): Promise<T> {

View file

@ -0,0 +1,132 @@
/**
* Unit tests for the shared regional CDN URL builders
* (`packages/shared/region-cache-urls.ts`).
*
* Both the backend cache writer/publisher and the UIs use these, so the path
* shapes here are a compatibility contract with the existing R2 buckets.
*/
import {
CACHE_FILENAMES,
availabilityCacheUrl,
buildEssentialUrls,
buildStoreDetailUrlTemplate,
cachedFileUrl,
regionCacheUrl,
slotsCacheUrl,
storeDetailCacheUrl,
} from '@packages/shared'
const DOMAIN = 'https://assets.test/'
const KEY = 'api-cache-dev'
const REGION = 1
const VERSIONS = { products: 12, availability: 34, slots: 56 }
describe('region cache URLs', () => {
it('builds the versioned files under the api cache key', () => {
expect(regionCacheUrl(DOMAIN, KEY, REGION, VERSIONS.products, CACHE_FILENAMES.products)).toBe(
'https://assets.test/api-cache-dev/regions/1/v-12/products.json'
)
expect(regionCacheUrl(DOMAIN, KEY, REGION, VERSIONS.products, CACHE_FILENAMES.stores)).toBe(
'https://assets.test/api-cache-dev/regions/1/v-12/stores.json'
)
expect(regionCacheUrl(DOMAIN, KEY, REGION, VERSIONS.products, CACHE_FILENAMES.banners)).toBe(
'https://assets.test/api-cache-dev/regions/1/v-12/banners.json'
)
expect(
regionCacheUrl(DOMAIN, KEY, REGION, VERSIONS.products, CACHE_FILENAMES.essentialConsts)
).toBe('https://assets.test/api-cache-dev/regions/1/v-12/essential-consts.json')
})
it('keeps availability and slots outside the api cache key', () => {
expect(availabilityCacheUrl(DOMAIN, REGION, VERSIONS.availability)).toBe(
'https://assets.test/regions/1/av-34/availability.json'
)
expect(slotsCacheUrl(DOMAIN, REGION, VERSIONS.slots)).toBe(
'https://assets.test/regions/1/slots/v-56/slots.json'
)
})
it('builds the store-detail URL and its {storeId} template', () => {
expect(storeDetailCacheUrl(DOMAIN, KEY, REGION, VERSIONS.products, 42)).toBe(
'https://assets.test/api-cache-dev/regions/1/v-12/stores/42.json'
)
const template = buildStoreDetailUrlTemplate(DOMAIN, KEY, REGION, VERSIONS.products)
expect(template).toBe(
'https://assets.test/api-cache-dev/regions/1/v-12/stores/{storeId}.json'
)
expect(template.replace('{storeId}', '42')).toBe(
storeDetailCacheUrl(DOMAIN, KEY, REGION, VERSIONS.products, 42)
)
})
it('normalises a domain without a trailing slash', () => {
expect(regionCacheUrl('https://assets.test', KEY, REGION, 3, CACHE_FILENAMES.products)).toBe(
'https://assets.test/api-cache-dev/regions/1/v-3/products.json'
)
})
it('publishes every URL from buildEssentialUrls', () => {
expect(buildEssentialUrls({ assetsDomain: DOMAIN, apiCacheKey: KEY, regionId: REGION, versions: VERSIONS }))
.toEqual({
productsUrl: 'https://assets.test/api-cache-dev/regions/1/v-12/products.json',
storesUrl: 'https://assets.test/api-cache-dev/regions/1/v-12/stores.json',
bannersUrl: 'https://assets.test/api-cache-dev/regions/1/v-12/banners.json',
essentialConstsUrl:
'https://assets.test/api-cache-dev/regions/1/v-12/essential-consts.json',
availabilityUrl: 'https://assets.test/regions/1/av-34/availability.json',
slotsUrl: 'https://assets.test/regions/1/slots/v-56/slots.json',
storeDetailUrlTemplate:
'https://assets.test/api-cache-dev/regions/1/v-12/stores/{storeId}.json',
})
})
it('sends empty strings when the domain is unavailable', () => {
const urls = buildEssentialUrls({
assetsDomain: null,
apiCacheKey: KEY,
regionId: REGION,
versions: VERSIONS,
})
expect(Object.values(urls).every((url) => url === '')).toBe(true)
})
it('still publishes availability/slots when only the api cache key is unavailable', () => {
const urls = buildEssentialUrls({
assetsDomain: DOMAIN,
apiCacheKey: '',
regionId: REGION,
versions: VERSIONS,
})
expect(urls.productsUrl).toBe('')
expect(urls.storesUrl).toBe('')
expect(urls.bannersUrl).toBe('')
expect(urls.essentialConstsUrl).toBe('')
expect(urls.storeDetailUrlTemplate).toBe('')
expect(urls.availabilityUrl).toBe('https://assets.test/regions/1/av-34/availability.json')
expect(urls.slotsUrl).toBe('https://assets.test/regions/1/slots/v-56/slots.json')
})
})
describe('cachedFileUrl', () => {
const urls = buildEssentialUrls({
assetsDomain: DOMAIN,
apiCacheKey: KEY,
regionId: REGION,
versions: VERSIONS,
})
it('maps a filename to its published URL', () => {
expect(cachedFileUrl(urls, CACHE_FILENAMES.products)).toBe(urls.productsUrl)
expect(cachedFileUrl(urls, CACHE_FILENAMES.stores)).toBe(urls.storesUrl)
expect(cachedFileUrl(urls, CACHE_FILENAMES.banners)).toBe(urls.bannersUrl)
expect(cachedFileUrl(urls, CACHE_FILENAMES.essentialConsts)).toBe(urls.essentialConstsUrl)
expect(cachedFileUrl(urls, CACHE_FILENAMES.availability)).toBe(urls.availabilityUrl)
expect(cachedFileUrl(urls, CACHE_FILENAMES.slots)).toBe(urls.slotsUrl)
})
it('returns null for a missing payload, unknown file, or empty URL', () => {
expect(cachedFileUrl(undefined, CACHE_FILENAMES.products)).toBeNull()
expect(cachedFileUrl(urls, 'unknown.json')).toBeNull()
expect(cachedFileUrl({ ...urls, productsUrl: '' }, CACHE_FILENAMES.products)).toBeNull()
})
})

View file

@ -0,0 +1,35 @@
/**
* Unit tests for the slot skuIds retention window.
*
* `staleSlotsCleanup` used to walk a rolling "20 newest rows by id" window of
* `delivery_slot_info` and clear one row per slot creation. A burst of creations
* (test suites/imports) pushed that window through upcoming slots and wiped
* their `sku_ids`, which the customer app reads as "no delivery slot" -> every
* product out of stock. The cleanup is now time-based: only slots delivered more
* than 36 hours ago lose their sku list.
*/
import { SLOT_SKU_RETENTION_HOURS, slotSkuCleanupCutoff } from '@/src/dbService'
const NOW = new Date('2026-10-25T12:00:00.000Z')
const HOUR_MS = 60 * 60 * 1000
describe('slot sku retention', () => {
it('retains skuIds for 36 hours after delivery', () => {
expect(SLOT_SKU_RETENTION_HOURS).toBe(36)
expect(slotSkuCleanupCutoff(NOW).toISOString()).toBe('2026-10-24T00:00:00.000Z')
})
it('only cuts off slots delivered at/ before the cutoff', () => {
const cutoff = slotSkuCleanupCutoff(NOW)
const isCleared = (delivery: Date) => delivery.getTime() <= cutoff.getTime()
// Upcoming and recently delivered slots are never cleared.
expect(isCleared(new Date(NOW.getTime() + HOUR_MS))).toBe(false)
expect(isCleared(new Date(NOW.getTime() - 35 * HOUR_MS))).toBe(false)
expect(isCleared(new Date('2026-10-26T02:30:00.000Z'))).toBe(false)
// Slots at or beyond the 36h boundary are cleared.
expect(isCleared(cutoff)).toBe(true)
expect(isCleared(new Date(NOW.getTime() - 37 * HOUR_MS))).toBe(true)
})
})

View file

@ -408,7 +408,7 @@ Mock `useAllProducts` via `common.essentialConsts` + versioned `products.json` a
| HOME-100 | edge | signed in, orders loading | small spinner card |
| HOME-101 | happy | one upcoming order | id, “N items • ₹total”, status |
| HOME-102 | edge | confirmed/packaged status | status chip hidden |
| HOME-103 | edge | flash order | FLASH + “30-Min” |
| HOME-103 | edge | flash order | FLASH + “1-Hour” |
| HOME-104 | edge | cancelled order | excluded |
| HOME-105 | edge | success delivery order | excluded |
| HOME-106 | edge | flash + scheduled orders | flash first |
@ -418,6 +418,13 @@ Mock `useAllProducts` via `common.essentialConsts` + versioned `products.json` a
| HOME-110 | edge | support mobile present | “Need help? Call …”; tap opens `tel:` |
| HOME-111 | happy | tap order card | navigation target set; `replace('/(drawer)/(tabs)/me')` |
| HOME-112 | edge | more than one order | pagination dots; scroll updates active dot |
| HOME-113 | edge | delivery > 24h ago | excluded from the glimpse |
| HOME-114 | edge | delivery within 24h | still shown |
| HOME-115 | edge | scheduled order, no delivery date | excluded |
| HOME-116 | edge | flash order, no delivery date | 1-hour promise keeps it visible |
| HOME-117 | edge | old flash order, no delivery date | excluded |
| HOME-118 | edge | new published version, file pending | previous catalog stays; no “Loading products...” |
| HOME-119 | edge | background refresh fails with data present | last catalog stays; no error screen |
---
@ -1448,6 +1455,11 @@ Covered by HOME-81..98, plus:
| API-17 | edge | availability error | products still render with defaults? assert current |
| API-18 | edge | region change | URL/query key changes |
| API-19 | edge | `useRegionalConsts` passthrough | same data |
| API-20 | happy | API `essentialUrls` present | used verbatim; constructed URLs untouched |
| API-21 | edge | `essentialUrls` empty | shared builders used as fallback |
| API-22 | happy | store-detail template | `{storeId}` replaced; fetched |
| API-23 | edge | empty store-detail template | shared builder fallback |
| API-24 | edge | version bump, new file pending | previous catalog stays; `isLoading` false, placeholder true |
### Region and location — `tests/lib/use-region.test.tsx`, `location-store.test.ts`
@ -1480,6 +1492,10 @@ Covered by HOME-81..98, plus:
| REGION-25 | edge | cached regions + address, live pending | starts from cache; live requests still run |
| REGION-26 | edge | live data differs from cache | region/bound/address reconcile to live |
| REGION-27 | edge | consumer above AuthProvider | does not settle launch decision; authenticated instance anchors on default |
| REGION-28 | edge | cached location resolution, live pending | opens cached region; live request still runs |
| REGION-29 | edge | live resolution differs from cache | region/bound switch to the live answer |
| REGION-30 | edge | live resolution succeeds | persisted to StorageServiceCasual |
| REGION-31 | edge | live resolution null, region adopted from cache | region cleared for the chooser |
| LOCSTORE-01 | happy | start once | one permission/fix; second start no-op |
| LOCSTORE-02 | error | denied | status denied, coords null |
| LOCSTORE-03 | edge | services off | status services-off |

View file

@ -682,7 +682,9 @@ export default function Dashboard() {
);
}
if (error || constsError) {
// Only take over the screen when there is nothing else to show. A failed
// background refresh keeps the last loaded catalog on screen.
if ((error || constsError) && products.length === 0) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<MaterialIcons name="error-outline" size={48} color="#EF4444" />

View file

@ -154,7 +154,7 @@ const OrderItem: React.FC<OrderItemProps> = ({
</MyText>
{item.isFlashDelivery && (
<View style={tw`flex-row items-center mt-1`}>
<MyText style={tw`text-[9px] font-bold text-amber-600 uppercase`}>⚡ 30-Min Delivery</MyText>
<MyText style={tw`text-[9px] font-bold text-amber-600 uppercase`}>⚡ 1-Hour Delivery</MyText>
</View>
)}
</View>

View file

@ -27,7 +27,7 @@ function OrderCard({ order, onPress, supportMobile }: OrderCardProps) {
const statusLabel = orderStatusManipulator(order.deliveryStatus);
const hideStatus = ['confirmed', 'packaged'].includes(statusLabel.toLowerCase());
const deliveryPrimaryLabel = order.isFlashDelivery
? "30-Min"
? "1-Hour"
: (() => {
const startTime = dayjs(order.deliveryDate);
const endTime = startTime.add(1, 'hour');

View file

@ -1,10 +1,10 @@
import React, { useEffect, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useQuery, keepPreviousData } from '@tanstack/react-query'
import { fetchJson } from '@/src/lib/fetch-json'
import { trpc } from '@/src/trpc-client'
import type { ProductPriceFlags } from '@packages/shared'
import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType, StoreWithProductsApiType, AvailabilityApiType } from "@backend/trpc/router";
import { CACHE_FILENAMES } from "@packages/shared";
import { CACHE_FILENAMES, availabilityCacheUrl, cachedFileUrl, regionCacheUrl, slotsCacheUrl, storeDetailCacheUrl } from "@packages/shared";
import { StorageServiceCasual } from 'common-ui';
import { useRegion } from '@/src/hooks/useRegion'
import { useAddressStore } from '@/src/store/addressStore'
@ -126,6 +126,11 @@ function useCacheUrl(filename: string): string | null {
const { data: essentialConsts } = useGetEssentialConsts()
const regionId = useDiscoveryRegionId(essentialConsts)
// The backend publishes these URLs. Trust them first; construct only when an
// older payload or a persisted snapshot from an older install lacks them.
const published = cachedFileUrl(essentialConsts?.essentialUrls, filename)
if (published) return published
const assetsDomain = essentialConsts?.assetsDomain
const apiCacheKey = essentialConsts?.apiCacheKey
const productsVersionNum = essentialConsts?.products_version_num
@ -134,13 +139,16 @@ function useCacheUrl(filename: string): string | null {
return null
}
return `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${productsVersionNum}/${filename}`
return regionCacheUrl(assetsDomain, apiCacheKey, regionId, productsVersionNum, filename) || null
}
function useAvailabilityCacheUrl(): string | null {
const { data: essentialConsts } = useGetEssentialConsts()
const regionId = useDiscoveryRegionId(essentialConsts)
const published = cachedFileUrl(essentialConsts?.essentialUrls, CACHE_FILENAMES.availability)
if (published) return published
const assetsDomain = essentialConsts?.assetsDomain
const availabilityVersionNum = essentialConsts?.availability_version_num
@ -148,13 +156,16 @@ function useAvailabilityCacheUrl(): string | null {
return null
}
return `${assetsDomain}regions/${regionId}/av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
return availabilityCacheUrl(assetsDomain, regionId, availabilityVersionNum) || null
}
function useSlotsCacheUrl(): string | null {
const { data: essentialConsts } = useGetEssentialConsts()
const regionId = useDiscoveryRegionId(essentialConsts)
const published = cachedFileUrl(essentialConsts?.essentialUrls, CACHE_FILENAMES.slots)
if (published) return published
const assetsDomain = essentialConsts?.assetsDomain
const slotsVersionNum = essentialConsts?.slots_version_num
@ -162,7 +173,7 @@ function useSlotsCacheUrl(): string | null {
return null
}
return `${assetsDomain}regions/${regionId}/slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
return slotsCacheUrl(assetsDomain, regionId, slotsVersionNum) || null
}
export function useAllProducts() {
@ -181,6 +192,9 @@ export function useAllProducts() {
},
staleTime: 60000, // 1 minute
enabled: !!cacheUrl,
// A published version bump changes the key. Keep showing the previous
// catalog until the new file lands, then swap atomically (no blank screen).
placeholderData: keepPreviousData,
})
const mergedProducts = React.useMemo(() => {
@ -237,6 +251,8 @@ export function useAvailability() {
},
staleTime: 60000, // 1 minute
enabled: !!cacheUrl,
// Keep the previous prices/flags while the new availability file loads.
placeholderData: keepPreviousData,
})
}
@ -255,6 +271,7 @@ export function useStores() {
},
staleTime: 60000, // 1 minute
enabled: !!cacheUrl,
placeholderData: keepPreviousData,
})
}
@ -273,6 +290,7 @@ export function useSlots() {
},
staleTime: 60000, // 1 minute
enabled: !!cacheUrl,
placeholderData: keepPreviousData,
})
}
@ -284,9 +302,12 @@ export function useStoreWithProducts(storeId: number) {
const apiCacheKey = essentialConsts?.apiCacheKey
const cacheVersion = essentialConsts?.products_version_num;
const cacheUrl = assetsDomain && apiCacheKey && regionId != null
? `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/stores/${storeId}.json`
: null
const publishedTemplate = essentialConsts?.essentialUrls?.storeDetailUrlTemplate
const cacheUrl = publishedTemplate
? publishedTemplate.replace('{storeId}', String(storeId))
: assetsDomain && apiCacheKey && regionId != null && cacheVersion != null
? storeDetailCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, storeId) || null
: null
const version = cacheUrl ?? ''
return useQuery<StoreWithProductsResponse>({
@ -300,5 +321,6 @@ export function useStoreWithProducts(storeId: number) {
},
staleTime: 60000, // 1 minute
enabled: !!cacheUrl,
placeholderData: keepPreviousData,
})
}

View file

@ -1,16 +1,19 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import type { RegionSummary, RegionBoundSummary } from '@packages/shared'
import type { RegionSummary, RegionBoundSummary, ResolvedRegion } from '@packages/shared'
import { useRegionStore } from '@/src/store/regionStore'
import { useAddressStore } from '@/src/store/addressStore'
import { useLocationStore } from '@/src/store/locationStore'
import { trpc } from '@/src/trpc-client'
import { confirmRegionSwitch } from '@/src/lib/region-switch'
import {
readCachedLocationResolution,
readCachedRegions,
readCachedUserAddresses,
writeCachedLocationResolution,
writeCachedRegions,
writeCachedUserAddresses,
type CachedLocationResolution,
type CachedUserAddressesResponse,
} from '@/src/lib/region-cache'
import { useAuthOptional } from '@/src/contexts/AuthContext'
@ -25,6 +28,15 @@ const RESOLVE_TIMEOUT_MS = 8000
let startupCheckDone = false
let startupLaunchRegionId: number | null | undefined
/**
* Identity of a coordinate resolution, used to notice that the live answer
* differs from the cached one the launch decision started from.
*/
function resolutionSignature(resolved: ResolvedRegion | null): string {
if (resolved == null) return 'none'
return `${resolved.region.id}:${resolved.bound?.id ?? 'none'}`
}
/**
* The single source of truth for the browsing region ("location").
*
@ -113,12 +125,17 @@ export function useRegion(): UseRegionResult {
ready: boolean
regions: RegionSummary[] | null
addresses: CachedUserAddressesResponse | null
}>({ ready: false, regions: null, addresses: null })
resolution: CachedLocationResolution | null
}>({ ready: false, regions: null, addresses: null, resolution: null })
const cacheBaselineRef = useRef<{
regions: RegionSummary[] | null
addresses: CachedUserAddressesResponse | null
} | null>(null)
const decisionSignatureRef = useRef<string | null>(null)
// The coordinate resolution the launch decision actually settled on.
const settledResolutionRef = useRef<string | null>(null)
// True when the launch decision settled on the cached answer, not live data.
const settledOnCachedResolutionRef = useRef(false)
// The user's default address — the anchor for the startup region decision.
const defaultAddressQuery = trpc.user.address.getDefaultAddress.useQuery(undefined, {
@ -139,18 +156,25 @@ export function useRegion(): UseRegionResult {
// query; updatedAt: 0 keeps the entry stale so the live request still fires.
useEffect(() => {
let cancelled = false
setCacheSnapshot({ ready: false, regions: null, addresses: null })
setCacheSnapshot({ ready: false, regions: null, addresses: null, resolution: null })
void (async () => {
const cachedRegions = await readCachedRegions()
const cachedAddresses =
const [cachedRegions, cachedAddresses, cachedResolution] = await Promise.all([
readCachedRegions(),
isAuthenticated && userId != null
? await readCachedUserAddresses(userId)
: null
? readCachedUserAddresses(userId)
: Promise.resolve(null),
readCachedLocationResolution(),
])
if (cancelled) return
cacheBaselineRef.current = { regions: cachedRegions, addresses: cachedAddresses }
setCacheSnapshot({ ready: true, regions: cachedRegions, addresses: cachedAddresses })
setCacheSnapshot({
ready: true,
regions: cachedRegions,
addresses: cachedAddresses,
resolution: cachedResolution,
})
if (cachedRegions && utils.common.listRegions.getData(undefined) === undefined) {
utils.common.listRegions.setData(undefined, cachedRegions, { updatedAt: 0 })
@ -256,7 +280,10 @@ export function useRegion(): UseRegionResult {
const lng = coords ? Math.round(coords.longitude * 1e5) / 1e5 : 0
const queryInput = useMemo(() => ({ lat, lng }), [lat, lng])
const shouldResolve = hydrated && coords != null && !startupResolved
// Keep the resolve query enabled whenever a fix exists: a cached start must
// still refresh in the background and reconcile if the device has moved.
// `staleTime: Infinity` keeps it to one request per rounded coordinate.
const shouldResolve = hydrated && coords != null
const resolution = trpc.common.resolveRegionByLocation.useQuery(queryInput, {
enabled: shouldResolve,
staleTime: Infinity,
@ -264,6 +291,13 @@ export function useRegion(): UseRegionResult {
refetchOnWindowFocus: false,
})
const cachedResolution = cacheSnapshot.resolution
const liveResolutionSettled = resolution.isFetched || resolution.isError
// The cached answer is the provisional launch input until the live call lands.
const resolved: ResolvedRegion | null = resolution.isSuccess
? resolution.data ?? null
: cachedResolution?.result ?? null
// Apply the launch outcome once. The default address anchors the decision:
// - location resolves to the default's region, or to no serviceable region
// (location off / out of area) -> use the default address;
@ -279,11 +313,12 @@ export function useRegion(): UseRegionResult {
// default-address anchor and show the chooser on every location-off launch.
if (!hasAuthContext) return
const resolved = resolution.data
// The cached resolution may have settled this launch before the live call
// answered; once live data lands it is used instead.
const locationSettled =
resolved != null ||
resolution.isFetched ||
resolution.isError ||
liveResolutionSettled ||
cachedResolution != null ||
locationStatus === 'denied' ||
locationStatus === 'services-off' ||
locationStatus === 'unavailable' ||
@ -324,6 +359,8 @@ export function useRegion(): UseRegionResult {
}
decisionSignatureRef.current = regionDataSignature
settledResolutionRef.current = resolutionSignature(resolved)
settledOnCachedResolutionRef.current = !resolution.isSuccess && cachedResolution != null
setStartupResolved(true)
// Only one consumer performs the switch; the rest just settle their spinner.
@ -388,6 +425,11 @@ export function useRegion(): UseRegionResult {
} else if (resolved.bound && resolved.bound.id !== boundId) {
setRegion(resolved.region, resolved.bound.id)
}
} else if (regionId != null && settledOnCachedResolutionRef.current) {
// The live answer says the device is outside every serviceable region, but
// the current region came from the cache. Fall back to the chooser rather
// than keeping a region the device has left.
clearRegion()
}
}, [
hydrated,
@ -395,6 +437,9 @@ export function useRegion(): UseRegionResult {
resolution.data,
resolution.isFetched,
resolution.isError,
resolved,
liveResolutionSettled,
cachedResolution,
locationStatus,
regionId,
boundId,
@ -488,6 +533,36 @@ export function useRegion(): UseRegionResult {
addresses,
])
// The launch decision can run on the persisted coordinate resolution before
// the live call answers. When the live answer differs (the device moved, a
// bound changed), re-arm the decision so the region/bound switch flows exactly
// as it would on a cache-less launch. Equal answers change nothing.
useEffect(() => {
if (!startupResolved || !resolution.isSuccess) return
const settledOn = settledResolutionRef.current
if (settledOn == null) return
settledResolutionRef.current = null
if (resolutionSignature(resolution.data ?? null) === settledOn) return
// Same re-arm as the cache/live reconcile above: the current region is the
// launch baseline, not a manual pick.
startupLaunchRegionId = regionId
startupCheckDone = false
setStartupResolved(false)
}, [startupResolved, resolution.isSuccess, resolution.data, regionId])
// Persist the live resolution for the next launch. Only server-confirmed
// answers are written, never the cached seed.
useEffect(() => {
if (!resolution.isSuccess) return
void writeCachedLocationResolution({
lat: queryInput.lat,
lng: queryInput.lng,
result: resolution.data ?? null,
})
}, [resolution.isSuccess, resolution.data, queryInput.lat, queryInput.lng])
// Sole-address safety net. The launch decision above runs once per app launch
// (`startupResolved`/`startupCheckDone`), but the address list can arrive
// later — e.g. the user was signed out when the gate first settled and logged

View file

@ -1,5 +1,5 @@
import { StorageServiceCasual } from 'common-ui'
import type { RegionSummary } from '@packages/shared'
import type { RegionSummary, ResolvedRegion } from '@packages/shared'
/**
* Only the fields the startup decision reads. The live query's serialized
@ -20,20 +20,36 @@ export interface CachedUserAddressesResponse {
}
/**
* Small, user-scoped snapshots of the two responses that decide where the app
* The last device-coordinate -> region/bound answer. Startup renders from it
* immediately; the live `common.resolveRegionByLocation` call still runs in the
* background and replaces it when the device is somewhere else.
*
* `result` is `null` when the saved coordinates fell outside every bound.
*/
export interface CachedLocationResolution {
lat: number
lng: number
result: ResolvedRegion | null
}
/**
* Small, user-scoped snapshots of the responses that decide where the app
* starts:
* - the global region list (`common.listRegions`)
* - the signed-in user's addresses (`user.address.getUserAddresses`)
* - the last coordinate resolution (`common.resolveRegionByLocation`)
*
* They are only a startup seed. The live tRPC queries always run in the
* background and overwrite both the React Query cache and these snapshots.
*/
// SecureStore only accepts alphanumeric, ".", "-" and "_" in keys.
export const REGION_LIST_CACHE_KEY = 'region_cache.list_regions.v1'
export const LOCATION_RESOLUTION_CACHE_KEY = 'region_cache.location_resolution.v1'
export const userAddressesCacheKey = (userId: number) =>
`region_cache.user_addresses.v1.${userId}`
let lastWrittenRegions: string | null = null
let lastWrittenResolution: string | null = null
const lastWrittenAddresses = new Map<number, string>()
function parseJson(raw: string | null): unknown {
@ -98,3 +114,39 @@ export async function writeCachedUserAddresses(
const stored = await StorageServiceCasual.setItem(userAddressesCacheKey(userId), serialized)
if (stored) lastWrittenAddresses.set(userId, serialized)
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value)
}
function isCachedLocationResolution(value: unknown): value is CachedLocationResolution {
if (value == null || typeof value !== 'object') return false
const candidate = value as Partial<CachedLocationResolution>
if (!isFiniteNumber(candidate.lat) || !isFiniteNumber(candidate.lng)) return false
if (candidate.result === null) return true
const result = candidate.result as Partial<ResolvedRegion> | undefined
return (
result != null &&
typeof result === 'object' &&
typeof result.region?.id === 'number' &&
typeof result.bound?.id === 'number' &&
typeof result.bound?.regionId === 'number'
)
}
export async function readCachedLocationResolution(): Promise<CachedLocationResolution | null> {
const parsed = parseJson(await StorageServiceCasual.getItem(LOCATION_RESOLUTION_CACHE_KEY))
return isCachedLocationResolution(parsed) ? parsed : null
}
export async function writeCachedLocationResolution(
resolution: CachedLocationResolution
): Promise<void> {
const serialized = JSON.stringify(resolution)
// useRegion is consumed by several components; only the first observer needs
// to write the same response.
if (serialized === lastWrittenResolution) return
const stored = await StorageServiceCasual.setItem(LOCATION_RESOLUTION_CACHE_KEY, serialized)
if (stored) lastWrittenResolution = serialized
}

View file

@ -9,6 +9,7 @@
* - stores.json -> scaffoldStores ({ stores })
* - stores/<id>.json -> scaffoldStoreWithProducts ({ store, products, tags })
*/
import { buildEssentialUrls } from '@packages/shared'
export const REGION_1 = {
id: 1,
@ -39,6 +40,18 @@ export const CONSTS = {
regionId: 1,
assetsDomain: CACHE_BASE,
apiCacheKey: API_CACHE_KEY,
// What the backend now publishes; the hooks prefer these and only fall back
// to constructing the same URLs from the version fields below.
essentialUrls: buildEssentialUrls({
assetsDomain: CACHE_BASE,
apiCacheKey: API_CACHE_KEY,
regionId: 1,
versions: {
products: PRODUCTS_VERSION_NUM,
availability: AVAILABILITY_VERSION_NUM,
slots: SLOTS_VERSION_NUM,
},
}),
products_version_num: PRODUCTS_VERSION_NUM,
availability_version_num: AVAILABILITY_VERSION_NUM,
slots_version_num: SLOTS_VERSION_NUM,

View file

@ -62,7 +62,7 @@ describe('isInNextOrderGlimpseWindow', () => {
expect(isInNextOrderGlimpseWindow(order({ deliveryDate: null }), NOW)).toBe(false)
})
it('uses createdAt + 30 minutes for a flash order with no delivery date', () => {
it('uses createdAt + 1 hour for a flash order with no delivery date', () => {
const recent = order({
isFlashDelivery: true,
deliveryDate: null,
@ -71,12 +71,12 @@ describe('isInNextOrderGlimpseWindow', () => {
const old = order({
isFlashDelivery: true,
deliveryDate: null,
createdAt: iso(-(NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS + 1) * HOUR),
createdAt: iso(-(NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS + 2) * HOUR),
})
expect(isInNextOrderGlimpseWindow(recent, NOW)).toBe(true)
expect(isInNextOrderGlimpseWindow(old, NOW)).toBe(false)
// The fallback really is the flash promise, not an arbitrary window.
expect(FLASH_DELIVERY_MINUTES).toBe(30)
expect(FLASH_DELIVERY_MINUTES).toBe(60)
})
})

View file

@ -21,6 +21,7 @@ import {
import {
setJsonResponse,
setJsonError,
setJsonPending,
jsonCalls,
jsonCallsFor,
} from '../mocks/fetch-json'
@ -61,6 +62,7 @@ import {
storeDetailCacheUrl,
storesCacheUrl,
} from '../fixtures'
import { buildEssentialUrls } from '@packages/shared'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
@ -255,7 +257,21 @@ describe('prominent API hooks', () => {
})
it('API-12: missing URL parts disable the hook and issue no fetch', async () => {
setProcedure('common.essentialConsts', { data: { ...CONSTS, assetsDomain: null } })
setProcedure('common.essentialConsts', {
data: {
...CONSTS,
assetsDomain: null,
essentialUrls: {
productsUrl: '',
storesUrl: '',
bannersUrl: '',
essentialConstsUrl: '',
availabilityUrl: '',
slotsUrl: '',
storeDetailUrlTemplate: '',
},
},
})
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
@ -352,7 +368,23 @@ describe('prominent API hooks', () => {
it('API-18: a region change produces a new CDN URL / query key', async () => {
setProcedure('common.essentialConsts', {
impl: () => ({ ...CONSTS, regionId: useRegionStore.getState().selectedRegionId }),
impl: () => {
const regionId = useRegionStore.getState().selectedRegionId ?? 1
return {
...CONSTS,
regionId,
essentialUrls: buildEssentialUrls({
assetsDomain: CONSTS.assetsDomain,
apiCacheKey: CONSTS.apiCacheKey,
regionId,
versions: {
products: CONSTS.products_version_num,
availability: CONSTS.availability_version_num,
slots: CONSTS.slots_version_num,
},
}),
}
},
})
setJsonResponse(productsCacheUrl(1), PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(1), AVAILABILITY_RESPONSE)
@ -383,4 +415,140 @@ describe('prominent API hooks', () => {
await waitFor(() => expect(result.current.regionalConsts).toBeTruthy())
expect(result.current.regionalConsts).toEqual(result.current.essentialConsts.data)
})
it('API-20: essentialUrls from the API are used verbatim', async () => {
const explicitProducts = 'https://cdn.example/explicit/products.json'
const explicitAvailability = 'https://cdn.example/explicit/availability.json'
setProcedure('common.essentialConsts', {
data: {
...CONSTS,
essentialUrls: {
...CONSTS.essentialUrls,
productsUrl: explicitProducts,
availabilityUrl: explicitAvailability,
},
},
})
setJsonResponse(explicitProducts, PRODUCTS_RESPONSE)
setJsonResponse(explicitAvailability, AVAILABILITY_RESPONSE)
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data).toBeTruthy())
expect(jsonCallsFor(explicitProducts)).toHaveLength(1)
expect(jsonCallsFor(explicitAvailability)).toHaveLength(1)
// The constructed (version-based) URLs are never touched.
expect(jsonCallsFor(productsCacheUrl())).toHaveLength(0)
expect(jsonCallsFor(availabilityCacheUrl())).toHaveLength(0)
})
it('API-21: empty essentialUrls fall back to the shared builders', async () => {
setProcedure('common.essentialConsts', {
data: {
...CONSTS,
essentialUrls: {
productsUrl: '',
storesUrl: '',
bannersUrl: '',
essentialConstsUrl: '',
availabilityUrl: '',
slotsUrl: '',
storeDetailUrlTemplate: '',
},
},
})
setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE)
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data).toBeTruthy())
expect(jsonCallsFor(productsCacheUrl())).toHaveLength(1)
expect(jsonCallsFor(availabilityCacheUrl())).toHaveLength(1)
})
it('API-22: store detail uses the published template', async () => {
const template = 'https://cdn.example/stores/{storeId}.json'
setProcedure('common.essentialConsts', {
data: {
...CONSTS,
essentialUrls: { ...CONSTS.essentialUrls, storeDetailUrlTemplate: template },
},
})
setJsonResponse('https://cdn.example/stores/2.json', STORE_DETAIL_1)
const { element, result } = makeProbe(() => useStoreWithProducts(2))
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.store).toBeTruthy())
expect(jsonCallsFor('https://cdn.example/stores/2.json')).toHaveLength(1)
expect(jsonCallsFor(storeDetailCacheUrl(2))).toHaveLength(0)
})
it('API-23: an empty store-detail template falls back to the shared builder', async () => {
setProcedure('common.essentialConsts', {
data: {
...CONSTS,
essentialUrls: { ...CONSTS.essentialUrls, storeDetailUrlTemplate: '' },
},
})
setJsonResponse(storeDetailCacheUrl(1), STORE_DETAIL_1)
const { element, result } = makeProbe(() => useStoreWithProducts(1))
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.store).toBeTruthy())
expect(jsonCallsFor(storeDetailCacheUrl(1))).toHaveLength(1)
})
it('API-24: a published version bump keeps the previous catalog on screen while the new file loads', async () => {
let productsVersion: number = CONSTS.products_version_num
setProcedure('common.essentialConsts', {
impl: () => ({
...CONSTS,
products_version_num: productsVersion,
essentialUrls: buildEssentialUrls({
assetsDomain: CONSTS.assetsDomain,
apiCacheKey: CONSTS.apiCacheKey,
regionId: 1,
versions: {
products: productsVersion,
availability: CONSTS.availability_version_num,
slots: CONSTS.slots_version_num,
},
}),
}),
})
setJsonResponse(productsCacheUrl(1, CONSTS.products_version_num), PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE)
const { element, result } = makeProbe(() => {
const consts = useGetEssentialConsts()
const products = useAllProducts()
return { consts, products }
})
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.products.data?.products).toBeTruthy())
const loadedCount = result.current.products.data!.products.length
// The backend publishes the next version; its file never resolves yet.
productsVersion += 1
setJsonPending(productsCacheUrl(1, productsVersion))
await act(async () => {
await result.current.consts.refetch()
})
await waitFor(() =>
expect(jsonCallsFor(productsCacheUrl(1, productsVersion))).toHaveLength(1)
)
// The old catalog is still rendered; the screen is not blanking out.
expect(result.current.products.data?.products).toHaveLength(loadedCount)
expect(result.current.products.isLoading).toBe(false)
expect(result.current.products.isPlaceholderData).toBe(true)
})
})

View file

@ -16,6 +16,8 @@
*/
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
import { buildEssentialUrls } from '@packages/shared'
/**
* `installTrpcNetworkMock()` (tests/setup.ts) is installed from the ROOT module
* registry, so `global.fetch` answers from the root copy of the procedure
@ -680,6 +682,151 @@ describe('useRegion', () => {
view.unmount()
})
})
it('REGION-28: a cached location resolution opens the region while the live call is pending', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, BOUND_1 } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: false, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.trpc.setProcedure('common.resolveRegionByLocation', { mode: 'pending' })
ctx.secure.__set(
ctx.regionCache.LOCATION_RESOLUTION_CACHE_KEY,
JSON.stringify({ lat: 17.00012, lng: 78.00034, result: { region: REGION_1, bound: BOUND_1 } })
)
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(4)
// No waiting on GPS/the resolve call: the cached answer is the launch input.
expect(result.current.regionId).toBe(1)
expect(result.current.boundId).toBe(7)
expect(result.current.isResolvingRegion).toBe(false)
// ...but the live request still runs in the background.
expect(ctx.trpc.procedureQueryCalls('common.resolveRegionByLocation').length).toBeGreaterThan(0)
view.unmount()
})
})
it('REGION-29: a live resolution that differs from the cache switches region and bound', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, BOUND_1 } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: false, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
data: {
region: REGION_2,
bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' },
},
})
ctx.secure.__set(
ctx.regionCache.LOCATION_RESOLUTION_CACHE_KEY,
JSON.stringify({ lat: 17.00012, lng: 78.00034, result: { region: REGION_1, bound: BOUND_1 } })
)
// Hold the live resolve so the cached answer settles first.
const networkMock = (global as any).fetch
let releaseResolve!: () => void
const resolveGate = new Promise<void>((resolve) => {
releaseResolve = resolve
})
;(global as any).fetch = jest.fn(async (input: any, init: any) => {
const response = await networkMock(input, init)
if (String(input).includes('common.resolveRegionByLocation')) await resolveGate
return response
})
try {
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(1)
expect(result.current.boundId).toBe(7)
await ctx.rtl.act(async () => {
releaseResolve()
})
await ctx.testUtils.flush(8)
// The live answer re-armed the launch decision and the switch flowed.
expect(result.current.regionId).toBe(2)
expect(result.current.boundId).toBe(8)
expect(ctx.regionStore.getState().selectedRegionId).toBe(2)
view.unmount()
} finally {
;(global as any).fetch = networkMock
}
})
})
it('REGION-30: a successful live resolution is persisted for the next launch', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, BOUND_1 } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: false, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1] })
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
data: { region: REGION_1, bound: BOUND_1 },
})
const { view } = ctx.renderRegion()
await ctx.testUtils.flush(6)
const persisted = JSON.parse(
ctx.secure.__store.get(ctx.regionCache.LOCATION_RESOLUTION_CACHE_KEY) as string
)
expect(persisted.result.region.id).toBe(1)
expect(persisted.result.bound.id).toBe(7)
expect(persisted.lat).toBeCloseTo(17.00012)
expect(persisted.lng).toBeCloseTo(78.00034)
view.unmount()
})
})
it('REGION-31: a live "no serviceable region" clears a region adopted from the cache', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, BOUND_1 } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: false, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1] })
ctx.trpc.setProcedure('common.resolveRegionByLocation', { data: null })
ctx.secure.__set(
ctx.regionCache.LOCATION_RESOLUTION_CACHE_KEY,
JSON.stringify({ lat: 17.00012, lng: 78.00034, result: { region: REGION_1, bound: BOUND_1 } })
)
// Hold the live resolve so the cached answer settles first.
const networkMock = (global as any).fetch
let releaseResolve!: () => void
const resolveGate = new Promise<void>((resolve) => {
releaseResolve = resolve
})
;(global as any).fetch = jest.fn(async (input: any, init: any) => {
const response = await networkMock(input, init)
if (String(input).includes('common.resolveRegionByLocation')) await resolveGate
return response
})
try {
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(1)
await ctx.rtl.act(async () => {
releaseResolve()
})
await ctx.testUtils.flush(8)
expect(result.current.regionId).toBeNull()
expect(result.current.isResolvingRegion).toBe(false)
view.unmount()
} finally {
;(global as any).fetch = networkMock
}
})
})
})
@ -760,7 +907,23 @@ describe('Home region integration (REGION-16..18)', () => {
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
ctx.trpc.setProcedure('common.essentialConsts', {
data: { ...ctx.fixtures.CONSTS, regionId: 2, boundId: 8 },
data: {
...ctx.fixtures.CONSTS,
regionId: 2,
boundId: 8,
// Published URLs must follow the payload's own region, exactly like the
// backend builds them.
essentialUrls: buildEssentialUrls({
assetsDomain: ctx.fixtures.CACHE_BASE,
apiCacheKey: ctx.fixtures.API_CACHE_KEY,
regionId: 2,
versions: {
products: ctx.fixtures.PRODUCTS_VERSION_NUM,
availability: ctx.fixtures.AVAILABILITY_VERSION_NUM,
slots: ctx.fixtures.SLOTS_VERSION_NUM,
},
}),
},
})
ctx.testUtils.seedJsonCache({ regionId: 1 })

View file

@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 6 — Home (`tests/pages/home.test.tsx`, HOME-01..112).
* Catalogue section 6 — Home (`tests/pages/home.test.tsx`, HOME-01..119).
*
* Products / availability / slots / stores come from the versioned CDN documents
* (`seedBoot`); the consts + orders come from the tRPC procedure registry. The
@ -37,6 +37,7 @@ import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget'
import { StorageServiceCasual, tw } from 'common-ui'
import { flush, renderWithProviders, seedBoot, seedSelectedAddress } from '../helpers/test-utils'
import { buildEssentialUrls } from '@packages/shared'
import { resetAllMocks } from '../helpers/reset'
import {
procedureQueryCalls,
@ -58,6 +59,10 @@ import {
CART_FLASH,
CART_REG,
CONSTS_FLASH_OFF,
CONSTS,
PRODUCTS_VERSION_NUM,
AVAILABILITY_VERSION_NUM,
SLOTS_VERSION_NUM,
P_CHICKEN,
SLOTS,
SLOTS_RESPONSE,
@ -336,6 +341,80 @@ describe('Home (HOME)', () => {
expect(queryByText('Our Stores')).toBeNull()
})
it('HOME-118: a new published version keeps the current catalog while it loads', async () => {
let productsVersion: number = PRODUCTS_VERSION_NUM
setProcedure('common.essentialConsts', {
impl: () => ({
...CONSTS,
products_version_num: productsVersion,
essentialUrls: buildEssentialUrls({
assetsDomain: CONSTS.assetsDomain,
apiCacheKey: CONSTS.apiCacheKey,
regionId: CONSTS.regionId,
versions: {
products: productsVersion,
availability: AVAILABILITY_VERSION_NUM,
slots: SLOTS_VERSION_NUM,
},
}),
}),
})
const view = await renderHome()
await waitFor(() => expect(mainListIds(view).length).toBeGreaterThan(0))
const before = mainListIds(view)
// The backend publishes the next products version; its file never resolves.
productsVersion += 1
setJsonPending(productsCacheUrl(1, productsVersion))
await emitFocus()
await waitFor(() =>
expect(jsonCallsFor(productsCacheUrl(1, productsVersion))).toHaveLength(1)
)
// The old catalog is still on screen: no full-screen loader, same rows.
expect(view.queryByText('Loading products...')).toBeNull()
expect(view.getByTestId('home-search')).toBeTruthy()
expect(mainListIds(view)).toEqual(before)
})
it('HOME-119: a failed background refresh keeps the last good catalog', async () => {
let productsVersion: number = PRODUCTS_VERSION_NUM
setProcedure('common.essentialConsts', {
impl: () => ({
...CONSTS,
products_version_num: productsVersion,
essentialUrls: buildEssentialUrls({
assetsDomain: CONSTS.assetsDomain,
apiCacheKey: CONSTS.apiCacheKey,
regionId: CONSTS.regionId,
versions: {
products: productsVersion,
availability: AVAILABILITY_VERSION_NUM,
slots: SLOTS_VERSION_NUM,
},
}),
}),
})
const view = await renderHome()
await waitFor(() => expect(mainListIds(view).length).toBeGreaterThan(0))
const before = mainListIds(view)
productsVersion += 1
setJsonError(productsCacheUrl(1, productsVersion), new Error('offline'))
await emitFocus()
await waitFor(() =>
expect(jsonCallsFor(productsCacheUrl(1, productsVersion)).length).toBeGreaterThan(0)
)
await flush(3)
// The background failure is not allowed to replace a usable catalog.
expect(view.queryByText('Oops!')).toBeNull()
expect(view.queryByText('Failed to load products')).toBeNull()
expect(mainListIds(view)).toEqual(before)
})
/* ------------------------------------------------------------------ */
/* 6.2 Tags and product grid */
/* ------------------------------------------------------------------ */
@ -1401,13 +1480,13 @@ describe('Home (HOME)', () => {
expect(queryByText('packaged')).toBeNull()
})
it('HOME-103: a flash order shows the FLASH tag and 30-Min', async () => {
it('HOME-103: a flash order shows the FLASH tag and 1-Hour', async () => {
signedIn()
setOrders([{ ...O1, isFlashDelivery: true }])
const { getByText } = await renderHome()
expect(getByText('FLASH')).toBeTruthy()
expect(getByText('30-Min')).toBeTruthy()
expect(getByText('1-Hour')).toBeTruthy()
})
it('HOME-104: a cancelled order is excluded', async () => {
@ -1561,7 +1640,7 @@ describe('Home (HOME)', () => {
expect(queryByTestId('next-order-glimpse')).toBeNull()
})
it('HOME-116: a flash order with no delivery date uses the 30-minute promise', async () => {
it('HOME-116: a flash order with no delivery date uses the 1-hour promise', async () => {
signedIn()
setOrders([
{
@ -1585,7 +1664,7 @@ describe('Home (HOME)', () => {
id: 1001,
isFlashDelivery: true,
deliveryDate: undefined,
createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString(),
createdAt: new Date(Date.now() - 26 * 60 * 60 * 1000).toISOString(),
},
])
const { queryByTestId } = await renderHome()

View file

@ -66,7 +66,7 @@ function OrderCard({ order, supportMobile, onPress }: OrderCardProps) {
<span className="mr-1.5 text-amber-600">{order.isFlashDelivery ? '⚡' : '🕐'}</span>
<p className="text-xs font-medium text-amber-800">
{order.isFlashDelivery
? '30-Min Delivery'
? '1-Hour Delivery'
: formatRange(order.deliveryDate || order.orderDate)}
</p>
</div>

View file

@ -1,5 +1,5 @@
import { useMemo, useEffect, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useQuery, keepPreviousData } from '@tanstack/react-query'
import axios from 'axios'
import { trpc } from '../lib/trpc-client'
import { useAuth } from '../lib/auth-context'
@ -15,7 +15,14 @@ import type {
BannersApiType,
StoreWithProductsApiType,
} from '@backend/trpc/router'
import { CACHE_FILENAMES } from '@packages/shared'
import {
CACHE_FILENAMES,
availabilityCacheUrl,
cachedFileUrl,
regionCacheUrl,
slotsCacheUrl,
storeDetailCacheUrl,
} from '@packages/shared'
const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}`
@ -246,6 +253,11 @@ function useCacheUrl(filename: string): string | null {
const { data: essentialConsts } = useGetEssentialConsts()
const regionId = useDiscoveryRegionId(essentialConsts)
// The backend publishes these URLs. Trust them first; construct only when an
// older payload (or a stale localStorage snapshot) lacks them.
const published = cachedFileUrl(essentialConsts?.essentialUrls, filename)
if (published) return published
const assetsDomain = essentialConsts?.assetsDomain
const apiCacheKey = essentialConsts?.apiCacheKey
const cacheVersion = essentialConsts?.products_version_num
@ -260,13 +272,16 @@ function useCacheUrl(filename: string): string | null {
return null
}
return `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/${filename}`
return regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, filename) || null
}
function useAvailabilityCacheUrl(): string | null {
const { data: essentialConsts } = useGetEssentialConsts()
const regionId = useDiscoveryRegionId(essentialConsts)
const published = cachedFileUrl(essentialConsts?.essentialUrls, CACHE_FILENAMES.availability)
if (published) return published
const assetsDomain = essentialConsts?.assetsDomain
const availabilityVersionNum = essentialConsts?.availability_version_num
@ -274,13 +289,16 @@ function useAvailabilityCacheUrl(): string | null {
return null
}
return `${assetsDomain}regions/${regionId}/av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
return availabilityCacheUrl(assetsDomain, regionId, availabilityVersionNum) || null
}
function useSlotsCacheUrl(): string | null {
const { data: essentialConsts } = useGetEssentialConsts()
const regionId = useDiscoveryRegionId(essentialConsts)
const published = cachedFileUrl(essentialConsts?.essentialUrls, CACHE_FILENAMES.slots)
if (published) return published
const assetsDomain = essentialConsts?.assetsDomain
const slotsVersionNum = essentialConsts?.slots_version_num
@ -288,7 +306,7 @@ function useSlotsCacheUrl(): string | null {
return null
}
return `${assetsDomain}regions/${regionId}/slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
return slotsCacheUrl(assetsDomain, regionId, slotsVersionNum) || null
}
export function useAllProducts() {
@ -309,7 +327,7 @@ export function useAllProducts() {
},
staleTime: 60000,
enabled: !!cacheUrl && isReady,
placeholderData: initialData,
placeholderData: initialData ?? keepPreviousData,
})
const mergedProducts = useMemo(() => {
@ -368,7 +386,7 @@ export function useAvailability() {
},
staleTime: 60000,
enabled: !!cacheUrl && isReady,
placeholderData: initialData,
placeholderData: initialData ?? keepPreviousData,
})
}
@ -389,7 +407,7 @@ export function useStores() {
},
staleTime: 60000,
enabled: !!cacheUrl && isReady,
placeholderData: initialData,
placeholderData: initialData ?? keepPreviousData,
})
}
@ -410,7 +428,7 @@ export function useSlots() {
},
staleTime: 60000,
enabled: !!cacheUrl && isReady,
placeholderData: initialData,
placeholderData: initialData ?? keepPreviousData,
})
}
@ -431,7 +449,7 @@ export function useBanners() {
},
staleTime: 60000,
enabled: !!cacheUrl && isReady,
placeholderData: initialData,
placeholderData: initialData ?? keepPreviousData,
})
}
@ -443,9 +461,11 @@ export function useStoreWithProducts(storeId: number) {
const apiCacheKey = essentialConsts?.apiCacheKey
const cacheVersion = essentialConsts?.products_version_num
const cacheUrl =
assetsDomain && apiCacheKey && regionId != null
? `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/stores/${storeId}.json`
const publishedTemplate = essentialConsts?.essentialUrls?.storeDetailUrlTemplate
const cacheUrl = publishedTemplate
? publishedTemplate.replace('{storeId}', String(storeId))
: assetsDomain && apiCacheKey && regionId != null && cacheVersion != null
? storeDetailCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, storeId) || null
: null
const version = cacheUrl ?? ''
const { initialData, isReady } = usePersistedCache<StoreWithProductsResponse>(CACHE_STORAGE_KEYS.storeProducts(storeId), version)
@ -462,6 +482,6 @@ export function useStoreWithProducts(storeId: number) {
},
staleTime: 60000,
enabled: !!cacheUrl && isReady,
placeholderData: initialData,
placeholderData: initialData ?? keepPreviousData,
})
}

View file

@ -137,7 +137,7 @@ function OrderCard({
})()}
</p>
{item.isFlashDelivery && (
<p className="mt-1 text-[9px] font-bold uppercase text-amber-600">⚡ 30-Min Delivery</p>
<p className="mt-1 text-[9px] font-bold uppercase text-amber-600">⚡ 1-Hour Delivery</p>
)}
</div>
</div>

View file

@ -9496,3 +9496,377 @@ opens WhatsApp without text. user-ui uses whatsapp://send, web uses https://wa.m
ends with the last order id). WhatsApp exposes no caret parameter; the trailing newline
was the likely cause of the caret landing at position 0 after its whitespace
normalization. user-ui + web-ui + ME-20 expectation updated.
[2026-10-25 08:42 IST] user-ui: cache the last location->region resolution in
StorageServiceCasual so startup renders from it instead of blocking on GPS +
common.resolveRegionByLocation. Cache first, live call in the background; when the live
answer differs, the launch decision re-arms so the switch flows normally. Web-ui has no
startup location resolve (its region is persisted by zustand), so no counterpart change.
--- a/apps/user-ui/src/lib/region-cache.ts
+++ b/apps/user-ui/src/lib/region-cache.ts
@@ imports
+import type { RegionSummary, ResolvedRegion } from '@packages/shared'
@@ new
+export interface CachedLocationResolution { lat, lng, result: ResolvedRegion | null }
+export const LOCATION_RESOLUTION_CACHE_KEY = 'region_cache.location_resolution.v1'
+readCachedLocationResolution(): validated (finite lat/lng, result null or region/bound ids)
+writeCachedLocationResolution(): de-duplicated JSON write
--- a/apps/user-ui/src/hooks/useRegion.ts
+++ b/apps/user-ui/src/hooks/useRegion.ts
@@ imports
+ readCachedLocationResolution, writeCachedLocationResolution, type CachedLocationResolution
@@ cacheSnapshot
+ resolution: CachedLocationResolution | null
@@ snapshot read
- const cachedRegions = await readCachedRegions()
- const cachedAddresses = ...
+ const [cachedRegions, cachedAddresses, cachedResolution] = await Promise.all([...])
+ setCacheSnapshot({ ready: true, regions, addresses, resolution: cachedResolution })
@@ resolve query
- const shouldResolve = hydrated && coords != null && !startupResolved
+ const shouldResolve = hydrated && coords != null // keep refreshing after a cached start
+ const resolved = resolution.isSuccess ? resolution.data ?? null : cachedResolution?.result ?? null
@@ launch decision
- const resolved = resolution.data
- locationSettled = resolved != null || resolution.isFetched || ...
+ locationSettled = resolved != null || liveResolutionSettled || cachedResolution != null || ...
+ settledResolutionRef.current = resolutionSignature(resolved)
@@ new reconcile effect
+ live resolve success && signature(live) != signature(settled on) -> re-arm the launch
+ decision (startupLaunchRegionId = regionId, startupCheckDone = false, startupResolved = false)
+ live null while the region came from the cache -> clearRegion() for the chooser
@@ new persist effect
+ on resolution.isSuccess: writeCachedLocationResolution({ lat, lng, result })
--- a/apps/user-ui/tests/lib/use-region.test.tsx
+++ b/apps/user-ui/tests/lib/use-region.test.tsx
@@ new cases
+ REGION-28: cached resolution opens the region while the live resolve is pending
+ (and the live request still runs)
+ REGION-29: a live resolution that differs from the cache switches region + bound
+ REGION-30: a successful live resolution is persisted for the next launch
+ REGION-31: a live "no serviceable region" clears a region adopted from the cache
--- a/apps/user-ui/JEST-TEST-CASES.md
+++ b/apps/user-ui/JEST-TEST-CASES.md
@@ Region table
+ REGION-28 | edge | cached location resolution, live pending | opens cached region; live still runs
+ REGION-29 | edge | live resolution differs from cache | region/bound switch to live
+ REGION-30 | edge | live resolution succeeds | persisted to StorageServiceCasual
+ REGION-31 | edge | live resolution null, region adopted from cache | region cleared for the chooser
[2026-10-25 09:26 IST] Flash delivery promise changes from 30 minutes to 1 hour. The glimpse
window fallback (createdAt + promise) and every flash label (user + web + admin) move
together so the card, order history and admin details cannot disagree.
--- a/packages/shared/order-glimpse.ts
+++ b/packages/shared/order-glimpse.ts
@@
-export const FLASH_DELIVERY_MINUTES = 30
+export const FLASH_DELIVERY_MINUTES = 60
@@ comments
- * flash order without a slot uses the 30-minute promise shown on the card.
+ * flash order without a slot uses the 1-hour promise shown on the card.
--- a/apps/user-ui/components/NextOrderGlimpse.tsx
+++ b/apps/user-ui/components/NextOrderGlimpse.tsx
@@ deliveryPrimaryLabel
- ? "30-Min"
+ ? "1-Hour"
--- a/apps/web-ui/src/components/me/NextOrderGlimpse.tsx
+++ b/apps/web-ui/src/components/me/NextOrderGlimpse.tsx
@@
- ? '30-Min Delivery'
+ ? '1-Hour Delivery'
--- a/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx
+++ b/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx
@@
- <MyText ...>⚡ 30-Min Delivery</MyText>
+ <MyText ...>⚡ 1-Hour Delivery</MyText>
--- a/apps/web-ui/src/routes/me.orders.tsx
+++ b/apps/web-ui/src/routes/me.orders.tsx
@@
- <p ...>⚡ 30-Min Delivery</p>
+ <p ...>⚡ 1-Hour Delivery</p>
--- a/apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx
+++ b/apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx
@@
- ⚡ 30-Min
+ ⚡ 1-Hour
--- a/apps/admin-web/src/routes/dashboard.orders.$id.tsx
+++ b/apps/admin-web/src/routes/dashboard.orders.$id.tsx
@@
- ⚡ 30-Min
+ ⚡ 1-Hour
--- a/apps/user-ui/tests/lib/order-glimpse.test.ts
+++ b/apps/user-ui/tests/lib/order-glimpse.test.ts
@@
- it('uses createdAt + 30 minutes for a flash order with no delivery date', () => {
+ it('uses createdAt + 1 hour for a flash order with no delivery date', () => {
@@ the "old" fixture moves past the 24h lookback once the promise is an hour
- createdAt: iso(-(NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS + 1) * HOUR),
+ createdAt: iso(-(NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS + 2) * HOUR),
@@
- expect(FLASH_DELIVERY_MINUTES).toBe(30)
+ expect(FLASH_DELIVERY_MINUTES).toBe(60)
--- a/apps/user-ui/tests/pages/home.test.tsx
+++ b/apps/user-ui/tests/pages/home.test.tsx
@@ HOME-103
- it('HOME-103: a flash order shows the FLASH tag and 30-Min', ...
- expect(getByText('30-Min')).toBeTruthy()
+ it('HOME-103: a flash order shows the FLASH tag and 1-Hour', ...
+ expect(getByText('1-Hour')).toBeTruthy()
@@ HOME-116 title
- it('HOME-116: a flash order with no delivery date uses the 30-minute promise', ...
+ it('HOME-116: a flash order with no delivery date uses the 1-hour promise', ...
@@ HOME-117 fixture: 25h ago + 1h = exactly the 24h edge, which is inclusive
- createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString(),
+ createdAt: new Date(Date.now() - 26 * 60 * 60 * 1000).toISOString(),
--- a/apps/user-ui/JEST-TEST-CASES.md
+++ b/apps/user-ui/JEST-TEST-CASES.md
@@
-| HOME-103 | edge | flash order | FLASH + “30-Min” |
+| HOME-103 | edge | flash order | FLASH + “1-Hour” |
[2026-10-25 09:47 IST] Regional CDN URLs move into @packages/shared and are published in
essentialConsts as `essentialUrls`. Backend + KV + both UIs use the same builders; the UI
prefers the API's URLs and falls back to constructing them (empty string = not available).
Availability/slots keep their existing path shapes (outside API_CACHE_KEY). Cache rebuilds
now bump the availability/slots counters BEFORE building any file, so essential-consts.json
and the KV mirror describe the versions actually being written.
--- a/packages/shared/region-cache-urls.ts (new)
+++ b/packages/shared/region-cache-urls.ts
+export const CACHE_FILENAMES (moved from index.ts)
+export interface CacheVersions { products, availability, slots }
+export interface EssentialUrls { productsUrl, storesUrl, bannersUrl, essentialConstsUrl,
+ availabilityUrl, slotsUrl, storeDetailUrlTemplate }
+export function regionCacheObjectKey(apiCacheKey, regionId, productsVersion, filename)
+export function availabilityObjectKey(regionId, availabilityVersion)
+export function slotsObjectKey(regionId, slotsVersion)
+export function storeDetailObjectKey(apiCacheKey, regionId, productsVersion, storeId)
+export function regionCacheUrl(...) // '' when a part is missing
+export function availabilityCacheUrl(...)
+export function slotsCacheUrl(...)
+export function storeDetailCacheUrl(...)
+export function storeDetailUrlTemplate(...)
+export function buildEssentialUrls({ assetsDomain, apiCacheKey, regionId, versions })
+export function cachedFileUrl(urls, filename) // API-first lookup by filename
--- a/packages/shared/index.ts
+++ b/packages/shared/index.ts
@@ CACHE_FILENAMES
-export const CACHE_FILENAMES = { ... }
+export * from './region-cache-urls'
--- a/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
+++ b/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
@@ imports
+import { buildEssentialUrls } from '@packages/shared'
@@ scaffoldEssentialConsts
+ const productsVersionNum / availabilityVersionNum / slotsVersionNum computed once
+ essentialUrls: buildEssentialUrls({ assetsDomain, apiCacheKey, regionId,
+ versions: { products, availability, slots } }),
--- a/apps/backend/src/lib/cloud_cache.ts
+++ b/apps/backend/src/lib/cloud_cache.ts
@@ local path/url helpers deleted
+ use shared regionCacheObjectKey / availabilityObjectKey / slotsObjectKey /
+ storeDetailObjectKey for uploads, and the shared *CacheUrl builders for purge
@@ createRegionCacheFiles
+ increment products + availability + slots versions up front
+ pass the hoisted versions into createSlotsCacheFile / createAvailabilityCacheFile
@@ createSlotsCacheFile / createAvailabilityCacheFile
+ optional `version` argument: use it instead of bumping again
--- a/apps/backend/src/lib/gen-store.ts
+++ b/apps/backend/src/lib/gen-store.ts
@@ putBound
+ comment: the scaffold payload carries essentialUrls, so the KV mirror stores them
--- a/apps/user-ui/src/hooks/prominent-api-hooks.ts
+++ b/apps/user-ui/src/hooks/prominent-api-hooks.ts
@@ imports
+import { CACHE_FILENAMES, availabilityCacheUrl, cachedFileUrl, regionCacheUrl,
+ slotsCacheUrl, storeDetailCacheUrl } from '@packages/shared'
@@ useCacheUrl / useAvailabilityCacheUrl / useSlotsCacheUrl
+ essentialConsts.essentialUrls.* first; shared builder fallback ('' -> null)
@@ useStoreWithProducts
+ storeDetailUrlTemplate.replace('{storeId}', id) first; shared builder fallback
--- a/apps/web-ui/src/hooks/prominent-api-hooks.ts
+++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts
same API-first + shared-builder fallback as user-ui (incl. banners)
--- a/apps/user-ui/tests/fixtures/index.ts
+++ b/apps/user-ui/tests/fixtures/index.ts
@@ CONSTS
+ essentialUrls: buildEssentialUrls({ CACHE_BASE, API_CACHE_KEY, 1,
+ versions: { products: PRODUCTS_VERSION_NUM, availability: AVAILABILITY_VERSION_NUM,
+ slots: SLOTS_VERSION_NUM } })
--- a/apps/user-ui/tests/lib/prominent-api-hooks.test.tsx
+++ b/apps/user-ui/tests/lib/prominent-api-hooks.test.tsx
@@ API-12
missing URL parts disable the hook: also clear essentialUrls
@@ new
+ API-20: the API's essentialUrls are used verbatim (and win over construction)
+ API-21: empty/missing essentialUrls fall back to the shared builders
+ API-22: store detail uses the API template, falls back to the shared builder
+ API-23: an empty store-detail template falls back to the shared builder
--- a/apps/user-ui/tests/lib/use-region.test.tsx
+++ b/apps/user-ui/tests/lib/use-region.test.tsx
@@ REGION-18
+ region-2 essentialConsts payload now builds region-2 essentialUrls too
--- a/apps/backend/tests/helpers/cache.ts
+++ b/apps/backend/tests/helpers/cache.ts
build the cache URLs with the shared builders (single source with the app)
--- a/apps/backend/tests/unit/region-cache-urls.test.ts (new)
+++ b/apps/backend/tests/unit/region-cache-urls.test.ts
+ exact URL shapes, empty-string behavior, availability/slots outside the cache key,
+ store-detail template + substitution
--- a/apps/backend/tests/api/cache-consts.test.ts
+++ b/apps/backend/tests/api/cache-consts.test.ts
+ CACHE-115: essentialUrls is present and matches the shared builders/version fields
--- a/apps/backend/tests/api/cache-banners.test.ts
+++ b/apps/backend/tests/api/cache-banners.test.ts
+ CACHE-116: essential-consts.json carries essentialUrls matching its own path versions
[2026-10-25 10:10 IST] Local dev DB test-data cleanup (freshyo-dev, wrangler local D1 only;
no repo files touched, no remote). Name-marker based deletes in one transaction (backup at
/tmp/freshyo-dev-before-cleanup.sqlite, SQL at /tmp/freshyo-clean-test-data.sql):
44 E2E regions + bounds/consts, 217 E2E stores, 177 E2E products (+skus, combos, deals,
features, market stats, tags, memberships), 45 E2E users (+11 addresses, 14 orders and their
items/status), 32 E2E + 6 TEST-named coupons, 7 test reserved_coupons, 3 orphan market_stats
(skus 154-156, pre-existing orphans), 6 test staff (e2e_prod_* + devslothook), 1 E2E banner,
3 E2E tags, 34 test slots (fixture dates + Oct 24/25 test-run ids >= 2136).
Before -> after: regions 45->1, bounds 68->2, stores 222->5, products 326->149,
slots 1711->1677, users 1378->1333, staff 9->3, orders 2472->2458, coupons 79->47.
Kept deliberately: harness accounts (e2e_super, staff shafi, user 388), owner-made rows
(SHAFI20/BNLS20/DEMO_FIRST coupons, Oct 20/22 orders by 388 with real skus), unmarked rows
(upload_url_status, unlogged_user_tokens), all real slots incl. 129-135-sku schedule.
FK check clean, integrity ok, VACUUM 6.6MB->5.2MB. KV mirror wiped (70 keys) and rebuilt
for live bounds only (essentialConsts_1/2); region 1 cache rebuilt (products v54) and
products.json serves 200. Dev server left running.
[2026-10-25 10:18 IST] Fix: bursty slot creation wiped the products off UPCOMING slots.
`staleSlotsCleanup` cleared `sku_ids` of the 20th-newest slot for a region after every
createSlot. With a long slot history, a burst of creations (the backend test suite creates
~30) walked that window through future slots, so region 1's only upcoming slots (2114,
2122) lost their sku lists -> slots.json had 2 slots with `products: []` -> the app's
`isSlotsLoaded && !getQuickestSlot(id)` rule marked every product out of stock.
(Superseded by the 10:25 entry below: the first attempt was a freeze-time guard; the final
fix is a 36-hour delivery-time retention window.)
Local data repair (not repo content): slots 2114/2122 had sku_ids restored to the 149
active region-1 skus. The test-run's prior destructive window advances cannot be
reconstructed beyond that; no other future slots exist.
[2026-10-25 10:25 IST] Replace the id-window slot cleanup with a 36-hour retention window.
`staleSlotsCleanup(regionId)` now clears `sku_ids` for EVERY slot in the region whose
delivery time is at/before `now - 36h` (previously: one row per createSlot = the 20th-newest
by id). Time-based, so bursts can never strip an upcoming slot's products. Rows already
empty are skipped; other regions untouched. It still runs after createSlot (awaited,
failure swallowed).
--- a/packages/db_helper_sqlite/src/admin-apis/slots.ts
+++ b/packages/db_helper_sqlite/src/admin-apis/slots.ts
@@ imports
+ lte, sql from drizzle-orm
@@ new
+export const SLOT_SKU_RETENTION_HOURS = 36
+export function slotSkuCleanupCutoff(now = new Date()): Date
+ return now - 36h
@@ staleSlotsCleanup
- 20 newest ids by id; clear the min id (one row)
+ UPDATE delivery_slot_info SET sku_ids='[]'
+ WHERE region_id = ? AND delivery_time <= cutoff
+ AND json_array_length(sku_ids) > 0
+ RETURNING id; return rows cleared
--- a/apps/backend/src/trpc/apis/admin-apis/apis/slots.ts
+++ b/apps/backend/src/trpc/apis/admin-apis/apis/slots.ts
@@ createSlot cleanup comment
+ "Drop skuIds from slots delivered more than 36h ago for THIS region only."
--- a/apps/backend/src/sqliteImporter.ts
+++ b/apps/backend/src/sqliteImporter.ts
@@ Admin - Slots exports
- shouldClearSlotSkus
+ SLOT_SKU_RETENTION_HOURS, slotSkuCleanupCutoff
--- a/packages/db_helper_sqlite/index.ts
+++ b/packages/db_helper_sqlite/index.ts
@@ Slots exports
+ SLOT_SKU_RETENTION_HOURS, slotSkuCleanupCutoff
--- a/apps/backend/tests/unit/slot-sku-cleanup.test.ts (new)
+++ b/apps/backend/tests/unit/slot-sku-cleanup.test.ts
+ 36h retention constant + cutoff exactness
+ upcoming / 35h-old slots kept; exactly-36h and 37h-old slots cleared
[2026-10-25 10:36 IST] Home/catalog version bumps no longer blank the screen. Every versioned
CDN query now keeps the previous result while the new version's file downloads and swaps in
when it lands (`placeholderData: keepPreviousData`). user-ui: products/availability/stores/
slots/store-detail; web-ui: the same six via `initialData ?? keepPreviousData` so the
persisted placeholder still wins. Home's error screen now only takes over when there is no
catalog to show, so a failed background refresh keeps the last good data.
--- a/apps/user-ui/src/hooks/prominent-api-hooks.ts
+++ b/apps/user-ui/src/hooks/prominent-api-hooks.ts
@@ imports
+import { useQuery, keepPreviousData } from '@tanstack/react-query'
@@ useAllProducts / useAvailability / useStores / useSlots / useStoreWithProducts
+ placeholderData: keepPreviousData
+ // new product/availability/store/slot version keeps the previous data until
+ // the CDN file resolves; isLoading stays false (isPlaceholderData true)
--- a/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
+++ b/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
@@ error guard
- if (error || constsError) {
+ if ((error || constsError) && products.length === 0) {
--- a/apps/web-ui/src/hooks/prominent-api-hooks.ts
+++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts
@@ imports
+import { useQuery, keepPreviousData } from '@tanstack/react-query'
@@ products / availability / stores / slots / banners / store detail
- placeholderData: initialData,
+ placeholderData: initialData ?? keepPreviousData,
--- a/apps/user-ui/tests/lib/prominent-api-hooks.test.tsx
+++ b/apps/user-ui/tests/lib/prominent-api-hooks.test.tsx
@@ new
+ API-24: published version bump keeps the previous catalog while the new file is pending
+ (data unchanged, isLoading false, isPlaceholderData true)
--- a/apps/user-ui/JEST-TEST-CASES.md
+++ b/apps/user-ui/JEST-TEST-CASES.md
@@ Prominent API hooks
+ API-24 | edge | version bump, new file pending | previous catalog stays; no loading state
[2026-10-25 10:38 IST] Tests for the no-blank version-bump behaviour.
- API-24 (tests/lib/prominent-api-hooks.test.tsx): products version bumps with the new CDN
file pending; the previous catalog stays, isLoading false, isPlaceholderData true.
- HOME-118 (tests/pages/home.test.tsx): same at the screen level -- the old rows and search
bar remain, "Loading products..." never renders.
- HOME-119: a failed background refresh (new version errors) keeps the last good catalog and
does not swap to the "Oops!" screen (cold-start failures still do, pinned by HOME-02).
- JEST-TEST-CASES.md rows HOME-113..119 added (113-117 were undocumented).

View file

@ -327,7 +327,7 @@
- `STRUCTURE` `user-ui: me/index.tsx:68-74` ↔ `web-ui: me.tsx:202-222` — see §2 location rows: "Delivery Address" inside Saved Information vs "Delivery Region" after Logout.
- `STRUCTURE` `user-ui: components/NextOrderGlimpse.tsx:92-98` ↔ `web-ui: src/components/me/NextOrderGlimpse.tsx:50-96` — mobile renders an OrderStatusTracker in the card; web has no tracker and instead shows up to 3 thumbnails, a "+N" chip and a "Track Order" label.
- `BEHAVIOUR` `user-ui: components/NextOrderGlimpse.tsx:26,84-88` ↔ `web-ui: src/components/me/NextOrderGlimpse.tsx:57-61` — mobile hides the status badge for `confirmed`/`packaged`; web always shows it.
- `CONTENT` `user-ui: components/NextOrderGlimpse.tsx:57,28,34-36,38-40` ↔ `web-ui: src/components/me/NextOrderGlimpse.tsx:45,68,25` — "FLASH" vs "Flash"; "30-Min" vs "30-Min Delivery"; delivery window "hh:mm - hh:mm A" vs "DD MMM, hh:mm A - hh:mm A"; mobile's secondary label ("Delivery"/"DD MMM") has no web equivalent.
- `CONTENT` `user-ui: components/NextOrderGlimpse.tsx:57,28,34-36,38-40` ↔ `web-ui: src/components/me/NextOrderGlimpse.tsx:45,68,25` — "FLASH" vs "Flash"; "1-Hour" vs "1-Hour Delivery"; delivery window "hh:mm - hh:mm A" vs "DD MMM, hh:mm A - hh:mm A"; mobile's secondary label ("Delivery"/"DD MMM") has no web equivalent.
- `BEHAVIOUR` `user-ui: components/NextOrderGlimpse.tsx:162-165` ↔ `web-ui: src/components/me/NextOrderGlimpse.tsx:165-167` — card tap: mobile writes a nav target then `router.replace()`s to /me; web navigates straight to the order detail.
- `BEHAVIOUR` `user-ui: me/my-orders/index.tsx:501` ↔ `web-ui: me.orders.tsx:326-330,409-411` — pagination: mobile auto-loads on `onEndReached`; web has an auto-load effect **and** a manual "Load more" button. *Verified.*
- `CONTENT` `user-ui: me/my-orders/index.tsx:114,246` ↔ `web-ui: me.orders.tsx:93,227` — "FLASH" vs "Flash"; "⚡ FAST" vs "⚡ Fast".

View file

@ -109,6 +109,8 @@ export {
getSlotDeliverySequence,
updateSlotDeliverySequence,
staleSlotsCleanup,
SLOT_SKU_RETENTION_HOURS,
slotSkuCleanupCutoff,
} from './src/admin-apis/slots'
export {

View file

@ -7,7 +7,7 @@ import {
vendorSnippets,
productGroupInfo,
} from '../db/schema'
import { and, asc, desc, eq, gt, inArray } from 'drizzle-orm'
import { and, asc, desc, eq, gt, inArray, lte, sql } from 'drizzle-orm'
import type {
AdminDeliverySlot,
AdminSlotWithProducts,
@ -158,31 +158,36 @@ export async function getActiveSlotsWithProducts(regionId: number, limit: number
}))
}
/** A delivered slot keeps its `skuIds` this long, then the cleanup clears them. */
export const SLOT_SKU_RETENTION_HOURS = 36
/** Slots delivered at/before this moment no longer need their skuIds stored. */
export function slotSkuCleanupCutoff(now: Date = new Date()): Date {
return new Date(now.getTime() - SLOT_SKU_RETENTION_HOURS * 60 * 60 * 1000)
}
/**
* Drops `sku_ids` from this region's slots delivered more than
* `SLOT_SKU_RETENTION_HOURS` ago. Time-based (not id-window based), so bursts of
* slot creation can never strip an upcoming slot's products. Already-empty rows
* and other regions are left untouched.
*/
export async function staleSlotsCleanup(regionId: number): Promise<number> {
// The 20-slot window is per region: one region's slot activity must never
// clear another region's product associations (and B's cache is not rebuilt
// by A's createSlot).
const recentSlots = await db
.select({ id: deliverySlotInfo.id })
.from(deliverySlotInfo)
.where(eq(deliverySlotInfo.regionId, regionId))
.orderBy(desc(deliverySlotInfo.id))
.limit(20)
const cutoff = slotSkuCleanupCutoff()
if (recentSlots.length < 20) {
return 0 // Less than 20 slots exist in this region, nothing to clean
}
// Get the threshold (the 20th most recent slot ID - minimum of the 20)
const threshold = Math.min(...recentSlots.map((s) => s.id))
// Clear productIds for the slot that just fell out of this region's window.
await db
const cleared = await db
.update(deliverySlotInfo)
.set({ skuIds: [] })
.where(and(eq(deliverySlotInfo.id, threshold), eq(deliverySlotInfo.regionId, regionId)))
.where(
and(
eq(deliverySlotInfo.regionId, regionId),
lte(deliverySlotInfo.deliveryTime, cutoff),
sql`json_array_length(${deliverySlotInfo.skuIds}) > 0`
)
)
.returning({ id: deliverySlotInfo.id })
return 1
return cleared.length
}
export async function getSlotsAfterDate(regionId: number | null, afterDate: Date): Promise<AdminDeliverySlot[]> {

View file

@ -1,11 +1,5 @@
export const CACHE_FILENAMES = {
products: 'products.json',
stores: 'stores.json',
slots: 'slots.json',
availability: 'availability.json',
essentialConsts: 'essential-consts.json',
banners: 'banners.json',
} as const
// Regional CDN cache-file URLs + filenames (shared by backend and UIs).
export * from './region-cache-urls'
/**
* Base origin of the backend API, shared by every UI (React Native and web).

View file

@ -7,7 +7,7 @@
*/
export const NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS = 24
export const FLASH_DELIVERY_MINUTES = 30
export const FLASH_DELIVERY_MINUTES = 60
const HOUR_MS = 60 * 60 * 1000
const MINUTE_MS = 60 * 1000
@ -20,7 +20,7 @@ export interface NextOrderGlimpseOrderLike {
/**
* The moment the order is promised for. Prefers the slot delivery date; a
* flash order without a slot uses the 30-minute promise shown on the card.
* flash order without a slot uses the 1-hour promise shown on the card.
*/
function deliveryMoment(order: NextOrderGlimpseOrderLike): Date | null {
if (order.deliveryDate) {

View file

@ -0,0 +1,251 @@
/**
* Regional CDN (R2) cache-file URLs.
*
* Single source of truth for the backend cache writer and both UIs:
* - the backend builds the URLs it publishes in `essentialConsts.essentialUrls`
* and the object keys it uploads/purges with them;
* - the UIs prefer `essentialUrls` from the API and fall back to these same
* builders when an older backend or a persisted snapshot does not carry it.
*
* Path shapes (do not change without migrating the existing buckets):
* {assetsDomain}{apiCacheKey}/regions/{regionId}/v-{productsVersion}/{file}
* {assetsDomain}regions/{regionId}/av-{availabilityVersion}/availability.json
* {assetsDomain}regions/{regionId}/slots/v-{slotsVersion}/slots.json
*
* Availability and slots intentionally sit OUTSIDE `apiCacheKey`. A builder
* returns an empty string when a part it needs is missing, never a malformed
* partial URL.
*/
export const CACHE_FILENAMES = {
products: 'products.json',
stores: 'stores.json',
slots: 'slots.json',
availability: 'availability.json',
essentialConsts: 'essential-consts.json',
banners: 'banners.json',
} as const
export type CacheFilename = (typeof CACHE_FILENAMES)[keyof typeof CACHE_FILENAMES]
export interface CacheVersions {
products: number
availability: number
slots: number
}
export interface EssentialUrls {
productsUrl: string
storesUrl: string
bannersUrl: string
essentialConstsUrl: string
availabilityUrl: string
slotsUrl: string
/** Per-store detail URL with a `{storeId}` placeholder for the caller to replace. */
storeDetailUrlTemplate: string
}
function clean(value: string | null | undefined): string {
return typeof value === 'string' ? value.trim() : ''
}
/** Assets domain with exactly one trailing slash ('' when unavailable). */
function domainBase(assetsDomain: string | null | undefined): string {
const domain = clean(assetsDomain)
if (!domain) return ''
return domain.endsWith('/') ? domain : `${domain}/`
}
function cacheKey(apiCacheKey: string | null | undefined): string {
return clean(apiCacheKey).replace(/^\/+|\/+$/g, '')
}
function version(value: number | null | undefined): string | null {
return typeof value === 'number' && Number.isFinite(value) ? String(value) : null
}
function joinUrl(domain: string, path: string): string {
return domain && path ? `${domain}${path}` : ''
}
/* -------------------------------------------------------------------------- */
/* Object keys (bucket-relative, used for uploads) */
/* -------------------------------------------------------------------------- */
export function regionCacheObjectKey(
apiCacheKeyValue: string | null | undefined,
regionId: number,
productsVersion: number,
filename: string
): string {
const key = cacheKey(apiCacheKeyValue)
const fileVersion = version(productsVersion)
if (!key || fileVersion == null) return ''
return `${key}/regions/${regionId}/v-${fileVersion}/${filename}`
}
export function availabilityObjectKey(
regionId: number,
availabilityVersion: number
): string {
const fileVersion = version(availabilityVersion)
if (fileVersion == null) return ''
return `regions/${regionId}/av-${fileVersion}/${CACHE_FILENAMES.availability}`
}
export function slotsObjectKey(regionId: number, slotsVersion: number): string {
const fileVersion = version(slotsVersion)
if (fileVersion == null) return ''
return `regions/${regionId}/slots/v-${fileVersion}/${CACHE_FILENAMES.slots}`
}
export function storeDetailObjectKey(
apiCacheKeyValue: string | null | undefined,
regionId: number,
productsVersion: number,
storeId: number
): string {
if (!Number.isFinite(storeId)) return ''
const key = cacheKey(apiCacheKeyValue)
const fileVersion = version(productsVersion)
if (!key || fileVersion == null) return ''
return `${key}/regions/${regionId}/v-${fileVersion}/stores/${storeId}.json`
}
/* -------------------------------------------------------------------------- */
/* CDN URLs */
/* -------------------------------------------------------------------------- */
export function regionCacheUrl(
assetsDomain: string | null | undefined,
apiCacheKeyValue: string | null | undefined,
regionId: number,
productsVersion: number,
filename: string
): string {
return joinUrl(
domainBase(assetsDomain),
regionCacheObjectKey(apiCacheKeyValue, regionId, productsVersion, filename)
)
}
export function availabilityCacheUrl(
assetsDomain: string | null | undefined,
regionId: number,
availabilityVersion: number
): string {
return joinUrl(domainBase(assetsDomain), availabilityObjectKey(regionId, availabilityVersion))
}
export function slotsCacheUrl(
assetsDomain: string | null | undefined,
regionId: number,
slotsVersion: number
): string {
return joinUrl(domainBase(assetsDomain), slotsObjectKey(regionId, slotsVersion))
}
export function storeDetailCacheUrl(
assetsDomain: string | null | undefined,
apiCacheKeyValue: string | null | undefined,
regionId: number,
productsVersion: number,
storeId: number
): string {
return joinUrl(
domainBase(assetsDomain),
storeDetailObjectKey(apiCacheKeyValue, regionId, productsVersion, storeId)
)
}
export function buildStoreDetailUrlTemplate(
assetsDomain: string | null | undefined,
apiCacheKeyValue: string | null | undefined,
regionId: number,
productsVersion: number
): string {
return regionCacheUrl(
assetsDomain,
apiCacheKeyValue,
regionId,
productsVersion,
'stores/{storeId}.json'
)
}
export interface EssentialUrlsInput {
assetsDomain?: string | null
apiCacheKey?: string | null
regionId: number
versions: CacheVersions
}
/** Every URL the browsing region can read from the CDN ('' when unavailable). */
export function buildEssentialUrls(input: EssentialUrlsInput): EssentialUrls {
const { assetsDomain, apiCacheKey: apiCacheKeyValue, regionId, versions } = input
return {
productsUrl: regionCacheUrl(
assetsDomain,
apiCacheKeyValue,
regionId,
versions.products,
CACHE_FILENAMES.products
),
storesUrl: regionCacheUrl(
assetsDomain,
apiCacheKeyValue,
regionId,
versions.products,
CACHE_FILENAMES.stores
),
bannersUrl: regionCacheUrl(
assetsDomain,
apiCacheKeyValue,
regionId,
versions.products,
CACHE_FILENAMES.banners
),
essentialConstsUrl: regionCacheUrl(
assetsDomain,
apiCacheKeyValue,
regionId,
versions.products,
CACHE_FILENAMES.essentialConsts
),
availabilityUrl: availabilityCacheUrl(assetsDomain, regionId, versions.availability),
slotsUrl: slotsCacheUrl(assetsDomain, regionId, versions.slots),
storeDetailUrlTemplate: buildStoreDetailUrlTemplate(
assetsDomain,
apiCacheKeyValue,
regionId,
versions.products
),
}
}
/**
* Look up the published URL for a cache file. Returns null when the payload has
* no usable URL for it (missing field or empty string), so callers can fall back
* to the builders above.
*/
export function cachedFileUrl(
urls: Partial<EssentialUrls> | null | undefined,
filename: string
): string | null {
if (!urls) return null
const field = (
{
[CACHE_FILENAMES.products]: 'productsUrl',
[CACHE_FILENAMES.stores]: 'storesUrl',
[CACHE_FILENAMES.banners]: 'bannersUrl',
[CACHE_FILENAMES.essentialConsts]: 'essentialConstsUrl',
[CACHE_FILENAMES.availability]: 'availabilityUrl',
[CACHE_FILENAMES.slots]: 'slotsUrl',
} as Record<string, keyof EssentialUrls>
)[filename]
const value = field ? urls[field] : null
return typeof value === 'string' && value.length > 0 ? value : null
}