enh
This commit is contained in:
parent
bebe23f5f0
commit
8889556bdf
9 changed files with 468 additions and 53 deletions
|
|
@ -23,7 +23,8 @@ interface VariantState {
|
||||||
isFlashAvailable: boolean
|
isFlashAvailable: boolean
|
||||||
isOutOfStock: boolean
|
isOutOfStock: boolean
|
||||||
isOffer: boolean
|
isOffer: boolean
|
||||||
isSuspended: boolean
|
/** This region's suspension — separate from the superadmin's global kill-switch. */
|
||||||
|
isSuspendedInRegion: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const toNumOrUndef = (v: string): number | undefined => {
|
const toNumOrUndef = (v: string): number | undefined => {
|
||||||
|
|
@ -44,7 +45,7 @@ function GlobalProductForm({ product, onSubmit, isLoading }: GlobalProductFormPr
|
||||||
isFlashAvailable: sku.isFlashAvailable ?? false,
|
isFlashAvailable: sku.isFlashAvailable ?? false,
|
||||||
isOutOfStock: sku.isOutOfStock ?? false,
|
isOutOfStock: sku.isOutOfStock ?? false,
|
||||||
isOffer: sku.isOffer ?? false,
|
isOffer: sku.isOffer ?? false,
|
||||||
isSuspended: sku.isSuspended ?? false,
|
isSuspendedInRegion: sku.isSuspendedInRegion ?? false,
|
||||||
})),
|
})),
|
||||||
[product]
|
[product]
|
||||||
)
|
)
|
||||||
|
|
@ -68,7 +69,10 @@ function GlobalProductForm({ product, onSubmit, isLoading }: GlobalProductFormPr
|
||||||
isOffer: v.isOffer,
|
isOffer: v.isOffer,
|
||||||
isComboOnly: sku.isComboOnly ?? false,
|
isComboOnly: sku.isComboOnly ?? false,
|
||||||
isDeleted: sku.isDeleted ?? false,
|
isDeleted: sku.isDeleted ?? false,
|
||||||
isSuspended: v.isSuspended,
|
// The global kill-switch is read-only for a region; the checkbox only
|
||||||
|
// owns this region's suspension flag.
|
||||||
|
isSuspended: sku.isSuspended ?? false,
|
||||||
|
isSuspendedInRegion: v.isSuspendedInRegion,
|
||||||
features: (sku.features || []).map((f) => ({
|
features: (sku.features || []).map((f) => ({
|
||||||
featureName: f.featureName,
|
featureName: f.featureName,
|
||||||
featureValue: f.featureValue,
|
featureValue: f.featureValue,
|
||||||
|
|
@ -173,8 +177,8 @@ function GlobalProductForm({ product, onSubmit, isLoading }: GlobalProductFormPr
|
||||||
<View style={tw`flex-row items-center mb-1`}>
|
<View style={tw`flex-row items-center mb-1`}>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
testID={`global-sku-${sku.id}-suspend`}
|
testID={`global-sku-${sku.id}-suspend`}
|
||||||
checked={v.isSuspended}
|
checked={v.isSuspendedInRegion}
|
||||||
onPress={() => setVariant(index, { isSuspended: !v.isSuspended })}
|
onPress={() => setVariant(index, { isSuspendedInRegion: !v.isSuspendedInRegion })}
|
||||||
style={tw`mr-3`}
|
style={tw`mr-3`}
|
||||||
/>
|
/>
|
||||||
<MyText style={tw`text-gray-700 font-medium`}>Suspend in my region</MyText>
|
<MyText style={tw`text-gray-700 font-medium`}>Suspend in my region</MyText>
|
||||||
|
|
|
||||||
|
|
@ -91,7 +91,9 @@ describe('GlobalProductForm (AGP-01..09)', () => {
|
||||||
const [payload] = onSubmit.mock.calls[0]
|
const [payload] = onSubmit.mock.calls[0]
|
||||||
expect(payload[0].isOutOfStock).toBe(true)
|
expect(payload[0].isOutOfStock).toBe(true)
|
||||||
expect(payload[0].isOffer).toBe(true)
|
expect(payload[0].isOffer).toBe(true)
|
||||||
expect(payload[0].isSuspended).toBe(true)
|
// The toggle owns the region's suspension; the global kill-switch is untouched.
|
||||||
|
expect(payload[0].isSuspendedInRegion).toBe(true)
|
||||||
|
expect(payload[0].isSuspended).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('AGP-06: an empty price is sent as 0', () => {
|
it('AGP-06: an empty price is sent as 0', () => {
|
||||||
|
|
|
||||||
|
|
@ -122,11 +122,11 @@ describe('Edit product (APEDIT-01..20)', () => {
|
||||||
expect(view.getAllByText('Global Paneer').length).toBeGreaterThanOrEqual(1)
|
expect(view.getAllByText('Global Paneer').length).toBeGreaterThanOrEqual(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('APEDIT-05: the global suspend toggle starts from the SKU state', async () => {
|
it('APEDIT-05: the global suspend toggle starts from the regional flag', async () => {
|
||||||
setProcedure('admin.product.getProductById', {
|
setProcedure('admin.product.getProductById', {
|
||||||
data: {
|
data: {
|
||||||
product: globalProduct({
|
product: globalProduct({
|
||||||
skus: [{ ...P_GLOBAL.skus[0], isSuspended: true, isSuspendedInRegion: false }],
|
skus: [{ ...P_GLOBAL.skus[0], isSuspended: false, isSuspendedInRegion: true }],
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
@ -284,14 +284,16 @@ describe('Edit product (APEDIT-01..20)', () => {
|
||||||
expect(sku.flashPrice).toBeNull()
|
expect(sku.flashPrice).toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('APEDIT-17: suspending a global SKU sends the flag', async () => {
|
it('APEDIT-17: suspending a global SKU sends the regional flag', async () => {
|
||||||
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
|
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
|
||||||
const view = await renderEdit()
|
const view = await renderEdit()
|
||||||
|
|
||||||
fireEvent.press(view.getByTestId('global-sku-91-suspend'))
|
fireEvent.press(view.getByTestId('global-sku-91-suspend'))
|
||||||
await submitGlobal(view)
|
await submitGlobal(view)
|
||||||
|
|
||||||
expect((await updatedPayload()).skus[0].isSuspended).toBe(true)
|
const sku = (await updatedPayload()).skus[0]
|
||||||
|
expect(sku.isSuspendedInRegion).toBe(true)
|
||||||
|
expect(sku.isSuspended).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('APEDIT-18: a failed global save alerts', async () => {
|
it('APEDIT-18: a failed global save alerts', async () => {
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,8 @@ interface VariantState {
|
||||||
isFlashAvailable: boolean
|
isFlashAvailable: boolean
|
||||||
isOutOfStock: boolean
|
isOutOfStock: boolean
|
||||||
isOffer: boolean
|
isOffer: boolean
|
||||||
isSuspended: boolean
|
/** This region's suspension — separate from the superadmin's global kill-switch. */
|
||||||
|
isSuspendedInRegion: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const toNumOrUndef = (v: string): number | undefined => {
|
const toNumOrUndef = (v: string): number | undefined => {
|
||||||
|
|
@ -42,7 +43,7 @@ function GlobalProductForm({ product, onSubmit, isLoading }: GlobalProductFormPr
|
||||||
isFlashAvailable: sku.isFlashAvailable ?? false,
|
isFlashAvailable: sku.isFlashAvailable ?? false,
|
||||||
isOutOfStock: sku.isOutOfStock ?? false,
|
isOutOfStock: sku.isOutOfStock ?? false,
|
||||||
isOffer: sku.isOffer ?? false,
|
isOffer: sku.isOffer ?? false,
|
||||||
isSuspended: sku.isSuspended ?? false,
|
isSuspendedInRegion: sku.isSuspendedInRegion ?? false,
|
||||||
})),
|
})),
|
||||||
[product]
|
[product]
|
||||||
)
|
)
|
||||||
|
|
@ -66,7 +67,10 @@ function GlobalProductForm({ product, onSubmit, isLoading }: GlobalProductFormPr
|
||||||
isOffer: v.isOffer,
|
isOffer: v.isOffer,
|
||||||
isComboOnly: sku.isComboOnly ?? false,
|
isComboOnly: sku.isComboOnly ?? false,
|
||||||
isDeleted: sku.isDeleted ?? false,
|
isDeleted: sku.isDeleted ?? false,
|
||||||
isSuspended: v.isSuspended,
|
// The global kill-switch is read-only for a region; the checkbox only
|
||||||
|
// owns this region's suspension flag.
|
||||||
|
isSuspended: sku.isSuspended ?? false,
|
||||||
|
isSuspendedInRegion: v.isSuspendedInRegion,
|
||||||
features: (sku.features || []).map((f) => ({
|
features: (sku.features || []).map((f) => ({
|
||||||
featureName: f.featureName,
|
featureName: f.featureName,
|
||||||
featureValue: f.featureValue,
|
featureValue: f.featureValue,
|
||||||
|
|
@ -138,7 +142,7 @@ function GlobalProductForm({ product, onSubmit, isLoading }: GlobalProductFormPr
|
||||||
{v.isFlashAvailable && numberInput('Flash price (₹)', v.flashPrice, (t) => setVariant(index, { flashPrice: t }))}
|
{v.isFlashAvailable && numberInput('Flash price (₹)', v.flashPrice, (t) => setVariant(index, { flashPrice: t }))}
|
||||||
{toggle('Out of stock', v.isOutOfStock, () => setVariant(index, { isOutOfStock: !v.isOutOfStock }))}
|
{toggle('Out of stock', v.isOutOfStock, () => setVariant(index, { isOutOfStock: !v.isOutOfStock }))}
|
||||||
{toggle('Offer SKU', v.isOffer, () => setVariant(index, { isOffer: !v.isOffer }))}
|
{toggle('Offer SKU', v.isOffer, () => setVariant(index, { isOffer: !v.isOffer }))}
|
||||||
{toggle('Suspend in my region', v.isSuspended, () => setVariant(index, { isSuspended: !v.isSuspended }))}
|
{toggle('Suspend in my region', v.isSuspendedInRegion, () => setVariant(index, { isSuspendedInRegion: !v.isSuspendedInRegion }))}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
|
|
||||||
|
|
@ -1157,6 +1157,9 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
|
||||||
| APROD-75 | edge | empty response/images | accepted? assert |
|
| APROD-75 | edge | empty response/images | accepted? assert |
|
||||||
| APROD-76 | edge | upload URLs claim | validated/claimed |
|
| APROD-76 | edge | upload URLs claim | validated/claimed |
|
||||||
| APROD-77 | edge | user token write | current gap |
|
| APROD-77 | edge | user token write | current gap |
|
||||||
|
| 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 |
|
||||||
|
|
||||||
### 7.5 `admin.order`
|
### 7.5 `admin.order`
|
||||||
|
|
||||||
|
|
@ -1792,7 +1795,7 @@ and side-effect tests. Use this table as the completion gate.
|
||||||
| admin.product | deleteProduct | APROD-43..45 |
|
| admin.product | deleteProduct | APROD-43..45 |
|
||||||
| admin.product | toggleOutOfStock | APROD-46..50 |
|
| admin.product | toggleOutOfStock | APROD-46..50 |
|
||||||
| admin.product | createProduct | APROD-17..33 |
|
| admin.product | createProduct | APROD-17..33 |
|
||||||
| admin.product | updateProduct | APROD-34..42 |
|
| admin.product | updateProduct | APROD-34..42, 78..80 |
|
||||||
| admin.product | getProductReviews | APROD-09..12 |
|
| admin.product | getProductReviews | APROD-09..12 |
|
||||||
| admin.product | respondToReview | APROD-73..77 |
|
| admin.product | respondToReview | APROD-73..77 |
|
||||||
| admin.product | getGroups | APROD-13 |
|
| admin.product | getGroups | APROD-13 |
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,6 @@ import { createAvailabilityCacheFile } from '@/src/lib/cloud_cache'
|
||||||
import {
|
import {
|
||||||
getAllProducts as getAllProductsInDb,
|
getAllProducts as getAllProductsInDb,
|
||||||
getProductById as getProductByIdInDb,
|
getProductById as getProductByIdInDb,
|
||||||
getProductImageKeys as getProductImageKeysInDb,
|
|
||||||
deleteProduct as deleteProductInDb,
|
deleteProduct as deleteProductInDb,
|
||||||
getProductReviews as getProductReviewsInDb,
|
getProductReviews as getProductReviewsInDb,
|
||||||
respondToReview as respondToReviewInDb,
|
respondToReview as respondToReviewInDb,
|
||||||
|
|
@ -31,6 +30,7 @@ import {
|
||||||
getProductTagById as getProductTagByIdInDb,
|
getProductTagById as getProductTagByIdInDb,
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
import type {
|
import type {
|
||||||
|
AdminProductWithDetails,
|
||||||
AdminProductWithRelations,
|
AdminProductWithRelations,
|
||||||
AdminProductGroupsResult,
|
AdminProductGroupsResult,
|
||||||
AdminProductGroupResponse,
|
AdminProductGroupResponse,
|
||||||
|
|
@ -43,6 +43,119 @@ import type {
|
||||||
AdminToggleOutOfStockResult,
|
AdminToggleOutOfStockResult,
|
||||||
} from '@packages/shared'
|
} from '@packages/shared'
|
||||||
|
|
||||||
|
const updateProductInput = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string().min(1, 'Name is required'),
|
||||||
|
shortDescription: z.string().optional(),
|
||||||
|
longDescription: z.string().optional(),
|
||||||
|
storeId: z.number().min(1, 'Store is required'),
|
||||||
|
incrementStep: z.number().optional().default(1),
|
||||||
|
productType: z.enum(['item', 'combo']).optional(),
|
||||||
|
skus: z.array(z.object({
|
||||||
|
id: z.number().optional(),
|
||||||
|
name: z.string().optional().nullable(),
|
||||||
|
price: z.number().positive('Price must be positive'),
|
||||||
|
marketPrice: z.number().optional().nullable(),
|
||||||
|
images: z.array(z.string()).optional().default([]),
|
||||||
|
isFlashAvailable: z.boolean().optional().default(false),
|
||||||
|
flashPrice: z.number().optional().nullable(),
|
||||||
|
isOutOfStock: z.boolean().optional().default(false),
|
||||||
|
isOffer: z.boolean().optional().default(false),
|
||||||
|
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'),
|
||||||
|
})).min(1, 'At least one feature is required'),
|
||||||
|
comboItems: z.array(z.object({
|
||||||
|
skuId: z.number().int().positive(),
|
||||||
|
})).optional(),
|
||||||
|
})).min(1, 'At least one SKU is required'),
|
||||||
|
deletedImageKeys: z.array(z.string()).optional().default([]),
|
||||||
|
newImageUrls: z.array(z.string()).optional().default([]),
|
||||||
|
})
|
||||||
|
|
||||||
|
type UpdateProductInput = z.infer<typeof updateProductInput>
|
||||||
|
|
||||||
|
const normalizeText = (value: string | null | undefined): string => (value ?? '').trim()
|
||||||
|
|
||||||
|
const sameText = (a: string | null | undefined, b: string | null | undefined): boolean =>
|
||||||
|
normalizeText(a) === normalizeText(b)
|
||||||
|
|
||||||
|
/** Order-insensitive comparison of image keys / combo SKU ids. */
|
||||||
|
const sameKeySet = (a: Array<string | number>, b: Array<string | number>): boolean => {
|
||||||
|
const left = new Set(a.map((value) => normalizeAssetRef(String(value))).filter(Boolean))
|
||||||
|
const right = new Set(b.map((value) => normalizeAssetRef(String(value))).filter(Boolean))
|
||||||
|
return left.size === right.size && [...left].every((key) => right.has(key))
|
||||||
|
}
|
||||||
|
|
||||||
|
const sameFeatures = (
|
||||||
|
incoming: Array<{ featureName?: string | null; featureValue: string }>,
|
||||||
|
current: Array<{ featureName: string | null; featureValue: string }>
|
||||||
|
): boolean =>
|
||||||
|
incoming.length === current.length &&
|
||||||
|
incoming.every(
|
||||||
|
(feature, index) =>
|
||||||
|
normalizeText(feature.featureName) === normalizeText(current[index].featureName) &&
|
||||||
|
feature.featureValue === current[index].featureValue
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A global product is owned by the superadmin; a regional admin may only change
|
||||||
|
* this region's market data (price, stock, offer, flash, regional suspension).
|
||||||
|
* Everything structural is rejected before any side effect runs, so image
|
||||||
|
* deletion/claiming can never touch the shared product.
|
||||||
|
*/
|
||||||
|
function assertRegionalGlobalProductEdit(current: AdminProductWithDetails, input: UpdateProductInput): void {
|
||||||
|
const blocked: string[] = []
|
||||||
|
|
||||||
|
if (!sameText(input.name, current.name)) blocked.push('name')
|
||||||
|
if (!sameText(input.shortDescription, current.shortDescription)) blocked.push('shortDescription')
|
||||||
|
if (!sameText(input.longDescription, current.longDescription)) blocked.push('longDescription')
|
||||||
|
if (input.storeId !== current.storeId) blocked.push('storeId')
|
||||||
|
if (input.incrementStep !== current.incrementStep) blocked.push('incrementStep')
|
||||||
|
if (input.productType != null && input.productType !== current.productType) blocked.push('productType')
|
||||||
|
if (input.deletedImageKeys.length > 0) blocked.push('deletedImageKeys')
|
||||||
|
if (input.newImageUrls.length > 0) blocked.push('newImageUrls')
|
||||||
|
|
||||||
|
const currentById = new Map(current.skus.map((sku) => [sku.id, sku]))
|
||||||
|
|
||||||
|
for (const sku of input.skus) {
|
||||||
|
if (sku.id == null) {
|
||||||
|
blocked.push('new SKU')
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = currentById.get(sku.id)
|
||||||
|
if (!existing) {
|
||||||
|
blocked.push(`SKU ${sku.id}`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sameText(sku.name, existing.name)) blocked.push(`SKU ${sku.id} name`)
|
||||||
|
if (!sameKeySet(sku.images, existing.imageKeys ?? [])) blocked.push(`SKU ${sku.id} images`)
|
||||||
|
if (!sameFeatures(sku.features, existing.features)) blocked.push(`SKU ${sku.id} features`)
|
||||||
|
if (!sameKeySet(
|
||||||
|
(sku.comboItems ?? []).map((item) => item.skuId),
|
||||||
|
(existing.comboItems ?? []).map((item) => item.skuId)
|
||||||
|
)) {
|
||||||
|
blocked.push(`SKU ${sku.id} comboItems`)
|
||||||
|
}
|
||||||
|
if ((sku.isComboOnly ?? false) !== existing.isComboOnly) blocked.push(`SKU ${sku.id} isComboOnly`)
|
||||||
|
if ((sku.isDeleted ?? false) !== existing.isDeleted) blocked.push(`SKU ${sku.id} isDeleted`)
|
||||||
|
if ((sku.isSuspended ?? false) !== existing.isSuspended) blocked.push(`SKU ${sku.id} isSuspended`)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (blocked.length > 0) {
|
||||||
|
throw new ApiError(
|
||||||
|
`A regional admin can only edit this global product's market data for their region. Rejected fields: ${[...new Set(blocked)].join(', ')}.`,
|
||||||
|
403
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const productRouter = router({
|
export const productRouter = router({
|
||||||
getProducts: protectedProcedure
|
getProducts: protectedProcedure
|
||||||
.query(async ({ ctx }): Promise<AdminProductListResponse> => {
|
.query(async ({ ctx }): Promise<AdminProductListResponse> => {
|
||||||
|
|
@ -271,47 +384,32 @@ export const productRouter = router({
|
||||||
}),
|
}),
|
||||||
|
|
||||||
updateProduct: protectedProcedure
|
updateProduct: protectedProcedure
|
||||||
.input(z.object({
|
.input(updateProductInput)
|
||||||
id: z.number(),
|
|
||||||
name: z.string().min(1, 'Name is required'),
|
|
||||||
shortDescription: z.string().optional(),
|
|
||||||
longDescription: z.string().optional(),
|
|
||||||
storeId: z.number().min(1, 'Store is required'),
|
|
||||||
incrementStep: z.number().optional().default(1),
|
|
||||||
productType: z.enum(['item', 'combo']).optional(),
|
|
||||||
skus: z.array(z.object({
|
|
||||||
id: z.number().optional(),
|
|
||||||
name: z.string().optional().nullable(),
|
|
||||||
price: z.number().positive('Price must be positive'),
|
|
||||||
marketPrice: z.number().optional().nullable(),
|
|
||||||
images: z.array(z.string()).optional().default([]),
|
|
||||||
isFlashAvailable: z.boolean().optional().default(false),
|
|
||||||
flashPrice: z.number().optional().nullable(),
|
|
||||||
isOutOfStock: z.boolean().optional().default(false),
|
|
||||||
isOffer: z.boolean().optional().default(false),
|
|
||||||
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'),
|
|
||||||
})).min(1, 'At least one feature is required'),
|
|
||||||
comboItems: z.array(z.object({
|
|
||||||
skuId: z.number().int().positive(),
|
|
||||||
})).optional(),
|
|
||||||
})).min(1, 'At least one SKU is required'),
|
|
||||||
deletedImageKeys: z.array(z.string()).optional().default([]),
|
|
||||||
newImageUrls: z.array(z.string()).optional().default([]),
|
|
||||||
}))
|
|
||||||
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
||||||
const { id, name, shortDescription, longDescription, storeId, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
|
const { id, name, shortDescription, longDescription, storeId, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
|
||||||
|
|
||||||
|
// Resolve the product before any side effect: an unknown/foreign product must
|
||||||
|
// 404 without deleting images, and a global product needs its structure
|
||||||
|
// checked before the update is allowed to touch the shared record.
|
||||||
|
const existingProduct = await getProductByIdInDb(ctx.staffUser!.regionId, id)
|
||||||
|
if (!existingProduct) {
|
||||||
|
throw new ApiError('Product not found', 404)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existingProduct.isGlobal) {
|
||||||
|
assertRegionalGlobalProductEdit(existingProduct, input)
|
||||||
|
}
|
||||||
|
|
||||||
// The product's own images are re-sent on every edit, so only the keys it does not already
|
// The product's own images are re-sent on every edit, so only the keys it does not already
|
||||||
// own count as new references: those (plus the declared newImageUrls) must be real pending
|
// own count as new references: those (plus the declared newImageUrls) must be real pending
|
||||||
// uploads. Without this a fabricated key — or another product's already-claimed image —
|
// uploads. Without this a fabricated key — or another product's already-claimed image —
|
||||||
// could be written straight onto a SKU through `skus[].images`.
|
// could be written straight onto a SKU through `skus[].images`.
|
||||||
const currentImageKeys = new Set(await getProductImageKeysInDb(ctx.staffUser!.regionId, id))
|
const currentImageKeys = new Set(
|
||||||
|
existingProduct.skus
|
||||||
|
.flatMap((sku) => sku.imageKeys ?? [])
|
||||||
|
.map((key) => normalizeAssetRef(key))
|
||||||
|
.filter(Boolean)
|
||||||
|
)
|
||||||
const incomingImageKeys = skus.flatMap((sku) =>
|
const incomingImageKeys = skus.flatMap((sku) =>
|
||||||
sku.images.map((url) => extractKeyFromPresignedUrl(url))
|
sku.images.map((url) => extractKeyFromPresignedUrl(url))
|
||||||
)
|
)
|
||||||
|
|
@ -326,8 +424,13 @@ export const productRouter = router({
|
||||||
// Before deleting any current image or writing the update: the new uploads must be real.
|
// Before deleting any current image or writing the update: the new uploads must be real.
|
||||||
await assertUploadUrlsClaimable(uploadsToValidate)
|
await assertUploadUrlsClaimable(uploadsToValidate)
|
||||||
|
|
||||||
if (deletedImageKeys.length > 0) {
|
// Delete only objects this product currently references; an arbitrary key
|
||||||
await deleteImageUtil({ keys: deletedImageKeys })
|
// must not reach the shared bucket.
|
||||||
|
const ownedDeletedImageKeys = deletedImageKeys.filter((key) =>
|
||||||
|
currentImageKeys.has(normalizeAssetRef(key))
|
||||||
|
)
|
||||||
|
if (ownedDeletedImageKeys.length > 0) {
|
||||||
|
await deleteImageUtil({ keys: ownedDeletedImageKeys })
|
||||||
}
|
}
|
||||||
|
|
||||||
const skuInputs = skus.map((sku) => ({
|
const skuInputs = skus.map((sku) => ({
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api'
|
import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api'
|
||||||
import { staffClient } from '../helpers/sessions'
|
import { staffClient, superadminClient } from '../helpers/sessions'
|
||||||
import { createProduct, createStore } from '../helpers/fixtures'
|
import { createProduct, createStore } from '../helpers/fixtures'
|
||||||
import { getEssentialConsts, scaffoldCache } from '../helpers/cache'
|
import { getEssentialConsts, scaffoldCache } from '../helpers/cache'
|
||||||
import { TEST_REGION_ID } from '../helpers/env'
|
import { TEST_REGION_ID } from '../helpers/env'
|
||||||
|
|
@ -108,6 +108,34 @@ async function createMultiSku(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Elevate a regional product to a global store (superadmin), returning the store
|
||||||
|
* the product now belongs to. Used by the regional-market-update guard cases.
|
||||||
|
*/
|
||||||
|
async function elevateToGlobal(
|
||||||
|
admin: ApiClient,
|
||||||
|
storeId: number,
|
||||||
|
skus: any[]
|
||||||
|
): Promise<{ productId: number; skuIds: number[]; storeId: number }> {
|
||||||
|
const created: any = await rawCreate(admin, { storeId, skus })
|
||||||
|
const productId = Number(created.product.id)
|
||||||
|
|
||||||
|
const superadmin = await superadminClient()
|
||||||
|
const globalStore: any = await superadmin.superadmin.globalStores.create.mutate({
|
||||||
|
name: `E2E GP store ${uniqueSuffix()}`,
|
||||||
|
description: 'Global-product fixture',
|
||||||
|
})
|
||||||
|
const globalStoreId = Number(globalStore.store.id)
|
||||||
|
|
||||||
|
await superadmin.superadmin.products.elevate.mutate({ productId, storeId: globalStoreId })
|
||||||
|
|
||||||
|
return {
|
||||||
|
productId,
|
||||||
|
skuIds: created.product.skus.map((s: any) => Number(s.id)),
|
||||||
|
storeId: globalStoreId,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
describe('admin.product.createProduct (APROD-17..33)', () => {
|
describe('admin.product.createProduct (APROD-17..33)', () => {
|
||||||
it('APROD-17: createProduct returns product/SKU ids, feature quantity and images', async () => {
|
it('APROD-17: createProduct returns product/SKU ids, feature quantity and images', async () => {
|
||||||
const admin = await staffClient()
|
const admin = await staffClient()
|
||||||
|
|
@ -594,6 +622,98 @@ describe('admin.product.updateProduct (APROD-34..42)', () => {
|
||||||
`products.json shows SKU ${skuId} at price 777`
|
`products.json shows SKU ${skuId} at price 777`
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('APROD-78: a regional admin can edit a global product market data', async () => {
|
||||||
|
const admin = await staffClient()
|
||||||
|
const store = await createStore()
|
||||||
|
const global = await elevateToGlobal(admin, store.storeId, [skuInput({ price: 100 })])
|
||||||
|
const before = await readProduct(admin, global.productId)
|
||||||
|
|
||||||
|
const res: any = await admin.admin.product.updateProduct.mutate({
|
||||||
|
id: global.productId,
|
||||||
|
name: before.name,
|
||||||
|
shortDescription: before.shortDescription ?? undefined,
|
||||||
|
storeId: before.storeId,
|
||||||
|
incrementStep: before.incrementStep,
|
||||||
|
productType: before.productType,
|
||||||
|
skus: [skuInput({
|
||||||
|
id: global.skuIds[0],
|
||||||
|
name: before.skus[0].name,
|
||||||
|
price: 175,
|
||||||
|
marketPrice: 220,
|
||||||
|
isSuspendedInRegion: true,
|
||||||
|
})],
|
||||||
|
deletedImageKeys: [],
|
||||||
|
newImageUrls: [],
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(res.message).toBe('Product updated successfully')
|
||||||
|
|
||||||
|
const after = await readProduct(admin, global.productId)
|
||||||
|
expect(after.isGlobal).toBe(true)
|
||||||
|
expect(after.skus[0].price).toBe('175')
|
||||||
|
expect(after.skus[0].isSuspendedInRegion).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('APROD-79: a regional admin cannot change a global product structure', async () => {
|
||||||
|
const admin = await staffClient()
|
||||||
|
const store = await createStore()
|
||||||
|
const global = await elevateToGlobal(admin, store.storeId, [skuInput({ price: 100 })])
|
||||||
|
const before = await readProduct(admin, global.productId)
|
||||||
|
|
||||||
|
await expectTrpcError(
|
||||||
|
() =>
|
||||||
|
admin.admin.product.updateProduct.mutate({
|
||||||
|
id: global.productId,
|
||||||
|
name: `Renamed by region ${uniqueSuffix()}`,
|
||||||
|
shortDescription: before.shortDescription ?? undefined,
|
||||||
|
storeId: before.storeId,
|
||||||
|
incrementStep: before.incrementStep,
|
||||||
|
productType: before.productType,
|
||||||
|
skus: [skuInput({ id: global.skuIds[0], name: before.skus[0].name, price: 100 })],
|
||||||
|
deletedImageKeys: [],
|
||||||
|
newImageUrls: [],
|
||||||
|
}),
|
||||||
|
'FORBIDDEN',
|
||||||
|
'Rejected fields: name'
|
||||||
|
)
|
||||||
|
|
||||||
|
const after = await readProduct(admin, global.productId)
|
||||||
|
expect(after.name).toBe(before.name)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('APROD-80: a regional admin cannot delete a global product image', async () => {
|
||||||
|
const admin = await staffClient()
|
||||||
|
const store = await createStore()
|
||||||
|
const gen: any = await admin.common.generateUploadUrls.mutate({
|
||||||
|
contextString: 'product_info',
|
||||||
|
mimeTypes: ['image/png'],
|
||||||
|
})
|
||||||
|
const url = gen.uploadUrls[0]
|
||||||
|
const key = keyFromUrl(url)
|
||||||
|
const global = await elevateToGlobal(admin, store.storeId, [skuInput({ images: [url] })])
|
||||||
|
const before = await readProduct(admin, global.productId)
|
||||||
|
|
||||||
|
await expectTrpcError(
|
||||||
|
() =>
|
||||||
|
admin.admin.product.updateProduct.mutate({
|
||||||
|
id: global.productId,
|
||||||
|
name: before.name,
|
||||||
|
shortDescription: before.shortDescription ?? undefined,
|
||||||
|
storeId: before.storeId,
|
||||||
|
incrementStep: before.incrementStep,
|
||||||
|
productType: before.productType,
|
||||||
|
skus: [skuInput({ id: global.skuIds[0], name: before.skus[0].name, images: [] })],
|
||||||
|
deletedImageKeys: [key],
|
||||||
|
newImageUrls: [],
|
||||||
|
}),
|
||||||
|
'FORBIDDEN',
|
||||||
|
'deletedImageKeys'
|
||||||
|
)
|
||||||
|
|
||||||
|
const after = await readProduct(admin, global.productId)
|
||||||
|
expect(after.skus[0].imageKeys).toEqual([key])
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('admin.product.deleteProduct (APROD-43..45)', () => {
|
describe('admin.product.deleteProduct (APROD-43..45)', () => {
|
||||||
|
|
|
||||||
|
|
@ -8945,3 +8945,35 @@ typecheck clean; backend tests typecheck clean. Admin-ui coupon suites: 5
|
||||||
suites / 88 tests pass (detail 11, list 31, create 12, edit 10, form 24 —
|
suites / 88 tests pass (detail 11, list 31, create 12, edit 10, form 24 —
|
||||||
counts include the new cases). Backend admin-coupon suite: 37/37 passes
|
counts include the new cases). Backend admin-coupon suite: 37/37 passes
|
||||||
(including ACOUP-15B).
|
(including ACOUP-15B).
|
||||||
|
|
||||||
|
[2026-10-24 14:01:03 IST] Harden admin.product.updateProduct for global products (review finding #1).
|
||||||
|
Cause: a regional admin could send deletedImageKeys for a GLOBAL product. The
|
||||||
|
router deleted the S3 objects before any permission check while the DB update
|
||||||
|
applies market data only, leaving broken image references in every region.
|
||||||
|
|
||||||
|
Planned diff:
|
||||||
|
- apps/backend/src/trpc/apis/admin-apis/apis/product.ts
|
||||||
|
* extract the updateProduct input schema to `updateProductInput` (same shape).
|
||||||
|
* load the product region-aware before any side effect; 404 early.
|
||||||
|
* new assertRegionalGlobalProductEdit(): for a global product edited by a
|
||||||
|
regional admin, reject changes to name/shortDescription/longDescription/
|
||||||
|
storeId/incrementStep/productType, deletedImageKeys/newImageUrls, and any
|
||||||
|
SKU structural field (id/name/images/features/comboItems/isComboOnly/
|
||||||
|
isDeleted/isSuspended) with a 403 listing the rejected fields.
|
||||||
|
* delete only deletedImageKeys the product currently owns (keys are
|
||||||
|
normalised through normalizeAssetRef).
|
||||||
|
* drop the now-redundant getProductImageKeys lookup/import.
|
||||||
|
- apps/admin-ui/src/components/GlobalProductForm.tsx
|
||||||
|
* the "Suspend in my region" toggle reads/writes isSuspendedInRegion and the
|
||||||
|
payload keeps the global isSuspended unchanged.
|
||||||
|
- apps/admin-web/src/components/GlobalProductForm.tsx: same mirror change.
|
||||||
|
- apps/admin-ui/tests/components/global-product-form.test.tsx
|
||||||
|
* AGP-05 asserts isSuspendedInRegion.
|
||||||
|
- apps/admin-ui/tests/pages/product-edit.test.tsx
|
||||||
|
* APEDIT-05 checks the regional flag, APEDIT-17 asserts isSuspendedInRegion
|
||||||
|
(and that the global flag stays false).
|
||||||
|
- apps/backend/tests/api/admin-product-crud.test.ts
|
||||||
|
* APROD-78: a regional admin can still edit global market data (happy path).
|
||||||
|
* 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.
|
||||||
|
|
|
||||||
145
code-review-MULTI_REGION_I2.md
Normal file
145
code-review-MULTI_REGION_I2.md
Normal file
|
|
@ -0,0 +1,145 @@
|
||||||
|
# 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.
|
||||||
Loading…
Add table
Reference in a new issue