487 lines
18 KiB
TypeScript
487 lines
18 KiB
TypeScript
import { useMemo, useEffect, useState } from 'react'
|
|
import { useQuery, keepPreviousData } from '@tanstack/react-query'
|
|
import axios from 'axios'
|
|
import { trpc } from '../lib/trpc-client'
|
|
import { useAuth } from '../lib/auth-context'
|
|
import { useAddressStore } from '../lib/stores'
|
|
import { useRegionStore } from '../lib/stores/region-store'
|
|
import type { ProductPriceFlags, EffectiveRegionSettings } from '@packages/shared'
|
|
import type {
|
|
AllProductsApiType,
|
|
AvailabilityApiType,
|
|
StoresApiType,
|
|
SlotsApiType,
|
|
EssentialConstsApiType,
|
|
BannersApiType,
|
|
StoreWithProductsApiType,
|
|
} from '@backend/trpc/router'
|
|
import {
|
|
CACHE_FILENAMES,
|
|
availabilityCacheUrl,
|
|
cachedFileUrl,
|
|
regionCacheUrl,
|
|
slotsCacheUrl,
|
|
storeDetailCacheUrl,
|
|
} from '@packages/shared'
|
|
|
|
const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}`
|
|
|
|
// The only persisted discovery payload: the small per-bound consts object.
|
|
const readEssentialConstsSnapshot = (boundId: number): string | null => {
|
|
try {
|
|
return typeof localStorage === 'undefined' ? null : localStorage.getItem(essentialConstsKey(boundId))
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
const writeEssentialConstsSnapshot = (boundId: number, value: string): void => {
|
|
try {
|
|
if (typeof localStorage !== 'undefined') {
|
|
localStorage.setItem(essentialConstsKey(boundId), value)
|
|
}
|
|
} catch {
|
|
// Quota or privacy mode — the snapshot is only a fast-start optimisation.
|
|
}
|
|
}
|
|
|
|
export const useGetEssentialConsts = () => {
|
|
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
|
const selectedRegion = useRegionStore((state) => state.selectedRegion)
|
|
const { isAuthenticated } = useAuth()
|
|
const selectedAddressId = useAddressStore((state) => state.selectedAddressId)
|
|
|
|
// The active bound (least-priority bound among the user's addresses in the
|
|
// region, else the region's effective bound) drives the constants. Derived
|
|
// server-side — the client does not know bound priorities.
|
|
const activeBoundQuery = trpc.common.activeBound.useQuery(
|
|
{ regionId: selectedRegionId ?? 0 },
|
|
{ enabled: selectedRegionId != null, staleTime: 60000 }
|
|
)
|
|
const activeBoundId = activeBoundQuery.data?.boundId ?? selectedRegion?.effectiveBoundId ?? null
|
|
|
|
// At checkout the selected address's bound overrides the active bound.
|
|
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
|
enabled: isAuthenticated && selectedAddressId != null,
|
|
})
|
|
const selectedAddress = addressesData?.data?.find((address) => address.id === selectedAddressId)
|
|
const boundId =
|
|
selectedAddress && selectedAddress.regionId === selectedRegionId && selectedAddress.boundId != null
|
|
? selectedAddress.boundId
|
|
: activeBoundId
|
|
|
|
const [initialData, setInitialData] = useState<DiscoveryData | undefined>(undefined)
|
|
const [isReady, setIsReady] = useState(false)
|
|
|
|
// Rehydrate the snapshot for THIS bound before the request is allowed.
|
|
useEffect(() => {
|
|
let cancelled = false
|
|
setIsReady(false)
|
|
setInitialData(undefined)
|
|
if (boundId == null) {
|
|
setIsReady(true)
|
|
return
|
|
}
|
|
const raw = readEssentialConstsSnapshot(boundId)
|
|
if (cancelled) return
|
|
if (raw) {
|
|
try {
|
|
const snapshot = JSON.parse(raw) as DiscoveryData
|
|
// A key alone is not proof of provenance: only hydrate a payload the
|
|
// backend built for this bound.
|
|
if (snapshot?.boundId === boundId) {
|
|
setInitialData(snapshot)
|
|
}
|
|
} catch {
|
|
// ignore corrupt snapshot
|
|
}
|
|
}
|
|
setIsReady(true)
|
|
return () => {
|
|
cancelled = true
|
|
}
|
|
}, [boundId])
|
|
|
|
// The backend resolves the flat payload for a single bound. tRPC includes the
|
|
// input in the query key, so switching bounds refetches discovery. Drop a
|
|
// snapshot from another bound on the render where boundId changed but the
|
|
// hydration effect has not reset `initialData` yet.
|
|
const placeholder = initialData?.boundId === boundId ? initialData : undefined
|
|
|
|
const query = trpc.common.essentialConsts.useQuery({ boundId: boundId ?? 0 }, {
|
|
refetchInterval: 60000,
|
|
enabled: isReady && boundId != null,
|
|
placeholderData: placeholder,
|
|
})
|
|
|
|
// Persist the latest response under this bound's key. Placeholder data belongs
|
|
// to the PREVIOUS bound and must never be written under the new one; the
|
|
// payload's own boundId is the authoritative check.
|
|
useEffect(() => {
|
|
if (!query.data || boundId == null) return
|
|
if (query.isPlaceholderData) return
|
|
if (query.data.boundId !== boundId) return
|
|
writeEssentialConstsSnapshot(boundId, JSON.stringify(query.data))
|
|
}, [query.data, query.isPlaceholderData, boundId])
|
|
|
|
return { ...query, refetch: query.refetch }
|
|
}
|
|
|
|
// Discovery payload under the FIXED regional contract: the existing
|
|
// essential-consts fields plus the browsing region's effective settings.
|
|
// Declared locally from existing contracts so this file typechecks before
|
|
// and after the backend adds the new fields.
|
|
export type DiscoveryData = EssentialConstsApiType & {
|
|
effectiveSettings?: EffectiveRegionSettings | null
|
|
/** Pre-rename alias the backend still sends; read as fallback. */
|
|
regionSettings?: EffectiveRegionSettings | null
|
|
}
|
|
|
|
// Backend sends `effectiveSettings` (canonical) plus a `regionSettings` alias
|
|
// for payloads cached in KV before the rename. Accept either so stale KV
|
|
// entries still resolve to the right region's values.
|
|
const discoverySettings = (discovery: DiscoveryData | undefined) =>
|
|
discovery?.effectiveSettings ?? discovery?.regionSettings ?? null
|
|
|
|
// Discovery data with the delivery/minimum display fields overridden from the
|
|
// region's effective settings (numeric parse, global fallback). Display-only;
|
|
// the backend remains authoritative for the actual charge.
|
|
export function useRegionalConsts() {
|
|
const { data } = useGetEssentialConsts()
|
|
return useMemo(() => {
|
|
const discovery = data as DiscoveryData | undefined
|
|
const settings = discoverySettings(discovery)?.settings
|
|
if (!settings) return data
|
|
const pickNumber = (key: string, fallback: unknown): number | undefined => {
|
|
const raw = settings[key]
|
|
if (raw == null || raw === '') return typeof fallback === 'number' ? fallback : undefined
|
|
const parsed = Number(raw)
|
|
return Number.isFinite(parsed) ? parsed : (typeof fallback === 'number' ? fallback : undefined)
|
|
}
|
|
return {
|
|
...data,
|
|
deliveryCharge: pickNumber('deliveryCharge', (data as any)?.deliveryCharge),
|
|
freeDeliveryThreshold: pickNumber('freeDeliveryThreshold', (data as any)?.freeDeliveryThreshold),
|
|
flashDeliveryCharge: pickNumber('flashDeliveryCharge', (data as any)?.flashDeliveryCharge),
|
|
flashFreeDeliveryThreshold: pickNumber('flashFreeDeliveryThreshold', (data as any)?.flashFreeDeliveryThreshold),
|
|
}
|
|
}, [data])
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Persisted cache helpers — store fetched JSON keyed by its versioned URL.
|
|
// Only refetch + repersist when the version (URL) changes.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
interface PersistedCache<T> {
|
|
version: string
|
|
data: T
|
|
}
|
|
|
|
const CACHE_STORAGE_KEYS = {
|
|
products: 'cache_products',
|
|
stores: 'cache_stores',
|
|
slots: 'cache_slots',
|
|
banners: 'cache_banners',
|
|
availability: 'cache_availability',
|
|
storeProducts: (storeId: number) => `cache_store_${storeId}`,
|
|
} as const
|
|
|
|
async function readPersistedCache<T>(key: string): Promise<PersistedCache<T> | null> {
|
|
try {
|
|
const raw = localStorage.getItem(key)
|
|
if (!raw) return null
|
|
return JSON.parse(raw) as PersistedCache<T>
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
async function writePersistedCache<T>(key: string, version: string, data: T): Promise<void> {
|
|
try {
|
|
localStorage.setItem(key, JSON.stringify({ version, data }))
|
|
} catch (e) {
|
|
console.error('writePersistedCache error:', e)
|
|
}
|
|
}
|
|
|
|
function usePersistedCache<T>(storageKey: string, version: string | null) {
|
|
const [initialData, setInitialData] = useState<T | undefined>(undefined)
|
|
const [isReady, setIsReady] = useState(false)
|
|
|
|
useEffect(() => {
|
|
let cancelled = false
|
|
setIsReady(false)
|
|
setInitialData(undefined)
|
|
if (!version) {
|
|
setIsReady(true)
|
|
return
|
|
}
|
|
readPersistedCache<T>(storageKey).then((persisted) => {
|
|
if (cancelled) return
|
|
if (persisted && persisted.version === version) {
|
|
setInitialData(persisted.data)
|
|
}
|
|
setIsReady(true)
|
|
})
|
|
return () => { cancelled = true }
|
|
}, [storageKey, version])
|
|
|
|
return { initialData, isReady }
|
|
}
|
|
|
|
type ProductsResponse = AllProductsApiType
|
|
type StoresResponse = StoresApiType
|
|
type SlotsResponse = SlotsApiType
|
|
type BannersResponse = BannersApiType
|
|
type StoreWithProductsResponse = StoreWithProductsApiType
|
|
type AvailabilityResponse = AvailabilityApiType
|
|
|
|
type BaseProduct = AllProductsApiType['products'][number]
|
|
type AvailabilityEntry = AvailabilityApiType['availability'][number]
|
|
|
|
export type MergedProduct = BaseProduct & ProductPriceFlags
|
|
|
|
function useDiscoveryRegionId(essentialConsts: unknown): number | null {
|
|
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
|
|
const discovery = essentialConsts as DiscoveryData | undefined
|
|
const effectiveRegionId = discoverySettings(discovery)?.regionId
|
|
return effectiveRegionId ?? selectedRegionId
|
|
}
|
|
|
|
function useCacheUrl(filename: string): string | null {
|
|
const { data: essentialConsts } = useGetEssentialConsts()
|
|
const regionId = useDiscoveryRegionId(essentialConsts)
|
|
|
|
// The backend publishes these URLs. Trust them first; construct only when an
|
|
// older payload (or a stale localStorage snapshot) lacks them.
|
|
const published = cachedFileUrl(essentialConsts?.essentialUrls, filename)
|
|
if (published) return published
|
|
|
|
const assetsDomain = essentialConsts?.assetsDomain
|
|
const apiCacheKey = essentialConsts?.apiCacheKey
|
|
const cacheVersion = essentialConsts?.products_version_num
|
|
|
|
if (
|
|
!assetsDomain ||
|
|
!apiCacheKey ||
|
|
cacheVersion === undefined ||
|
|
cacheVersion === null ||
|
|
regionId == null
|
|
) {
|
|
return null
|
|
}
|
|
|
|
return regionCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, filename) || null
|
|
}
|
|
|
|
function useAvailabilityCacheUrl(): string | null {
|
|
const { data: essentialConsts } = useGetEssentialConsts()
|
|
const regionId = useDiscoveryRegionId(essentialConsts)
|
|
|
|
const published = cachedFileUrl(essentialConsts?.essentialUrls, CACHE_FILENAMES.availability)
|
|
if (published) return published
|
|
|
|
const assetsDomain = essentialConsts?.assetsDomain
|
|
const availabilityVersionNum = essentialConsts?.availability_version_num
|
|
|
|
if (!assetsDomain || availabilityVersionNum === undefined || availabilityVersionNum === null || regionId == null) {
|
|
return null
|
|
}
|
|
|
|
return availabilityCacheUrl(assetsDomain, regionId, availabilityVersionNum) || null
|
|
}
|
|
|
|
function useSlotsCacheUrl(): string | null {
|
|
const { data: essentialConsts } = useGetEssentialConsts()
|
|
const regionId = useDiscoveryRegionId(essentialConsts)
|
|
|
|
const published = cachedFileUrl(essentialConsts?.essentialUrls, CACHE_FILENAMES.slots)
|
|
if (published) return published
|
|
|
|
const assetsDomain = essentialConsts?.assetsDomain
|
|
const slotsVersionNum = essentialConsts?.slots_version_num
|
|
|
|
if (!assetsDomain || slotsVersionNum === undefined || slotsVersionNum === null || regionId == null) {
|
|
return null
|
|
}
|
|
|
|
return slotsCacheUrl(assetsDomain, regionId, slotsVersionNum) || null
|
|
}
|
|
|
|
export function useAllProducts() {
|
|
const cacheUrl = useCacheUrl(CACHE_FILENAMES.products)
|
|
const { data: availabilityData } = useAvailability()
|
|
const version = cacheUrl ?? ''
|
|
const { initialData, isReady } = usePersistedCache<ProductsResponse>(CACHE_STORAGE_KEYS.products, version)
|
|
|
|
const productsQuery = useQuery<ProductsResponse>({
|
|
queryKey: ['all-products', version],
|
|
queryFn: async () => {
|
|
if (!cacheUrl) {
|
|
throw new Error('Cache URL not available')
|
|
}
|
|
const response = await axios.get<ProductsResponse>(cacheUrl)
|
|
await writePersistedCache(CACHE_STORAGE_KEYS.products, version, response.data)
|
|
return response.data
|
|
},
|
|
staleTime: 60000,
|
|
enabled: !!cacheUrl && isReady,
|
|
placeholderData: initialData ?? keepPreviousData,
|
|
})
|
|
|
|
const mergedProducts = useMemo(() => {
|
|
// Combo-only SKUs stay in products.json but are hidden from the user app.
|
|
const rawProducts = (productsQuery.data?.products || []).filter(
|
|
(p: any) => !p.isComboOnly
|
|
)
|
|
const availabilityById: Record<number, AvailabilityEntry> = {}
|
|
availabilityData?.availability?.forEach((entry: AvailabilityEntry) => {
|
|
availabilityById[entry.id] = entry
|
|
})
|
|
|
|
return rawProducts.map((product) => {
|
|
const availability = availabilityById[product.id]
|
|
return {
|
|
...product,
|
|
price: availability ? Number(availability.price) : 0,
|
|
marketPrice: availability?.marketPrice != null ? Number(availability.marketPrice) : null,
|
|
flashPrice: availability?.flashPrice ?? null,
|
|
isFlashAvailable: availability?.isFlashAvailable ?? false,
|
|
isOutOfStock: availability?.isOutOfStock ?? false,
|
|
isSuspended: availability?.isSuspended ?? false,
|
|
isOffer: availability?.isOffer ?? false,
|
|
}
|
|
})
|
|
}, [productsQuery.data, availabilityData])
|
|
|
|
const mergedData = useMemo(() => {
|
|
if (!productsQuery.data) return undefined
|
|
return {
|
|
...productsQuery.data,
|
|
products: mergedProducts,
|
|
} as Omit<ProductsResponse, 'products'> & { products: MergedProduct[] }
|
|
}, [productsQuery.data, mergedProducts])
|
|
|
|
return {
|
|
...productsQuery,
|
|
data: mergedData,
|
|
}
|
|
}
|
|
|
|
export function useAvailability() {
|
|
const cacheUrl = useAvailabilityCacheUrl()
|
|
const version = cacheUrl ?? ''
|
|
const { initialData, isReady } = usePersistedCache<AvailabilityResponse>(CACHE_STORAGE_KEYS.availability, version)
|
|
|
|
return useQuery<AvailabilityResponse>({
|
|
queryKey: ['availability', version],
|
|
queryFn: async () => {
|
|
if (!cacheUrl) {
|
|
throw new Error('Cache URL not available')
|
|
}
|
|
const response = await axios.get<AvailabilityResponse>(cacheUrl)
|
|
await writePersistedCache(CACHE_STORAGE_KEYS.availability, version, response.data)
|
|
return response.data
|
|
},
|
|
staleTime: 60000,
|
|
enabled: !!cacheUrl && isReady,
|
|
placeholderData: initialData ?? keepPreviousData,
|
|
})
|
|
}
|
|
|
|
export function useStores() {
|
|
const cacheUrl = useCacheUrl(CACHE_FILENAMES.stores)
|
|
const version = cacheUrl ?? ''
|
|
const { initialData, isReady } = usePersistedCache<StoresResponse>(CACHE_STORAGE_KEYS.stores, version)
|
|
|
|
return useQuery<StoresResponse>({
|
|
queryKey: ['stores', version],
|
|
queryFn: async () => {
|
|
if (!cacheUrl) {
|
|
throw new Error('Cache URL not available')
|
|
}
|
|
const response = await axios.get<StoresResponse>(cacheUrl)
|
|
await writePersistedCache(CACHE_STORAGE_KEYS.stores, version, response.data)
|
|
return response.data
|
|
},
|
|
staleTime: 60000,
|
|
enabled: !!cacheUrl && isReady,
|
|
placeholderData: initialData ?? keepPreviousData,
|
|
})
|
|
}
|
|
|
|
export function useSlots() {
|
|
const cacheUrl = useSlotsCacheUrl()
|
|
const version = cacheUrl ?? ''
|
|
const { initialData, isReady } = usePersistedCache<SlotsResponse>(CACHE_STORAGE_KEYS.slots, version)
|
|
|
|
return useQuery<SlotsResponse>({
|
|
queryKey: ['slots', version],
|
|
queryFn: async () => {
|
|
if (!cacheUrl) {
|
|
throw new Error('Cache URL not available')
|
|
}
|
|
const response = await axios.get<SlotsResponse>(cacheUrl + '?v=123')
|
|
await writePersistedCache(CACHE_STORAGE_KEYS.slots, version, response.data)
|
|
return response.data
|
|
},
|
|
staleTime: 60000,
|
|
enabled: !!cacheUrl && isReady,
|
|
placeholderData: initialData ?? keepPreviousData,
|
|
})
|
|
}
|
|
|
|
export function useBanners() {
|
|
const cacheUrl = useCacheUrl(CACHE_FILENAMES.banners)
|
|
const version = cacheUrl ?? ''
|
|
const { initialData, isReady } = usePersistedCache<BannersResponse>(CACHE_STORAGE_KEYS.banners, version)
|
|
|
|
return useQuery<BannersResponse>({
|
|
queryKey: ['banners', version],
|
|
queryFn: async () => {
|
|
if (!cacheUrl) {
|
|
throw new Error('Cache URL not available')
|
|
}
|
|
const response = await axios.get<BannersResponse>(cacheUrl)
|
|
await writePersistedCache(CACHE_STORAGE_KEYS.banners, version, response.data)
|
|
return response.data
|
|
},
|
|
staleTime: 60000,
|
|
enabled: !!cacheUrl && isReady,
|
|
placeholderData: initialData ?? keepPreviousData,
|
|
})
|
|
}
|
|
|
|
export function useStoreWithProducts(storeId: number) {
|
|
const { data: essentialConsts } = useGetEssentialConsts()
|
|
const regionId = useDiscoveryRegionId(essentialConsts)
|
|
|
|
const assetsDomain = essentialConsts?.assetsDomain
|
|
const apiCacheKey = essentialConsts?.apiCacheKey
|
|
const cacheVersion = essentialConsts?.products_version_num
|
|
|
|
const publishedTemplate = essentialConsts?.essentialUrls?.storeDetailUrlTemplate
|
|
const cacheUrl = publishedTemplate
|
|
? publishedTemplate.replace('{storeId}', String(storeId))
|
|
: assetsDomain && apiCacheKey && regionId != null && cacheVersion != null
|
|
? storeDetailCacheUrl(assetsDomain, apiCacheKey, regionId, cacheVersion, storeId) || null
|
|
: null
|
|
const version = cacheUrl ?? ''
|
|
const { initialData, isReady } = usePersistedCache<StoreWithProductsResponse>(CACHE_STORAGE_KEYS.storeProducts(storeId), version)
|
|
|
|
return useQuery<StoreWithProductsResponse>({
|
|
queryKey: ['store-with-products', storeId, version],
|
|
queryFn: async () => {
|
|
if (!cacheUrl) {
|
|
throw new Error('Cache URL not available')
|
|
}
|
|
const response = await axios.get<StoreWithProductsResponse>(cacheUrl)
|
|
await writePersistedCache(CACHE_STORAGE_KEYS.storeProducts(storeId), version, response.data)
|
|
return response.data
|
|
},
|
|
staleTime: 60000,
|
|
enabled: !!cacheUrl && isReady,
|
|
placeholderData: initialData ?? keepPreviousData,
|
|
})
|
|
}
|