This commit is contained in:
shafi54 2026-10-20 17:31:30 +05:30
parent 264bb493d7
commit 8cf3cc9776
9 changed files with 1128 additions and 273 deletions

File diff suppressed because it is too large Load diff

View file

@ -55,15 +55,15 @@ export const initializeAllStores = async (regionId?: number): Promise<void> => {
};
export const scheduleStoreInitialization = async (regionId?: number): Promise<void> => {
console.log("scheduling store initialization")
console.log(`regionId=${regionId} scheduling store initialization \n\n\n\n`)
const env = (globalThis as { ENV?: { CACHE_CREATOR?: DurableObjectNamespace; ENABLE_TEST_ROUTES?: string } }).ENV
// Test mode: the live API suite reads cache documents through the guarded
// scaffold routes and triggers the pipeline explicitly via /api/test/rebuild.
// Do not spawn background Durable Object rebuilds during tests.
if (env?.ENABLE_TEST_ROUTES === 'true') {
return
}
// if (env?.ENABLE_TEST_ROUTES === 'true') {
// return
// }
if (!env?.CACHE_CREATOR) {
console.warn('CACHE_CREATOR durable object binding not available for store initialization')

View file

@ -193,6 +193,7 @@ export const slotsRouter = router({
throw new ApiError('Slot not found', 404)
}
console.log('regenerating cacehe file \n\n\n\n', )
// Regenerate slots cache file (availability/products stay as-is)
await createSlotsCacheFile(ctx.staffUser!.regionId).catch((error) => {
console.error('Failed to regenerate slots cache after slot update:', error)

View file

@ -1461,6 +1461,13 @@ Covered by HOME-81..98, plus:
| REGION-13 | edge | stored bound missing | fills active bound |
| REGION-14 | edge | stored bound present | not overwritten |
| REGION-15 | edge | refreshLocation | re-arms startup check |
| REGION-16 | integration | default + location in its region | Home opens that region |
| REGION-17 | integration | location in another region | chooser, no regional cache fetches |
| REGION-18 | integration | no default, location region | Home opens the location region |
| REGION-19 | edge | one non-default address, location off | sole address opens (region + selected id) |
| REGION-20 | edge | one non-default address, location elsewhere | sole address still wins |
| REGION-21 | integration | sole non-default address, location off | Home opens its region; only its cache is fetched |
| REGION-22 | integration | sole non-default address, location elsewhere | Home still opens the sole address's region |
| LOCSTORE-01 | happy | start once | one permission/fix; second start no-op |
| LOCSTORE-02 | error | denied | status denied, coords null |
| LOCSTORE-03 | edge | services off | status services-off |

View file

@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import type { RegionSummary, RegionBoundSummary } from '@packages/shared'
import { useRegionStore } from '@/src/store/regionStore'
import { useAddressStore } from '@/src/store/addressStore'
import { useLocationStore } from '@/src/store/locationStore'
import { trpc } from '@/src/trpc-client'
import { confirmRegionSwitch } from '@/src/lib/region-switch'
@ -31,6 +32,10 @@ let startupLaunchRegionId: number | null | undefined
* region's effective bound). If the resolved region differs from the saved one
* the region is switched (clears carts, refreshes region-scoped data). When the
* location is unusable the saved region is kept, or the chooser is shown.
*
* A sole saved address (even when it is not flagged as default) is treated as
* the delivery anchor: there is only one place the user can receive an order, so
* it opens directly instead of asking them to pick it from a one-item list.
*/
export interface UseRegionResult {
/** The region the user is currently browsing. `null` until one is chosen. */
@ -94,6 +99,17 @@ export function useRegion(): UseRegionResult {
})
const defaultAddress = defaultAddressQuery.data?.data ?? null
// A sole address is a valid anchor even when it is not flagged as default.
// Query the list only for signed-in users; the result is shared with the
// location bar / checkout through the same React Query cache entry.
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
enabled: hydrated && isAuthenticated,
staleTime: 60000,
})
const addresses = addressesQuery.data?.data ?? null
const soleAddress =
!defaultAddress && addresses?.length === 1 ? addresses[0] : null
// Region summaries (needed to build the RegionSummary when adopting a region
// from the default address).
const regionsQuery = trpc.common.listRegions.useQuery(undefined, {
@ -148,8 +164,10 @@ export function useRegion(): UseRegionResult {
// - location resolves to the default's region, or to no serviceable region
// (location off / out of area) -> use the default address;
// - location resolves to a DIFFERENT serviceable region -> let the user pick.
// Without a default address we keep the previous behaviour (use the resolved
// region, else let the user pick).
// A sole saved address is the exception: there is only one delivery option, so
// it always wins and is opened directly (even if it is not marked default).
// Without any anchor we keep the previous behaviour (use the resolved region,
// else let the user pick).
useEffect(() => {
if (!hydrated || startupResolved) return
@ -169,11 +187,12 @@ export function useRegion(): UseRegionResult {
// reconsider).
if (isAuthLoading) return
// Signed-in users: wait for the default address (+ regions) so the decision
// is anchored correctly before we settle.
// Signed-in users: wait for the default address and the address list (+
// regions) so a sole address can anchor the decision before we settle.
if (isAuthenticated) {
if (defaultAddressQuery.isLoading) return
if (defaultAddress?.regionId != null && !regions) return
if (!defaultAddress && addressesQuery.isLoading) return
if ((defaultAddress?.regionId ?? soleAddress?.regionId) != null && !regions) return
}
setStartupResolved(true)
@ -187,22 +206,39 @@ export function useRegion(): UseRegionResult {
startupLaunchRegionId !== undefined && startupLaunchRegionId !== regionId
if (userChangedRegion) return
const defaultRegionId = isAuthenticated ? defaultAddress?.regionId ?? null : null
const anchorAddress = defaultAddress ?? soleAddress
const anchorRegionId = isAuthenticated ? anchorAddress?.regionId ?? null : null
// A sole address is the only place we can deliver, so it wins even when the
// launch location resolves to a different serviceable region.
const soleAddressWins = isAuthenticated && soleAddress?.regionId != null
if (defaultRegionId != null) {
const inDefaultRegion = resolved?.region?.id === defaultRegionId
if (anchorRegionId != null) {
const inAnchorRegion = resolved?.region?.id === anchorRegionId
// No serviceable region found -> treat like a disabled location.
const noServiceableRegion = resolved == null
if (inDefaultRegion || noServiceableRegion) {
const region = regions?.find((candidate) => candidate.id === defaultRegionId) ?? null
if (soleAddressWins || inAnchorRegion || noServiceableRegion) {
const region = regions?.find((candidate) => candidate.id === anchorRegionId) ?? null
if (region) {
// Picking the sole address also makes it the active delivery address,
// so the bar / checkout don't fall back to "no address".
const selectSoleAddress = () => {
if (soleAddress != null) {
useAddressStore.getState().setSelectedAddressId(soleAddress.id)
}
}
if (regionId == null) {
// First region of this launch — adopt it without clearing the cart.
setRegion(region, defaultAddress?.boundId ?? null)
setRegion(region, anchorAddress?.boundId ?? null)
selectSoleAddress()
} else if (region.id !== regionId) {
void confirmRegionSwitch(region, queryClient, defaultAddress?.boundId ?? null)
} else if (defaultAddress?.boundId != null && defaultAddress.boundId !== boundId) {
setRegion(region, defaultAddress.boundId)
void confirmRegionSwitch(region, queryClient, anchorAddress?.boundId ?? null).then(
selectSoleAddress
)
} else if (anchorAddress?.boundId != null && anchorAddress.boundId !== boundId) {
setRegion(region, anchorAddress.boundId)
selectSoleAddress()
} else {
selectSoleAddress()
}
}
return
@ -213,7 +249,7 @@ export function useRegion(): UseRegionResult {
return
}
// No default address: derive the region from the location as before.
// No default or sole address: derive the region from the location as before.
if (resolved?.region) {
if (regionId == null) {
// First region of this launch — adopt it without clearing the cart.
@ -239,7 +275,9 @@ export function useRegion(): UseRegionResult {
isAuthenticated,
isAuthLoading,
defaultAddressQuery.isLoading,
addressesQuery.isLoading,
defaultAddress,
soleAddress,
regions,
])

View file

@ -48,7 +48,9 @@ async function withFreshModules(fn: (ctx: any) => Promise<void>) {
testUtils: require('../helpers/test-utils'),
fixtures: require('../fixtures'),
secure: require('../mocks/secure-store-mock'),
fetchJson: require('../mocks/fetch-json'),
regionStore: require('@/src/store/regionStore').useRegionStore,
addressStore: require('@/src/store/addressStore').useAddressStore,
locationStore: require('@/src/store/locationStore').useLocationStore,
useRegion: require('@/src/hooks/useRegion').useRegion,
}
@ -413,4 +415,210 @@ describe('useRegion', () => {
view.unmount()
})
})
it('REGION-19: a sole non-default address opens when location is off', async () => {
await withFreshModules(async (ctx) => {
const { A1 } = ctx.fixtures
const sole = { ...A1, isDefault: false }
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.locationMock.__configure({ permission: 'denied' })
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [sole] } })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(5)
expect(result.current.isResolvingRegion).toBe(false)
expect(result.current.regionId).toBe(1)
expect(result.current.boundId).toBe(7)
expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id)
view.unmount()
})
})
it('REGION-20: a sole non-default address wins over a location in another region', async () => {
await withFreshModules(async (ctx) => {
const { A1, REGION_2 } = ctx.fixtures
const sole = { ...A1, isDefault: false }
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
data: {
region: REGION_2,
bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' },
},
})
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [sole] } })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(6)
expect(result.current.regionId).toBe(1)
expect(result.current.boundId).toBe(7)
expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id)
view.unmount()
})
})
})
describe('Home region integration (REGION-16..18)', () => {
it('REGION-16: a default address and a location in its region open Home in that region', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, BOUND_1, A1, A2, productsCacheUrl } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: true, 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_1, bound: BOUND_1 },
})
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: A1 } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
ctx.testUtils.seedJsonCache({ regionId: 1 })
ctx.testUtils.seedJsonCache({ regionId: 2 })
ctx.testUtils.seedCentralStores()
ctx.testUtils.seedSelectedAddress(A1.id)
const Home = require('@/app/(drawer)/(tabs)/home/index').default
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
await ctx.testUtils.flush(8)
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
expect(ctx.regionStore.getState().selectedBoundId).toBe(7)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
expect(view.getByText('Mahabubnagar')).toBeTruthy()
view.unmount()
})
})
it('REGION-17: a location in another region clears the default region and opens the chooser', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, A1, A2, productsCacheUrl } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: true, 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.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: A1 } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
ctx.testUtils.seedJsonCache({ regionId: 1 })
ctx.testUtils.seedJsonCache({ regionId: 2 })
ctx.testUtils.seedCentralStores()
const Home = require('@/app/(drawer)/(tabs)/home/index').default
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
await ctx.testUtils.flush(8)
expect(ctx.regionStore.getState().selectedRegionId).toBeNull()
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1))).toHaveLength(0)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
expect(view.getByText('Choose your address')).toBeTruthy()
view.unmount()
})
})
it('REGION-18: without a default address, the location alone opens its region', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, A1, A2, productsCacheUrl } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: true, 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.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
ctx.trpc.setProcedure('common.essentialConsts', {
data: { ...ctx.fixtures.CONSTS, regionId: 2, boundId: 8 },
})
ctx.testUtils.seedJsonCache({ regionId: 1 })
ctx.testUtils.seedJsonCache({ regionId: 2 })
ctx.testUtils.seedCentralStores()
const Home = require('@/app/(drawer)/(tabs)/home/index').default
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
await ctx.testUtils.flush(8)
expect(ctx.regionStore.getState().selectedRegionId).toBe(2)
expect(ctx.regionStore.getState().selectedBoundId).toBe(8)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2)).length).toBeGreaterThan(0)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1))).toHaveLength(0)
expect(view.getByText('Hyderabad')).toBeTruthy()
view.unmount()
})
})
it('REGION-21: a sole non-default address opens Home with location off', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, A1, productsCacheUrl } = ctx.fixtures
const sole = { ...A1, isDefault: false }
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.locationMock.__configure({ permission: 'denied' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [sole] } })
ctx.testUtils.seedJsonCache({ regionId: 1 })
ctx.testUtils.seedJsonCache({ regionId: 2 })
ctx.testUtils.seedCentralStores()
const Home = require('@/app/(drawer)/(tabs)/home/index').default
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
await ctx.testUtils.flush(8)
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
expect(ctx.regionStore.getState().selectedBoundId).toBe(7)
expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
expect(view.getByText('Mahabubnagar')).toBeTruthy()
view.unmount()
})
})
it('REGION-22: a sole non-default address opens Home even when location is elsewhere', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, A1, productsCacheUrl } = ctx.fixtures
const sole = { ...A1, isDefault: false }
ctx.auth.__setAuthState({ isAuthenticated: true, 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.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [sole] } })
ctx.testUtils.seedJsonCache({ regionId: 1 })
ctx.testUtils.seedJsonCache({ regionId: 2 })
ctx.testUtils.seedCentralStores()
const Home = require('@/app/(drawer)/(tabs)/home/index').default
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
await ctx.testUtils.flush(8)
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
expect(ctx.regionStore.getState().selectedBoundId).toBe(7)
expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0)
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
expect(view.getByText('Mahabubnagar')).toBeTruthy()
view.unmount()
})
})
})

View file

@ -2,7 +2,9 @@ import React, { useEffect, useState } from 'react'
import { useLocation } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { trpc } from '../lib/trpc-client'
import { useAuth } from '../lib/auth-context'
import { useRegionStore } from '../lib/stores/region-store'
import { useAddressStore } from '../lib/stores/address-store'
import { RegionSelector } from './RegionSelector'
/**
@ -20,6 +22,8 @@ export function RegionGate({ children }: { children: React.ReactNode }) {
const selectedRegion = useRegionStore((state) => state.selectedRegion)
const setRegion = useRegionStore((state) => state.setRegion)
const clearRegion = useRegionStore((state) => state.clearRegion)
const setSelectedAddressId = useAddressStore((state) => state.setSelectedAddressId)
const { isAuthenticated, isLoading: isAuthLoading } = useAuth()
const location = useLocation()
@ -28,6 +32,15 @@ export function RegionGate({ children }: { children: React.ReactNode }) {
)
const { data: regions } = trpc.common.listRegions.useQuery()
// A sole saved address is the only delivery option, so it opens directly
// instead of showing a one-item region/address chooser.
const { data: addressesData, isLoading: addressesLoading } = trpc.user.address.getUserAddresses.useQuery(
undefined,
{ enabled: hasHydrated && isAuthenticated }
)
const soleAddress =
isAuthenticated && addressesData?.data?.length === 1 ? addressesData.data[0] : null
// Wait for the persisted region to load before deciding whether to prompt.
useEffect(() => {
if (useRegionStore.persist.hasHydrated()) {
@ -58,6 +71,25 @@ export function RegionGate({ children }: { children: React.ReactNode }) {
}
}, [hasHydrated, regions, selectedRegionId, selectedRegion, setRegion, clearRegion])
// No saved region + exactly one address -> adopt that address's region.
useEffect(() => {
if (!hasHydrated || selectedRegionId != null || isAuthLoading) return
if (!soleAddress || soleAddress.regionId == null || !regions) return
const match = regions.find((region) => region.id === soleAddress.regionId)
if (!match) return
setRegion(match)
setSelectedAddressId(soleAddress.id)
}, [
hasHydrated,
selectedRegionId,
isAuthLoading,
soleAddress,
regions,
setRegion,
setSelectedAddressId,
])
// Standalone full-screen routes opt out of the region gate overlay.
if (location.pathname === '/location-selector') {
return <>{children}</>
@ -67,6 +99,22 @@ export function RegionGate({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
// Wait for auth/addresses before deciding whether the sole-address shortcut
// applies; otherwise the chooser would flash before it is dismissed.
if (
selectedRegionId == null &&
(isAuthLoading || (isAuthenticated && addressesLoading))
) {
return (
<>
{children}
<div className="fixed inset-0 z-[90] flex items-center justify-center bg-white">
<Loader2 className="h-8 w-8 animate-spin text-brand-500" />
</div>
</>
)
}
if (selectedRegionId == null) {
return (
<>

View file

@ -8279,3 +8279,67 @@ Web counterpart (apps/web-ui/src/components/AddressForm.tsx)
Run: bun run test -- tests/components/address-form.test.tsx -> 37/37 passed (no test
assertions needed changing; address-city / address-city-option-* IDs preserved).
Typecheck: user-ui clean; web-ui `npm run typecheck` clean.
================================================================================
[2026-10-20 17:29:14 IST] TEST-2026-10-20-22 sole-address Home integration tests
================================================================================
apps/user-ui/tests/lib/use-region.test.tsx
- REGION-21: one non-default address + location off -> Home opens that address's
region, fetches only that region's cache, and marks the address selected.
- REGION-22: one non-default address + location resolving elsewhere -> Home still
opens the sole address's region and fetches only its cache.
Verification: user-ui `npm run test:typecheck` clean. Jest not run (per repo
instruction).
================================================================================
[2026-10-20 17:21:00 IST] UI-2026-10-20-21 auto-open a sole saved address
================================================================================
apps/user-ui/src/hooks/useRegion.ts
- Query `user.address.getUserAddresses` during startup for signed-in users.
- If there is no default but exactly one saved address, use that address as the
startup anchor (region + bound) instead of leaving regionId null and showing
the chooser. The sole address wins even when location resolves to a different
serviceable region.
- Select the sole address in `useAddressStore` after the region is adopted so
the location bar / checkout don't fall back to "no address".
apps/user-ui/tests/lib/use-region.test.tsx
- REGION-19: location off + one non-default address -> region/bound adopted and
the address id selected.
- REGION-20: location in another region + one non-default address -> the sole
address still wins.
apps/web-ui/src/components/RegionGate.tsx
- Mirror: when no region is selected and the signed-in user has exactly one
saved address with a region, adopt that region and select the address instead
of showing the region chooser.
Verification: user-ui `npm run test:typecheck` clean; web-ui `npm run typecheck`
clean. Jest not run (per repo instruction).
================================================================================
[2026-10-20 17:20:00 IST] TEST-2026-10-20-20 home region integration tests
================================================================================
New tests in apps/user-ui/tests/lib/use-region.test.tsx (REGION-16..18):
- multiple addresses (A1 region 1 default + A2 region 2) + granted location in the
default region: Home renders region 1 and fetches only region-1 cache files.
- same addresses + location resolving to region 2: the region is cleared (chooser),
Home does not fetch either region's products.
- multiple addresses with no default + location region 2: Home adopts region 2 and
fetches only region-2 cache files.
Adds a `fetchJson` handle to the isolated-module harness so the CDN cache calls can
be asserted. No app code changes.
Run: bun run test -- tests/lib/use-region.test.tsx -> 18/18 passed (REGION-16..18
cover the three Home scenarios). user-ui typecheck clean.
- Timestamp: 2026-10-20 16:22:49
Fix 0006 migration FOREIGN KEY failure. `coupon_applicable_products` is a
leaf child of coupons(id) and product_skus(id), but was dropped at the end
(after both parents), so DROP TABLE product_skus failed with
SQLITE_CONSTRAINT.
File: packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
Changes:
- move the coupon_applicable_products -> coupons.sku_ids fold to before the
`__new_coupons` copy (the old `coupons` table is still present there);
- add `DROP TABLE coupon_applicable_products;` to the leaf-first drop block,
before product_skus/coupons;
- remove the late Phase 4 UPDATE + DROP block at the end of the file;
- update the header comment to match.
Verified by replaying the file on a copy of the local D1 DB with
PRAGMA foreign_keys=ON. Not applied to the live DB.

View file

@ -8,9 +8,10 @@
-- removal of the retired `minRegularOrderValue`
--
-- Also folds in 0007_coupon_targets_json (never applied on its own): coupon product
-- targeting collapses into `coupons.sku_ids` / `reserved_coupons.sku_ids` and the
-- `coupon_applicable_products` table is dropped (Phase 4). The file does not create
-- that table at all any more.
-- targeting collapses into `coupons.sku_ids` / `reserved_coupons.sku_ids`, and the
-- `coupon_applicable_products` table is folded then dropped leaf-first before the
-- rebuild (it references coupons/product_skus). The file does not create a
-- replacement for that table.
--
-- The originals created two throwaway staging tables purely to copy from and
-- then drop them:
@ -327,6 +328,27 @@ CREATE TABLE `__new_addresses` (
INSERT INTO `__new_addresses` (`id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`is_default`,`latitude`,`longitude`,`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,`region_id`,`bound_id`,`vague_backfilled_coords`)
SELECT `id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`is_default`,COALESCE(`latitude`, 16.750504),COALESCE(`longitude`, 77.993621),`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),(SELECT `id` FROM `region_bounds` WHERE `region_id` = (SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') ORDER BY CAST(`priority` AS REAL) ASC LIMIT 1),CASE WHEN `latitude` IS NULL OR `longitude` IS NULL THEN 1 ELSE 0 END FROM `addresses`;
--> statement-breakpoint
-- Fold relation-table coupon targets into `coupons.sku_ids` before the rebuild
-- copies that column. `coupon_applicable_products` is a leaf of
-- coupons/product_skus, so it is dropped in the leaf-first drop block below.
UPDATE `coupons`
SET `sku_ids` = (
SELECT json_group_array(`sku`)
FROM (
SELECT DISTINCT `sku` FROM (
SELECT CAST(je.`value` AS INTEGER) AS `sku`
FROM json_each(CASE WHEN json_valid(`coupons`.`sku_ids`) THEN `coupons`.`sku_ids` ELSE '[]' END) AS je
UNION
SELECT cap.`sku_id` AS `sku`
FROM `coupon_applicable_products` AS cap
WHERE cap.`coupon_id` = `coupons`.`id`
)
)
)
WHERE EXISTS (
SELECT 1 FROM `coupon_applicable_products` AS cap WHERE cap.`coupon_id` = `coupons`.`id`
);
--> statement-breakpoint
CREATE TABLE `__new_coupons` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`coupon_code` text NOT NULL,
@ -701,6 +723,10 @@ INSERT INTO `__new_user_incidents` (`id`,`user_id`,`order_id`,`date_added`,`admi
SELECT `id`,`user_id`,`order_id`,`date_added`,`admin_comment`,`added_by`,`negativity_score` FROM `user_incidents`;
--> statement-breakpoint
-- Drop originals leaf-first (nothing references a table when it is dropped).
-- `coupon_applicable_products` has no dependents and references coupons and
-- product_skus, both of which are dropped below — so it goes first.
DROP TABLE `coupon_applicable_products`;
--> statement-breakpoint
DROP TABLE `user_incidents`;
--> statement-breakpoint
DROP TABLE `complaints`;
@ -1048,33 +1074,10 @@ INSERT OR IGNORE INTO `user_regions` (`user_id`, `region_id`, `from_address`, `f
SELECT DISTINCT `user_id`, `region_id`, 1, 0 FROM `addresses` WHERE `region_id` IS NOT NULL;
--> statement-breakpoint
-- =====================================================================
-- Phase 4 (from 0007_coupon_targets_json): coupon product targets.
-- Coupon product targets (from 0007_coupon_targets_json).
--
-- `coupon_applicable_products` is not rebuilt above and is dropped here: a
-- coupon's target SKUs live in its own `coupons.sku_ids` JSON array (and
-- `reserved_coupons.sku_ids` for a secret code, copied onto the coupon the
-- customer redeems). Empty array / NULL means "applies to the whole cart".
--
-- Any targets that only ever existed in the relation table are folded into the
-- arrays first. The table was never written from a UI (the admin forms had no
-- product picker), so on real data this backfill is a no-op.
-- The fold into `coupons.sku_ids` and the `coupon_applicable_products` drop
-- now run before the rebuild: that table is a leaf of coupons/product_skus,
-- so it must be dropped leaf-first (see the drop block above), and its rows
-- must be folded before `__new_coupons` copies `sku_ids`.
-- =====================================================================
UPDATE `coupons`
SET `sku_ids` = (
SELECT json_group_array(`sku`)
FROM (
SELECT DISTINCT `sku` FROM (
SELECT CAST(je.`value` AS INTEGER) AS `sku`
FROM json_each(CASE WHEN json_valid(`coupons`.`sku_ids`) THEN `coupons`.`sku_ids` ELSE '[]' END) AS je
UNION
SELECT cap.`sku_id` AS `sku`
FROM `coupon_applicable_products` AS cap
WHERE cap.`coupon_id` = `coupons`.`id`
)
)
)
WHERE EXISTS (
SELECT 1 FROM `coupon_applicable_products` AS cap WHERE cap.`coupon_id` = `coupons`.`id`
);
--> statement-breakpoint
DROP TABLE `coupon_applicable_products`;