Compare commits
2 commits
8889556bdf
...
0289c285c9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0289c285c9 | ||
|
|
bccc66372a |
50 changed files with 2164 additions and 481 deletions
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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: [],
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
)}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
)}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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: [],
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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 |
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -10,10 +10,9 @@ import {
|
|||
deleteGlobalProductById,
|
||||
} from '@/src/dbService'
|
||||
|
||||
const skuInput = z.object({
|
||||
const skuFields = {
|
||||
id: z.number().int().positive().optional(),
|
||||
name: z.string().optional().nullable(),
|
||||
price: z.number().nonnegative('Price must be positive'),
|
||||
marketPrice: z.number().optional().nullable(),
|
||||
images: z.array(z.string()).optional().default([]),
|
||||
isFlashAvailable: z.boolean().optional().default(false),
|
||||
|
|
@ -28,6 +27,21 @@ const skuInput = z.object({
|
|||
featureValue: z.string().min(1, 'Value is required'),
|
||||
})).min(1, 'At least one feature is required'),
|
||||
comboItems: z.array(z.object({ skuId: z.number().int().positive() })).optional(),
|
||||
}
|
||||
|
||||
const skuInput = z.object({
|
||||
...skuFields,
|
||||
price: z.number().nonnegative('Price must be positive'),
|
||||
})
|
||||
|
||||
/**
|
||||
* Editing an existing global SKU does not take a price: price is a create-time
|
||||
* seed and each region owns its market row afterwards (the structural update
|
||||
* never writes market data). A newly added SKU still needs its seed price.
|
||||
*/
|
||||
const skuUpdateInput = z.object({
|
||||
...skuFields,
|
||||
price: z.number().nonnegative('Price must be positive').optional(),
|
||||
})
|
||||
|
||||
export const superadminGlobalProductsRouter = router({
|
||||
|
|
@ -93,7 +107,19 @@ export const superadminGlobalProductsRouter = router({
|
|||
storeId: z.number().min(1, 'A global store is required'),
|
||||
incrementStep: z.number().optional().default(1),
|
||||
productType: z.enum(['item', 'combo']).optional().default('item'),
|
||||
skus: z.array(skuInput).min(1, 'At least one SKU is required'),
|
||||
skus: z.array(skuUpdateInput)
|
||||
.min(1, 'At least one SKU is required')
|
||||
.superRefine((skus, ctx) => {
|
||||
skus.forEach((sku, index) => {
|
||||
if (sku.id == null && sku.price == null) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: [index, 'price'],
|
||||
message: 'Price is required for a new SKU',
|
||||
})
|
||||
}
|
||||
})
|
||||
}),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
const { id, ...rest } = input
|
||||
|
|
|
|||
|
|
@ -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 }) => {
|
||||
|
|
|
|||
|
|
@ -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: {
|
||||
|
|
|
|||
|
|
@ -91,6 +91,44 @@ async function readProduct(admin: ApiClient, id: number): Promise<any> {
|
|||
return res.product
|
||||
}
|
||||
|
||||
/**
|
||||
* Round-trip an admin product read into the update payload the form sends.
|
||||
* Structural values are copied verbatim so a global-product edit passes the
|
||||
* regional guard unchanged.
|
||||
*/
|
||||
function updatePayloadFrom(product: any, skuOverrides: Record<string, any> = {}): any {
|
||||
return {
|
||||
id: Number(product.id),
|
||||
name: product.name,
|
||||
shortDescription: product.shortDescription ?? undefined,
|
||||
longDescription: product.longDescription ?? undefined,
|
||||
storeId: Number(product.storeId),
|
||||
incrementStep: product.incrementStep,
|
||||
productType: product.productType,
|
||||
skus: product.skus.map((sku: any) => ({
|
||||
id: Number(sku.id),
|
||||
name: sku.name,
|
||||
price: Number(sku.price),
|
||||
marketPrice: sku.marketPrice != null ? Number(sku.marketPrice) : null,
|
||||
images: sku.images ?? [],
|
||||
isFlashAvailable: !!sku.isFlashAvailable,
|
||||
flashPrice: sku.flashPrice != null ? Number(sku.flashPrice) : null,
|
||||
isOutOfStock: !!sku.isOutOfStock,
|
||||
isOffer: !!sku.isOffer,
|
||||
isComboOnly: !!sku.isComboOnly,
|
||||
isDeleted: !!sku.isDeleted,
|
||||
isSuspended: !!sku.isSuspended,
|
||||
isSuspendedInRegion: !!sku.isSuspendedInRegion,
|
||||
features: (sku.features ?? []).map((feature: any) => ({
|
||||
featureName: feature.featureName,
|
||||
featureValue: feature.featureValue,
|
||||
})),
|
||||
comboItems: (sku.comboItems ?? []).map((item: any) => ({ skuId: Number(item.skuId) })),
|
||||
...skuOverrides,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/** Create one product with a fixed number of SKUs and return ids. */
|
||||
async function createMultiSku(
|
||||
admin: ApiClient,
|
||||
|
|
@ -397,6 +435,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 +626,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 +643,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)
|
||||
})
|
||||
|
||||
|
|
@ -719,8 +812,9 @@ describe('admin.product.updateProduct (APROD-34..42)', () => {
|
|||
describe('admin.product.deleteProduct (APROD-43..45)', () => {
|
||||
it('APROD-43 (current): deleting a product with SKUs soft-deletes instead of failing', async () => {
|
||||
// `softDeleteProduct` flags the SKUs `isDeleted` and clears the dependent
|
||||
// rows; no FK/raw failure is surfaced. `getProducts` then hides it while
|
||||
// `getProductById` still returns the (soft-deleted) row.
|
||||
// rows (market pricing is kept so a restore is lossless); no FK/raw failure
|
||||
// is surfaced. `getProducts` then hides it while `getProductById` still
|
||||
// returns the (soft-deleted) row.
|
||||
const admin = await staffClient()
|
||||
const store = await createStore()
|
||||
const { productId, skuIds } = await createMultiSku(admin, store.storeId, 2)
|
||||
|
|
@ -768,6 +862,54 @@ describe('admin.product.deleteProduct (APROD-43..45)', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('admin.product suspension vs active combos (APROD-55a..55b)', () => {
|
||||
it('APROD-55a (regression): suspending a component of an active combo is rejected', async () => {
|
||||
const admin = await staffClient()
|
||||
const store = await createStore()
|
||||
const component = await createProduct({ storeId: store.storeId, price: 199 })
|
||||
await rawCreate(admin, {
|
||||
storeId: store.storeId,
|
||||
productType: 'combo',
|
||||
skus: [skuInput({ name: 'combo', comboItems: [{ skuId: component.skuId }] })],
|
||||
})
|
||||
|
||||
const current = await readProduct(admin, component.productId)
|
||||
const payload = updatePayloadFrom(current, { isSuspendedInRegion: true })
|
||||
|
||||
await expectTrpcError(
|
||||
() => admin.admin.product.updateProduct.mutate(payload),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'combo'
|
||||
)
|
||||
})
|
||||
|
||||
it('APROD-55b (regression): a regional combo blocks suspending its GLOBAL component', async () => {
|
||||
// Finding #5: the regional global-product edit path returned before the combo
|
||||
// guard, so a regional admin could hide a global component out from under an
|
||||
// active combo in their own region.
|
||||
const admin = await staffClient()
|
||||
const store = await createStore()
|
||||
const global = await elevateToGlobal(admin, store.storeId, [
|
||||
skuInput({ name: '1pc', price: 210 }),
|
||||
])
|
||||
|
||||
await rawCreate(admin, {
|
||||
storeId: store.storeId,
|
||||
productType: 'combo',
|
||||
skus: [skuInput({ name: 'combo', comboItems: [{ skuId: global.skuIds[0] }] })],
|
||||
})
|
||||
|
||||
const current = await readProduct(admin, global.productId)
|
||||
const payload = updatePayloadFrom(current, { isSuspendedInRegion: true })
|
||||
|
||||
await expectTrpcError(
|
||||
() => admin.admin.product.updateProduct.mutate(payload),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'combo'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('admin.product stock + prices (APROD-46..55)', () => {
|
||||
it('APROD-46: toggling the whole product flips every SKU and bumps availability', async () => {
|
||||
const admin = await staffClient()
|
||||
|
|
|
|||
|
|
@ -153,6 +153,26 @@ describe('slots.json shape (CACHE-63..64, 68..69)', () => {
|
|||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe('slots.json exclusions (CACHE-65..67, 75)', () => {
|
||||
it('CACHE-77 (regression): a deleted SKU is excluded from productAvailability', async () => {
|
||||
// Soft delete keeps the SKU's market rows so a restore is lossless, so the
|
||||
// slots payload must drop deleted SKUs by flag rather than by row absence.
|
||||
const admin = await staffClient()
|
||||
const store = await createStore()
|
||||
const product = await createProduct({ storeId: store.storeId, price: 199 })
|
||||
|
||||
const before = await currentSlots(admin)
|
||||
expect(
|
||||
before.productAvailability.some((entry: any) => Number(entry.id) === product.skuId)
|
||||
).toBe(true)
|
||||
|
||||
await admin.admin.product.deleteProduct.mutate({ id: product.productId })
|
||||
|
||||
const after = await currentSlots(admin)
|
||||
expect(
|
||||
after.productAvailability.some((entry: any) => Number(entry.id) === product.skuId)
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('CACHE-65: a slot whose delivery time has passed is excluded', async () => {
|
||||
const admin = await staffClient()
|
||||
const created = await createSlotAt(admin, {
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
|
|
|||
|
|
@ -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,88 @@ 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-10b (regression): an existing SKU updates without a price and keeps every region price', async () => {
|
||||
// Finding #6: price is a create-time seed. The API returns it inside
|
||||
// marketStats, so the form has no single price to resend for an existing SKU;
|
||||
// the structural update must not require one or touch any region's row.
|
||||
const superadmin = await superadminClient()
|
||||
const owned = await makeGlobalProduct()
|
||||
|
||||
const before: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
|
||||
const pricesBefore = before.product.skus[0].marketStats
|
||||
.map((ms: any) => `${ms.regionId}:${String(ms.ourPrice)}`)
|
||||
.sort()
|
||||
|
||||
const skuWithoutPrice = { ...skuUpdate(owned.skuIds[0]) } as any
|
||||
delete skuWithoutPrice.price
|
||||
const newName = `E2E GP price edit ${uniqueSuffix()}`
|
||||
const res: any = await superadmin.superadmin.globalProducts.update.mutate({
|
||||
id: owned.productId,
|
||||
name: newName,
|
||||
storeId: owned.storeId,
|
||||
productType: 'item',
|
||||
skus: [skuWithoutPrice],
|
||||
} as any)
|
||||
|
||||
expect(res.message).toBe('Global product updated successfully')
|
||||
|
||||
const after: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
|
||||
expect(after.product.name).toBe(newName)
|
||||
expect(
|
||||
after.product.skus[0].marketStats
|
||||
.map((ms: any) => `${ms.regionId}:${String(ms.ourPrice)}`)
|
||||
.sort()
|
||||
).toEqual(pricesBefore)
|
||||
})
|
||||
|
||||
it('SGPROD-10c: a NEW SKU still requires a price', async () => {
|
||||
const superadmin = await superadminClient()
|
||||
const owned = await makeGlobalProduct()
|
||||
|
||||
const newSkuWithoutPrice = { ...skuUpdate(0, { id: undefined, name: '2pc' }) } as any
|
||||
delete newSkuWithoutPrice.price
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
superadmin.superadmin.globalProducts.update.mutate({
|
||||
id: owned.productId,
|
||||
name: owned.name,
|
||||
storeId: owned.storeId,
|
||||
productType: 'item',
|
||||
skus: [skuUpdate(owned.skuIds[0]), newSkuWithoutPrice],
|
||||
} as any),
|
||||
'BAD_REQUEST',
|
||||
'price'
|
||||
)
|
||||
})
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
|
@ -415,6 +487,83 @@ describe('superadmin.globalProducts.delete (SGPROD-11..12)', () => {
|
|||
expect(list.products.some((product: any) => Number(product.id) === owned.productId)).toBe(true)
|
||||
})
|
||||
|
||||
it('SGPROD-11b (regression): delete keeps market rows so a restore is not priced at zero', async () => {
|
||||
// Keep per-region pricing through a soft delete. Otherwise a restored global
|
||||
// SKU has no market row in any region and the order path prices it at 0.
|
||||
const superadmin = await superadminClient()
|
||||
const owned = await makeGlobalProduct()
|
||||
|
||||
const before: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
|
||||
const pricesBefore = before.product.skus[0].marketStats
|
||||
.map((ms: any) => String(ms.ourPrice))
|
||||
.sort()
|
||||
expect(pricesBefore.length).toBeGreaterThan(0)
|
||||
expect(pricesBefore.every((price: string) => Number(price) > 0)).toBe(true)
|
||||
|
||||
await superadmin.superadmin.globalProducts.delete.mutate({ id: owned.productId })
|
||||
|
||||
const deleted: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
|
||||
expect(deleted.product.skus[0].isDeleted).toBe(true)
|
||||
expect(
|
||||
deleted.product.skus[0].marketStats.map((ms: any) => String(ms.ourPrice)).sort()
|
||||
).toEqual(pricesBefore)
|
||||
|
||||
await superadmin.superadmin.globalProducts.update.mutate({
|
||||
id: owned.productId,
|
||||
name: owned.name,
|
||||
storeId: owned.storeId,
|
||||
productType: 'item',
|
||||
skus: [skuUpdate(owned.skuIds[0], { isDeleted: false })],
|
||||
} as any)
|
||||
|
||||
const restored: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
|
||||
expect(restored.product.skus[0].isDeleted).toBe(false)
|
||||
expect(
|
||||
restored.product.skus[0].marketStats.map((ms: any) => String(ms.ourPrice)).sort()
|
||||
).toEqual(pricesBefore)
|
||||
})
|
||||
|
||||
it('SGPROD-11c (regression): a structural suspension is blocked while a global combo is active', async () => {
|
||||
// The superadmin kill-switch reaches every region, so an active global combo
|
||||
// must be suspended first. Checkout validates the combo SKU, not components.
|
||||
const superadmin = await superadminClient()
|
||||
const owned = await makeGlobalProduct()
|
||||
|
||||
await superadmin.superadmin.globalProducts.create.mutate({
|
||||
name: `E2E GP combo ${uniqueSuffix()}`,
|
||||
storeId: owned.storeId,
|
||||
productType: 'combo',
|
||||
skus: [{
|
||||
name: 'combo',
|
||||
price: 500,
|
||||
marketPrice: 600,
|
||||
images: [],
|
||||
isFlashAvailable: false,
|
||||
flashPrice: null,
|
||||
isOutOfStock: false,
|
||||
isOffer: false,
|
||||
isComboOnly: false,
|
||||
isDeleted: false,
|
||||
isSuspended: false,
|
||||
features: [{ featureName: 'quantity', featureValue: '1 combo' }],
|
||||
comboItems: [{ skuId: owned.skuIds[0] }],
|
||||
}],
|
||||
} as any)
|
||||
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
superadmin.superadmin.globalProducts.update.mutate({
|
||||
id: owned.productId,
|
||||
name: owned.name,
|
||||
storeId: owned.storeId,
|
||||
productType: 'item',
|
||||
skus: [skuUpdate(owned.skuIds[0], { isSuspended: true })],
|
||||
} as any),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'combo'
|
||||
)
|
||||
})
|
||||
|
||||
it('SGPROD-12: deleting an unknown product is 404', async () => {
|
||||
const superadmin = await superadminClient()
|
||||
await expectTrpcError(
|
||||
|
|
|
|||
|
|
@ -276,6 +276,31 @@ describe('superadmin.regions.create (SREG-04..11)', () => {
|
|||
'BAD_REQUEST'
|
||||
)
|
||||
})
|
||||
|
||||
it('SREG-11b (regression): a region with 17 bounds batches both seed inserts', async () => {
|
||||
// 6 bounds used to build a 120-parameter region_bound_consts insert, past
|
||||
// D1's 100-parameter cap; 17 bounds also splits the region_bounds insert.
|
||||
const bounds = Array.from({ length: 17 }, (_, index) => ({
|
||||
lat: 15.5 + index * 0.01,
|
||||
lng: 77.5 + index * 0.01,
|
||||
priority: String(index + 1),
|
||||
}))
|
||||
const region = await createRegionRaw({ bounds })
|
||||
|
||||
expect(region.boundIds).toHaveLength(bounds.length)
|
||||
|
||||
for (const boundId of region.boundIds) {
|
||||
const settings = await boundSettingsMap(boundId)
|
||||
expect(Object.keys(settings).sort()).toEqual([
|
||||
'deliveryCharge',
|
||||
'flashDeliveryCharge',
|
||||
'flashFreeDeliveryThreshold',
|
||||
'freeDeliveryThreshold',
|
||||
'isFlashDeliveryEnabled',
|
||||
])
|
||||
expect(settings.deliveryCharge).toBe('20')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
70
apps/superadmin-ui/src/lib/global-product-form.test.ts
Normal file
70
apps/superadmin-ui/src/lib/global-product-form.test.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
canSubmitGlobalProduct,
|
||||
skuPricePayload,
|
||||
type GlobalProductSkuDraft,
|
||||
type GlobalProductSubmitState,
|
||||
} from './global-product-form'
|
||||
|
||||
const sku = (overrides: Partial<GlobalProductSkuDraft> = {}): GlobalProductSkuDraft => ({
|
||||
id: 1,
|
||||
price: '',
|
||||
features: [{ featureValue: '1kg' }],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const state = (overrides: Partial<GlobalProductSubmitState> = {}): GlobalProductSubmitState => ({
|
||||
name: 'Fresh Chicken',
|
||||
storeId: 1,
|
||||
skus: [sku()],
|
||||
pending: false,
|
||||
isUploading: false,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('canSubmitGlobalProduct', () => {
|
||||
it('allows saving an existing SKU without a price', () => {
|
||||
expect(canSubmitGlobalProduct(state())).toBe(true)
|
||||
})
|
||||
|
||||
it('still requires a price for a new SKU', () => {
|
||||
expect(canSubmitGlobalProduct(state({ skus: [sku({ id: undefined })] }))).toBe(false)
|
||||
expect(
|
||||
canSubmitGlobalProduct(state({ skus: [sku({ id: undefined, price: '199' })] }))
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects an invalid new-SKU price', () => {
|
||||
expect(
|
||||
canSubmitGlobalProduct(state({ skus: [sku({ id: undefined, price: 'abc' })] }))
|
||||
).toBe(false)
|
||||
expect(
|
||||
canSubmitGlobalProduct(state({ skus: [sku({ id: undefined, price: '-1' })] }))
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('requires a name, a store, a SKU, and a feature value', () => {
|
||||
expect(canSubmitGlobalProduct(state({ name: ' ' }))).toBe(false)
|
||||
expect(canSubmitGlobalProduct(state({ storeId: null }))).toBe(false)
|
||||
expect(canSubmitGlobalProduct(state({ skus: [] }))).toBe(false)
|
||||
expect(
|
||||
canSubmitGlobalProduct(state({ skus: [sku({ features: [{ featureValue: ' ' }] })] }))
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('is disabled while saving or uploading', () => {
|
||||
expect(canSubmitGlobalProduct(state({ pending: true }))).toBe(false)
|
||||
expect(canSubmitGlobalProduct(state({ isUploading: true }))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('skuPricePayload', () => {
|
||||
it('omits a blank price so an existing SKU keeps every region row', () => {
|
||||
expect(skuPricePayload({ price: '' })).toEqual({})
|
||||
expect(skuPricePayload({ price: ' ' })).toEqual({})
|
||||
})
|
||||
|
||||
it('sends an entered seed price', () => {
|
||||
expect(skuPricePayload({ price: '199' })).toEqual({ price: 199 })
|
||||
})
|
||||
})
|
||||
56
apps/superadmin-ui/src/lib/global-product-form.ts
Normal file
56
apps/superadmin-ui/src/lib/global-product-form.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/**
|
||||
* Pure form rules for the superadmin global-product form.
|
||||
*
|
||||
* Price is a create-time seed only: the global update API never writes market
|
||||
* data for an existing SKU (each region owns its `product_market_stats` row), so
|
||||
* an existing SKU must be saveable with a blank price.
|
||||
*/
|
||||
export interface GlobalProductSkuDraft {
|
||||
id?: number
|
||||
price: string
|
||||
features: Array<{ featureValue: string }>
|
||||
}
|
||||
|
||||
export interface GlobalProductSubmitState {
|
||||
name: string
|
||||
storeId: number | null
|
||||
skus: GlobalProductSkuDraft[]
|
||||
pending: boolean
|
||||
isUploading: boolean
|
||||
}
|
||||
|
||||
/** Only a NEW SKU needs a seed price; an existing SKU keeps its region rows. */
|
||||
export function hasRequiredPrice(
|
||||
sku: Pick<GlobalProductSkuDraft, 'id' | 'price'>
|
||||
): boolean {
|
||||
if (sku.id != null) return true
|
||||
if (sku.price.trim() === '') return false
|
||||
const price = Number.parseFloat(sku.price)
|
||||
return Number.isFinite(price) && price >= 0
|
||||
}
|
||||
|
||||
export function canSubmitGlobalProduct(state: GlobalProductSubmitState): boolean {
|
||||
return (
|
||||
state.name.trim() !== '' &&
|
||||
state.storeId != null &&
|
||||
state.skus.length > 0 &&
|
||||
state.skus.every(
|
||||
(sku) =>
|
||||
hasRequiredPrice(sku) &&
|
||||
sku.features.some((feature) => feature.featureValue.trim() !== '')
|
||||
) &&
|
||||
!state.pending &&
|
||||
!state.isUploading
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Omit a blank price from the payload so editing an existing SKU does not send
|
||||
* a value the backend ignores (and does not force the superadmin to re-enter it).
|
||||
*/
|
||||
export function skuPricePayload(
|
||||
sku: Pick<GlobalProductSkuDraft, 'price'>
|
||||
): { price?: number } {
|
||||
if (sku.price.trim() === '') return {}
|
||||
return { price: Number.parseFloat(sku.price) }
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ import { SimpleSelect } from '@/components/ui/simple-select'
|
|||
import { alert, confirm } from '@/components/ui/dialog-host'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage'
|
||||
import { canSubmitGlobalProduct, skuPricePayload } from '../lib/global-product-form'
|
||||
|
||||
export const Route = createFileRoute('/global-products')({
|
||||
component: () => (
|
||||
|
|
@ -145,8 +146,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()
|
||||
|
|
@ -386,18 +408,7 @@ function GlobalProductForm({
|
|||
e.target.value = ''
|
||||
}
|
||||
|
||||
const canSubmit =
|
||||
name.trim() !== '' &&
|
||||
!!storeId &&
|
||||
skus.length > 0 &&
|
||||
skus.every(
|
||||
(s) =>
|
||||
s.price.trim() !== '' &&
|
||||
parseFloat(s.price) >= 0 &&
|
||||
s.features.some((f) => f.featureValue.trim() !== '')
|
||||
) &&
|
||||
!pending &&
|
||||
!isUploading
|
||||
const canSubmit = canSubmitGlobalProduct({ name, storeId, skus, pending, isUploading })
|
||||
|
||||
const submit = async () => {
|
||||
setError(null)
|
||||
|
|
@ -412,7 +423,7 @@ function GlobalProductForm({
|
|||
skusPayload.push({
|
||||
id: s.id,
|
||||
name: s.name || null,
|
||||
price: parseFloat(s.price),
|
||||
...skuPricePayload(s),
|
||||
marketPrice: s.marketPrice.trim() !== '' ? parseFloat(s.marketPrice) : null,
|
||||
images,
|
||||
isFlashAvailable: false,
|
||||
|
|
@ -505,8 +516,16 @@ function GlobalProductForm({
|
|||
<div key={sku.id ?? `new-${index}`} className="mb-3 rounded-lg border border-gray-200 bg-gray-50 p-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<PInput topLabel="SKU name (optional)" value={sku.name} onChange={(e) => updateSku(index, { name: e.target.value })} />
|
||||
<PInput topLabel="Price (₹)" value={sku.price} onChange={(e) => updateSku(index, { price: e.target.value })} placeholder="e.g. 199" />
|
||||
<PInput topLabel="Market price (₹)" value={sku.marketPrice} onChange={(e) => updateSku(index, { marketPrice: e.target.value })} placeholder="Optional" />
|
||||
{sku.id == null ? (
|
||||
<>
|
||||
<PInput topLabel="Price (₹)" value={sku.price} onChange={(e) => updateSku(index, { price: e.target.value })} placeholder="e.g. 199" />
|
||||
<PInput topLabel="Market price (₹)" value={sku.marketPrice} onChange={(e) => updateSku(index, { marketPrice: e.target.value })} placeholder="Optional" />
|
||||
</>
|
||||
) : (
|
||||
<div className="rounded-lg bg-white px-3 py-2 text-xs text-gray-500 ring-1 ring-gray-200 sm:col-span-2">
|
||||
Price is managed per region after creation; this form only seeds it for a new SKU.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-3">
|
||||
|
|
|
|||
|
|
@ -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` |
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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 }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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 }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
454
change-log.txt
454
change-log.txt
|
|
@ -8977,3 +8977,457 @@ 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.
|
||||
|
||||
[2026-10-24 15:40 IST] Fix follow-up review finding #1 (restored global SKU priced at ₹0).
|
||||
Soft delete now keeps the per-region market rows instead of deleting them, so a
|
||||
restore (`isDeleted -> false`) no longer comes back with no price row in any region.
|
||||
Every catalogue/cache reader already hides a deleted SKU by `isDeleted`; only the
|
||||
slots payload's `productAvailability` relied on row absence, so it now filters
|
||||
`isDeleted` explicitly.
|
||||
|
||||
--- a/packages/db_helper_sqlite/src/admin-apis/product.ts
|
||||
+++ b/packages/db_helper_sqlite/src/admin-apis/product.ts
|
||||
@@ softDeleteProduct doc comment
|
||||
* would either trip D1's FK enforcement or blank out historical order lines.
|
||||
+ *
|
||||
+ * Per-region market stats are deliberately KEPT: every reader hides a deleted SKU
|
||||
+ * by `isDeleted` (catalogue, availability cache, admin list), and retaining the
|
||||
+ * rows makes a later restore lossless — otherwise a restored global SKU comes back
|
||||
+ * with no price row in any region and the order path prices it at 0.
|
||||
*/
|
||||
@@ -382,7 +387,6 @@
|
||||
if (skuIds.length > 0) {
|
||||
await db.batch([
|
||||
- db.delete(productMarketStats).where(inArray(productMarketStats.skuId, skuIds)),
|
||||
db.delete(cartItems).where(inArray(cartItems.skuId, skuIds)),
|
||||
|
||||
--- a/packages/db_helper_sqlite/src/user-apis/slots.ts
|
||||
+++ b/packages/db_helper_sqlite/src/user-apis/slots.ts
|
||||
@@ -61,7 +61,12 @@ getProductAvailability
|
||||
// Global products (null region) are servable in every region.
|
||||
return productRegionId === regionId || productRegionId == null
|
||||
})
|
||||
- .filter((stat) => !(stat as typeof stat & { sku?: { isSuspended?: boolean } | null }).sku?.isSuspended)
|
||||
+ .filter((stat) => {
|
||||
+ const sku = (stat as typeof stat & { sku?: { isSuspended?: boolean; isDeleted?: boolean } | null }).sku
|
||||
+ // Market rows outlive a soft delete, so row presence no longer means
|
||||
+ // "sellable": mirror the catalogue and drop deleted SKUs here too.
|
||||
+ return !sku?.isSuspended && !sku?.isDeleted
|
||||
+ })
|
||||
.map((stat) => ({
|
||||
|
||||
--- a/apps/backend/tests/api/superadmin-global-products.test.ts
|
||||
+++ b/apps/backend/tests/api/superadmin-global-products.test.ts
|
||||
@@ SGPROD-11b (new regression row, after SGPROD-11)
|
||||
+ it('SGPROD-11b (regression): delete keeps market rows so a restore is not priced at zero', ...)
|
||||
+ // captures per-region ourPrice, deletes, asserts rows/prices survive, restores
|
||||
+ // via update({ isDeleted: false }), asserts rows/prices are still there.
|
||||
|
||||
--- a/apps/backend/tests/api/cache-slots.test.ts
|
||||
+++ b/apps/backend/tests/api/cache-slots.test.ts
|
||||
@@ CACHE-77 (new row, after CACHE-69)
|
||||
+ it('CACHE-77 (regression): a deleted SKU is excluded from productAvailability', ...)
|
||||
+ // creates a product, asserts it is in productAvailability, soft-deletes it,
|
||||
+ // asserts it is gone from the slots payload.
|
||||
|
||||
--- a/apps/backend/tests/api/admin-product-crud.test.ts
|
||||
+++ b/apps/backend/tests/api/admin-product-crud.test.ts
|
||||
@@ APROD-43 comment
|
||||
- // rows; no FK/raw failure is surfaced.
|
||||
+ // rows (market pricing is kept so a restore is lossless); no FK/raw failure
|
||||
+ // is surfaced.
|
||||
|
||||
[2026-10-24 15:49 IST] Fix follow-up review finding #5 (global-product edits bypass the
|
||||
active-combo suspension guard).
|
||||
Suspending a SKU that an active combo depends on is now rejected on every write path:
|
||||
the superadmin's structural suspension, a regional product's regional suspension, and
|
||||
(previous hole) a regional admin editing a GLOBAL product's market row, which returned
|
||||
early before the old inline check. Guard extracted to `assertNoActiveComboMembers` and
|
||||
made transition-based, so re-saving an already-suspended SKU (the admin form always
|
||||
sends the flag) still works. Scope matches the write: a regional suspension only checks
|
||||
combos sold in that region; a structural suspension checks combos active in any region.
|
||||
|
||||
--- a/packages/db_helper_sqlite/src/admin-apis/product.ts
|
||||
+++ b/packages/db_helper_sqlite/src/admin-apis/product.ts
|
||||
@@ after assertSkuIdsInRegion / before updateProductMarketDataForRegion
|
||||
+/**
|
||||
+ * Reject suspending a SKU that a still-sellable combo depends on. Checkout
|
||||
+ * validates the combo SKU, not its components, so a suspended component would
|
||||
+ * otherwise keep selling inside an active combo.
|
||||
+ * ...
|
||||
+ */
|
||||
+async function assertNoActiveComboMembers(
|
||||
+ suspendingSkuIds: number[],
|
||||
+ regionId: number | null
|
||||
+): Promise<void> { ... }
|
||||
@@ updateProductMarketDataForRegion
|
||||
const existingSkus = await db.query.productSkus.findMany({
|
||||
where: eq(productSkus.productId, id),
|
||||
columns: { id: true },
|
||||
+ with: { marketStats: true },
|
||||
})
|
||||
const existingSkuIdSet = new Set(existingSkus.map((s) => s.id))
|
||||
+ // A regional admin editing a global product used to return before the combo
|
||||
+ // guard; block false -> true regional suspensions here.
|
||||
+ const skusBeingSuspended = skus.filter(...)
|
||||
+ await assertNoActiveComboMembers(..., regionId)
|
||||
@@ updateProduct validation
|
||||
const existingSkus = await db.query.productSkus.findMany({
|
||||
where: eq(productSkus.productId, id),
|
||||
- columns: { id: true },
|
||||
+ columns: { id: true, isSuspended: true },
|
||||
+ with: { marketStats: true },
|
||||
})
|
||||
...
|
||||
- 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 = ...
|
||||
- ... inline combo lookup ...
|
||||
- }
|
||||
+ const skusBeingSuspended = /* false -> true transitions only */
|
||||
+ await assertNoActiveComboMembers(..., regionId)
|
||||
|
||||
--- a/apps/backend/tests/api/admin-product-crud.test.ts
|
||||
+++ b/apps/backend/tests/api/admin-product-crud.test.ts
|
||||
@@ new regression rows after APROD-26
|
||||
+ it('APROD-55a (regression): a regional COMBO blocks regional suspension of its regional component', ...)
|
||||
+ it('APROD-55b (regression): a regional COMBO blocks a regional admin suspending its GLOBAL component', ...)
|
||||
+ // APROD-55b is the finding #5 bypass: component elevated to global, regional
|
||||
+ // combo still references it, regional market edit must not suspend it.
|
||||
|
||||
--- a/apps/backend/tests/api/superadmin-global-products.test.ts
|
||||
+++ b/apps/backend/tests/api/superadmin-global-products.test.ts
|
||||
@@ new regression row after SGPROD-11b
|
||||
+ it('SGPROD-11c (regression): a structural suspension is blocked while a global combo is active', ...)
|
||||
|
||||
[2026-10-24 15:52 IST] Fix follow-up review finding #6 (global-product edit required re-entering every price).
|
||||
The global-products API returns prices only inside `sku.marketStats`, so the superadmin form
|
||||
initialized every existing SKU's price as blank and `canSubmit` disabled Save until all were
|
||||
filled — even though the backend ignores those prices for existing global SKUs. Price is a
|
||||
create-time seed; after that each region owns its market row.
|
||||
- superadmin-ui: price/market-price inputs render for NEW SKUs only; `canSubmit` requires a
|
||||
price only when `id == null`; submit omits a blank price. Pure form logic moved to
|
||||
src/lib/global-product-form.ts with a vitest suite.
|
||||
- backend superadmin.globalProducts.update: `price` is optional for an existing SKU and still
|
||||
required (zod superRefine) for a new one.
|
||||
|
||||
--- a/apps/superadmin-ui/src/routes/global-products.tsx
|
||||
+++ b/apps/superadmin-ui/src/routes/global-products.tsx
|
||||
@@ imports
|
||||
+import { canSubmitGlobalProduct, skuPricePayload } from '../lib/global-product-form'
|
||||
@@ canSubmit
|
||||
- const canSubmit =
|
||||
- name.trim() !== '' && !!storeId && skus.length > 0 &&
|
||||
- skus.every((s) => s.price.trim() !== '' && parseFloat(s.price) >= 0 && features...)
|
||||
+ const canSubmit = canSubmitGlobalProduct({ name, storeId, skus, pending, isUploading })
|
||||
@@ submit
|
||||
- price: parseFloat(s.price),
|
||||
+ ...skuPricePayload(s),
|
||||
@@ SKU card price inputs
|
||||
- <PInput topLabel="Price (₹)" ... />
|
||||
- <PInput topLabel="Market price (₹)" ... />
|
||||
+ {sku.id == null ? (<price + market price inputs>) : (<note: price is per-region, set at create>)}
|
||||
|
||||
--- a/apps/superadmin-ui/src/lib/global-product-form.ts (new)
|
||||
+export const skuPricePayload = (sku) => ...
|
||||
+export const canSubmitGlobalProduct = (input) => ...
|
||||
|
||||
--- a/apps/superadmin-ui/src/lib/global-product-form.test.ts (new)
|
||||
+ existing SKU with blank price is submittable
|
||||
+ new SKU still requires a price
|
||||
+ blank price is omitted from the payload, entered price is included
|
||||
|
||||
--- a/apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts
|
||||
+++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts
|
||||
@@ schema split
|
||||
-const skuInput = z.object({ id, name, price, marketPrice, ... })
|
||||
+const skuFields = { id, name, marketPrice, ... }
|
||||
+const skuInput = z.object({ ...skuFields, price: z.number().nonnegative(...) })
|
||||
+const skuUpdateInput = z.object({ ...skuFields, price: z.number().nonnegative(...).optional() })
|
||||
@@ update input
|
||||
- skus: z.array(skuInput).min(1, ...),
|
||||
+ skus: z.array(skuUpdateInput).min(1, ...).superRefine((skus, ctx) => {
|
||||
+ // a new SKU still needs its seed price; existing SKUs take each region's row
|
||||
+ }),
|
||||
|
||||
--- a/apps/backend/tests/api/superadmin-global-products.test.ts
|
||||
+++ b/apps/backend/tests/api/superadmin-global-products.test.ts
|
||||
@@ new rows in superadmin.globalProducts.update
|
||||
+ it('SGPROD-10b (regression): an existing SKU updates without a price and keeps every region price', ...)
|
||||
+ it('SGPROD-10c: a NEW SKU still requires a price', ...)
|
||||
|
||||
[2026-10-24 15:54 IST] Fix follow-up review finding #8 (region create exceeds D1's parameter cap).
|
||||
`createRegionWithBounds` seeded every bound's five settings in one insert: 4 columns x
|
||||
5 keys x 6 bounds = 120 bound parameters, past D1's 100-parameter per-statement limit,
|
||||
so the region was created and then compensated away. Both multi-row inserts in that
|
||||
transaction are now chunked sequentially (still one transaction):
|
||||
- region_bounds: 6 columns/row, 16 rows per statement (96 params).
|
||||
- region_bound_consts: 4 columns/row, 25 rows per statement (100 params).
|
||||
No migration needed; the rows and defaults are unchanged.
|
||||
|
||||
--- a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts
|
||||
+++ b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts
|
||||
@@ chunk constants
|
||||
+const REGION_BOUND_INSERT_CHUNK_SIZE = 16
|
||||
+const BOUND_CONST_INSERT_CHUNK_SIZE = 25
|
||||
@@ createRegionWithBounds
|
||||
- const inserted = await tx.insert(regionBounds).values(
|
||||
- input.bounds.map(...)
|
||||
- ).returning()
|
||||
+ const boundValues = input.bounds.map(...)
|
||||
+ const inserted: Array<typeof regionBounds.$inferSelect> = []
|
||||
+ for (let i = 0; i < boundValues.length; i += REGION_BOUND_INSERT_CHUNK_SIZE) {
|
||||
+ inserted.push(...(await tx.insert(regionBounds)
|
||||
+ .values(boundValues.slice(i, i + REGION_BOUND_INSERT_CHUNK_SIZE)).returning()))
|
||||
+ }
|
||||
@@ bound settings seed
|
||||
- await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing()
|
||||
+ for (let i = 0; i < boundRows.length; i += BOUND_CONST_INSERT_CHUNK_SIZE) {
|
||||
+ await tx.insert(regionBoundConsts)
|
||||
+ .values(boundRows.slice(i, i + BOUND_CONST_INSERT_CHUNK_SIZE))
|
||||
+ .onConflictDoNothing()
|
||||
+ }
|
||||
|
||||
--- a/apps/backend/tests/api/superadmin-regions.test.ts
|
||||
+++ b/apps/backend/tests/api/superadmin-regions.test.ts
|
||||
@@ new regression row after SREG-11
|
||||
+ it('SREG-11b (regression): a region with 17 bounds creates and seeds every bound', ...)
|
||||
+ // 6 bounds overflowed the old 120-param settings insert; 17 also splits the
|
||||
+ // region_bounds insert. Asserts 17 bounds and 5 settings on each.
|
||||
|
|
|
|||
|
|
@ -1,145 +0,0 @@
|
|||
# Code Review: MULTI_REGION_I2 against main
|
||||
|
||||
## High priority
|
||||
|
||||
### 1. [P1] Regional admins can delete shared global-product images
|
||||
|
||||
**Location:** `apps/backend/src/trpc/apis/admin-apis/apis/product.ts:314–330`
|
||||
|
||||
A regional admin can resend a global product’s existing images and put their keys in `deletedImageKeys`. Validation passes and deletes the objects, although the subsequent database update permits only regional market-data changes. Every region then has broken image references.
|
||||
|
||||
**Recommendation:** Enforce structural-edit permissions before deleting images.
|
||||
|
||||
### 2. [P1] Creating slots can erase another region’s slot contents
|
||||
|
||||
**Location:** `apps/backend/src/trpc/apis/admin-apis/apis/slots.ts:127–130`
|
||||
|
||||
`staleSlotsCleanup()` still selects the globally latest 20 slots and clears the 20th slot’s `skuIds`. Creating slots in region A can therefore empty an active slot in B, without refreshing B’s cache.
|
||||
|
||||
**Recommendation:** Pass the region into cleanup and scope both its selection and update.
|
||||
|
||||
### 3. [P1] Pending scheduled orders become unfulfillable after three calendar days
|
||||
|
||||
**Location:** `packages/db_helper_sqlite/src/lib/order-items-archive.ts:228–233`
|
||||
|
||||
Archiving checks creation time but not fulfillment status or delivery date. An order placed several days before delivery loses its relational items; packaging operations subsequently return “not found” because archived orders are read-only.
|
||||
|
||||
**Recommendation:** Preserve open orders in the archive query, migration backfill, and corresponding admin-list window.
|
||||
|
||||
## Correctness issues
|
||||
|
||||
### 4. [P2] Editing an address can silently replace its delivery location
|
||||
|
||||
**Location:** `apps/user-ui/src/components/AddressForm.tsx:172–180`
|
||||
|
||||
The device-location prefill also runs in edit mode. The addresses screen omits initial coordinates for saved Maps-URL addresses, so editing only their name or phone while elsewhere replaces their coordinates—and potentially their town—with the device’s current location.
|
||||
|
||||
**Recommendation:** Preserve the saved location and restrict automatic prefilling to new addresses.
|
||||
|
||||
### 5. [P2] Restarting can assign a saved cart to the wrong region
|
||||
|
||||
**Location:** `apps/user-ui/src/hooks/useRegion.ts:358–360, 383–385`
|
||||
|
||||
Region selection is non-persistent, but active carts persist under unscoped keys. Restarting in A after shopping in B adopts A without reconciling B’s cart. A later switch stashes that cart under A and restores an outdated or empty B snapshot.
|
||||
|
||||
**Recommendation:** Persist and reconcile the active cart’s owning region during startup.
|
||||
|
||||
### 6. [P2] Bound changes can persist another bound’s constants
|
||||
|
||||
**Location:** `apps/user-ui/src/hooks/prominent-api-hooks.ts:74–79`
|
||||
|
||||
On a bound change, `initialData` still contains the previous bound’s snapshot for one render. The persistence effect writes that placeholder under the new bound’s key. A failed request or restart can then hydrate incorrect fees, region identity, and cache versions.
|
||||
|
||||
**Recommendation:** Validate snapshot provenance and avoid persisting placeholder responses. The web counterpart has the same issue at `apps/web-ui/src/hooks/prominent-api-hooks.ts:101–106`.
|
||||
|
||||
### 7. [P2] “Suspend in my region” does not update regional suspension
|
||||
|
||||
**Location:** `apps/admin-ui/src/components/GlobalProductForm.tsx:70–72`
|
||||
|
||||
The form reads and submits `isSuspended`, but the global-product market-data path only updates `isSuspendedInRegion`. Saving reports success while leaving regional suspension unchanged.
|
||||
|
||||
**Recommendation:** Read and submit the regional field in both this component and `apps/admin-web/src/components/GlobalProductForm.tsx`.
|
||||
|
||||
### 8. [P2] Failed reserved-coupon redemption permanently consumes the secret
|
||||
|
||||
**Location:** `packages/db_helper_sqlite/src/user-apis/coupon.ts:127–144`
|
||||
|
||||
The reservation is marked redeemed before inserting the coupon. The project’s D1 `transaction` wrapper does not roll back, so an insertion failure leaves it consumed without granting anything. A concrete case is collision with an ordinary coupon code, which reserved-coupon creation permits.
|
||||
|
||||
**Recommendation:** Make claiming and issuance atomic or compensate on failure.
|
||||
|
||||
### 9. [P2] Migration discards historical discount amounts
|
||||
|
||||
**Location:** `packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql:576–577`
|
||||
|
||||
Every existing order receives `discount_amount = '0'`, including discounted orders. Both new order-detail implementations treat this field as authoritative, so historical coupon discounts disappear from their bills.
|
||||
|
||||
**Recommendation:** Backfill the actual charged discount from existing item totals, delivery charge, and order total.
|
||||
|
||||
### 10. [P2] Fractional prices produce different checkout and persisted totals
|
||||
|
||||
**Location:** `packages/shared/cart-pricing.ts:313–317`
|
||||
|
||||
Flooring each sub-order’s discount capacity loses fractional rupees. For two ₹99.50 sub-orders and a ₹199 flat coupon, `computeCouponStack` previews a ₹199 discount, but `computeCartPricing` allocates only ₹198 and charges ₹1.
|
||||
|
||||
**Recommendation:** Use consistent minor-unit arithmetic for previews and allocation.
|
||||
|
||||
### 11. [P2] Newly created foreign-region addresses bypass region switching
|
||||
|
||||
**Location:** `apps/user-ui/components/CartAddressGate.tsx:129–132`
|
||||
|
||||
Saving an address in B while browsing A only closes the form and refetches addresses. `apps/user-ui/components/CheckoutAddressSelector.tsx:290–297` likewise selects newly created addresses without its existing cross-region confirmation flow. Checkout can retain A’s products/slots with B’s address and fail.
|
||||
|
||||
**Recommendation:** Route successful creation through the same region-switch flow as existing foreign addresses.
|
||||
|
||||
### 12. [P2] Vendor snippets reject valid global SKUs
|
||||
|
||||
**Location:** `packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts:113–115, 202–203`
|
||||
|
||||
These checks require the product’s region to equal the staff region, excluding global products whose region is null. Standalone snippet creation/update rejects them, and existing snippets lose their displayed products after elevation.
|
||||
|
||||
**Recommendation:** Apply the global-SKU exception already used by slot creation.
|
||||
|
||||
### 13. [P2] Elevating a combo leaves regional-only components attached
|
||||
|
||||
**Location:** `packages/db_helper_sqlite/src/superadmin-apis/products.ts:80–83`
|
||||
|
||||
Elevation makes the combo global without validating its components. A combo containing A-only products becomes available in B, where cache generation removes those components and publishes an incomplete combo.
|
||||
|
||||
**Recommendation:** Require global components before elevation or explicitly elevate the dependencies.
|
||||
|
||||
### 14. [P2] Global stores show zero products despite having a populated catalog
|
||||
|
||||
**Location:** `packages/db_helper_sqlite/src/user-apis/stores.ts:25–28`
|
||||
|
||||
The summary filter excludes every global product. A global store containing global products therefore publishes `productCount: 0` and no previews, although its detail document contains them.
|
||||
|
||||
**Recommendation:** Include null product regions when collecting active SKUs.
|
||||
|
||||
### 15. [P2] Global stores lose all regional category filters
|
||||
|
||||
**Location:** `apps/backend/src/stores/product-tag-store.ts:116–124`
|
||||
|
||||
Tag lookup infers the browsing region from store ownership and returns an empty list for global stores. Regional tags attached to those stores never reach their cache documents.
|
||||
|
||||
**Recommendation:** Pass the browsing region from `scaffoldStoreWithProducts(regionId, storeId)` instead.
|
||||
|
||||
### 16. [P2] Global SKU selectors use no region’s price or suspension data
|
||||
|
||||
**Location:** `packages/db_helper_sqlite/src/user-apis/product.ts:347–349`
|
||||
|
||||
Although this function receives the caller’s region, it selects market data using the product’s region—which is null for global products. Global SKUs consequently appear priced at ₹0 and ignore regional suspension in admin selectors.
|
||||
|
||||
**Recommendation:** Select market data using the requested region.
|
||||
|
||||
### 17. [P2] Global-product creation fails once there are 12 regions
|
||||
|
||||
**Location:** `packages/db_helper_sqlite/src/admin-apis/product.ts:472–481`
|
||||
|
||||
The unchunked insert generates 108 bound parameters for 12 regions, exceeding D1’s 100-parameter limit. Creation then fails after product/SKU rows have already been written. Adding a global SKU repeats this at lines 750–759.
|
||||
|
||||
**Recommendation:** Chunk both regional market-stat insertions.
|
||||
|
||||
## Review execution
|
||||
|
||||
No test suites or migrations were run, and no files were changed during the review.
|
||||
|
|
@ -458,6 +458,7 @@ export {
|
|||
export {
|
||||
listAllProducts,
|
||||
elevateProductToGlobal,
|
||||
getElevationDependents,
|
||||
} from './src/superadmin-apis/products'
|
||||
|
||||
export {
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ import {
|
|||
} from '../db/schema'
|
||||
import { and, desc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm'
|
||||
import { runBatched } from '../lib/run-batched'
|
||||
import { marketStatsForRegion, isSkuSuspended } from '../lib/market-stats'
|
||||
import { marketStatsForRegion } from '../lib/market-stats'
|
||||
import type { InferSelectModel } from 'drizzle-orm'
|
||||
|
||||
// Chunk sizes for multi-row inserts so no single statement exceeds SQLite's
|
||||
|
|
@ -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.
|
||||
|
|
@ -360,6 +364,11 @@ export async function getProductById(regionId: number, id: number): Promise<Admi
|
|||
* so the product and its SKUs are kept: the SKU is flagged `is_deleted` and only the
|
||||
* state that keeps the product orderable/visible is removed. Deleting the rows instead
|
||||
* would either trip D1's FK enforcement or blank out historical order lines.
|
||||
*
|
||||
* Per-region market stats are deliberately KEPT: every reader hides a deleted SKU by
|
||||
* `isDeleted` (catalogue, availability cache, admin list), and retaining the rows makes
|
||||
* a later restore lossless — otherwise a restored global SKU comes back with no price
|
||||
* row in any region and the order path prices it at 0.
|
||||
*/
|
||||
async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
|
||||
const product = await db.query.productInfo.findFirst({
|
||||
|
|
@ -375,7 +384,6 @@ async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
|
|||
|
||||
if (skuIds.length > 0) {
|
||||
await db.batch([
|
||||
db.delete(productMarketStats).where(inArray(productMarketStats.skuId, skuIds)),
|
||||
db.delete(cartItems).where(inArray(cartItems.skuId, skuIds)),
|
||||
// Coupon product targets are a JSON array on the coupon row itself; a deleted
|
||||
// SKU is deliberately left in it. It can never appear in a cart again, and
|
||||
|
|
@ -459,7 +467,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 +479,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) => {
|
||||
|
|
@ -524,6 +541,76 @@ export async function createProduct(input: CreateProductInput, regionId: number
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject suspending a SKU that a still-sellable combo depends on. Checkout
|
||||
* validates the combo SKU, not its components, so a suspended component would
|
||||
* otherwise keep selling inside an active combo.
|
||||
*
|
||||
* The scope matches the suspension being written: a region suspension only
|
||||
* affects combos sold there (including that region's global combos), while the
|
||||
* superadmin's structural suspension applies everywhere, so the combo must be
|
||||
* inactive in every region where it is sold. Transitions are evaluated by the
|
||||
* caller: only false -> true counts as "suspending".
|
||||
*/
|
||||
async function assertNoActiveComboMembers(
|
||||
suspendingSkuIds: number[],
|
||||
regionId: number | null
|
||||
): Promise<void> {
|
||||
if (suspendingSkuIds.length === 0) return
|
||||
|
||||
const memberships = await db.query.productCombos.findMany({
|
||||
where: inArray(productCombos.skuId, suspendingSkuIds),
|
||||
columns: { comboSkuId: true },
|
||||
})
|
||||
if (memberships.length === 0) return
|
||||
|
||||
const comboIds = Array.from(new Set(memberships.map((membership) => membership.comboSkuId)))
|
||||
const combos = await db.query.productSkus.findMany({
|
||||
where: inArray(productSkus.id, comboIds),
|
||||
columns: { id: true, isSuspended: true, isDeleted: true },
|
||||
with: {
|
||||
marketStats: true,
|
||||
product: { columns: { regionId: true } },
|
||||
},
|
||||
})
|
||||
|
||||
// A structural suspension applies everywhere, so a global combo is active unless
|
||||
// every existing region has it suspended — a missing region row counts as active.
|
||||
const regionCount = regionId == null
|
||||
? (await db.select({ id: regions.id }).from(regions)).length
|
||||
: 0
|
||||
|
||||
const activeComboIds = combos
|
||||
.filter((combo) => {
|
||||
// A deleted or structurally suspended combo cannot be sold anywhere.
|
||||
if (combo.isDeleted || combo.isSuspended) return false
|
||||
|
||||
const comboRegionId = combo.product?.regionId ?? null
|
||||
if (regionId != null) {
|
||||
// A suspension in one region cannot affect a combo sold in another.
|
||||
if (comboRegionId != null && comboRegionId !== regionId) return false
|
||||
return !marketStatsForRegion(combo.marketStats, regionId)?.isSuspendedInRegion
|
||||
}
|
||||
|
||||
// Structural suspension reaches every region: regional combos only in
|
||||
// their own region, global combos in all of them.
|
||||
if (comboRegionId != null) {
|
||||
return !marketStatsForRegion(combo.marketStats, comboRegionId)?.isSuspendedInRegion
|
||||
}
|
||||
return (
|
||||
combo.marketStats.length < regionCount ||
|
||||
combo.marketStats.some((stats) => !stats.isSuspendedInRegion)
|
||||
)
|
||||
})
|
||||
.map((combo) => combo.id)
|
||||
|
||||
if (activeComboIds.length > 0) {
|
||||
throw new Error(
|
||||
`Cannot suspend SKU(s): they are members of combo(s) ${activeComboIds.join(', ')} that are not suspended`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// A regional admin editing a GLOBAL product may change only this region's market
|
||||
// data — never the product's structure (owned by the superadmin).
|
||||
async function updateProductMarketDataForRegion(regionId: number, id: number, input: any): Promise<void> {
|
||||
|
|
@ -532,8 +619,26 @@ async function updateProductMarketDataForRegion(regionId: number, id: number, in
|
|||
const existingSkus = await db.query.productSkus.findMany({
|
||||
where: eq(productSkus.productId, id),
|
||||
columns: { id: true },
|
||||
with: { marketStats: true },
|
||||
})
|
||||
const existingSkuIdSet = new Set(existingSkus.map((s) => s.id))
|
||||
const existingById = new Map(existingSkus.map((s) => [s.id, s]))
|
||||
|
||||
// This path returns before updateProduct's validation, so it needs the combo
|
||||
// guard too: a regional admin must not suspend a global component while a
|
||||
// combo that contains it is still active in this region.
|
||||
const skusBeingSuspended = skus.filter((sku: any) => {
|
||||
if (sku?.id == null || !existingSkuIdSet.has(sku.id)) return false
|
||||
return (
|
||||
sku.isSuspendedInRegion === true &&
|
||||
!marketStatsForRegion(existingById.get(sku.id)!.marketStats, regionId)?.isSuspendedInRegion
|
||||
)
|
||||
})
|
||||
await assertNoActiveComboMembers(
|
||||
skusBeingSuspended.map((sku: any) => Number(sku.id)),
|
||||
regionId
|
||||
)
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
for (const sku of skus) {
|
||||
if (sku?.id == null || !existingSkuIdSet.has(sku.id)) continue
|
||||
|
|
@ -608,9 +713,10 @@ export async function updateProduct(regionId: number | null, id: number, input:
|
|||
|
||||
const existingSkus = await db.query.productSkus.findMany({
|
||||
where: eq(productSkus.productId, id),
|
||||
columns: { id: true },
|
||||
columns: { id: true, isSuspended: true },
|
||||
with: { marketStats: true },
|
||||
})
|
||||
const existingSkuIdSet = new Set(existingSkus.map((s) => s.id))
|
||||
const existingById = new Map(existingSkus.map((s) => [s.id, s]))
|
||||
|
||||
await assertSkuIdsInRegion(
|
||||
db,
|
||||
|
|
@ -619,33 +725,24 @@ 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 a false -> true transition suspends; the admin form re-sends the flag
|
||||
// on every edit, so re-saving an already-suspended SKU must stay allowed.
|
||||
// The flag this caller can write differs: the superadmin owns the structural
|
||||
// flag, a region owns its market row.
|
||||
const skusBeingSuspended = skus.filter((sku: any) => {
|
||||
if (sku.id == null) return false
|
||||
const existing = existingById.get(sku.id)
|
||||
if (!existing) return false
|
||||
if (regionId == null) return sku.isSuspended === true && !existing.isSuspended
|
||||
return (
|
||||
sku.isSuspendedInRegion === true &&
|
||||
!marketStatsForRegion(existing.marketStats, regionId)?.isSuspendedInRegion
|
||||
)
|
||||
})
|
||||
await assertNoActiveComboMembers(
|
||||
skusBeingSuspended.map((sku: any) => Number(sku.id)),
|
||||
regionId
|
||||
)
|
||||
if (skusBeingSuspended.length > 0) {
|
||||
const suspendingIds = skusBeingSuspended.map((sku: any) => sku.id)
|
||||
const comboMemberships = await db.query.productCombos.findMany({
|
||||
where: inArray(productCombos.skuId, suspendingIds),
|
||||
columns: { comboSkuId: true },
|
||||
})
|
||||
const comboIds = Array.from(new Set(comboMemberships.map((c) => c.comboSkuId)))
|
||||
|
||||
if (comboIds.length > 0) {
|
||||
const combos = await db.query.productSkus.findMany({
|
||||
where: inArray(productSkus.id, comboIds),
|
||||
columns: { id: true, isSuspended: true },
|
||||
with: { marketStats: true },
|
||||
})
|
||||
const activeComboIds = combos
|
||||
.filter((c) => !isSkuSuspended(c.isSuspended, marketStatsForRegion(c.marketStats, regionId)))
|
||||
.map((c) => c.id)
|
||||
if (activeComboIds.length > 0) {
|
||||
throw new Error(
|
||||
`Cannot suspend SKU(s): they are members of combo(s) ${activeComboIds.join(', ')} that are not suspended`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
@ -676,7 +773,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 +795,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 +853,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) => {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,13 @@ import type {
|
|||
// Bounds are ordered by numeric priority ascending (lower number = higher precedence).
|
||||
const priorityOrder = sql`CAST(${regionBounds.priority} AS REAL) ASC`
|
||||
|
||||
// D1 caps a single statement at 100 bound parameters. Creation seeds every
|
||||
// bound in one go, so keep each multi-row insert under that cap:
|
||||
// region_bounds -> 6 columns/row (16 rows = 96 params)
|
||||
// region_bound_consts -> 4 columns/row (25 rows = 100 params)
|
||||
const REGION_BOUND_INSERT_CHUNK_SIZE = 16
|
||||
const BOUND_CONST_INSERT_CHUNK_SIZE = 25
|
||||
|
||||
/**
|
||||
* Bounding-box centre of a bound's GeoJSON: every coordinate of every feature is
|
||||
* visited, so a Polygon and a MultiPolygon are both handled (the client never
|
||||
|
|
@ -224,31 +231,39 @@ export async function createRegionWithBounds(
|
|||
0
|
||||
)
|
||||
|
||||
const inserted = await tx
|
||||
.insert(regionBounds)
|
||||
.values(
|
||||
input.bounds.map((bound, index) => {
|
||||
const center =
|
||||
index === firstPriorityIndex && input.center != null
|
||||
? input.center
|
||||
: boundCenter(bound.geojson)
|
||||
return {
|
||||
regionId: region.id,
|
||||
description: bound.description ?? null,
|
||||
geojson: bound.geojson,
|
||||
priority: String(bound.priority),
|
||||
centerLat: center?.lat ?? null,
|
||||
centerLng: center?.lng ?? null,
|
||||
}
|
||||
})
|
||||
const boundValues = input.bounds.map((bound, index) => {
|
||||
const center =
|
||||
index === firstPriorityIndex && input.center != null
|
||||
? input.center
|
||||
: boundCenter(bound.geojson)
|
||||
return {
|
||||
regionId: region.id,
|
||||
description: bound.description ?? null,
|
||||
geojson: bound.geojson,
|
||||
priority: String(bound.priority),
|
||||
centerLat: center?.lat ?? null,
|
||||
centerLng: center?.lng ?? null,
|
||||
}
|
||||
})
|
||||
|
||||
const inserted: Array<typeof regionBounds.$inferSelect> = []
|
||||
for (let i = 0; i < boundValues.length; i += REGION_BOUND_INSERT_CHUNK_SIZE) {
|
||||
inserted.push(
|
||||
...(await tx
|
||||
.insert(regionBounds)
|
||||
.values(boundValues.slice(i, i + REGION_BOUND_INSERT_CHUNK_SIZE))
|
||||
.returning())
|
||||
)
|
||||
.returning()
|
||||
}
|
||||
|
||||
await tx.insert(regionConsts).values(defaultRegionRows(region.id)).onConflictDoNothing()
|
||||
|
||||
const boundRows = inserted.flatMap((bound) => defaultBoundRows(region.id, bound.id))
|
||||
if (boundRows.length > 0) {
|
||||
await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing()
|
||||
for (let i = 0; i < boundRows.length; i += BOUND_CONST_INSERT_CHUNK_SIZE) {
|
||||
await tx
|
||||
.insert(regionBoundConsts)
|
||||
.values(boundRows.slice(i, i + BOUND_CONST_INSERT_CHUNK_SIZE))
|
||||
.onConflictDoNothing()
|
||||
}
|
||||
|
||||
// Seed this region with every global SKU's market-stats row, copied from
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -61,7 +61,12 @@ export async function getProductAvailability(regionId: number): Promise<UserSlot
|
|||
// Global products (null region) are servable in every region.
|
||||
return productRegionId === regionId || productRegionId == null
|
||||
})
|
||||
.filter((stat) => !(stat as typeof stat & { sku?: { isSuspended?: boolean } | null }).sku?.isSuspended)
|
||||
.filter((stat) => {
|
||||
const sku = (stat as typeof stat & { sku?: { isSuspended?: boolean; isDeleted?: boolean } | null }).sku
|
||||
// Market rows outlive a soft delete, so row presence no longer means
|
||||
// "sellable": mirror the catalogue and drop deleted SKUs here too.
|
||||
return !sku?.isSuspended && !sku?.isDeleted
|
||||
})
|
||||
.map((stat) => ({
|
||||
id: stat.skuId,
|
||||
isOutOfStock: stat.isOutOfStock,
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -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[]
|
||||
}
|
||||
|
|
|
|||
165
unfixed-issues-MULTI_REGION_I2.md
Normal file
165
unfixed-issues-MULTI_REGION_I2.md
Normal 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.
|
||||
Loading…
Add table
Reference in a new issue