This commit is contained in:
shafi54 2026-10-24 15:19:39 +05:30
parent 8889556bdf
commit bccc66372a
42 changed files with 1362 additions and 268 deletions

View file

@ -293,6 +293,8 @@ Use these fixture names in the cases below.
| APEDIT-18 | error | global save fails | alert |
| APEDIT-19 | edge | refresh | getProductById refetch |
| APEDIT-20 | edge | image keys conversion | bucket-relative, query removed |
| APEDIT-21 | edge | regional suspend toggle | reads/sends isSuspendedInRegion; isSuspended untouched |
| APEDIT-22 | edge | legacy structural suspension | shown as the regional toggle; sent as isSuspendedInRegion |
### 4.5 Product detail page

View file

@ -86,7 +86,7 @@ export default function AddProduct() {
isOffer: variant.isOffer || false,
isComboOnly: variant.isComboOnly || false,
isDeleted: variant.isDeleted || false,
isSuspended: variant.isSuspended || false,
isSuspendedInRegion: variant.isSuspendedInRegion || false,
features: variant.features.map((attr: any) => ({
featureName: attr.featureName,
featureValue: attr.featureValue,
@ -133,7 +133,7 @@ export default function AddProduct() {
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
isSuspendedInRegion: false,
features: [{ featureName: 'quantity', featureValue: '' }],
comboItems: [],
},

View file

@ -63,9 +63,12 @@ export default function EditProduct() {
isOffer: sku.isOffer || false,
isComboOnly: sku.isComboOnly || false,
isDeleted: sku.isDeleted || false,
// Global products are market-data-only for a regional admin: the toggle is
// this region's suspension, not the superadmin kill-switch.
isSuspended: (productData.isGlobal ? sku.isSuspendedInRegion : sku.isSuspended) || false,
// The product form's suspend toggle is this region's suspension, not the
// superadmin's global kill-switch. Legacy rows still carry suspension in
// the structural column: show it here; the next regional save folds it
// into the region's market row.
isSuspendedInRegion:
sku.isSuspendedInRegion || (!productData.isGlobal && sku.isSuspended) || false,
features: (sku.features || []).map((f) => ({
featureName: f.featureName,
featureValue: f.featureValue,
@ -168,9 +171,8 @@ export default function EditProduct() {
isOffer: variant.isOffer || false,
isComboOnly: variant.isComboOnly || false,
isDeleted: variant.isDeleted || false,
isSuspended: variant.isSuspended || false,
// Read only by the regional market-data path (global products).
isSuspendedInRegion: productData?.isGlobal ? (variant.isSuspended || false) : undefined,
// Region-owned suspension; the structural flag stays superadmin-owned.
isSuspendedInRegion: variant.isSuspendedInRegion || false,
features: variant.features.map((attr: any) => ({
featureName: attr.featureName,
featureValue: attr.featureValue,

View file

@ -25,7 +25,7 @@ type Variant = Omit<
isFlashAvailable: boolean
isOffer: boolean
isComboOnly: boolean
isSuspended: boolean
isSuspendedInRegion: boolean
features: Attribute[]
comboItems: CreateComboItemInput[]
}
@ -70,7 +70,7 @@ const defaultVariant = (): Variant => ({
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
isSuspendedInRegion: false,
features: [quantityAttribute()],
comboItems: [],
})
@ -519,11 +519,11 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
testID={`variant-${vIndex}-suspend`}
checked={variant.isSuspended}
onPress={() => setFieldValue(`variants.${vIndex}.isSuspended`, !variant.isSuspended)}
checked={variant.isSuspendedInRegion}
onPress={() => setFieldValue(`variants.${vIndex}.isSuspendedInRegion`, !variant.isSuspendedInRegion)}
style={tw`mr-3`}
/>
<MyText style={tw`text-gray-700 font-medium`}>Suspend SKU</MyText>
<MyText style={tw`text-gray-700 font-medium`}>Suspend in my region</MyText>
</View>
)}

View file

@ -22,7 +22,7 @@ const variant = (over: Record<string, any> = {}) => ({
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
isSuspendedInRegion: false,
features: [{ featureName: 'quantity', featureValue: '1kg' }],
comboItems: [],
...over,

View file

@ -347,4 +347,42 @@ describe('Edit product (APEDIT-01..20)', () => {
const payload = await updatedPayload()
expect(payload.skus[0].images).toEqual(['product-images/1.jpg'])
})
it('APEDIT-21: the regional suspend toggle sends the region flag', async () => {
setProcedure('admin.product.getProductById', {
data: {
product: regularProduct({
skus: [{ ...P_CHICKEN.skus[0], isSuspended: false, isSuspendedInRegion: true }],
}),
},
})
const view = await renderEdit()
expect(view.getByTestId('variant-0-suspend').props.accessibilityState.checked).toBe(true)
fireEvent.press(view.getByTestId('variant-0-suspend'))
await submit(view)
const sku = (await updatedPayload()).skus[0]
// The regional form writes the region's flag and never the global switch.
expect(sku.isSuspendedInRegion).toBe(false)
expect(sku.isSuspended).toBeUndefined()
})
it('APEDIT-22: a legacy structural suspension shows as the regional toggle', async () => {
setProcedure('admin.product.getProductById', {
data: {
product: regularProduct({
skus: [{ ...P_CHICKEN.skus[0], isSuspended: true, isSuspendedInRegion: false }],
}),
},
})
const view = await renderEdit()
expect(view.getByTestId('variant-0-suspend').props.accessibilityState.checked).toBe(true)
await submit(view)
expect((await updatedPayload()).skus[0].isSuspendedInRegion).toBe(true)
})
})

View file

@ -26,7 +26,7 @@ type Variant = Omit<
isFlashAvailable: boolean
isOffer: boolean
isComboOnly: boolean
isSuspended: boolean
isSuspendedInRegion: boolean
features: Attribute[]
comboItems: CreateComboItemInput[]
}
@ -88,7 +88,7 @@ const defaultVariant = (): Variant => ({
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
isSuspendedInRegion: false,
features: [quantityAttribute()],
comboItems: [],
})
@ -522,10 +522,10 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
{mode === 'edit' && (
<div className="flex flex-row items-center mb-3" data-testid={`variant-suspend-row-${vIndex}`}>
<Checkbox
checked={variant.isSuspended}
onPress={() => setFieldValue(`variants.${vIndex}.isSuspended`, !variant.isSuspended)}
checked={variant.isSuspendedInRegion}
onPress={() => setFieldValue(`variants.${vIndex}.isSuspendedInRegion`, !variant.isSuspendedInRegion)}
/>
<P className="text-gray-700 font-medium ml-3">Suspend SKU</P>
<P className="text-gray-700 font-medium ml-3">Suspend in my region</P>
</div>
)}

View file

@ -59,9 +59,12 @@ function EditProduct() {
isOffer: sku.isOffer || false,
isComboOnly: sku.isComboOnly || false,
isDeleted: sku.isDeleted || false,
// Global products are market-data-only for a regional admin: the toggle is
// this region's suspension, not the superadmin kill-switch.
isSuspended: (productData.isGlobal ? sku.isSuspendedInRegion : sku.isSuspended) || false,
// The product form's suspend toggle is this region's suspension, not the
// superadmin's global kill-switch. Legacy rows still carry suspension in
// the structural column: show it here; the next regional save folds it
// into the region's market row.
isSuspendedInRegion:
sku.isSuspendedInRegion || (!productData.isGlobal && sku.isSuspended) || false,
features: (sku.features || []).map((f) => ({
featureName: f.featureName,
featureValue: f.featureValue,
@ -161,9 +164,8 @@ function EditProduct() {
isOffer: variant.isOffer || false,
isComboOnly: variant.isComboOnly || false,
isDeleted: variant.isDeleted || false,
isSuspended: variant.isSuspended || false,
// Read only by the regional market-data path (global products).
isSuspendedInRegion: productData?.isGlobal ? (variant.isSuspended || false) : undefined,
// Region-owned suspension; the structural flag stays superadmin-owned.
isSuspendedInRegion: variant.isSuspendedInRegion || false,
features: variant.features.map((attr: any) => ({
featureName: attr.featureName,
featureValue: attr.featureValue,

View file

@ -80,7 +80,7 @@ function AddProduct() {
isOffer: variant.isOffer || false,
isComboOnly: variant.isComboOnly || false,
isDeleted: variant.isDeleted || false,
isSuspended: variant.isSuspended || false,
isSuspendedInRegion: variant.isSuspendedInRegion || false,
features: variant.features.map((attr: any) => ({
featureName: attr.featureName,
featureValue: attr.featureValue,
@ -127,7 +127,7 @@ function AddProduct() {
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
isSuspendedInRegion: false,
features: [{ featureName: 'quantity', featureValue: '' }],
comboItems: [],
},

View file

@ -383,6 +383,8 @@ availability ${assetsDomain}regions/${regionId}/av-${availability_version_n
| CACHE-60 | cache | delete store | removed after rebuild |
| CACHE-61 | edge | detail file can be a later version than captured | resolve current version each poll |
| CACHE-62 | edge | cross-region store | absent from other region's stores/detail |
| CACHE-113 | edge | global store with a global product | productCount/samples include global products; count matches detail |
| CACHE-114 | edge | global store tagged in the region | detail keeps the region-scoped tag |
### 4.4 slots.json
@ -483,6 +485,8 @@ availability ${assetsDomain}regions/${regionId}/av-${availability_version_n
| COMMON-14 | edge | multi-SKU product | all SKUs |
| COMMON-15 | edge | region isolation | no foreign SKU |
| COMMON-16 | edge | no token | 401 |
| COMMON-17 | edge | global SKU price | uses the caller region’s market row (not 0) |
| COMMON-18 | edge | global SKU regional suspension | hidden only in the suspending region |
### 5.3 `common.getStoresSummary`
@ -783,6 +787,7 @@ Covered comprehensively by section 4 (CACHE-01..24); add procedure-level cases:
| UCOUP-18 | edge | race two users redeem same secret | one success, one 400 |
| UCOUP-19 | edge | no token | 401 |
| UCOUP-20 | edge | secret case | lookup as supplied? assert current |
| UCOUP-21 | error | coupon-code collision on redeem | redemption fails; reserved coupon stays unredeemed |
### 6.11 `user.order.placeOrder`
@ -1120,7 +1125,7 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
| APROD-38 | edge | deleting images | deletedImageKeys removed after update |
| APROD-39 | edge | new image URL validation | claim before delete |
| APROD-40 | edge | current image re-sent | not treated as new |
| APROD-41 | edge | isSuspendedInRegion | stored |
| APROD-41 | edge | regional suspension | stored in product_market_stats.is_suspended_in_region |
| APROD-42 | cache | update schedule | eventually |
| APROD-43 | error | delete product with SKUs | current FK/raw failure; assert rejection |
| APROD-44 | error | delete unknown | 404 |
@ -1160,6 +1165,8 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
| APROD-78 | happy | regional admin edits a global product | market data only |
| APROD-79 | error | regional admin changes global structure | 403, rejected fields named |
| APROD-80 | error | regional admin deletes a global image | 403; image key kept |
| APROD-81 | error | regional update sets the structural isSuspended | global flag untouched |
| APROD-82 | edge | regional create with isSuspended | region flag set; global false |
### 7.5 `admin.order`
@ -1508,6 +1515,8 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
| SGPROD-12 | error | unknown | 404 |
| SGPROD-13 | edge | product assigned to region | visible in region caches after sync |
| SGPROD-14 | error | no token/staff/user | 401 |
| SGPROD-16 | edge | create with >=12 regions | market rows seeded via chunked insert |
| SGPROD-17 | edge | update adds a SKU with >=12 regions | new SKU's market rows seeded |
| SGPROD-15 | cache | global create/update/delete | all regions rebuild (no narrowing) |
### 8.6 `superadmin.globalStores`
@ -1567,6 +1576,8 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
| SPROD-12 | error | unknown store | 400/404 |
| SPROD-13 | cache | elevate | all-region rebuild |
| SPROD-14 | error | no token | 401 |
| SPROD-15 | edge | elevationDependents | regional combo components listed |
| SPROD-16 | happy | elevate combo | components elevated; market rows seeded |
### 8.9 `superadmin.complaint`
@ -1734,7 +1745,7 @@ and side-effect tests. Use this table as the completion gate.
| Router | Procedure | Case IDs |
| --- | --- | --- |
| common.product | getAllProductsSummary | COMMON-01..10 |
| common.product | getAllSkusSummary | COMMON-11..16 |
| common.product | getAllSkusSummary | COMMON-11..18 |
| common | getStoresSummary | COMMON-17..21 |
| common | checkLocationInPolygon | COMMON-22..29 |
| common | generateUploadUrls | COMMON-30..45, UPL-01..28 |
@ -1794,8 +1805,8 @@ and side-effect tests. Use this table as the completion gate.
| admin.product | getProductById | APROD-05..08 |
| admin.product | deleteProduct | APROD-43..45 |
| admin.product | toggleOutOfStock | APROD-46..50 |
| admin.product | createProduct | APROD-17..33 |
| admin.product | updateProduct | APROD-34..42, 78..80 |
| admin.product | createProduct | APROD-17..33, 82 |
| admin.product | updateProduct | APROD-34..42, 78..81 |
| admin.product | getProductReviews | APROD-09..12 |
| admin.product | respondToReview | APROD-73..77 |
| admin.product | getGroups | APROD-13 |
@ -1890,8 +1901,8 @@ and side-effect tests. Use this table as the completion gate.
| superadmin.staff | remove | SSTAFF-11..15 |
| superadmin.globalProducts | list | SGPROD-01 |
| superadmin.globalProducts | get | SGPROD-02..03 |
| superadmin.globalProducts | create | SGPROD-04..07 |
| superadmin.globalProducts | update | SGPROD-08..10 |
| superadmin.globalProducts | create | SGPROD-04..07, 16 |
| superadmin.globalProducts | update | SGPROD-08..10, 17 |
| superadmin.globalProducts | delete | SGPROD-11..15 |
| superadmin.globalStores | list | SGSTORE-01 |
| superadmin.globalStores | get | SGSTORE-02..03 |
@ -1904,7 +1915,8 @@ and side-effect tests. Use this table as the completion gate.
| superadmin.globalCoupons | update | SGCOUP-11..13 |
| superadmin.globalCoupons | delete | SGCOUP-14..17 |
| superadmin.products | list | SPROD-01..05 |
| superadmin.products | elevate | SPROD-06..09 |
| superadmin.products | elevate | SPROD-06..09, 16 |
| superadmin.products | elevationDependents | SPROD-15 |
| superadmin.stores | list | SPROD-10 |
| superadmin.stores | elevate | SPROD-11..14 |
| superadmin.complaint | getAll | SCOMP-01..06 |

View file

@ -3,7 +3,6 @@ import {
getAllTagsForCache,
getAllTagProductMappings,
getAllProductTags,
db,
} from '@/src/dbService'
import { scaffoldAssetUrl } from '@/src/lib/s3-client'
import type { ProductTagCore } from '@packages/shared'
@ -86,42 +85,12 @@ export async function initializeProductTagStore(regionId: number): Promise<void>
}
}
export async function getTagsByStoreId(storeId: number): Promise<Tag[]> {
export async function getTagsByStoreId(storeId: number, regionId: number): Promise<Tag[]> {
try {
// Get all keys matching the pattern "tag:*"
// const keys = await redisClient.KEYS('tag:*')
//
// if (keys.length === 0) {
// return []
// }
//
// // Get all tags using MGET for better performance
// const tagsData = await redisClient.MGET(keys)
//
// const storeTags: Tag[] = []
// for (const tagData of tagsData) {
// if (tagData) {
// const tag = JSON.parse(tagData) as Tag
// if (tag.relatedStores.includes(storeId)) {
// storeTags.push(tag)
// }
// }
// }
//
// return storeTags
// Scope tags to the store's own region (user path has no staff region).
// NOTE: callback-form `where` so operators come from the db's own
// drizzle copy (backend must not import drizzle-orm directly: dual copy).
const store = await db.query.storeInfo.findFirst({
where: (f, { eq }) => eq(f.id, storeId),
columns: { regionId: true },
})
if (store?.regionId == null) {
return []
}
const tags = await getAllProductTags(store.regionId)
// Tags are region-scoped. Use the caller's browsing region rather than the
// store's own region: a global store has region_id NULL but still carries
// the tags attached to it in the region being browsed.
const tags = await getAllProductTags(regionId)
const result: Tag[] = []
for (const tag of tags) {

View file

@ -313,6 +313,7 @@ export const productRouter = router({
isComboOnly: z.boolean().optional().default(false),
isDeleted: z.boolean().optional().default(false),
isSuspended: z.boolean().optional().default(false),
isSuspendedInRegion: z.boolean().optional(),
features: z.array(z.object({
featureName: z.string().nullable().optional(),
featureValue: z.string().min(1, 'Value is required'),
@ -344,6 +345,7 @@ export const productRouter = router({
isComboOnly: sku.isComboOnly,
isDeleted: sku.isDeleted ?? false,
isSuspended: sku.isSuspended,
isSuspendedInRegion: sku.isSuspendedInRegion,
features: sku.features.map((f) => ({
featureName: f.featureName?.trim() || null,
featureValue: f.featureValue,

View file

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

View file

@ -2,7 +2,7 @@ import { router, superadminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { ApiError } from '@/src/lib/api-error'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import { listAllProducts, elevateProductToGlobal } from '@/src/dbService'
import { listAllProducts, elevateProductToGlobal, getElevationDependents } from '@/src/dbService'
export const superadminProductsRouter = router({
// Every product across all regions (global + regional), paginated + name search.
@ -18,6 +18,13 @@ export const superadminProductsRouter = router({
}),
// Elevate a regional product to a global one attached to a global store.
// Regional component products of a combo are elevated in the same operation.
elevationDependents: superadminProcedure
.input(z.object({ productId: z.number() }))
.query(async ({ input }) => {
return { dependents: await getElevationDependents(input.productId) }
}),
elevate: superadminProcedure
.input(z.object({ productId: z.number(), storeId: z.number() }))
.mutation(async ({ input }) => {

View file

@ -64,7 +64,7 @@ export async function scaffoldStoreWithProducts(regionId: number, storeId: numbe
productQuantity: product.productQuantity,
}))
const tags = await getTagsByStoreId(storeId)
const tags = await getTagsByStoreId(storeId, regionId)
return {
store: {

View file

@ -397,6 +397,19 @@ describe('admin.product.createProduct (APROD-17..33)', () => {
expect(Number(listed.storeId)).toBe(store.storeId)
expect(Number(listed.price)).toBe(456)
})
it('APROD-82: a regional create marks suspension on the region flag', async () => {
const admin = await staffClient()
const store = await createStore()
const created: any = await rawCreate(admin, {
storeId: store.storeId,
skus: [skuInput({ isSuspended: true })],
})
const read = await readProduct(admin, Number(created.product.id))
expect(read.skus[0].isSuspended).toBe(false)
expect(read.skus[0].isSuspendedInRegion).toBe(true)
})
})
describe('admin.product.updateProduct (APROD-34..42)', () => {
@ -575,11 +588,10 @@ describe('admin.product.updateProduct (APROD-34..42)', () => {
expect(read.skus[0].images).toEqual([`${domain}/${key}`])
})
it('APROD-41 (current): isSuspendedInRegion is schema-accepted but not persisted on a regional update', async () => {
// `updateProduct` accepts `isSuspendedInRegion`, but the regional update path
// only writes `isSuspendedInRegion` for a *global* product edited from a
// region (`updateProductMarketDataForRegion`); a normal regional product's
// market-stats write omits it, so the flag stays false.
it('APROD-41: a regional update persists suspension on the region flag, not the global flag', async () => {
// The regional update path writes product_market_stats.is_suspended_in_region
// for its own region; the structural product_skus.is_suspended kill-switch is
// superadmin-owned and stays untouched.
const admin = await staffClient()
const store = await createStore()
const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput()] })
@ -593,7 +605,50 @@ describe('admin.product.updateProduct (APROD-34..42)', () => {
skus: [skuInput({ id: skuId, isSuspendedInRegion: true })],
})
let read = await readProduct(admin, productId)
expect(read.skus[0].isSuspendedInRegion).toBe(true)
expect(read.skus[0].isSuspended).toBe(false)
// And an omitted flag keeps the current regional value.
await admin.admin.product.updateProduct.mutate({
id: productId,
name: created.product.name,
storeId: store.storeId,
skus: [skuInput({ id: skuId, price: 250 })],
})
read = await readProduct(admin, productId)
expect(read.skus[0].isSuspendedInRegion).toBe(true)
// Explicitly clearing it un-suspends the region.
await admin.admin.product.updateProduct.mutate({
id: productId,
name: created.product.name,
storeId: store.storeId,
skus: [skuInput({ id: skuId, isSuspendedInRegion: false })],
})
read = await readProduct(admin, productId)
expect(read.skus[0].isSuspendedInRegion).toBe(false)
})
it('APROD-81: a regional update cannot set the global suspension flag', async () => {
const admin = await staffClient()
const store = await createStore()
const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput()] })
const productId = Number(created.product.id)
const skuId = Number(created.product.skus[0].id)
await admin.admin.product.updateProduct.mutate({
id: productId,
name: created.product.name,
storeId: store.storeId,
// A client that only knows the old structural field must not reach it.
skus: [skuInput({ id: skuId, isSuspended: true })],
})
const read = await readProduct(admin, productId)
expect(read.skus[0].isSuspended).toBe(false)
expect(read.skus[0].isSuspendedInRegion).toBe(false)
})

View file

@ -1,5 +1,5 @@
/**
* CACHE-51..62 — `stores.json` and per-store detail (catalogue §4.3).
* CACHE-51..62, 113..114 — `stores.json` and per-store detail (catalogue §4.3).
*
* `stores.json` is built by `scaffoldStores` (region stores + globals) and the
* per-store `stores/<id>.json` by `scaffoldStoreWithProducts`. Both are rebuilt
@ -19,7 +19,7 @@
import { uniqueSuffix, type ApiClient } from '../helpers/api'
import { staffClient, superadminClient } from '../helpers/sessions'
import { createStore } from '../helpers/fixtures'
import { createProduct, createStore } from '../helpers/fixtures'
import {
getEssentialConsts,
scaffoldCache,
@ -189,6 +189,54 @@ describe('stores/<id>.json shape (CACHE-52..54, 61)', () => {
}
})
it('CACHE-113: a global store counts and samples its global products', async () => {
const superadmin = await superadminClient()
const store = await createStore()
const product = await createProduct({
storeId: store.storeId,
name: `E2E Global Store Product ${uniqueSuffix()}`,
})
const created: any = await superadmin.superadmin.globalStores.create.mutate({
name: `E2E Global Store ${uniqueSuffix()}`,
description: 'CACHE-113 fixture',
})
const globalStoreId = Number(created.store.id)
await superadmin.superadmin.products.elevate.mutate({
productId: product.productId,
storeId: globalStoreId,
})
const doc: any = await scaffoldCache('stores', { regionId: TEST_REGION_ID })
const listed = doc.stores.find((entry: any) => Number(entry.id) === globalStoreId)
expect(listed).toBeTruthy()
expect(listed.productCount).toBeGreaterThan(0)
expect(listed.sampleProducts.map((sample: any) => Number(sample.id))).toContain(product.skuId)
const detail: any = await scaffoldStore(globalStoreId, { regionId: TEST_REGION_ID })
expect(listed.productCount).toBe(detail.products.length)
})
it('CACHE-114: a global store keeps its region-scoped tags', async () => {
const admin = await staffClient()
const superadmin = await superadminClient()
const created: any = await superadmin.superadmin.globalStores.create.mutate({
name: `E2E Global Tag Store ${uniqueSuffix()}`,
description: 'CACHE-114 fixture',
})
const globalStoreId = Number(created.store.id)
const tagName = `E2E Store Tag ${uniqueSuffix()}`
const tag: any = await admin.admin.product.createProductTag.mutate({
tagName,
relatedStores: [globalStoreId],
})
const detail: any = await scaffoldStore(globalStoreId, { regionId: TEST_REGION_ID })
const listed = detail.tags.find((entry: any) => Number(entry.id) === Number(tag.tag.id))
expect(listed).toBeTruthy()
expect(listed.tagName).toBe(tagName)
})
it('(current) CACHE-61: the detail file is resolved at the current version each poll', async () => {
// The detail file for an early seeded store exists at the current version;
// re-reading the version each attempt keeps it valid across rebuilds.

View file

@ -1,5 +1,5 @@
/**
* COMMON-01..16 — `common.product.getAllProductsSummary` / `getAllSkusSummary`
* COMMON-01..18 — `common.product.getAllProductsSummary` / `getAllSkusSummary`
* (catalogue §5.1/§5.2).
*
* Both reads are `protectedProcedure` scoped to `ctx.staffUser.regionId` and read
@ -287,7 +287,74 @@ describe('common.product.getAllProductsSummary (COMMON-01..10)', () => {
/* 5.2 getAllSkusSummary */
/* -------------------------------------------------------------------------- */
describe('common.product.getAllSkusSummary (COMMON-11..16)', () => {
/** A region-1 product elevated to a fresh global store, plus a region-2 staff. */
async function setupGlobalSku(): Promise<{
admin: ApiClient
r2: Awaited<ReturnType<typeof region2>>
product: Awaited<ReturnType<typeof createProduct>>
globalStoreId: number
}> {
const admin = await staffClient()
const superadmin = await superadminClient()
const store = await createStore()
const product = await createProduct({ storeId: store.storeId, price: 222 })
const created: any = await superadmin.superadmin.globalStores.create.mutate({
name: `E2E Global Store ${uniqueSuffix()}`,
description: 'COMMON global fixture',
})
const globalStoreId = Number(created.store.id)
await superadmin.superadmin.products.elevate.mutate({
productId: product.productId,
storeId: globalStoreId,
})
return { admin, r2: await region2(), product, globalStoreId }
}
/**
* A market-data-only update for the elevated global product. A regional admin
* cannot change structural fields, so they must match the stored row.
*/
function globalMarketUpdate(args: {
productId: number
productName: string
skuId: number
globalStoreId: number
price?: number
isSuspendedInRegion?: boolean
}) {
const price = args.price ?? 222
return {
id: args.productId,
name: args.productName,
shortDescription: 'Created by backend API tests',
storeId: args.globalStoreId,
incrementStep: 1,
productType: 'item' as const,
skus: [{
id: args.skuId,
name: '1pc',
price,
marketPrice: price + 50,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
isSuspendedInRegion: args.isSuspendedInRegion ?? false,
features: [{ featureName: 'quantity', featureValue: '1pc' }],
comboItems: [],
}],
deletedImageKeys: [],
newImageUrls: [],
}
}
describe('common.product.getAllSkusSummary (COMMON-11..18)', () => {
it('COMMON-11 (current): staff call returns id/name/price/images/label per SKU', async () => {
const admin = await staffClient()
const store = await createStore()
@ -364,4 +431,45 @@ describe('common.product.getAllSkusSummary (COMMON-11..16)', () => {
'UNAUTHORIZED'
)
})
it("COMMON-17: a global SKU uses the caller region's price, not ₹0", async () => {
const { admin, r2, product, globalStoreId } = await setupGlobalSku()
// Region 2 sets its own market price for the global SKU.
await r2.client.admin.product.updateProduct.mutate(
globalMarketUpdate({
productId: product.productId,
productName: product.productName,
skuId: product.skuId,
globalStoreId,
price: 333,
}) as any
)
const r1: any = await admin.common.product.getAllSkusSummary.query()
const r2Summary: any = await r2.client.common.product.getAllSkusSummary.query()
expect(r1.skus.find((s: any) => s.id === product.skuId)?.price).toBe('222')
expect(r2Summary.skus.find((s: any) => s.id === product.skuId)?.price).toBe('333')
})
it('COMMON-18: a global SKU suspended in one region is hidden there only', async () => {
const { admin, r2, product, globalStoreId } = await setupGlobalSku()
await r2.client.admin.product.updateProduct.mutate(
globalMarketUpdate({
productId: product.productId,
productName: product.productName,
skuId: product.skuId,
globalStoreId,
isSuspendedInRegion: true,
}) as any
)
const r1: any = await admin.common.product.getAllSkusSummary.query()
const r2Summary: any = await r2.client.common.product.getAllSkusSummary.query()
expect(r1.skus.some((s: any) => s.id === product.skuId)).toBe(true)
expect(r2Summary.skus.some((s: any) => s.id === product.skuId)).toBe(false)
})
})

View file

@ -1,5 +1,5 @@
/**
* SPROD-01..14 — `superadmin.products` / `superadmin.stores` (catalogue §8.8).
* SPROD-01..16 — `superadmin.products` / `superadmin.stores` (catalogue §8.8).
*
* Live HTTP/tRPC suite. One `it()` per catalogue row; rows that pin current
* (not intended) behaviour are prefixed `(current)`.
@ -19,6 +19,7 @@ import { apiClient, expectTrpcError, uniqueSuffix } from '../helpers/api'
import { anonClient, staffSession, superadminClient, userSession } from '../helpers/sessions'
import { createProduct, createRegion, createStore } from '../helpers/fixtures'
import { scaffoldCache } from '../helpers/cache'
import { TEST_OTHER_REGION_ID } from '../helpers/env'
jest.setTimeout(300_000)
@ -181,6 +182,90 @@ describe('superadmin.products.elevate (SPROD-06..09)', () => {
})
})
/* -------------------------------------------------------------------------- */
/* products.elevate + combo dependents */
/* -------------------------------------------------------------------------- */
describe('superadmin.products.elevate dependents (SPROD-15..16)', () => {
it("SPROD-15: elevationDependents lists a combo's regional component products", async () => {
const superadmin = await superadminClient()
const store = await createStore()
const component = await createProduct({
storeId: store.storeId,
name: `E2E Combo Part ${uniqueSuffix()}`,
price: 120,
})
const combo = await createProduct({
storeId: store.storeId,
name: `E2E Combo ${uniqueSuffix()}`,
price: 300,
productType: 'combo',
comboItems: [{ skuId: component.skuId }],
})
const res: any = await superadmin.superadmin.products.elevationDependents.query({
productId: combo.productId,
})
expect(res.dependents).toHaveLength(1)
expect(res.dependents[0]).toEqual(
expect.objectContaining({
id: component.productId,
name: component.productName,
regionId: 1,
})
)
expect(typeof res.dependents[0].regionName).toBe('string')
})
it('SPROD-16: elevating a combo elevates its regional components', async () => {
const superadmin = await superadminClient()
const store = await createStore()
const component = await createProduct({
storeId: store.storeId,
name: `E2E Combo Part ${uniqueSuffix()}`,
price: 120,
})
const combo = await createProduct({
storeId: store.storeId,
name: `E2E Combo ${uniqueSuffix()}`,
price: 300,
productType: 'combo',
comboItems: [{ skuId: component.skuId }],
})
const globalStoreId = await createGlobalStore()
const res: any = await superadmin.superadmin.products.elevate.mutate({
productId: combo.productId,
storeId: globalStoreId,
})
expect(res.product.regionId).toBeNull()
expect(Number(res.product.storeId)).toBe(globalStoreId)
const globals: any = await superadmin.superadmin.globalProducts.list.query()
const globalIds = new Set(globals.products.map((product: any) => Number(product.id)))
expect(globalIds.has(combo.productId)).toBe(true)
expect(globalIds.has(component.productId)).toBe(true)
// The component's market row was seeded for the other region too.
const other: any = await scaffoldCache('products', { regionId: TEST_OTHER_REGION_ID })
const rows = new Map(
(other.products ?? []).map((product: any) => [Number(product.id), product])
)
expect(rows.has(combo.skuId)).toBe(true)
expect(rows.has(component.skuId)).toBe(true)
expect(Number((rows.get(combo.skuId) as any).price)).toBe(300)
expect(Number((rows.get(component.skuId) as any).price)).toBe(120)
// The whole point: no regional component is left behind, so region B's
// cache filter (which drops non-global components) keeps the full combo.
const after: any = await superadmin.superadmin.products.elevationDependents.query({
productId: combo.productId,
})
expect(after.dependents).toEqual([])
})
})
/* -------------------------------------------------------------------------- */
/* stores */
/* -------------------------------------------------------------------------- */

View file

@ -1,5 +1,5 @@
/**
* SGPROD-01..15 — `superadmin.globalProducts` (catalogue §8.5).
* SGPROD-01..17 — `superadmin.globalProducts` (catalogue §8.5).
*
* Live HTTP/tRPC suite. One `it()` per catalogue row; rows that pin current
* (not intended) behaviour are prefixed `(current)` with a comment recording the
@ -12,10 +12,8 @@
* the omitted SKU is left untouched.
*
* `create` (and an update that adds a SKU) seeds one `product_market_stats` row
* per region in a single multi-row INSERT (9 binds per row). With more than ~11
* regions that exceeds D1's 100-bound-parameter cap and 500s; with fewer it
* succeeds. SGPROD-04/07/10 therefore branch on the live region count and assert
* the contract that actually applies.
* per region; that insert is chunked so it stays under D1's 100-bound-parameter
* cap regardless of how many regions exist.
*/
import { apiClient, expectTrpcError, uniqueSuffix } from '../helpers/api'
@ -92,18 +90,12 @@ async function createGlobalStore(): Promise<number> {
return Number(res.store.id)
}
/**
* Run a call and return either the value or its error.
*
* Local D1 caps bound parameters ("too many SQL variables"); the threshold
* depends on how many regions exist when the suite runs (observed: 180 binds
* succeed, 414 fail). These `(current)` rows therefore accept either outcome.
*/
async function attempt<T>(fn: () => Promise<T>): Promise<{ ok: true; value: T } | { ok: false; error: Error }> {
try {
return { ok: true, value: await fn() }
} catch (error) {
return { ok: false, error: error as Error }
/** Ensure the DB has at least `count` regions (the market-row bind cap starts at 12). */
async function ensureAtLeastRegions(count: number): Promise<void> {
const superadmin = await superadminClient()
const regions = (await superadmin.superadmin.regions.list.query()) as any[]
for (let i = regions.length; i < count; i++) {
await createRegion()
}
}
@ -204,7 +196,7 @@ describe('superadmin.globalProducts reads (SGPROD-01..03)', () => {
/* -------------------------------------------------------------------------- */
describe('superadmin.globalProducts.create (SGPROD-04..07)', () => {
it('SGPROD-04 (current): create succeeds under the bind cap, 500s above it', async () => {
it('SGPROD-04: create succeeds and seeds the region market rows', async () => {
const superadmin = await superadminClient()
const storeId = await createGlobalStore()
const name = `E2E GP create ${uniqueSuffix()}`
@ -216,13 +208,7 @@ describe('superadmin.globalProducts.create (SGPROD-04..07)', () => {
skus: [skuUpdate(0, { id: undefined, price: 150 })],
} as any
const result = await attempt(() => superadmin.superadmin.globalProducts.create.mutate(payload))
if (!result.ok) {
expect(result.error.message).toContain('Failed to create product')
return
}
const res: any = result.value
const res: any = await superadmin.superadmin.globalProducts.create.mutate(payload)
const productId = Number(res.product?.id)
expect(productId).toBeGreaterThan(0)
expect(res.message).toBe('Global product created successfully')
@ -230,6 +216,7 @@ describe('superadmin.globalProducts.create (SGPROD-04..07)', () => {
const got: any = await superadmin.superadmin.globalProducts.get.query({ id: productId })
expect(got.product.name).toBe(name)
expect(got.product.skus).toHaveLength(1)
expect(got.product.skus[0].marketStats.length).toBeGreaterThan(0)
})
it('SGPROD-05: an invalid name, price or feature value is BAD_REQUEST', async () => {
@ -279,7 +266,7 @@ describe('superadmin.globalProducts.create (SGPROD-04..07)', () => {
)
})
it('SGPROD-07 (current): a multi-SKU create succeeds under the bind cap, 500s above it', async () => {
it('SGPROD-07: a multi-SKU create seeds both SKUs', async () => {
const superadmin = await superadminClient()
const storeId = await createGlobalStore()
const payload = {
@ -289,18 +276,33 @@ describe('superadmin.globalProducts.create (SGPROD-04..07)', () => {
skus: [skuUpdate(0, { id: undefined }), skuUpdate(0, { id: undefined, name: '2pc', price: 250 })],
} as any
const result = await attempt(() => superadmin.superadmin.globalProducts.create.mutate(payload))
if (!result.ok) {
expect(result.error.message).toContain('Failed to create product')
return
}
const res: any = result.value
const res: any = await superadmin.superadmin.globalProducts.create.mutate(payload)
const productId = Number(res.product?.id)
expect(productId).toBeGreaterThan(0)
const got: any = await superadmin.superadmin.globalProducts.get.query({ id: productId })
expect(got.product.skus).toHaveLength(2)
expect(got.product.skus.every((sku: any) => sku.marketStats.length > 0)).toBe(true)
})
it('SGPROD-16: a global create seeds every region past the D1 bind cap', async () => {
// 12 regions x 9 params used to exceed D1's 100-parameter limit.
await ensureAtLeastRegions(12)
const superadmin = await superadminClient()
const storeId = await createGlobalStore()
const res: any = await superadmin.superadmin.globalProducts.create.mutate({
name: `E2E GP chunked ${uniqueSuffix()}`,
shortDescription: 'SGPROD-16',
storeId,
productType: 'item',
skus: [skuUpdate(0, { id: undefined, price: 150 })],
} as any)
const got: any = await superadmin.superadmin.globalProducts.get.query({
id: Number(res.product.id),
})
expect(got.product.skus[0].marketStats.length).toBeGreaterThanOrEqual(12)
})
})
@ -379,18 +381,34 @@ describe('superadmin.globalProducts.update (SGPROD-08..10)', () => {
],
} as any
const addedResult = await attempt(() => superadmin.superadmin.globalProducts.update.mutate(addPayload))
if (!addedResult.ok) {
expect(addedResult.error.message).toContain('Failed to update product')
return
}
const added: any = addedResult.value
const added: any = await superadmin.superadmin.globalProducts.update.mutate(addPayload)
expect(added.message).toBe('Global product updated successfully')
const afterAdd: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
expect(afterAdd.product.skus).toHaveLength(owned.skuIds.length + 1)
})
it('SGPROD-17: adding a SKU to a global product seeds every region', async () => {
await ensureAtLeastRegions(12)
const superadmin = await superadminClient()
const owned = await makeGlobalProduct()
await superadmin.superadmin.globalProducts.update.mutate({
id: owned.productId,
name: owned.name,
storeId: owned.storeId,
productType: 'item',
skus: [
skuUpdate(owned.skuIds[0]),
skuUpdate(0, { id: undefined, name: '2pc', price: 250 }),
],
} as any)
const got: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
const added = got.product.skus.find((sku: any) => !owned.skuIds.includes(Number(sku.id)))
expect(added).toBeTruthy()
expect(added.marketStats.length).toBeGreaterThanOrEqual(12)
})
})
/* -------------------------------------------------------------------------- */

View file

@ -1,5 +1,5 @@
/**
* UCOUP-01..20 — `user.coupon.*` (catalogue §6.10).
* UCOUP-01..21 — `user.coupon.*` (catalogue §6.10).
*
* NOTE: the shared `createCoupon` fixture always sends `null` for the optional
* numeric/date columns, which the admin schema (`z.number().optional()`) rejects
@ -232,7 +232,7 @@ describe('user.coupon.getMyCoupons (UCOUP-08..12)', () => {
/* redeemReservedCoupon */
/* -------------------------------------------------------------------------- */
describe('user.coupon.redeemReservedCoupon (UCOUP-13..20)', () => {
describe('user.coupon.redeemReservedCoupon (UCOUP-13..21)', () => {
it('UCOUP-13: a valid secret redeems and the coupon appears as personal', async () => {
const user = await registerThrowawayUser()
const secret = couponCode('RED')
@ -340,4 +340,28 @@ describe('user.coupon.redeemReservedCoupon (UCOUP-13..20)', () => {
expect(res.success).toBe(true)
expect(res.coupon.couponCode).toBe(secret)
})
it('UCOUP-21: a coupon-code collision does not consume the secret', async () => {
const user = await registerThrowawayUser()
const admin = await staffClient()
const secret = couponCode('COLL')
// Reserved first, then an ordinary coupon takes the same code. The two admin
// create paths only check their own table, so the collision is reachable.
await createReservedCoupon({ couponCode: secret })
await createAdminCoupon({ couponCode: secret, isApplyForAll: true, flatDiscount: 10 })
// The insert hits coupons.coupon_code's unique constraint. The batch must roll
// the claim back, so the redemption fails without burning the secret.
const [outcome] = await Promise.allSettled([
apiClient(user.token).user.coupon.redeemReservedCoupon.mutate({ secretCode: secret }),
])
expect(outcome.status).toBe('rejected')
const reserved: any = await admin.admin.coupon.getReservedCoupons.query({ search: secret })
const row = reserved.coupons.find((entry: any) => entry.secretCode === secret)
expect(row).toBeTruthy()
expect(row.isRedeemed).toBe(false)
expect(row.redeemedBy).toBeNull()
})
})

View file

@ -65,6 +65,9 @@ describe('admin.slots.createSlot cleanup', () => {
expect(mockedCreate).toHaveBeenCalledTimes(1)
expect(mockedCache).toHaveBeenCalledTimes(1)
expect(mockedCleanup).toHaveBeenCalledTimes(1)
// Cleanup must stay inside the caller's region; a global window would let
// region A clear region B's slots.
expect(mockedCleanup).toHaveBeenCalledWith(ctx.staffUser.regionId)
expect(settled).toBe(false)
release()
@ -80,5 +83,6 @@ describe('admin.slots.createSlot cleanup', () => {
expect(result).toEqual(expect.objectContaining({ message: 'Slot created' }))
expect(mockedCleanup).toHaveBeenCalledTimes(1)
expect(mockedCleanup).toHaveBeenCalledWith(ctx.staffUser.regionId)
})
})

View file

@ -145,8 +145,29 @@ function RegionProductsTab({ regionId }: { regionId: number }) {
void alert('Choose a global store')
return
}
const storeId = Number(storeChoice)
try {
await elevate.mutateAsync({ productId, storeId: Number(storeChoice) })
// Combo products depend on their component products. Confirm before any
// write: the backend elevates the whole set, so the superadmin sees which
// regional products will also become global.
const { dependents } = await utils.superadmin.products.elevationDependents.fetch({ productId })
if (dependents.length > 0) {
const storeName =
stores.find((store: any) => Number(store.id) === storeId)?.name ?? 'the selected store'
const list = dependents
.map(
(dependent: any) =>
`• ${dependent.name}${dependent.regionName ? ` (${dependent.regionName})` : ''}`
)
.join('\n')
const confirmed = await confirm(
`Elevate product with dependent products?\n\nThese regional products will also become global and attach to ${storeName}:\n${list}`,
{ confirmText: 'Elevate all', cancelText: 'Cancel' }
)
if (!confirmed) return
}
await elevate.mutateAsync({ productId, storeId })
setElevatingId(null)
setStoreChoice('')
await utils.superadmin.products.list.invalidate()

View file

@ -958,7 +958,8 @@ real.
| ADDR-17 | happy | form success | modal closes; list refetches |
| ADDR-18 | edge | mark data fetchers | refetch |
| ADDR-19 | edge | address without line2 | formatted without comma |
| ADDR-20 | edge | address with Google Maps URL and coords | edit passes coords undefined when URL present |
| ADDR-20 | edge | address with Google Maps URL and coords | edit keeps the saved coordinates |
| ADDR-21 | edge | vague-backfilled address | edit withholds placeholder coordinates |
### 17.2 AddressForm
@ -1001,6 +1002,8 @@ real.
| ADDRF-35 | edge | map message invalid JSON/type | ignored |
| ADDRF-36 | edge | map URL with lat/lng | query params present |
| ADDRF-37 | edge | map URL without lat/lng | base URL only |
| ADDRF-38 | edge | edit + device fix | submits saved coords; device never auto-attached |
| ADDRF-39 | edge | edit region differs from browsing | saved address town kept |
---
@ -1430,6 +1433,8 @@ Covered by HOME-81..98, plus:
| API-04 | edge | no bound | query disabled |
| API-05 | edge | cached consts per bound | immediate placeholder; corrupt cache ignored |
| API-06 | edge | cache key differs by bound | no cross-bound leak |
| API-20 | edge | switch bounds while the new request is pending | previous snapshot never written under the new key |
| API-21 | edge | snapshot stored under the wrong bound | ignored (payload boundId must match) |
| API-07 | happy | products URL | `${assets}${key}/regions/${id}/v-${products_version_num}/products.json` |
| API-08 | happy | availability URL | `av-${availability_version_num}` |
| API-09 | happy | slots URL | `slots/v-${slots_version_num}/slots.json?v=123` |

View file

@ -15,6 +15,7 @@ type Address = Pick<
latitude?: number | null
longitude?: number | null
googleMapsUrl?: string | null
vagueBackfilledCoords?: boolean | null
}
function AddressCard({ address, onEdit, onDelete, onSetDefault, isDeleting }: {
@ -299,8 +300,15 @@ export default function Addresses() {
city: editingAddress.city,
state: editingAddress.state,
isDefault: editingAddress.isDefault,
latitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.latitude ?? undefined),
longitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.longitude ?? undefined),
// Preserve the saved location. Migration-backfilled placeholder
// coordinates are the only ones we withhold, so the user has to
// pick a real point instead of editing around a fake one.
latitude: editingAddress.vagueBackfilledCoords
? undefined
: (editingAddress.latitude ?? undefined),
longitude: editingAddress.vagueBackfilledCoords
? undefined
: (editingAddress.longitude ?? undefined),
googleMapsUrl: editingAddress.googleMapsUrl ?? undefined,
} : undefined}
isEdit={!!editingAddress}

View file

@ -37,11 +37,14 @@ const AddressForm: React.FC<AddressFormProps & {
? { latitude: initialValues.latitude, longitude: initialValues.longitude }
: null
);
// The town (region) for this address. Pre-selected from the app's current
// browsing region when one exists; otherwise picked from the City dropdown.
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(() =>
browsingRegionId != null ? { regionId: browsingRegionId, boundId: browsingBoundId } : null
);
// The town (region) for this address. When editing, the saved address's own
// town wins; otherwise pre-select the app's current browsing region.
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(() => {
if (initialValues?.regionId != null) {
return { regionId: initialValues.regionId, boundId: null }
}
return browsingRegionId != null ? { regionId: browsingRegionId, boundId: browsingBoundId } : null
});
const [locationError, setLocationError] = useState<string | null>(null);
const [locationSource, setLocationSource] = useState<LocationSource | null>(
initialValues?.latitude != null && initialValues?.longitude != null ? 'device' : null
@ -170,14 +173,17 @@ const AddressForm: React.FC<AddressFormProps & {
}, []);
// If the app already knows the device location, attach it as the address
// location by default (the user can still choose another on the map).
// location by default — for a NEW address only. Editing must never move a
// saved address just because the user happens to be somewhere else; the
// caller supplies the saved coordinates, which resolve on mount above.
useEffect(() => {
if (isEdit) return;
if (currentLocation != null) return;
if (initialValues?.latitude != null) return;
if (deviceCoords == null) return;
void resolveLocation(deviceCoords);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [deviceCoords]);
}, [deviceCoords, isEdit]);
// Pre-select the browsing town once the app knows it (e.g. after the location
// resolves) — unless the user already picked a town or attached a location.

View file

@ -53,7 +53,13 @@ export const useGetEssentialConsts = () => {
if (cancelled) return
if (raw) {
try {
setInitialData(JSON.parse(raw))
const snapshot = JSON.parse(raw) as DiscoveryData
// The key alone is not proof of provenance: only hydrate a payload the
// backend built for this bound (a wrong-bound write must not survive a
// restart).
if (snapshot?.boundId === boundId) {
setInitialData(snapshot)
}
} catch {
// ignore corrupt cache
}
@ -64,19 +70,26 @@ export const useGetEssentialConsts = () => {
}, [boundId])
// The backend resolves the flat payload for a single bound. tRPC includes the
// input in the query key, so switching bounds refetches discovery.
// input in the query key, so switching bounds refetches discovery. Never hand
// the query a snapshot from another bound, even on the render where boundId
// changes but the hydration effect above 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: initialData as any,
placeholderData: placeholder as any,
})
// Persist the latest response under this bound's key.
// 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) {
StorageServiceCasual.setItem(essentialConstsKey(boundId), JSON.stringify(query.data))
}
}, [query.data, boundId])
if (!query.data || boundId == null) return
if (query.isPlaceholderData) return
if (query.data.boundId !== boundId) return
StorageServiceCasual.setItem(essentialConstsKey(boundId), JSON.stringify(query.data))
}, [query.data, query.isPlaceholderData, boundId])
return { ...query, refetch: query.refetch }
}

View file

@ -2,7 +2,7 @@
/**
* Catalogue section 17.2 — `AddressForm` (`tests/components/address-form.test.tsx`).
*
* ADDRF-01..37. The region/coordinate resolution goes through
* ADDRF-01..39. The region/coordinate resolution goes through
* `utils.common.resolveRegionByLocation.fetch` / `utils.common.resolveBound.fetch`,
* which the procedure mock does NOT record (only `useQuery`/`useMutation` are
* recorded). So the inputs are captured with an `impl` spy instead, and the
@ -668,4 +668,38 @@ describe('AddressForm', () => {
expect(getByTestId('webview').props.source.uri).toBe(MAP_BASE)
})
it('ADDRF-38: editing submits the saved coordinates, never the device location', async () => {
// A device fix is available while editing an address saved elsewhere. The
// form must not auto-attach it: saving must keep the saved coordinates.
// (The shared resolveRegionByLocation spy also sees useRegion's startup
// check, so the assertion is on the submitted update payload instead.)
grantLocation(12.34, 56.78)
spyResolveRegion()
const { getByText, getByTestId } = renderForm({
isEdit: true,
initialValues: { id: 42, ...withCoords() },
})
await waitFor(() => expect(getByText('Current Location Attached')).toBeTruthy())
fireEvent.press(getByTestId('address-submit'))
await waitFor(() => expect(procedureMutationCalls('user.address.updateAddress')).toHaveLength(1))
const input = lastProcedureInput('user.address.updateAddress')
expect(input.id).toBe(42)
expect(input.latitude).toBe(17)
expect(input.longitude).toBe(78)
})
it('ADDRF-39: editing keeps the saved address town over the browsing town', async () => {
denyLocation()
seedRegion(REGION_1, 7)
const { getByText } = renderForm({
isEdit: true,
initialValues: { id: 42, regionId: 2, ...BASE_VALUES },
})
await flush()
expect(getByText('Hyderabad')).toBeTruthy()
})
})

View file

@ -29,7 +29,7 @@ import {
lastProcedureInput,
procedureCallCount,
} from '../mocks/trpc-client'
import { __set as setSecureItem } from '../mocks/secure-store-mock'
import { __set as setSecureItem, __snapshot as secureSnapshot } from '../mocks/secure-store-mock'
import { __setAuthState } from '../mocks/auth-context'
import { __configure as configureLocation } from '../mocks/expo-location-mock'
import {
@ -155,7 +155,7 @@ describe('prominent API hooks', () => {
// Keep the request in flight so the bound-keyed cache stays the placeholder.
setProcedure('common.essentialConsts', { mode: 'pending' })
setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 111 }))
setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 222 }))
setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, boundId: 8, freeDeliveryThreshold: 222 }))
seedRegion(REGION_1 as any, 8)
const { element, result } = makeProbe(() => useGetEssentialConsts())
@ -165,6 +165,43 @@ describe('prominent API hooks', () => {
expect(result.current.data!.freeDeliveryThreshold).not.toBe(111)
})
it('API-20: switching bounds never persists the previous bound snapshot under the new key', async () => {
// The request never settles, so the only data the hook can hold for bound 8
// is whatever was carried over from bound 7.
setProcedure('common.essentialConsts', { mode: 'pending' })
setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, boundId: 7, freeDeliveryThreshold: 111 }))
const { element, result } = makeProbe(() => useGetEssentialConsts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.freeDeliveryThreshold).toBe(111))
await flush(2)
act(() => {
useRegionStore.getState().setRegion(REGION_1 as any, 8)
})
await flush(2)
// Before the fix the b7 placeholder was written to essential_consts_b8 on
// the switch render, leaving bound 8 with bound 7's fees after a failure.
expect(secureSnapshot().essential_consts_b8).toBeUndefined()
})
it('API-21: a snapshot stored under the wrong bound is ignored', async () => {
setProcedure('common.essentialConsts', { mode: 'pending' })
setSecureItem(
'essential_consts_b8',
JSON.stringify({ ...CONSTS, boundId: 7, freeDeliveryThreshold: 111 })
)
seedRegion(REGION_1 as any, 8)
const { element, result } = makeProbe(() => useGetEssentialConsts())
renderWithProviders(element, { auth: false })
await flush(2)
expect(result.current.data).toBeUndefined()
})
it('API-07: builds the versioned products CDN URL', async () => {
setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE)

View file

@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 17.1 — the saved-address list
* (`app/(drawer)/(tabs)/me/addresses/index.tsx`, ADDR-01..20).
* (`app/(drawer)/(tabs)/me/addresses/index.tsx`, ADDR-01..21).
*
* `AddressForm` has its own suite (ADDRF-*), so this file only exercises the
* list: loading/error/empty states, the card actions and the modal wiring.
@ -105,7 +105,7 @@ async function emitFocus() {
})
}
describe('Addresses (ADDR-01..ADDR-20)', () => {
describe('Addresses (ADDR-01..ADDR-21)', () => {
beforeEach(() => {
resetAllMocks()
mockFocusCallbacks.clear()
@ -371,7 +371,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
expect(getByText('📍 45 Office Street, Hyderabad, Telangana')).toBeTruthy()
})
it('ADDR-20: a Google Maps address passes coords as undefined to the form', async () => {
it('ADDR-20: a Google Maps address keeps its saved coordinates for editing', async () => {
const mapped = {
...S2,
googleMapsUrl: 'https://maps.google.com/?q=18,79',
@ -384,6 +384,26 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
fireEvent.press(view.getByTestId('address-edit-12'))
await flush()
const values = view.UNSAFE_getByType(AddressForm).props.initialValues
expect(values.googleMapsUrl).toBe('https://maps.google.com/?q=18,79')
expect(values.latitude).toBe(18)
expect(values.longitude).toBe(79)
})
it('ADDR-21: a vague-backfilled address withholds its placeholder coordinates', async () => {
const mapped = {
...S2,
googleMapsUrl: 'https://maps.google.com/?q=18,79',
latitude: 16.750504,
longitude: 77.993621,
vagueBackfilledCoords: true,
}
setAddresses([mapped])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-edit-12'))
await flush()
const values = view.UNSAFE_getByType(AddressForm).props.initialValues
expect(values.googleMapsUrl).toBe('https://maps.google.com/?q=18,79')
expect(values.latitude).toBeUndefined()

View file

@ -79,7 +79,12 @@ export const useGetEssentialConsts = () => {
if (cancelled) return
if (raw) {
try {
setInitialData(JSON.parse(raw) as DiscoveryData)
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
}
@ -91,19 +96,26 @@ export const useGetEssentialConsts = () => {
}, [boundId])
// The backend resolves the flat payload for a single bound. tRPC includes the
// input in the query key, so switching bounds refetches discovery.
// 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: initialData,
placeholderData: placeholder,
})
// Persist the latest response under this bound's key.
// 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) {
writeEssentialConstsSnapshot(boundId, JSON.stringify(query.data))
}
}, [query.data, boundId])
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 }
}

View file

@ -17,6 +17,7 @@ type Address = Pick<
latitude?: number | null
longitude?: number | null
googleMapsUrl?: string | null
vagueBackfilledCoords?: boolean | null
}
const formatAddress = (addr: Address) => {
@ -245,10 +246,12 @@ function AddressesPage() {
city: editingAddress.city,
state: editingAddress.state,
isDefault: editingAddress.isDefault,
latitude: editingAddress.googleMapsUrl
// Preserve the saved location; only migration-backfilled
// placeholder coordinates are withheld.
latitude: editingAddress.vagueBackfilledCoords
? undefined
: editingAddress.latitude ?? undefined,
longitude: editingAddress.googleMapsUrl
longitude: editingAddress.vagueBackfilledCoords
? undefined
: editingAddress.longitude ?? undefined,
googleMapsUrl: editingAddress.googleMapsUrl ?? undefined,

View file

@ -8977,3 +8977,235 @@ Planned diff:
* APROD-79: a regional admin cannot change a global product's structure (403).
* APROD-80: a regional admin cannot delete a global product's images (403).
- apps/backend/API-TEST-CASES.md: register APROD-78/79/80.
[2026-10-24 14:06:23 IST] Scope stale slot cleanup to the creating region (review finding #2).
Cause: staleSlotsCleanup() selected the 20 newest slot ids globally and cleared
the 20th slot's skuIds. Creating slots in region A could empty an active slot in
region B without regenerating B's cache.
Planned diff:
- packages/db_helper_sqlite/src/admin-apis/slots.ts
* staleSlotsCleanup(regionId: number): the 20-row window is filtered by
delivery_slot_info.region_id; the update also matches region_id.
- apps/backend/src/trpc/apis/admin-apis/apis/slots.ts
* createSlot calls staleSlotsCleanup(ctx.staffUser.regionId).
- apps/backend/tests/unit/slots-create-cleanup.test.ts
* assert cleanup receives the caller's region id.
No change to packages/db_helper_postgres (abandoned).
[2026-10-24 14:08:50 IST] Stop the address edit form from relocating a saved address (review finding #4).
Cause: AddressForm's device-location effect runs in edit mode too. The caller
omits latitude/longitude whenever the saved address has a googleMapsUrl, so
currentLocation stayed null and the effect attached the device coords; saving
then replaced the address's location/region.
Planned diff:
- apps/user-ui/src/components/AddressForm.tsx
* the automatic device-location attach effect returns early when isEdit.
* resolvedRegion initialises from initialValues.regionId first (the saved
address's town), falling back to the browsing region.
- apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx
* Address type + vagueBackfilledCoords.
* pass stored latitude/longitude unless the row is vague-backfilled (drop the
googleMapsUrl condition), so the edit form preserves the real location.
- apps/web-ui/src/routes/me.addresses.tsx: mirror the caller change.
- apps/user-ui/tests/pages/addresses.test.tsx
* ADDR-20 now expects the saved coords; ADDR-21 covers vague backfills.
- apps/user-ui/tests/components/address-form.test.tsx
* ADDRF-38: editing resolves saved coords, never the device location.
* ADDRF-39: editing keeps the saved town over the browsing town.
- apps/user-ui/JEST-TEST-CASES.md: register ADDR-21 and ADDRF-38/39.
[2026-10-24 14:13:25 IST] Fix wrong-bound essential-consts snapshot writes (review finding #6).
Cause: placeholderData is the previous bound's snapshot on the render where
boundId changes. The persistence effect then writes query.data (the placeholder)
under the NEW bound's key. A failed/aborted fetch leaves the wrong snapshot
until it is overwritten, so the next launch can hydrate another bound's fees,
region identity and cache versions.
Planned diff:
- apps/user-ui/src/hooks/prominent-api-hooks.ts
* hydrate only a snapshot whose payload.boundId matches the key.
* pass placeholderData only when initialData.boundId === boundId.
* persist only non-placeholder data whose data.boundId === boundId.
- apps/web-ui/src/hooks/prominent-api-hooks.ts: same guards (localStorage).
- apps/user-ui/tests/lib/prominent-api-hooks.test.tsx
* API-06 fixture gains the matching boundId (b8).
* API-20: switching bounds never writes the previous snapshot under the new key.
* API-21: a snapshot stored under the wrong bound is ignored.
- apps/user-ui/JEST-TEST-CASES.md: register API-20/21.
No reload/refetch is added: the tRPC input already keys the query per bound.
[2026-10-24 14:18:30 IST] Split suspension writes: superadmin -> product_skus.is_suspended, regional admin -> product_market_stats.is_suspended_in_region (review finding #7).
Cause: a regional admin editing one of their own regional products wrote the
"Suspend SKU" checkbox to product_skus.is_suspended (the global/superadmin
kill-switch), while is_suspended_in_region was ignored on that path. Only the
global-product market path honoured the regional flag.
Planned diff:
- packages/shared/types/admin.ts: CreateSkuInput + isSuspendedInRegion?.
- packages/db_helper_sqlite/src/admin-apis/product.ts
* createProduct: structural isSuspended only when regionId == null; the
region's market row carries isSuspendedInRegion (legacy isSuspended input is
honoured for a regional create).
* updateProduct: regional edits never set product_skus.isSuspended (they only
clear a legacy true while folding it into the region's flag); they write
isSuspendedInRegion into the region's market row (omitted -> keep).
* global-product structural edits (regionId null) still write isSuspended.
* new-SKU inserts follow the same split.
* combo-suspension guard checks the flag that the caller can write.
- apps/backend/src/trpc/apis/admin-apis/apis/product.ts: createProduct schema
accepts/passes isSuspendedInRegion.
- admin-ui + admin-web ProductForm: label "Suspend in my region".
- admin-ui/web edit + add pages: the toggle reads/writes isSuspendedInRegion
(legacy structural suspensions are shown as the region's flag on edit and are
folded into is_suspended_in_region on the next regional save).
- tests:
* backend APROD-41 now asserts the regional flag is persisted.
* new APROD-81: a regional update cannot set the global flag.
* new APROD-82: a regional create marks suspension on the region flag.
* admin-ui APEDIT-20: the regional suspend toggle sends isSuspendedInRegion.
* API-TEST-CASES.md / JEST-TEST-CASES.md updated.
Superadmin global-products API/UI unchanged (already global column).
[2026-10-24 14:28:47 IST] Make reserved-coupon redemption atomic on D1 (review finding #8).
Cause: redeemReservedCoupon ran inside the repo's db.transaction wrapper, which
is a pass-through (D1 has no interactive transactions). The reserved row was
marked redeemed before the coupon insert; a failure (e.g. coupons.coupon_code
collision) left the secret consumed without issuing a coupon.
Planned diff:
- packages/db_helper_sqlite/src/user-apis/coupon.ts
* redeemReservedCoupon uses one db.batch (D1's atomic unit) with:
1. the conditional claim update (returning id),
2. INSERT ... SELECT into coupons guarded by the same claimed row,
3. INSERT ... SELECT into coupon_applicable_users via the reserved row.
* a failed insert rolls the claim back; a lost race inserts nothing and
returns null; the coupon is fetched after the batch for the response.
- apps/backend/tests/api/user-coupon.test.ts
* UCOUP-21: a coupon-code collision rejects the redemption and leaves the
reserved coupon unredeemed.
- apps/backend/API-TEST-CASES.md: register UCOUP-21.
No global change to the db.transaction wrapper.
[2026-10-24 14:35:59 IST] Count global products on global store cards (review finding #14).
Cause: getStoreSummaries filtered active SKUs with product.regionId === regionId,
excluding every global product (regionId null). A global store with a populated
global catalogue therefore published productCount 0 / no sample products, while
its detail document (which already unions globals) listed them.
Planned diff:
- packages/db_helper_sqlite/src/user-apis/stores.ts
* getStoreSummaries counts SKUs whose product region is the requested region
OR null (global), matching getStoreDetail and the store visibility rule.
- apps/backend/tests/api/cache-stores.test.ts
* CACHE-113: a global store counts/samples its global products and its
productCount equals the detail document's products length.
- apps/backend/API-TEST-CASES.md: register CACHE-113.
[2026-10-24 14:37:45 IST] Elevate a combo's regional component products too (review finding #13).
Cause: elevateProductToGlobal cleared only the product's own region and seeded
only its own SKUs. A combo elevated from region A kept regional-A components, so
region B's cache published the global combo with an empty comboItems list.
Behaviour: the superadmin's Confirm action first asks for the dependent regional
products (existing shadcn confirm dialog), lists them, and only then elevates.
The backend elevates the whole set regardless of the UI.
Planned diff:
- packages/db_helper_sqlite/src/superadmin-apis/products.ts
* getElevationDependents(productId): cycle-safe BFS over product_combos,
returning the regional component products (id/name/region).
* elevateProductToGlobal: one db.batch seeds every region's market rows from
each product's source region, then clears region_id / attaches the whole set
to the chosen global store. The old try/catch compensation is removed (batch
is atomic on D1).
- packages/db_helper_sqlite/index.ts: export getElevationDependents.
- apps/backend/src/trpc/apis/superadmin-apis/apis/products.ts:
* new elevationDependents query (superadmin).
- apps/superadmin-ui/src/routes/global-products.tsx:
* doElevate fetches the dependents, shows confirm() listing them + the target
store, and aborts when cancelled (before any write).
- apps/backend/tests/api/superadmin-elevate.test.ts
* SPROD-15: elevationDependents lists a combo's regional components.
* SPROD-16: elevating a combo elevates its components and seeds their market
rows for other regions.
- apps/backend/API-TEST-CASES.md: register SPROD-15/16.
[2026-10-24 14:55:51 IST] Keep region-scoped tags on global store detail caches (review finding #15).
Cause: getTagsByStoreId inferred the region from the store row. A global store
has region_id NULL, so it returned [] and its per-store cache document lost every
category tag attached in the browsing region.
Planned diff:
- apps/backend/src/stores/product-tag-store.ts
* getTagsByStoreId(storeId, regionId): use the caller's browsing region for
getAllProductTags instead of looking the region up from the store.
* drop the now-unused db import.
- apps/backend/src/trpc/apis/user-apis/apis/stores.ts
* scaffoldStoreWithProducts passes its regionId to getTagsByStoreId.
- apps/backend/tests/api/cache-stores.test.ts
* CACHE-114: a global store's detail keeps a tag attached in the test region.
- apps/backend/API-TEST-CASES.md: register CACHE-114.
[2026-10-24 14:58:52 IST] Read global SKUs' market data from the caller's region (review finding #16).
Cause: getAllSkusSummary selected product_market_stats with
marketStatsForRegion(sku.marketStats, sku.product.regionId). A global product's
region is null, so the admin SKU pickers showed price "0" and ignored the
region's is_suspended_in_region flag.
Planned diff:
- packages/db_helper_sqlite/src/user-apis/product.ts
* getAllSkusSummary resolves market stats with regionId when supplied, falling
back to the product's own region only for the unscoped call.
- apps/backend/tests/api/common-product.test.ts
* COMMON-17: region 2's price for a global SKU is used in region 2 while
region 1 keeps its own.
* COMMON-18: a global SKU suspended in region 2 is filtered there but still
listed in region 1.
- apps/backend/API-TEST-CASES.md: register COMMON-17/18.
[2026-10-24 15:01:09 IST] Chunk the region fan-out market-stat inserts (review finding #17).
Cause: createProduct and the update path's new-SKU branch inserted one
product_market_stats row per region in a single statement. At 12 regions that is
108 bound parameters, over D1's 100-parameter limit, so global product creation /
SKU addition failed after the product/SKU rows were written.
Planned diff:
- packages/db_helper_sqlite/src/admin-apis/product.ts
* MARKET_STATS_INSERT_CHUNK_SIZE = 11 (9 params per row; D1 caps at 100).
* createProduct and updateProduct's new-SKU branch insert the per-region rows
through runBatched.
- apps/backend/tests/api/superadmin-global-products.test.ts
* SGPROD-04/07/10 no longer accept the bind-cap 500 (chunking removes it).
* SGPROD-16: creating a global product with >=12 regions seeds every region.
* SGPROD-17: adding a SKU to a global product with >=12 regions seeds every region.
- apps/backend/API-TEST-CASES.md: register SGPROD-16/17.
[2026-10-24 15:35 IST] Fix redeemReservedCoupon batch items (test failure follow-up).
The first batch version used db.run(sql...) raw statements inside db.batch. D1's
batch path calls preparedQuery.stmt.bind(...), which is undefined for raw
queries, so every redemption crashed with "Cannot read properties of undefined
(reading 'bind')" (5 failures in user-coupon.test.ts, incl. the previously
passing redeem/race cases). Rewrote both writes as query-builder
insert().select() statements (selected fields follow the table column order;
raw literals use .as(alias)), which are proper batchable RunnableQuery items.
Verified: user-coupon suite 21/21 green, including new UCOUP-21 (collision
rolls the claim back) and UCOUP-18 (two-user race still resolves 1/1).
[2026-10-24 16:10 IST] Test-run follow-ups for findings #8, #13, #16, #17.
- Finding #8 (redeemReservedCoupon batch): the first batch version used raw
db.run(sql...) items. D1's batch path needs prepared statements, so every
redemption crashed ("Cannot read properties of undefined (reading 'bind')").
Rewrote both writes as query-builder insert().select() (raw literals use
.as(alias)). user-coupon 21/21 green incl. UCOUP-18 (race) and UCOUP-21.
- Finding #13 (elevate seed): same raw-in-batch crash in the market-row seed
(surfaced via COMMON-17/18 fixtures). Rewrote as insert().select() with
inner joins + crossJoin(regions) and a NOT EXISTS guard.
- SPROD-16 assertion fixes: region-2 scaffold prices are numbers, not strings;
scaffoldCache('products') rows carry no comboItems, so the regression tail now
asserts elevationDependents is empty post-elevation (no regional component
left for B's cache filter to drop) instead.
- user-ui ADDRF-38 rewrite: the shared resolveRegionByLocation spy also sees
useRegion's startup check, so the test now asserts the submitted update
payload keeps the saved coordinates instead of asserting on the spy.

View file

@ -458,6 +458,7 @@ export {
export {
listAllProducts,
elevateProductToGlobal,
getElevationDependents,
} from './src/superadmin-apis/products'
export {

View file

@ -34,6 +34,10 @@ import type { InferSelectModel } from 'drizzle-orm'
const SKU_INSERT_CHUNK_SIZE = 100 // 6 params per SKU row
const FEATURE_INSERT_CHUNK_SIZE = 200 // 3 params per feature row
const COMBO_ITEM_INSERT_CHUNK_SIZE = 400 // 2 params per combo-item row
// The market-stats insert fans out over every region, so it is sized for D1's
// tighter 100-bound-parameter cap: 9 params per row (the auto id is literal
// NULL), i.e. at most 11 regions per statement.
const MARKET_STATS_INSERT_CHUNK_SIZE = 11
// product_combos has a UNIQUE index on (comboSkuId, skuId) — drop duplicates
// (by skuId) before inserting so a repeated pick doesn't fail the insert.
@ -459,7 +463,9 @@ export async function createProduct(input: CreateProductInput, regionId: number
images: sku.images ?? null,
isComboOnly: sku.isComboOnly ?? false,
isDeleted: sku.isDeleted ?? false,
isSuspended: sku.isSuspended ?? false,
// The structural kill-switch is superadmin-owned. A regional create
// stores its suspension in the region's market row below.
isSuspended: regionId == null ? (sku.isSuspended ?? false) : false,
}))
).returning()
})
@ -469,16 +475,23 @@ export async function createProduct(input: CreateProductInput, regionId: number
const skuRow = skuRows[i]
const sku = skus[i]
await tx.insert(productMarketStats).values(targetRegionIds.map((rid) => ({
skuId: skuRow.id,
regionId: rid,
marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null,
ourPrice: sku.price != null ? String(sku.price) : '0',
isFlashAvailable: sku.isFlashAvailable ?? false,
flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null,
isOutOfStock: sku.isOutOfStock ?? false,
isOffer: sku.isOffer ?? false,
})))
await runBatched(tx, targetRegionIds, MARKET_STATS_INSERT_CHUNK_SIZE, async (t, regionChunk) => {
await t.insert(productMarketStats).values(regionChunk.map((rid) => ({
skuId: skuRow.id,
regionId: rid,
marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null,
ourPrice: sku.price != null ? String(sku.price) : '0',
isFlashAvailable: sku.isFlashAvailable ?? false,
flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null,
isOutOfStock: sku.isOutOfStock ?? false,
// Global creates seed every region unsuspended (the structural flag is
// the global switch); a regional create owns only its own row.
isSuspendedInRegion: regionId == null
? false
: (sku.isSuspendedInRegion ?? sku.isSuspended ?? false),
isOffer: sku.isOffer ?? false,
})))
})
if (sku.features && sku.features.length > 0) {
await runBatched(tx, sku.features, FEATURE_INSERT_CHUNK_SIZE, async (t, chunk) => {
@ -619,9 +632,14 @@ export async function updateProduct(regionId: number | null, id: number, input:
'Combo SKU'
)
const skusBeingSuspended = skus.filter(
(sku: any) => sku.isSuspended && sku.id != null && existingSkuIdSet.has(sku.id)
)
// Only the flag this caller can actually write counts: the superadmin owns
// the structural flag, a region owns its market row.
const skusBeingSuspended = skus.filter((sku: any) => {
if (sku.id == null || !existingSkuIdSet.has(sku.id)) return false
return regionId == null
? sku.isSuspended === true
: sku.isSuspendedInRegion === true
})
if (skusBeingSuspended.length > 0) {
const suspendingIds = skusBeingSuspended.map((sku: any) => sku.id)
const comboMemberships = await db.query.productCombos.findMany({
@ -676,7 +694,15 @@ export async function updateProduct(regionId: number | null, id: number, input:
name: sku.name ?? null,
images: sku.images ?? null,
isComboOnly: sku.isComboOnly ?? false,
isSuspended: sku.isSuspended ?? false,
// Global suspension is the superadmin's kill-switch. A regional
// edit writes the region's flag in market stats below; when it
// supplies that flag, any legacy structural suspension is folded
// into it (a regional product has no global owner).
...(regionId == null
? { isSuspended: sku.isSuspended ?? false }
: sku.isSuspendedInRegion !== undefined
? { isSuspended: false }
: {}),
...(sku.isDeleted !== undefined && { isDeleted: sku.isDeleted }),
})
.where(eq(productSkus.id, sku.id))
@ -690,6 +716,10 @@ export async function updateProduct(regionId: number | null, id: number, input:
isFlashAvailable: sku.isFlashAvailable ?? false,
flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null,
isOutOfStock: sku.isOutOfStock ?? false,
// Region-owned suspension. Omitted -> keep the current value.
...(sku.isSuspendedInRegion !== undefined && {
isSuspendedInRegion: sku.isSuspendedInRegion,
}),
isOffer: sku.isOffer ?? false,
}
const existingMarketStats = await tx.query.productMarketStats.findFirst({
@ -744,19 +774,24 @@ export async function updateProduct(regionId: number | null, id: number, input:
images: sku.images ?? null,
isComboOnly: sku.isComboOnly ?? false,
isDeleted: sku.isDeleted ?? false,
isSuspended: sku.isSuspended ?? false,
isSuspended: regionId == null ? (sku.isSuspended ?? false) : false,
}).returning()
await tx.insert(productMarketStats).values(targetRegionIds.map((rid) => ({
skuId: newSku.id,
regionId: rid,
marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null,
ourPrice: sku.price != null ? String(sku.price) : '0',
isFlashAvailable: sku.isFlashAvailable ?? false,
flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null,
isOutOfStock: sku.isOutOfStock ?? false,
isOffer: sku.isOffer ?? false,
})))
await runBatched(tx, targetRegionIds, MARKET_STATS_INSERT_CHUNK_SIZE, async (t, regionChunk) => {
await t.insert(productMarketStats).values(regionChunk.map((rid) => ({
skuId: newSku.id,
regionId: rid,
marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null,
ourPrice: sku.price != null ? String(sku.price) : '0',
isFlashAvailable: sku.isFlashAvailable ?? false,
flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null,
isOutOfStock: sku.isOutOfStock ?? false,
isSuspendedInRegion: regionId == null
? false
: (sku.isSuspendedInRegion ?? sku.isSuspended ?? false),
isOffer: sku.isOffer ?? false,
})))
})
if (sku.features && sku.features.length > 0) {
await runBatched(tx, sku.features, FEATURE_INSERT_CHUNK_SIZE, async (t, chunk) => {

View file

@ -158,26 +158,29 @@ export async function getActiveSlotsWithProducts(regionId: number, limit: number
}))
}
export async function staleSlotsCleanup(): Promise<number> {
// Get the 20 most recent slot IDs
export async function staleSlotsCleanup(regionId: number): Promise<number> {
// The 20-slot window is per region: one region's slot activity must never
// clear another region's product associations (and B's cache is not rebuilt
// by A's createSlot).
const recentSlots = await db
.select({ id: deliverySlotInfo.id })
.from(deliverySlotInfo)
.where(eq(deliverySlotInfo.regionId, regionId))
.orderBy(desc(deliverySlotInfo.id))
.limit(20)
if (recentSlots.length < 20) {
return 0 // Less than 20 slots exist, nothing to clean
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 all slots older than threshold
const result = await db
// Clear productIds for the slot that just fell out of this region's window.
await db
.update(deliverySlotInfo)
.set({ skuIds: [] })
.where(eq(deliverySlotInfo.id, threshold))
.where(and(eq(deliverySlotInfo.id, threshold), eq(deliverySlotInfo.regionId, regionId)))
return 1
}

View file

@ -1,6 +1,6 @@
import { db } from '../db/db_index'
import { productInfo } from '../db/schema'
import { and, eq, isNull, like, or, sql } from 'drizzle-orm'
import { productCombos, productInfo, productMarketStats, productSkus, regions } from '../db/schema'
import { and, eq, inArray, like, or, sql } from 'drizzle-orm'
import { isGlobalStore } from './global-stores'
const productWith = {
@ -57,11 +57,81 @@ export async function listAllProducts(opts: ListAllProductsOptions = {}) {
return { products: rows, total: Number(countRows[0]?.count ?? 0) }
}
export interface ElevationDependent {
id: number
name: string
regionId: number
regionName: string | null
}
/**
* Elevate a regional product to a global one attached to `globalStoreId`:
* clears its region and seeds each OTHER region's market-stats row from the
* source region (price/stock/offer/flash copied; region-suspension reset to
* false). The source region's own row is kept unchanged.
* The regional products a combo needs in order to become global: walk
* product_combos from the product's SKUs to each component SKU's product, then
* recurse through combos (cycle-safe). A component product that is already
* global is traversed but not reported.
*/
export async function getElevationDependents(productId: number): Promise<ElevationDependent[]> {
const root = await db.query.productInfo.findFirst({
where: eq(productInfo.id, productId),
columns: { id: true, regionId: true },
})
if (!root) throw new Error('Product not found')
if (root.regionId == null) return []
const dependents = new Map<number, ElevationDependent>()
const visited = new Set<number>([productId])
let frontier = [productId]
while (frontier.length > 0) {
const skuRows = await db
.select({ id: productSkus.id })
.from(productSkus)
.where(inArray(productSkus.productId, frontier))
if (skuRows.length === 0) break
const comboRows = await db.query.productCombos.findMany({
where: inArray(productCombos.comboSkuId, skuRows.map((row) => row.id)),
with: {
sku: {
with: {
product: {
columns: { id: true, name: true, regionId: true },
with: { region: { columns: { name: true } } },
},
},
},
},
})
const next: number[] = []
for (const row of comboRows) {
const componentProduct = row.sku?.product
if (!componentProduct || visited.has(componentProduct.id)) continue
visited.add(componentProduct.id)
next.push(componentProduct.id)
if (componentProduct.regionId == null) continue // already global
dependents.set(componentProduct.id, {
id: componentProduct.id,
name: componentProduct.name,
regionId: componentProduct.regionId,
regionName: componentProduct.region?.name ?? null,
})
}
frontier = next
}
return [...dependents.values()]
}
/**
* Elevate a regional product to a global one attached to `globalStoreId`.
* Combo dependencies (regional component products) are elevated in the same
* operation: each region's market row is seeded from that product's source
* region (price/stock/offer/flash copied; region-suspension reset to false),
* then every product in the set becomes global on the chosen store.
*
* D1 has no interactive transactions, so the set is written with `db.batch`:
* the seed and the region/store update commit or roll back together.
*/
export async function elevateProductToGlobal(productId: number, globalStoreId: number) {
const product = await db.query.productInfo.findFirst({
@ -72,46 +142,51 @@ export async function elevateProductToGlobal(productId: number, globalStoreId: n
if (product.regionId == null) throw new Error('Product is already global')
if (!(await isGlobalStore(globalStoreId))) throw new Error('Target store is not a global store')
const sourceRegionId = product.regionId
const dependents = await getElevationDependents(productId)
const productIds = [productId, ...dependents.map((dependent) => dependent.id)]
try {
return await db.transaction(async (tx) => {
await tx
.update(productInfo)
.set({ regionId: null, storeId: globalStoreId })
.where(eq(productInfo.id, productId))
await tx.run(sql`
INSERT INTO product_market_stats
(sku_id, region_id, market_price, our_price, is_flash_available, flash_price, is_out_of_stock, is_suspended_in_region, is_offer)
SELECT ms.sku_id, r.id, ms.market_price, ms.our_price, ms.is_flash_available, ms.flash_price,
ms.is_out_of_stock, false, ms.is_offer
FROM product_market_stats ms
CROSS JOIN regions r
WHERE ms.region_id = ${sourceRegionId}
AND ms.sku_id IN (SELECT id FROM product_skus WHERE product_id = ${productId})
AND NOT EXISTS (
SELECT 1 FROM product_market_stats x WHERE x.sku_id = ms.sku_id AND x.region_id = r.id
// D1 has no interactive transactions, so the set is written with `db.batch`:
// the seed and the region/store update commit or roll back together. The seed
// must be a query-builder `insert().select()` — raw `db.run(sql...)` has no
// prepared statement and crashes the D1 batch path.
await db.batch([
// Runs first: it reads each product's source region from product_info, so it
// must happen before the region is cleared below.
db.insert(productMarketStats).select(
db
.select({
id: sql`NULL`.as('id'),
skuId: productMarketStats.skuId,
regionId: regions.id,
marketPrice: productMarketStats.marketPrice,
ourPrice: productMarketStats.ourPrice,
isFlashAvailable: productMarketStats.isFlashAvailable,
flashPrice: productMarketStats.flashPrice,
isOutOfStock: productMarketStats.isOutOfStock,
isSuspendedInRegion: sql`0`.as('is_suspended_in_region'),
isOffer: productMarketStats.isOffer,
})
.from(productMarketStats)
.innerJoin(productSkus, eq(productMarketStats.skuId, productSkus.id))
.innerJoin(productInfo, eq(productSkus.productId, productInfo.id))
.crossJoin(regions)
.where(
and(
inArray(productInfo.id, productIds),
eq(productMarketStats.regionId, productInfo.regionId),
sql`not exists (select 1 from product_market_stats x where x.sku_id = ${productMarketStats.skuId} and x.region_id = ${regions.id})`
)
`)
)
),
db
.update(productInfo)
.set({ regionId: null, storeId: globalStoreId })
.where(inArray(productInfo.id, productIds)),
])
const updated = await tx.query.productInfo.findFirst({
where: eq(productInfo.id, productId),
with: productWith,
})
return updated ?? null
})
} catch (error) {
// Compensate: D1 may leave the region_id change committed when the seed
// fails, so put the product back into its original region/store.
try {
await db
.update(productInfo)
.set({ regionId: sourceRegionId, storeId: product.storeId ?? null })
.where(and(eq(productInfo.id, productId), isNull(productInfo.regionId)))
} catch (cleanupError) {
console.error('Failed to revert elevateProductToGlobal', productId, cleanupError)
}
throw error
}
const updated = await db.query.productInfo.findFirst({
where: eq(productInfo.id, productId),
with: productWith,
})
return updated ?? null
}

View file

@ -5,7 +5,7 @@ import {
coupons,
reservedCoupons,
} from '../db/schema'
import { and, eq, gt, isNull, or } from 'drizzle-orm'
import { and, eq, gt, isNull, or, sql } from 'drizzle-orm'
import type { InferSelectModel } from 'drizzle-orm'
import type { UserCoupon, UserCouponApplicableUser, UserCouponUsage, UserCouponWithRelations } from '@packages/shared'
@ -120,11 +120,25 @@ export async function getReservedCouponByCode(secretCode: string): Promise<Reser
}
export async function redeemReservedCoupon(userId: number, reservedCoupon: ReservedCouponRow): Promise<UserCoupon | null> {
return db.transaction(async (tx) => {
// D1 has no interactive transactions (the repo's `db.transaction` wrapper is a
// pass-through), so use `db.batch`: D1 executes the statements as one
// transaction and rolls every one of them back if any fails. Issuance is tied
// to the claim by the guarded INSERTs, so a failure (e.g. a coupon_code
// collision) leaves the secret unredeemed instead of burning it.
//
// Every batch item must be a query-builder statement: raw `db.run(sql...)`
// has no prepared statement and crashes the D1 batch path (`stmt` is
// undefined), so both inserts are `insert().select()` over the reserved row.
const claimedGuard = and(
eq(reservedCoupons.id, reservedCoupon.id),
eq(reservedCoupons.isRedeemed, true),
eq(reservedCoupons.redeemedBy, userId)
)
const [claimed] = await db.batch([
// Claim the secret before creating anything: the conditional update closes the gap
// between getReservedCouponByCode and this write, so two customers racing on the same
// code can never both receive a coupon. A null return means the race was lost.
const claimed = await tx
db
.update(reservedCoupons)
.set({
isRedeemed: true,
@ -137,32 +151,56 @@ export async function redeemReservedCoupon(userId: number, reservedCoupon: Reser
eq(reservedCoupons.isRedeemed, false)
)
)
.returning({ id: reservedCoupons.id })
.returning({ id: reservedCoupons.id }),
if (claimed.length === 0) return null
// Only the caller that won the claim inserts a coupon. The values are copied
// from the reserved row inside the same transaction, so the display object
// passed in can never affect what is issued. Selected fields follow the
// coupons column order positionally.
db.insert(coupons).select(
db
.select({
id: sql`NULL`.as('id'),
regionId: reservedCoupons.regionId,
couponCode: reservedCoupons.couponCode,
isUserBased: sql`1`.as('is_user_based'),
discountPercent: reservedCoupons.discountPercent,
flatDiscount: reservedCoupons.flatDiscount,
minOrder: reservedCoupons.minOrder,
skuIds: reservedCoupons.skuIds,
createdBy: reservedCoupons.createdBy,
maxValue: reservedCoupons.maxValue,
isApplyForAll: sql`0`.as('is_apply_for_all'),
validTill: reservedCoupons.validTill,
maxLimitForUser: reservedCoupons.maxLimitForUser,
isInvalidated: sql`0`.as('is_invalidated'),
exclusiveApply: reservedCoupons.exclusiveApply,
isFirstOrderOnly: reservedCoupons.isFirstOrderOnly,
createdAt: sql`CURRENT_TIMESTAMP`.as('created_at'),
})
.from(reservedCoupons)
.where(claimedGuard)
),
const [coupon] = await tx.insert(coupons).values({
regionId: reservedCoupon.regionId as number,
couponCode: reservedCoupon.couponCode,
isUserBased: true,
discountPercent: reservedCoupon.discountPercent,
flatDiscount: reservedCoupon.flatDiscount,
minOrder: reservedCoupon.minOrder,
skuIds: reservedCoupon.skuIds,
maxValue: reservedCoupon.maxValue,
isApplyForAll: false,
validTill: reservedCoupon.validTill,
maxLimitForUser: reservedCoupon.maxLimitForUser,
exclusiveApply: reservedCoupon.exclusiveApply,
isFirstOrderOnly: reservedCoupon.isFirstOrderOnly,
createdBy: reservedCoupon.createdBy,
}).returning()
// The coupon's code is unique, so this links exactly the row inserted above.
db.insert(couponApplicableUsers).select(
db
.select({
id: sql`NULL`.as('id'),
couponId: coupons.id,
userId: sql`${userId}`.as('user_id'),
})
.from(coupons)
.innerJoin(reservedCoupons, eq(coupons.couponCode, reservedCoupons.couponCode))
.where(claimedGuard)
),
])
await tx.insert(couponApplicableUsers).values({
couponId: coupon.id,
userId,
})
if (claimed.length === 0) return null
return mapCoupon(coupon)
const coupon = await db.query.coupons.findFirst({
where: eq(coupons.couponCode, reservedCoupon.couponCode),
})
return coupon ? mapCoupon(coupon) : null
}

View file

@ -345,7 +345,12 @@ export async function getAllSkusSummary(regionId: number | null = null): Promise
return skus
.filter((sku) => regionId == null || sku.product?.regionId === regionId || sku.product?.regionId == null)
.map((sku) => ({ sku, marketStats: marketStatsForRegion(sku.marketStats, sku.product?.regionId) }))
.map((sku) => ({
sku,
// The caller's region is authoritative for global SKUs too: their market
// row lives under the browsing region, not the (null) product region.
marketStats: marketStatsForRegion(sku.marketStats, regionId ?? sku.product?.regionId ?? null),
}))
.filter(({ sku, marketStats }) => !isSkuSuspended(sku.isSuspended, marketStats) && !sku.isDeleted)
.map(({ sku, marketStats }) => {
const featureValues = (sku.features || []).map((f) => f.featureValue)

View file

@ -24,7 +24,10 @@ export async function getStoreSummaries(regionId: number): Promise<UserStoreSumm
})
const activeSkus = skus.filter((sku) =>
!sku.isDeleted &&
sku.product?.regionId === regionId &&
// The region's own products plus global ones (a global store is visible from
// every region, so its global catalogue must count here too). This mirrors
// getStoreDetail's product query.
(sku.product?.regionId === regionId || sku.product?.regionId == null) &&
!isSkuSuspended(sku.isSuspended, marketStatsForRegion(sku.marketStats, regionId))
)

View file

@ -322,6 +322,8 @@ export interface CreateSkuInput extends SkuFlagCore {
marketPrice?: number | null
images?: string[] | null
flashPrice?: number | null
/** Region suspension (product_market_stats); valid for regional creates. */
isSuspendedInRegion?: boolean
features: SkuFeatureLike[]
comboItems?: CreateComboItemInput[]
}

View file

@ -0,0 +1,165 @@
# Unfixed issues — MULTI_REGION_I2
## 3. [P1] Pending scheduled orders become unfulfillable after three calendar days
**Location:** `packages/db_helper_sqlite/src/lib/order-items-archive.ts:224–233`
**Still present:** `listEligibleOrderIds` selects orders only by creation time:
```ts
sql`datetime(${orders.createdAt}) < datetime(${cutoff.toISOString()})`
```
It does not exclude orders that are still open (not delivered/cancelled) or whose
delivery slot is in the future. Once archived, `order_items` rows are deleted and
the order becomes read-only, so packaging/fulfilment operations hit the archived
path and return “not found”.
**Failure scenario:** An order is placed several days before its scheduled
delivery (or is simply still pending after three calendar days). The nightly
archive job moves its items into `orders.items_json`, after which the admin can
no longer package or fulfil it.
**Recommended fix:** Add a fulfilment guard to the archive query (and the `0006`
migration snapshot): skip orders whose status is not terminal and/or whose slot
delivery time is still in the future. Mirror the same window in the admin order
list so archived orders and open orders never overlap incorrectly.
---
## 5. [P2] Restarting can assign a saved cart to the wrong region
**Location:** `apps/user-ui/src/hooks/useRegion.ts:358–360, 383–385`
**Still present:** On startup, when `regionId == null`, both branches adopt the
resolved region “without clearing the cart”:
```ts
if (regionId == null) {
// First region of this launch — adopt it without clearing the cart.
setRegion(region, anchorAddress?.boundId ?? null)
}
```
The active cart is still persisted under unscoped keys (`cart_items` /
`flash_cart_items` — see `apps/user-ui/hooks/cart-query-hooks.tsx`), with no
recorded owning region.
**Failure scenario:** Shop in region B, leave items in the cart, terminate the
app, then restart where GPS/default address resolves to region A. B's cart is
adopted as A's cart. Switching back to B later stashes that cart under A and
restores B's older/empty snapshot, losing the latest B cart.
**Recommended fix:** Persist the owning region with the active cart (or add a
`cart_region` marker). During startup adoption, if the persisted cart belongs to
another region, stash it under that region before `setRegion`, and restore the
new region's snapshot.
---
## 9. [P2] Migration discards historical discount amounts
**Location:** `packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql:576–577`
**Still present:** The orders rebuild hard-codes the discount to `'0'`:
```sql
SELECT ..., o.`total_amount`, o.`delivery_charge`, '0', o.`readable_id`, ...
```
Both order-detail implementations read `orders.discount_amount` as the
authoritative discount, so every historical coupon discount disappears from
existing order bills after the migration.
**Recommended fix:** Backfill the real charged discount in the migration. It can
be derived from the pre-migration order/item totals (e.g. sum of item totals +
delivery charge − `total_amount`, clamped at 0), or copied from the old order
discount source if one exists. Historical orders must keep their final payable
amount unchanged.
---
## 10. [P2] Fractional prices produce different checkout and persisted totals
**Location:** `packages/shared/cart-pricing.ts:313–317`
**Still present:** `allocateBounded` floors each sub-order's discount capacity:
```ts
const limits = caps.map((cap) => Math.max(0, Math.floor(cap)))
```
`computeCouponStack` previews a discount on fractional prices, but
`computeCartPricing` can allocate less after flooring the per-sub-order caps.
**Failure scenario:** Two ₹99.50 sub-orders with a ₹199 flat coupon.
`computeCouponStack` previews ₹199 off, while `computeCartPricing` allocates ₹99
to each sub-order (₹198 total) and charges ₹1 more than the preview.
**Recommended fix:** Use one arithmetic model for previews and allocation —
either do all allocation in paise/minor units and round only at the boundary, or
make `computeCouponStack` apply the same per-cap flooring rule so the preview
matches the persisted totals exactly.
---
## 11. [P2] Newly created foreign-region addresses bypass region switching
**Location:** `apps/user-ui/components/CartAddressGate.tsx:129–132`;
`apps/user-ui/components/CheckoutAddressSelector.tsx:290–297`
**Still present:** Both success handlers accept a newly created address without
applying the region the address form resolved:
- `CartAddressGate` closes the form and refetches addresses.
- `CheckoutAddressSelector` closes the dialog, selects the new address id, and
invalidates queries.
The existing-address click path already routes through `confirmRegionSwitch`
(`CheckoutAddressSelector.tsx:116`); the create path does not.
**Failure scenario:** Browsing region A, the customer uses “Choose another
location” and saves an address in region B. The app keeps region A's products and
slots while selecting the B address, so checkout submits conflicting region /
address data and fails (or quotes the wrong products).
**Recommended fix:** Consume `AddressForm`'s resolved region on create. If it
differs from the browsing region, call the same `confirmRegionSwitch` flow used
for existing foreign addresses before selecting the new address (in both the gate
and the checkout selector).
---
## 12. [P2] Vendor snippets reject valid global SKUs
**Location:** `packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts:113–115, 202–203`
**Still present:** Both checks require the product's region to equal the staff
region:
```ts
const foreign = rows.filter((r: any) => r.product?.regionId !== regionId)
// ...
.filter((sku) => !sku.isDeleted && (regionId == null || sku.product?.regionId === regionId))
```
A global product's `regionId` is `null`, which `!== regionId`, so global SKUs are
rejected on snippet create/update and dropped from snippet listings. Slot
creation already allows global SKUs, so this is inconsistent.
**Failure scenario:** An admin creates a vendor snippet containing a global SKU
→ 400 “belongs to a different region”. Existing snippets that reference a SKU
that was later elevated stop displaying that product.
**Recommended fix:** Use the same region rule as slots:
`sku.product?.regionId == null || sku.product?.regionId === regionId`.
Update both `assertSnippetSkuIdsInRegion` and the listing filter.
---
## Verification notes
- Statuses above were verified by reading the current working tree.
- No test suites were run while producing this list.