enh
This commit is contained in:
parent
ec8e73a0c0
commit
ad6b525748
34 changed files with 1465 additions and 143 deletions
|
|
@ -272,7 +272,7 @@ export default function OrderDetails() {
|
||||||
</MyText>
|
</MyText>
|
||||||
{order.isFlashDelivery && (
|
{order.isFlashDelivery && (
|
||||||
<MyText style={tw`text-[9px] font-bold text-amber-600 mt-0.5`}>
|
<MyText style={tw`text-[9px] font-bold text-amber-600 mt-0.5`}>
|
||||||
⚡ 30-Min
|
⚡ 1-Hour
|
||||||
</MyText>
|
</MyText>
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
|
|
|
||||||
|
|
@ -274,7 +274,7 @@ function OrderDetails() {
|
||||||
</MyText>
|
</MyText>
|
||||||
{order.isFlashDelivery && (
|
{order.isFlashDelivery && (
|
||||||
<MyText className="mt-0.5 block text-[9px] font-bold text-amber-600">
|
<MyText className="mt-0.5 block text-[9px] font-bold text-amber-600">
|
||||||
⚡ 30-Min
|
⚡ 1-Hour
|
||||||
</MyText>
|
</MyText>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -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-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-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-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
|
### 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-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-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-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
|
### 4.7 Cross-file invariants
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -15,31 +15,20 @@ import {
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
import { imageUploadS3 } from '@/src/lib/s3-client'
|
import { imageUploadS3 } from '@/src/lib/s3-client'
|
||||||
import { getApiCacheKey, getCloudflareApiToken, getCloudflareZoneId, getAssetsDomain } from '@/src/lib/env-exporter'
|
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 { retryWithExponentialBackoff } from '@/src/lib/retry'
|
||||||
import { refreshGenKvForRegion } from '@/src/lib/gen-store'
|
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 {
|
export interface RegionCacheFilesResult {
|
||||||
regionId: number
|
regionId: number
|
||||||
cacheVersion: 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}...`)
|
console.log(`Starting creation of cache files for region ${regionId}...`)
|
||||||
|
|
||||||
const cacheVersion = await incrementRegionCacheVersion(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
|
// Create all per-region cache files in parallel
|
||||||
const [
|
const [
|
||||||
productsKey,
|
productsKey,
|
||||||
essentialConstsKey,
|
essentialConstsKey,
|
||||||
storesKey,
|
storesKey,
|
||||||
slotsVersion,
|
|
||||||
availabilityVersion,
|
|
||||||
bannersKey,
|
bannersKey,
|
||||||
individualStoreKeys,
|
individualStoreKeys,
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
createProductsFileInternal(regionId, cacheVersion),
|
createProductsFileInternal(regionId, cacheVersion),
|
||||||
createEssentialConstsFileInternal(regionId, cacheVersion),
|
createEssentialConstsFileInternal(regionId, cacheVersion),
|
||||||
createStoresFileInternal(regionId, cacheVersion),
|
createStoresFileInternal(regionId, cacheVersion),
|
||||||
createSlotsCacheFile(regionId, false),
|
|
||||||
createAvailabilityCacheFile(regionId, false),
|
|
||||||
createBannersFileInternal(regionId, cacheVersion),
|
createBannersFileInternal(regionId, cacheVersion),
|
||||||
createAllStoresFilesInternal(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 stores = await getStoresSummary(regionId)
|
||||||
|
const assetsDomain = getAssetsDomain()
|
||||||
|
const apiCacheKey = getApiCacheKey()
|
||||||
|
|
||||||
// Collect all per-region URLs for batch cache purge
|
// Collect all per-region URLs for batch cache purge
|
||||||
const urls = [
|
const urls = [
|
||||||
constructRegionCacheUrl(regionId, CACHE_FILENAMES.products, cacheVersion),
|
regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, CACHE_FILENAMES.products),
|
||||||
constructRegionCacheUrl(regionId, CACHE_FILENAMES.essentialConsts, cacheVersion),
|
regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, CACHE_FILENAMES.essentialConsts),
|
||||||
constructRegionCacheUrl(regionId, CACHE_FILENAMES.stores, cacheVersion),
|
regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, CACHE_FILENAMES.stores),
|
||||||
constructRegionSlotsUrl(regionId, slotsVersion),
|
slotsCacheUrl(assetsDomain, regionId, slotsVersion),
|
||||||
constructRegionAvailabilityUrl(regionId, availabilityVersion),
|
availabilityCacheUrl(assetsDomain, regionId, availabilityVersion),
|
||||||
constructRegionCacheUrl(regionId, CACHE_FILENAMES.banners, cacheVersion),
|
regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, CACHE_FILENAMES.banners),
|
||||||
...stores.map((store) => constructRegionCacheUrl(regionId, `stores/${store.id}.json`, cacheVersion)),
|
...stores.map((store) =>
|
||||||
]
|
storeDetailCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, store.id)
|
||||||
|
),
|
||||||
|
].filter((url) => url.length > 0)
|
||||||
|
|
||||||
// Purge all caches in one batch with retry
|
// Purge all caches in one batch with retry
|
||||||
try {
|
try {
|
||||||
|
|
@ -134,7 +131,12 @@ async function createProductsFileInternal(regionId: number, version: number): Pr
|
||||||
const productsData = await scaffoldProducts(regionId)
|
const productsData = await scaffoldProducts(regionId)
|
||||||
const jsonContent = JSON.stringify(productsData, null, 2)
|
const jsonContent = JSON.stringify(productsData, null, 2)
|
||||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
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)
|
console.log(filePath)
|
||||||
return await imageUploadS3(
|
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> {
|
export async function createAvailabilityCacheFile(
|
||||||
const version = await incrementRegionAvailabilityVersionNum(regionId)
|
regionId: number,
|
||||||
|
refresh = true,
|
||||||
|
version?: number
|
||||||
|
): Promise<number> {
|
||||||
|
const fileVersion = version ?? (await incrementRegionAvailabilityVersionNum(regionId))
|
||||||
const availabilityData = await scaffoldAvailability(regionId)
|
const availabilityData = await scaffoldAvailability(regionId)
|
||||||
const jsonContent = JSON.stringify(availabilityData, null, 2)
|
const jsonContent = JSON.stringify(availabilityData, null, 2)
|
||||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||||
const filePath = buildRegionAvailabilityPath(regionId, version)
|
const filePath = availabilityObjectKey(regionId, fileVersion)
|
||||||
|
|
||||||
console.log(filePath)
|
console.log(filePath)
|
||||||
await imageUploadS3(
|
await imageUploadS3(
|
||||||
|
|
@ -161,7 +167,7 @@ export async function createAvailabilityCacheFile(regionId: number, refresh = tr
|
||||||
|
|
||||||
if (refresh) await refreshGenKvForRegion(regionId)
|
if (refresh) await refreshGenKvForRegion(regionId)
|
||||||
|
|
||||||
return version
|
return fileVersion
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createEssentialConstsFileInternal(regionId: number, version: number): Promise<string> {
|
async function createEssentialConstsFileInternal(regionId: number, version: number): Promise<string> {
|
||||||
|
|
@ -173,7 +179,7 @@ async function createEssentialConstsFileInternal(regionId: number, version: numb
|
||||||
return await imageUploadS3(
|
return await imageUploadS3(
|
||||||
buffer,
|
buffer,
|
||||||
'application/json',
|
'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(
|
return await imageUploadS3(
|
||||||
buffer,
|
buffer,
|
||||||
'application/json',
|
'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> {
|
export async function createSlotsCacheFile(
|
||||||
const version = await incrementRegionSlotsVersionNum(regionId)
|
regionId: number,
|
||||||
|
refresh = true,
|
||||||
|
version?: number
|
||||||
|
): Promise<number> {
|
||||||
|
const fileVersion = version ?? (await incrementRegionSlotsVersionNum(regionId))
|
||||||
const slotsData = await scaffoldSlotsWithProducts(regionId)
|
const slotsData = await scaffoldSlotsWithProducts(regionId)
|
||||||
const jsonContent = JSON.stringify(slotsData, null, 2)
|
const jsonContent = JSON.stringify(slotsData, null, 2)
|
||||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||||
const filePath = buildRegionSlotsPath(regionId, version)
|
const filePath = slotsObjectKey(regionId, fileVersion)
|
||||||
|
|
||||||
console.log(filePath)
|
console.log(filePath)
|
||||||
await imageUploadS3(
|
await imageUploadS3(
|
||||||
|
|
@ -204,7 +214,7 @@ export async function createSlotsCacheFile(regionId: number, refresh = true): Pr
|
||||||
|
|
||||||
if (refresh) await refreshGenKvForRegion(regionId)
|
if (refresh) await refreshGenKvForRegion(regionId)
|
||||||
|
|
||||||
return version
|
return fileVersion
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createBannersFileInternal(regionId: number, version: number): Promise<string> {
|
async function createBannersFileInternal(regionId: number, version: number): Promise<string> {
|
||||||
|
|
@ -214,7 +224,7 @@ async function createBannersFileInternal(regionId: number, version: number): Pro
|
||||||
return await imageUploadS3(
|
return await imageUploadS3(
|
||||||
buffer,
|
buffer,
|
||||||
'application/json',
|
'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(
|
const s3Key = await imageUploadS3(
|
||||||
buffer,
|
buffer,
|
||||||
'application/json',
|
'application/json',
|
||||||
`${getApiCacheKey()}/${buildRegionCachePath(regionId, version, `stores/${store.id}.json`)}`
|
storeDetailObjectKey(getApiCacheKey(), regionId, version, store.id)
|
||||||
)
|
)
|
||||||
results.push(s3Key)
|
results.push(s3Key)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,8 @@ async function allBoundIds(): Promise<number[]> {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function putBound(kv: any, boundId: number): Promise<void> {
|
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)
|
const payload = await buildEssentialConsts(boundId)
|
||||||
await kv.put(genKvKeyForBound(boundId), JSON.stringify(payload))
|
await kv.put(genKvKeyForBound(boundId), JSON.stringify(payload))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -92,6 +92,8 @@ export {
|
||||||
getSlotDeliverySequence,
|
getSlotDeliverySequence,
|
||||||
updateSlotDeliverySequence,
|
updateSlotDeliverySequence,
|
||||||
staleSlotsCleanup,
|
staleSlotsCleanup,
|
||||||
|
SLOT_SKU_RETENTION_HOURS,
|
||||||
|
slotSkuCleanupCutoff,
|
||||||
// Admin - Staff User
|
// Admin - Staff User
|
||||||
getStaffUserByName,
|
getStaffUserByName,
|
||||||
getStaffUserById,
|
getStaffUserById,
|
||||||
|
|
|
||||||
|
|
@ -124,9 +124,9 @@ export const slotsRouter = router({
|
||||||
console.error('Failed to regenerate slots cache after slot create:', error)
|
console.error('Failed to regenerate slots cache after slot create:', error)
|
||||||
})
|
})
|
||||||
|
|
||||||
// Cleanup stale product slot associations for THIS region only. Awaited so
|
// Drop skuIds from slots delivered more than 36h ago for THIS region only.
|
||||||
// the incremental 20-slot window is not skipped when the mutation returns;
|
// Awaited so the cleanup is not skipped when the mutation returns; the
|
||||||
// the .catch keeps a cleanup failure from failing slot creation.
|
// .catch keeps a cleanup failure from failing slot creation.
|
||||||
await staleSlotsCleanup(ctx.staffUser.regionId).catch((error) => {
|
await staleSlotsCleanup(ctx.staffUser.regionId).catch((error) => {
|
||||||
console.error('Failed to cleanup stale slots:', error)
|
console.error('Failed to cleanup stale slots:', error)
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@ import {
|
||||||
} from '@/src/lib/const-store'
|
} from '@/src/lib/const-store'
|
||||||
import { readEssentialConstsFromKv } from '@/src/lib/gen-store'
|
import { readEssentialConstsFromKv } from '@/src/lib/gen-store'
|
||||||
import { getAssetsDomain, getApiCacheKey } from '@/src/lib/env-exporter'
|
import { getAssetsDomain, getApiCacheKey } from '@/src/lib/env-exporter'
|
||||||
|
import { buildEssentialUrls } from '@packages/shared'
|
||||||
|
|
||||||
const polygon = turfPolygon(mbnrGeoJson.features[0].geometry.coordinates);
|
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
|
// Flat union of global + region + bound consts (+ env + identity). Key names
|
||||||
// match the three tables exactly so clients read one flat object.
|
// 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 {
|
return {
|
||||||
// global_consts
|
// global_consts
|
||||||
versionNum: pickRaw(global['versionNum'], null),
|
versionNum: pickRaw(global['versionNum'], null),
|
||||||
|
|
@ -61,9 +68,9 @@ export async function scaffoldEssentialConsts(boundId: number) {
|
||||||
appStoreUrl: pickRaw(global['appStoreUrl'], null),
|
appStoreUrl: pickRaw(global['appStoreUrl'], null),
|
||||||
internalAppVersion: pickNumber(global['internalAppVersion'], 1),
|
internalAppVersion: pickNumber(global['internalAppVersion'], 1),
|
||||||
// region_consts
|
// region_consts
|
||||||
products_version_num: pickNumber(region['products_version_num'], 0),
|
products_version_num: productsVersionNum,
|
||||||
availability_version_num: pickNumber(region['availability_version_num'], 0),
|
availability_version_num: availabilityVersionNum,
|
||||||
slots_version_num: pickNumber(region['slots_version_num'], 0),
|
slots_version_num: slotsVersionNum,
|
||||||
popularItems: pickRaw(region['popularItems'], null),
|
popularItems: pickRaw(region['popularItems'], null),
|
||||||
allItemsOrder: pickRaw(region['allItemsOrder'], null),
|
allItemsOrder: pickRaw(region['allItemsOrder'], null),
|
||||||
supportMobile: pickRaw(region['supportMobile'], ''),
|
supportMobile: pickRaw(region['supportMobile'], ''),
|
||||||
|
|
@ -77,10 +84,22 @@ export async function scaffoldEssentialConsts(boundId: number) {
|
||||||
// Per bound: each bound switches flash delivery on/off independently.
|
// Per bound: each bound switches flash delivery on/off independently.
|
||||||
isFlashDeliveryEnabled: pickBool(boundConsts['isFlashDeliveryEnabled'], false),
|
isFlashDeliveryEnabled: pickBool(boundConsts['isFlashDeliveryEnabled'], false),
|
||||||
// env + identity
|
// env + identity
|
||||||
assetsDomain: getAssetsDomain(),
|
assetsDomain,
|
||||||
apiCacheKey: getApiCacheKey(),
|
apiCacheKey,
|
||||||
regionId,
|
regionId,
|
||||||
boundId,
|
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)
|
// stale-client notice (overridden per-request in the procedure)
|
||||||
webViewHtml: null,
|
webViewHtml: null,
|
||||||
webviewHtml: null,
|
webviewHtml: null,
|
||||||
|
|
|
||||||
|
|
@ -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).
|
* (catalogue §4.6).
|
||||||
*
|
*
|
||||||
* `banners.json` is rebuilt asynchronously with `products_version_num` (the
|
* `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.webViewHtml).toBeNull()
|
||||||
expect(doc.isWebviewClosable).toBe(true)
|
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`
|
||||||
|
)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -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
|
* `common.essentialConsts({ boundId })` is served from the per-bound KV mirror
|
||||||
* (`readEssentialConstsFromKv`); the payload is a flat union of
|
* (`readEssentialConstsFromKv`); the payload is a flat union of
|
||||||
|
|
@ -30,7 +30,16 @@ import {
|
||||||
setRegionConstant,
|
setRegionConstant,
|
||||||
squareGeojson,
|
squareGeojson,
|
||||||
} from '../helpers/fixtures'
|
} 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'
|
import { TEST_BOUND_ID, TEST_OTHER_BOUND_ID, TEST_REGION_ID, TEST_OTHER_REGION_ID } from '../helpers/env'
|
||||||
|
|
||||||
jest.setTimeout(300_000)
|
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)', () => {
|
describe('common.essentialConsts fallbacks (CACHE-06..11)', () => {
|
||||||
it('CACHE-06: a missing numeric bound const falls back to 200/0/500/69', async () => {
|
it('CACHE-06: a missing numeric bound const falls back to 200/0/500/69', async () => {
|
||||||
await withBoundSettings(
|
await withBoundSettings(
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,13 @@
|
||||||
import { apiClient, sleep } from './api'
|
import { apiClient, sleep } from './api'
|
||||||
import { staffSession } from './sessions'
|
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 { 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 {
|
export interface EssentialConsts {
|
||||||
regionId: number
|
regionId: number
|
||||||
|
|
@ -27,6 +34,8 @@ export interface EssentialConsts {
|
||||||
products_version_num: number
|
products_version_num: number
|
||||||
slots_version_num: number
|
slots_version_num: number
|
||||||
availability_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
|
webviewHtml?: string | null
|
||||||
isWebviewClosable?: boolean
|
isWebviewClosable?: boolean
|
||||||
[key: string]: unknown
|
[key: string]: unknown
|
||||||
|
|
@ -117,38 +126,46 @@ export function versionOf(consts: EssentialConsts, kind: CacheKind): number {
|
||||||
return value
|
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')) =>
|
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')) =>
|
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 = (
|
export const storeDetailCacheUrl = (
|
||||||
c: EssentialConsts,
|
c: EssentialConsts,
|
||||||
storeId: number,
|
storeId: number,
|
||||||
regionId?: number,
|
regionId?: number,
|
||||||
version = versionOf(c, 'products')
|
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')) =>
|
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 = (
|
export const essentialConstsCacheUrl = (
|
||||||
c: EssentialConsts,
|
c: EssentialConsts,
|
||||||
regionId?: number,
|
regionId?: number,
|
||||||
version = versionOf(c, 'products')
|
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')) =>
|
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 = (
|
export const availabilityCacheUrl = (
|
||||||
c: EssentialConsts,
|
c: EssentialConsts,
|
||||||
regionId?: number,
|
regionId?: number,
|
||||||
version = versionOf(c, 'availability')
|
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. */
|
/** 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> {
|
export async function fetchCacheJson<T = unknown>(url: string): Promise<T> {
|
||||||
|
|
|
||||||
132
apps/backend/tests/unit/region-cache-urls.test.ts
Normal file
132
apps/backend/tests/unit/region-cache-urls.test.ts
Normal 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()
|
||||||
|
})
|
||||||
|
})
|
||||||
35
apps/backend/tests/unit/slot-sku-cleanup.test.ts
Normal file
35
apps/backend/tests/unit/slot-sku-cleanup.test.ts
Normal 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)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -408,7 +408,7 @@ Mock `useAllProducts` via `common.essentialConsts` + versioned `products.json` a
|
||||||
| HOME-100 | edge | signed in, orders loading | small spinner card |
|
| HOME-100 | edge | signed in, orders loading | small spinner card |
|
||||||
| HOME-101 | happy | one upcoming order | id, “N items • ₹total”, status |
|
| HOME-101 | happy | one upcoming order | id, “N items • ₹total”, status |
|
||||||
| HOME-102 | edge | confirmed/packaged status | status chip hidden |
|
| 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-104 | edge | cancelled order | excluded |
|
||||||
| HOME-105 | edge | success delivery order | excluded |
|
| HOME-105 | edge | success delivery order | excluded |
|
||||||
| HOME-106 | edge | flash + scheduled orders | flash first |
|
| HOME-106 | edge | flash + scheduled orders | flash first |
|
||||||
|
|
@ -1448,6 +1448,10 @@ Covered by HOME-81..98, plus:
|
||||||
| API-17 | edge | availability error | products still render with defaults? assert current |
|
| API-17 | edge | availability error | products still render with defaults? assert current |
|
||||||
| API-18 | edge | region change | URL/query key changes |
|
| API-18 | edge | region change | URL/query key changes |
|
||||||
| API-19 | edge | `useRegionalConsts` passthrough | same data |
|
| 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 |
|
||||||
|
|
||||||
### Region and location — `tests/lib/use-region.test.tsx`, `location-store.test.ts`
|
### Region and location — `tests/lib/use-region.test.tsx`, `location-store.test.ts`
|
||||||
|
|
||||||
|
|
@ -1480,6 +1484,10 @@ Covered by HOME-81..98, plus:
|
||||||
| REGION-25 | edge | cached regions + address, live pending | starts from cache; live requests still run |
|
| 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-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-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-01 | happy | start once | one permission/fix; second start no-op |
|
||||||
| LOCSTORE-02 | error | denied | status denied, coords null |
|
| LOCSTORE-02 | error | denied | status denied, coords null |
|
||||||
| LOCSTORE-03 | edge | services off | status services-off |
|
| LOCSTORE-03 | edge | services off | status services-off |
|
||||||
|
|
|
||||||
|
|
@ -154,7 +154,7 @@ const OrderItem: React.FC<OrderItemProps> = ({
|
||||||
</MyText>
|
</MyText>
|
||||||
{item.isFlashDelivery && (
|
{item.isFlashDelivery && (
|
||||||
<View style={tw`flex-row items-center mt-1`}>
|
<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>
|
</View>
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@ function OrderCard({ order, onPress, supportMobile }: OrderCardProps) {
|
||||||
const statusLabel = orderStatusManipulator(order.deliveryStatus);
|
const statusLabel = orderStatusManipulator(order.deliveryStatus);
|
||||||
const hideStatus = ['confirmed', 'packaged'].includes(statusLabel.toLowerCase());
|
const hideStatus = ['confirmed', 'packaged'].includes(statusLabel.toLowerCase());
|
||||||
const deliveryPrimaryLabel = order.isFlashDelivery
|
const deliveryPrimaryLabel = order.isFlashDelivery
|
||||||
? "30-Min"
|
? "1-Hour"
|
||||||
: (() => {
|
: (() => {
|
||||||
const startTime = dayjs(order.deliveryDate);
|
const startTime = dayjs(order.deliveryDate);
|
||||||
const endTime = startTime.add(1, 'hour');
|
const endTime = startTime.add(1, 'hour');
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { fetchJson } from '@/src/lib/fetch-json'
|
||||||
import { trpc } from '@/src/trpc-client'
|
import { trpc } from '@/src/trpc-client'
|
||||||
import type { ProductPriceFlags } from '@packages/shared'
|
import type { ProductPriceFlags } from '@packages/shared'
|
||||||
import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType, StoreWithProductsApiType, AvailabilityApiType } from "@backend/trpc/router";
|
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 { StorageServiceCasual } from 'common-ui';
|
||||||
import { useRegion } from '@/src/hooks/useRegion'
|
import { useRegion } from '@/src/hooks/useRegion'
|
||||||
import { useAddressStore } from '@/src/store/addressStore'
|
import { useAddressStore } from '@/src/store/addressStore'
|
||||||
|
|
@ -126,6 +126,11 @@ function useCacheUrl(filename: string): string | null {
|
||||||
const { data: essentialConsts } = useGetEssentialConsts()
|
const { data: essentialConsts } = useGetEssentialConsts()
|
||||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
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 assetsDomain = essentialConsts?.assetsDomain
|
||||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||||
const productsVersionNum = essentialConsts?.products_version_num
|
const productsVersionNum = essentialConsts?.products_version_num
|
||||||
|
|
@ -134,13 +139,16 @@ function useCacheUrl(filename: string): string | null {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${productsVersionNum}/${filename}`
|
return regionCacheUrl(assetsDomain, apiCacheKey, regionId, productsVersionNum, filename) || null
|
||||||
}
|
}
|
||||||
|
|
||||||
function useAvailabilityCacheUrl(): string | null {
|
function useAvailabilityCacheUrl(): string | null {
|
||||||
const { data: essentialConsts } = useGetEssentialConsts()
|
const { data: essentialConsts } = useGetEssentialConsts()
|
||||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||||
|
|
||||||
|
const published = cachedFileUrl(essentialConsts?.essentialUrls, CACHE_FILENAMES.availability)
|
||||||
|
if (published) return published
|
||||||
|
|
||||||
const assetsDomain = essentialConsts?.assetsDomain
|
const assetsDomain = essentialConsts?.assetsDomain
|
||||||
const availabilityVersionNum = essentialConsts?.availability_version_num
|
const availabilityVersionNum = essentialConsts?.availability_version_num
|
||||||
|
|
||||||
|
|
@ -148,13 +156,16 @@ function useAvailabilityCacheUrl(): string | null {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}regions/${regionId}/av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
|
return availabilityCacheUrl(assetsDomain, regionId, availabilityVersionNum) || null
|
||||||
}
|
}
|
||||||
|
|
||||||
function useSlotsCacheUrl(): string | null {
|
function useSlotsCacheUrl(): string | null {
|
||||||
const { data: essentialConsts } = useGetEssentialConsts()
|
const { data: essentialConsts } = useGetEssentialConsts()
|
||||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||||
|
|
||||||
|
const published = cachedFileUrl(essentialConsts?.essentialUrls, CACHE_FILENAMES.slots)
|
||||||
|
if (published) return published
|
||||||
|
|
||||||
const assetsDomain = essentialConsts?.assetsDomain
|
const assetsDomain = essentialConsts?.assetsDomain
|
||||||
const slotsVersionNum = essentialConsts?.slots_version_num
|
const slotsVersionNum = essentialConsts?.slots_version_num
|
||||||
|
|
||||||
|
|
@ -162,7 +173,7 @@ function useSlotsCacheUrl(): string | null {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}regions/${regionId}/slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
|
return slotsCacheUrl(assetsDomain, regionId, slotsVersionNum) || null
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAllProducts() {
|
export function useAllProducts() {
|
||||||
|
|
@ -284,9 +295,12 @@ export function useStoreWithProducts(storeId: number) {
|
||||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||||
const cacheVersion = essentialConsts?.products_version_num;
|
const cacheVersion = essentialConsts?.products_version_num;
|
||||||
|
|
||||||
const cacheUrl = assetsDomain && apiCacheKey && regionId != null
|
const publishedTemplate = essentialConsts?.essentialUrls?.storeDetailUrlTemplate
|
||||||
? `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/stores/${storeId}.json`
|
const cacheUrl = publishedTemplate
|
||||||
: null
|
? publishedTemplate.replace('{storeId}', String(storeId))
|
||||||
|
: assetsDomain && apiCacheKey && regionId != null && cacheVersion != null
|
||||||
|
? storeDetailCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, storeId) || null
|
||||||
|
: null
|
||||||
const version = cacheUrl ?? ''
|
const version = cacheUrl ?? ''
|
||||||
|
|
||||||
return useQuery<StoreWithProductsResponse>({
|
return useQuery<StoreWithProductsResponse>({
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,19 @@
|
||||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
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 { useRegionStore } from '@/src/store/regionStore'
|
||||||
import { useAddressStore } from '@/src/store/addressStore'
|
import { useAddressStore } from '@/src/store/addressStore'
|
||||||
import { useLocationStore } from '@/src/store/locationStore'
|
import { useLocationStore } from '@/src/store/locationStore'
|
||||||
import { trpc } from '@/src/trpc-client'
|
import { trpc } from '@/src/trpc-client'
|
||||||
import { confirmRegionSwitch } from '@/src/lib/region-switch'
|
import { confirmRegionSwitch } from '@/src/lib/region-switch'
|
||||||
import {
|
import {
|
||||||
|
readCachedLocationResolution,
|
||||||
readCachedRegions,
|
readCachedRegions,
|
||||||
readCachedUserAddresses,
|
readCachedUserAddresses,
|
||||||
|
writeCachedLocationResolution,
|
||||||
writeCachedRegions,
|
writeCachedRegions,
|
||||||
writeCachedUserAddresses,
|
writeCachedUserAddresses,
|
||||||
|
type CachedLocationResolution,
|
||||||
type CachedUserAddressesResponse,
|
type CachedUserAddressesResponse,
|
||||||
} from '@/src/lib/region-cache'
|
} from '@/src/lib/region-cache'
|
||||||
import { useAuthOptional } from '@/src/contexts/AuthContext'
|
import { useAuthOptional } from '@/src/contexts/AuthContext'
|
||||||
|
|
@ -25,6 +28,15 @@ const RESOLVE_TIMEOUT_MS = 8000
|
||||||
let startupCheckDone = false
|
let startupCheckDone = false
|
||||||
let startupLaunchRegionId: number | null | undefined
|
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").
|
* The single source of truth for the browsing region ("location").
|
||||||
*
|
*
|
||||||
|
|
@ -113,12 +125,17 @@ export function useRegion(): UseRegionResult {
|
||||||
ready: boolean
|
ready: boolean
|
||||||
regions: RegionSummary[] | null
|
regions: RegionSummary[] | null
|
||||||
addresses: CachedUserAddressesResponse | null
|
addresses: CachedUserAddressesResponse | null
|
||||||
}>({ ready: false, regions: null, addresses: null })
|
resolution: CachedLocationResolution | null
|
||||||
|
}>({ ready: false, regions: null, addresses: null, resolution: null })
|
||||||
const cacheBaselineRef = useRef<{
|
const cacheBaselineRef = useRef<{
|
||||||
regions: RegionSummary[] | null
|
regions: RegionSummary[] | null
|
||||||
addresses: CachedUserAddressesResponse | null
|
addresses: CachedUserAddressesResponse | null
|
||||||
} | null>(null)
|
} | null>(null)
|
||||||
const decisionSignatureRef = useRef<string | 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.
|
// The user's default address — the anchor for the startup region decision.
|
||||||
const defaultAddressQuery = trpc.user.address.getDefaultAddress.useQuery(undefined, {
|
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.
|
// query; updatedAt: 0 keeps the entry stale so the live request still fires.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
setCacheSnapshot({ ready: false, regions: null, addresses: null })
|
setCacheSnapshot({ ready: false, regions: null, addresses: null, resolution: null })
|
||||||
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
const cachedRegions = await readCachedRegions()
|
const [cachedRegions, cachedAddresses, cachedResolution] = await Promise.all([
|
||||||
const cachedAddresses =
|
readCachedRegions(),
|
||||||
isAuthenticated && userId != null
|
isAuthenticated && userId != null
|
||||||
? await readCachedUserAddresses(userId)
|
? readCachedUserAddresses(userId)
|
||||||
: null
|
: Promise.resolve(null),
|
||||||
|
readCachedLocationResolution(),
|
||||||
|
])
|
||||||
if (cancelled) return
|
if (cancelled) return
|
||||||
|
|
||||||
cacheBaselineRef.current = { regions: cachedRegions, addresses: cachedAddresses }
|
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) {
|
if (cachedRegions && utils.common.listRegions.getData(undefined) === undefined) {
|
||||||
utils.common.listRegions.setData(undefined, cachedRegions, { updatedAt: 0 })
|
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 lng = coords ? Math.round(coords.longitude * 1e5) / 1e5 : 0
|
||||||
const queryInput = useMemo(() => ({ lat, lng }), [lat, lng])
|
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, {
|
const resolution = trpc.common.resolveRegionByLocation.useQuery(queryInput, {
|
||||||
enabled: shouldResolve,
|
enabled: shouldResolve,
|
||||||
staleTime: Infinity,
|
staleTime: Infinity,
|
||||||
|
|
@ -264,6 +291,13 @@ export function useRegion(): UseRegionResult {
|
||||||
refetchOnWindowFocus: false,
|
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:
|
// Apply the launch outcome once. The default address anchors the decision:
|
||||||
// - location resolves to the default's region, or to no serviceable region
|
// - location resolves to the default's region, or to no serviceable region
|
||||||
// (location off / out of area) -> use the default address;
|
// (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.
|
// default-address anchor and show the chooser on every location-off launch.
|
||||||
if (!hasAuthContext) return
|
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 =
|
const locationSettled =
|
||||||
resolved != null ||
|
resolved != null ||
|
||||||
resolution.isFetched ||
|
liveResolutionSettled ||
|
||||||
resolution.isError ||
|
cachedResolution != null ||
|
||||||
locationStatus === 'denied' ||
|
locationStatus === 'denied' ||
|
||||||
locationStatus === 'services-off' ||
|
locationStatus === 'services-off' ||
|
||||||
locationStatus === 'unavailable' ||
|
locationStatus === 'unavailable' ||
|
||||||
|
|
@ -324,6 +359,8 @@ export function useRegion(): UseRegionResult {
|
||||||
}
|
}
|
||||||
|
|
||||||
decisionSignatureRef.current = regionDataSignature
|
decisionSignatureRef.current = regionDataSignature
|
||||||
|
settledResolutionRef.current = resolutionSignature(resolved)
|
||||||
|
settledOnCachedResolutionRef.current = !resolution.isSuccess && cachedResolution != null
|
||||||
setStartupResolved(true)
|
setStartupResolved(true)
|
||||||
|
|
||||||
// Only one consumer performs the switch; the rest just settle their spinner.
|
// 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) {
|
} else if (resolved.bound && resolved.bound.id !== boundId) {
|
||||||
setRegion(resolved.region, resolved.bound.id)
|
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,
|
hydrated,
|
||||||
|
|
@ -395,6 +437,9 @@ export function useRegion(): UseRegionResult {
|
||||||
resolution.data,
|
resolution.data,
|
||||||
resolution.isFetched,
|
resolution.isFetched,
|
||||||
resolution.isError,
|
resolution.isError,
|
||||||
|
resolved,
|
||||||
|
liveResolutionSettled,
|
||||||
|
cachedResolution,
|
||||||
locationStatus,
|
locationStatus,
|
||||||
regionId,
|
regionId,
|
||||||
boundId,
|
boundId,
|
||||||
|
|
@ -488,6 +533,36 @@ export function useRegion(): UseRegionResult {
|
||||||
addresses,
|
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
|
// Sole-address safety net. The launch decision above runs once per app launch
|
||||||
// (`startupResolved`/`startupCheckDone`), but the address list can arrive
|
// (`startupResolved`/`startupCheckDone`), but the address list can arrive
|
||||||
// later — e.g. the user was signed out when the gate first settled and logged
|
// later — e.g. the user was signed out when the gate first settled and logged
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { StorageServiceCasual } from 'common-ui'
|
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
|
* 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:
|
* starts:
|
||||||
* - the global region list (`common.listRegions`)
|
* - the global region list (`common.listRegions`)
|
||||||
* - the signed-in user's addresses (`user.address.getUserAddresses`)
|
* - 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
|
* 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.
|
* background and overwrite both the React Query cache and these snapshots.
|
||||||
*/
|
*/
|
||||||
// SecureStore only accepts alphanumeric, ".", "-" and "_" in keys.
|
// SecureStore only accepts alphanumeric, ".", "-" and "_" in keys.
|
||||||
export const REGION_LIST_CACHE_KEY = 'region_cache.list_regions.v1'
|
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) =>
|
export const userAddressesCacheKey = (userId: number) =>
|
||||||
`region_cache.user_addresses.v1.${userId}`
|
`region_cache.user_addresses.v1.${userId}`
|
||||||
|
|
||||||
let lastWrittenRegions: string | null = null
|
let lastWrittenRegions: string | null = null
|
||||||
|
let lastWrittenResolution: string | null = null
|
||||||
const lastWrittenAddresses = new Map<number, string>()
|
const lastWrittenAddresses = new Map<number, string>()
|
||||||
|
|
||||||
function parseJson(raw: string | null): unknown {
|
function parseJson(raw: string | null): unknown {
|
||||||
|
|
@ -98,3 +114,39 @@ export async function writeCachedUserAddresses(
|
||||||
const stored = await StorageServiceCasual.setItem(userAddressesCacheKey(userId), serialized)
|
const stored = await StorageServiceCasual.setItem(userAddressesCacheKey(userId), serialized)
|
||||||
if (stored) lastWrittenAddresses.set(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
|
||||||
|
}
|
||||||
|
|
|
||||||
13
apps/user-ui/tests/fixtures/index.ts
vendored
13
apps/user-ui/tests/fixtures/index.ts
vendored
|
|
@ -9,6 +9,7 @@
|
||||||
* - stores.json -> scaffoldStores ({ stores })
|
* - stores.json -> scaffoldStores ({ stores })
|
||||||
* - stores/<id>.json -> scaffoldStoreWithProducts ({ store, products, tags })
|
* - stores/<id>.json -> scaffoldStoreWithProducts ({ store, products, tags })
|
||||||
*/
|
*/
|
||||||
|
import { buildEssentialUrls } from '@packages/shared'
|
||||||
|
|
||||||
export const REGION_1 = {
|
export const REGION_1 = {
|
||||||
id: 1,
|
id: 1,
|
||||||
|
|
@ -39,6 +40,18 @@ export const CONSTS = {
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
assetsDomain: CACHE_BASE,
|
assetsDomain: CACHE_BASE,
|
||||||
apiCacheKey: API_CACHE_KEY,
|
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,
|
products_version_num: PRODUCTS_VERSION_NUM,
|
||||||
availability_version_num: AVAILABILITY_VERSION_NUM,
|
availability_version_num: AVAILABILITY_VERSION_NUM,
|
||||||
slots_version_num: SLOTS_VERSION_NUM,
|
slots_version_num: SLOTS_VERSION_NUM,
|
||||||
|
|
|
||||||
|
|
@ -62,7 +62,7 @@ describe('isInNextOrderGlimpseWindow', () => {
|
||||||
expect(isInNextOrderGlimpseWindow(order({ deliveryDate: null }), NOW)).toBe(false)
|
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({
|
const recent = order({
|
||||||
isFlashDelivery: true,
|
isFlashDelivery: true,
|
||||||
deliveryDate: null,
|
deliveryDate: null,
|
||||||
|
|
@ -71,12 +71,12 @@ describe('isInNextOrderGlimpseWindow', () => {
|
||||||
const old = order({
|
const old = order({
|
||||||
isFlashDelivery: true,
|
isFlashDelivery: true,
|
||||||
deliveryDate: null,
|
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(recent, NOW)).toBe(true)
|
||||||
expect(isInNextOrderGlimpseWindow(old, NOW)).toBe(false)
|
expect(isInNextOrderGlimpseWindow(old, NOW)).toBe(false)
|
||||||
// The fallback really is the flash promise, not an arbitrary window.
|
// The fallback really is the flash promise, not an arbitrary window.
|
||||||
expect(FLASH_DELIVERY_MINUTES).toBe(30)
|
expect(FLASH_DELIVERY_MINUTES).toBe(60)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -61,6 +61,7 @@ import {
|
||||||
storeDetailCacheUrl,
|
storeDetailCacheUrl,
|
||||||
storesCacheUrl,
|
storesCacheUrl,
|
||||||
} from '../fixtures'
|
} from '../fixtures'
|
||||||
|
import { buildEssentialUrls } from '@packages/shared'
|
||||||
|
|
||||||
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
|
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
|
||||||
|
|
||||||
|
|
@ -255,7 +256,21 @@ describe('prominent API hooks', () => {
|
||||||
})
|
})
|
||||||
|
|
||||||
it('API-12: missing URL parts disable the hook and issue no fetch', async () => {
|
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())
|
const { element, result } = makeProbe(() => useAllProducts())
|
||||||
renderWithProviders(element, { auth: false })
|
renderWithProviders(element, { auth: false })
|
||||||
|
|
@ -352,7 +367,23 @@ describe('prominent API hooks', () => {
|
||||||
|
|
||||||
it('API-18: a region change produces a new CDN URL / query key', async () => {
|
it('API-18: a region change produces a new CDN URL / query key', async () => {
|
||||||
setProcedure('common.essentialConsts', {
|
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(productsCacheUrl(1), PRODUCTS_RESPONSE)
|
||||||
setJsonResponse(availabilityCacheUrl(1), AVAILABILITY_RESPONSE)
|
setJsonResponse(availabilityCacheUrl(1), AVAILABILITY_RESPONSE)
|
||||||
|
|
@ -383,4 +414,91 @@ describe('prominent API hooks', () => {
|
||||||
await waitFor(() => expect(result.current.regionalConsts).toBeTruthy())
|
await waitFor(() => expect(result.current.regionalConsts).toBeTruthy())
|
||||||
expect(result.current.regionalConsts).toEqual(result.current.essentialConsts.data)
|
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)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,8 @@
|
||||||
*/
|
*/
|
||||||
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
|
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
|
||||||
|
|
||||||
|
import { buildEssentialUrls } from '@packages/shared'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `installTrpcNetworkMock()` (tests/setup.ts) is installed from the ROOT module
|
* `installTrpcNetworkMock()` (tests/setup.ts) is installed from the ROOT module
|
||||||
* registry, so `global.fetch` answers from the root copy of the procedure
|
* registry, so `global.fetch` answers from the root copy of the procedure
|
||||||
|
|
@ -680,6 +682,151 @@ describe('useRegion', () => {
|
||||||
view.unmount()
|
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.getDefaultAddress', { data: { data: null } })
|
||||||
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
|
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
|
||||||
ctx.trpc.setProcedure('common.essentialConsts', {
|
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 })
|
ctx.testUtils.seedJsonCache({ regionId: 1 })
|
||||||
|
|
|
||||||
|
|
@ -1401,13 +1401,13 @@ describe('Home (HOME)', () => {
|
||||||
expect(queryByText('packaged')).toBeNull()
|
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()
|
signedIn()
|
||||||
setOrders([{ ...O1, isFlashDelivery: true }])
|
setOrders([{ ...O1, isFlashDelivery: true }])
|
||||||
const { getByText } = await renderHome()
|
const { getByText } = await renderHome()
|
||||||
|
|
||||||
expect(getByText('FLASH')).toBeTruthy()
|
expect(getByText('FLASH')).toBeTruthy()
|
||||||
expect(getByText('30-Min')).toBeTruthy()
|
expect(getByText('1-Hour')).toBeTruthy()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('HOME-104: a cancelled order is excluded', async () => {
|
it('HOME-104: a cancelled order is excluded', async () => {
|
||||||
|
|
@ -1561,7 +1561,7 @@ describe('Home (HOME)', () => {
|
||||||
expect(queryByTestId('next-order-glimpse')).toBeNull()
|
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()
|
signedIn()
|
||||||
setOrders([
|
setOrders([
|
||||||
{
|
{
|
||||||
|
|
@ -1585,7 +1585,7 @@ describe('Home (HOME)', () => {
|
||||||
id: 1001,
|
id: 1001,
|
||||||
isFlashDelivery: true,
|
isFlashDelivery: true,
|
||||||
deliveryDate: undefined,
|
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()
|
const { queryByTestId } = await renderHome()
|
||||||
|
|
|
||||||
|
|
@ -66,7 +66,7 @@ function OrderCard({ order, supportMobile, onPress }: OrderCardProps) {
|
||||||
<span className="mr-1.5 text-amber-600">{order.isFlashDelivery ? '⚡' : '🕐'}</span>
|
<span className="mr-1.5 text-amber-600">{order.isFlashDelivery ? '⚡' : '🕐'}</span>
|
||||||
<p className="text-xs font-medium text-amber-800">
|
<p className="text-xs font-medium text-amber-800">
|
||||||
{order.isFlashDelivery
|
{order.isFlashDelivery
|
||||||
? '30-Min Delivery'
|
? '1-Hour Delivery'
|
||||||
: formatRange(order.deliveryDate || order.orderDate)}
|
: formatRange(order.deliveryDate || order.orderDate)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,14 @@ import type {
|
||||||
BannersApiType,
|
BannersApiType,
|
||||||
StoreWithProductsApiType,
|
StoreWithProductsApiType,
|
||||||
} from '@backend/trpc/router'
|
} 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}`
|
const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}`
|
||||||
|
|
||||||
|
|
@ -246,6 +253,11 @@ function useCacheUrl(filename: string): string | null {
|
||||||
const { data: essentialConsts } = useGetEssentialConsts()
|
const { data: essentialConsts } = useGetEssentialConsts()
|
||||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
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 assetsDomain = essentialConsts?.assetsDomain
|
||||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||||
const cacheVersion = essentialConsts?.products_version_num
|
const cacheVersion = essentialConsts?.products_version_num
|
||||||
|
|
@ -260,13 +272,16 @@ function useCacheUrl(filename: string): string | null {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/${filename}`
|
return regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, filename) || null
|
||||||
}
|
}
|
||||||
|
|
||||||
function useAvailabilityCacheUrl(): string | null {
|
function useAvailabilityCacheUrl(): string | null {
|
||||||
const { data: essentialConsts } = useGetEssentialConsts()
|
const { data: essentialConsts } = useGetEssentialConsts()
|
||||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||||
|
|
||||||
|
const published = cachedFileUrl(essentialConsts?.essentialUrls, CACHE_FILENAMES.availability)
|
||||||
|
if (published) return published
|
||||||
|
|
||||||
const assetsDomain = essentialConsts?.assetsDomain
|
const assetsDomain = essentialConsts?.assetsDomain
|
||||||
const availabilityVersionNum = essentialConsts?.availability_version_num
|
const availabilityVersionNum = essentialConsts?.availability_version_num
|
||||||
|
|
||||||
|
|
@ -274,13 +289,16 @@ function useAvailabilityCacheUrl(): string | null {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}regions/${regionId}/av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
|
return availabilityCacheUrl(assetsDomain, regionId, availabilityVersionNum) || null
|
||||||
}
|
}
|
||||||
|
|
||||||
function useSlotsCacheUrl(): string | null {
|
function useSlotsCacheUrl(): string | null {
|
||||||
const { data: essentialConsts } = useGetEssentialConsts()
|
const { data: essentialConsts } = useGetEssentialConsts()
|
||||||
const regionId = useDiscoveryRegionId(essentialConsts)
|
const regionId = useDiscoveryRegionId(essentialConsts)
|
||||||
|
|
||||||
|
const published = cachedFileUrl(essentialConsts?.essentialUrls, CACHE_FILENAMES.slots)
|
||||||
|
if (published) return published
|
||||||
|
|
||||||
const assetsDomain = essentialConsts?.assetsDomain
|
const assetsDomain = essentialConsts?.assetsDomain
|
||||||
const slotsVersionNum = essentialConsts?.slots_version_num
|
const slotsVersionNum = essentialConsts?.slots_version_num
|
||||||
|
|
||||||
|
|
@ -288,7 +306,7 @@ function useSlotsCacheUrl(): string | null {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}regions/${regionId}/slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
|
return slotsCacheUrl(assetsDomain, regionId, slotsVersionNum) || null
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAllProducts() {
|
export function useAllProducts() {
|
||||||
|
|
@ -443,9 +461,11 @@ export function useStoreWithProducts(storeId: number) {
|
||||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||||
const cacheVersion = essentialConsts?.products_version_num
|
const cacheVersion = essentialConsts?.products_version_num
|
||||||
|
|
||||||
const cacheUrl =
|
const publishedTemplate = essentialConsts?.essentialUrls?.storeDetailUrlTemplate
|
||||||
assetsDomain && apiCacheKey && regionId != null
|
const cacheUrl = publishedTemplate
|
||||||
? `${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${cacheVersion}/stores/${storeId}.json`
|
? publishedTemplate.replace('{storeId}', String(storeId))
|
||||||
|
: assetsDomain && apiCacheKey && regionId != null && cacheVersion != null
|
||||||
|
? storeDetailCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, storeId) || null
|
||||||
: null
|
: null
|
||||||
const version = cacheUrl ?? ''
|
const version = cacheUrl ?? ''
|
||||||
const { initialData, isReady } = usePersistedCache<StoreWithProductsResponse>(CACHE_STORAGE_KEYS.storeProducts(storeId), version)
|
const { initialData, isReady } = usePersistedCache<StoreWithProductsResponse>(CACHE_STORAGE_KEYS.storeProducts(storeId), version)
|
||||||
|
|
|
||||||
|
|
@ -137,7 +137,7 @@ function OrderCard({
|
||||||
})()}
|
})()}
|
||||||
</p>
|
</p>
|
||||||
{item.isFlashDelivery && (
|
{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>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
324
change-log.txt
324
change-log.txt
|
|
@ -9496,3 +9496,327 @@ 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
|
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
|
was the likely cause of the caret landing at position 0 after its whitespace
|
||||||
normalization. user-ui + web-ui + ME-20 expectation updated.
|
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
|
||||||
|
|
|
||||||
|
|
@ -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: 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.
|
- `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.
|
- `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: 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.*
|
- `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".
|
- `CONTENT` `user-ui: me/my-orders/index.tsx:114,246` ↔ `web-ui: me.orders.tsx:93,227` — "FLASH" vs "Flash"; "⚡ FAST" vs "⚡ Fast".
|
||||||
|
|
|
||||||
|
|
@ -109,6 +109,8 @@ export {
|
||||||
getSlotDeliverySequence,
|
getSlotDeliverySequence,
|
||||||
updateSlotDeliverySequence,
|
updateSlotDeliverySequence,
|
||||||
staleSlotsCleanup,
|
staleSlotsCleanup,
|
||||||
|
SLOT_SKU_RETENTION_HOURS,
|
||||||
|
slotSkuCleanupCutoff,
|
||||||
} from './src/admin-apis/slots'
|
} from './src/admin-apis/slots'
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import {
|
||||||
vendorSnippets,
|
vendorSnippets,
|
||||||
productGroupInfo,
|
productGroupInfo,
|
||||||
} from '../db/schema'
|
} 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 {
|
import type {
|
||||||
AdminDeliverySlot,
|
AdminDeliverySlot,
|
||||||
AdminSlotWithProducts,
|
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> {
|
export async function staleSlotsCleanup(regionId: number): Promise<number> {
|
||||||
// The 20-slot window is per region: one region's slot activity must never
|
const cutoff = slotSkuCleanupCutoff()
|
||||||
// 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)
|
|
||||||
|
|
||||||
if (recentSlots.length < 20) {
|
const cleared = await db
|
||||||
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
|
|
||||||
.update(deliverySlotInfo)
|
.update(deliverySlotInfo)
|
||||||
.set({ skuIds: [] })
|
.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[]> {
|
export async function getSlotsAfterDate(regionId: number | null, afterDate: Date): Promise<AdminDeliverySlot[]> {
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,5 @@
|
||||||
export const CACHE_FILENAMES = {
|
// Regional CDN cache-file URLs + filenames (shared by backend and UIs).
|
||||||
products: 'products.json',
|
export * from './region-cache-urls'
|
||||||
stores: 'stores.json',
|
|
||||||
slots: 'slots.json',
|
|
||||||
availability: 'availability.json',
|
|
||||||
essentialConsts: 'essential-consts.json',
|
|
||||||
banners: 'banners.json',
|
|
||||||
} as const
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base origin of the backend API, shared by every UI (React Native and web).
|
* Base origin of the backend API, shared by every UI (React Native and web).
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export const NEXT_ORDER_GLIMPSE_LOOKBACK_HOURS = 24
|
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 HOUR_MS = 60 * 60 * 1000
|
||||||
const MINUTE_MS = 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
|
* 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 {
|
function deliveryMoment(order: NextOrderGlimpseOrderLike): Date | null {
|
||||||
if (order.deliveryDate) {
|
if (order.deliveryDate) {
|
||||||
|
|
|
||||||
251
packages/shared/region-cache-urls.ts
Normal file
251
packages/shared/region-cache-urls.ts
Normal 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
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue