This commit is contained in:
shafi54 2026-10-24 16:05:06 +05:30
parent bccc66372a
commit 0289c285c9
13 changed files with 809 additions and 220 deletions

View file

@ -10,10 +10,9 @@ import {
deleteGlobalProductById, deleteGlobalProductById,
} from '@/src/dbService' } from '@/src/dbService'
const skuInput = z.object({ const skuFields = {
id: z.number().int().positive().optional(), id: z.number().int().positive().optional(),
name: z.string().optional().nullable(), name: z.string().optional().nullable(),
price: z.number().nonnegative('Price must be positive'),
marketPrice: z.number().optional().nullable(), marketPrice: z.number().optional().nullable(),
images: z.array(z.string()).optional().default([]), images: z.array(z.string()).optional().default([]),
isFlashAvailable: z.boolean().optional().default(false), isFlashAvailable: z.boolean().optional().default(false),
@ -28,6 +27,21 @@ const skuInput = z.object({
featureValue: z.string().min(1, 'Value is required'), featureValue: z.string().min(1, 'Value is required'),
})).min(1, 'At least one feature is required'), })).min(1, 'At least one feature is required'),
comboItems: z.array(z.object({ skuId: z.number().int().positive() })).optional(), 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({ export const superadminGlobalProductsRouter = router({
@ -93,7 +107,19 @@ export const superadminGlobalProductsRouter = router({
storeId: z.number().min(1, 'A global store is required'), storeId: z.number().min(1, 'A global store is required'),
incrementStep: z.number().optional().default(1), incrementStep: z.number().optional().default(1),
productType: z.enum(['item', 'combo']).optional().default('item'), 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 }) => { .mutation(async ({ input }) => {
const { id, ...rest } = input const { id, ...rest } = input

View file

@ -91,6 +91,44 @@ async function readProduct(admin: ApiClient, id: number): Promise<any> {
return res.product 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. */ /** Create one product with a fixed number of SKUs and return ids. */
async function createMultiSku( async function createMultiSku(
admin: ApiClient, admin: ApiClient,
@ -774,8 +812,9 @@ describe('admin.product.updateProduct (APROD-34..42)', () => {
describe('admin.product.deleteProduct (APROD-43..45)', () => { describe('admin.product.deleteProduct (APROD-43..45)', () => {
it('APROD-43 (current): deleting a product with SKUs soft-deletes instead of failing', async () => { it('APROD-43 (current): deleting a product with SKUs soft-deletes instead of failing', async () => {
// `softDeleteProduct` flags the SKUs `isDeleted` and clears the dependent // `softDeleteProduct` flags the SKUs `isDeleted` and clears the dependent
// rows; no FK/raw failure is surfaced. `getProducts` then hides it while // rows (market pricing is kept so a restore is lossless); no FK/raw failure
// `getProductById` still returns the (soft-deleted) row. // is surfaced. `getProducts` then hides it while `getProductById` still
// returns the (soft-deleted) row.
const admin = await staffClient() const admin = await staffClient()
const store = await createStore() const store = await createStore()
const { productId, skuIds } = await createMultiSku(admin, store.storeId, 2) const { productId, skuIds } = await createMultiSku(admin, store.storeId, 2)
@ -823,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)', () => { describe('admin.product stock + prices (APROD-46..55)', () => {
it('APROD-46: toggling the whole product flips every SKU and bumps availability', async () => { it('APROD-46: toggling the whole product flips every SKU and bumps availability', async () => {
const admin = await staffClient() const admin = await staffClient()

View file

@ -153,6 +153,26 @@ describe('slots.json shape (CACHE-63..64, 68..69)', () => {
/* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */
describe('slots.json exclusions (CACHE-65..67, 75)', () => { 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 () => { it('CACHE-65: a slot whose delivery time has passed is excluded', async () => {
const admin = await staffClient() const admin = await staffClient()
const created = await createSlotAt(admin, { const created = await createSlotAt(admin, {

View file

@ -388,6 +388,60 @@ describe('superadmin.globalProducts.update (SGPROD-08..10)', () => {
expect(afterAdd.product.skus).toHaveLength(owned.skuIds.length + 1) 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 () => { it('SGPROD-17: adding a SKU to a global product seeds every region', async () => {
await ensureAtLeastRegions(12) await ensureAtLeastRegions(12)
const superadmin = await superadminClient() const superadmin = await superadminClient()
@ -433,6 +487,83 @@ describe('superadmin.globalProducts.delete (SGPROD-11..12)', () => {
expect(list.products.some((product: any) => Number(product.id) === owned.productId)).toBe(true) 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 () => { it('SGPROD-12: deleting an unknown product is 404', async () => {
const superadmin = await superadminClient() const superadmin = await superadminClient()
await expectTrpcError( await expectTrpcError(

View file

@ -276,6 +276,31 @@ describe('superadmin.regions.create (SREG-04..11)', () => {
'BAD_REQUEST' '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')
}
})
}) })
/* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */

View 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 })
})
})

View 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) }
}

View file

@ -9,6 +9,7 @@ import { SimpleSelect } from '@/components/ui/simple-select'
import { alert, confirm } from '@/components/ui/dialog-host' import { alert, confirm } from '@/components/ui/dialog-host'
import { trpc } from '../lib/trpc-client' import { trpc } from '../lib/trpc-client'
import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage' import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage'
import { canSubmitGlobalProduct, skuPricePayload } from '../lib/global-product-form'
export const Route = createFileRoute('/global-products')({ export const Route = createFileRoute('/global-products')({
component: () => ( component: () => (
@ -407,18 +408,7 @@ function GlobalProductForm({
e.target.value = '' e.target.value = ''
} }
const canSubmit = const canSubmit = canSubmitGlobalProduct({ name, storeId, skus, pending, isUploading })
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 submit = async () => { const submit = async () => {
setError(null) setError(null)
@ -433,7 +423,7 @@ function GlobalProductForm({
skusPayload.push({ skusPayload.push({
id: s.id, id: s.id,
name: s.name || null, name: s.name || null,
price: parseFloat(s.price), ...skuPricePayload(s),
marketPrice: s.marketPrice.trim() !== '' ? parseFloat(s.marketPrice) : null, marketPrice: s.marketPrice.trim() !== '' ? parseFloat(s.marketPrice) : null,
images, images,
isFlashAvailable: false, isFlashAvailable: false,
@ -526,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 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"> <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="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" /> {sku.id == null ? (
<PInput topLabel="Market price (₹)" value={sku.marketPrice} onChange={(e) => updateSku(index, { marketPrice: e.target.value })} placeholder="Optional" /> <>
<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>
<div className="mt-3"> <div className="mt-3">

View file

@ -9209,3 +9209,225 @@ rolls the claim back) and UCOUP-18 (two-user race still resolves 1/1).
- user-ui ADDRF-38 rewrite: the shared resolveRegionByLocation spy also sees - user-ui ADDRF-38 rewrite: the shared resolveRegionByLocation spy also sees
useRegion's startup check, so the test now asserts the submitted update useRegion's startup check, so the test now asserts the submitted update
payload keeps the saved coordinates instead of asserting on the spy. 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.

View file

@ -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.

View file

@ -26,7 +26,7 @@ import {
} from '../db/schema' } from '../db/schema'
import { and, desc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm' import { and, desc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm'
import { runBatched } from '../lib/run-batched' 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' import type { InferSelectModel } from 'drizzle-orm'
// Chunk sizes for multi-row inserts so no single statement exceeds SQLite's // Chunk sizes for multi-row inserts so no single statement exceeds SQLite's
@ -364,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 * 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 * 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. * 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> { async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
const product = await db.query.productInfo.findFirst({ const product = await db.query.productInfo.findFirst({
@ -379,7 +384,6 @@ async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
if (skuIds.length > 0) { if (skuIds.length > 0) {
await db.batch([ await db.batch([
db.delete(productMarketStats).where(inArray(productMarketStats.skuId, skuIds)),
db.delete(cartItems).where(inArray(cartItems.skuId, skuIds)), db.delete(cartItems).where(inArray(cartItems.skuId, skuIds)),
// Coupon product targets are a JSON array on the coupon row itself; a deleted // 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 // SKU is deliberately left in it. It can never appear in a cart again, and
@ -537,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 // A regional admin editing a GLOBAL product may change only this region's market
// data — never the product's structure (owned by the superadmin). // data — never the product's structure (owned by the superadmin).
async function updateProductMarketDataForRegion(regionId: number, id: number, input: any): Promise<void> { async function updateProductMarketDataForRegion(regionId: number, id: number, input: any): Promise<void> {
@ -545,8 +619,26 @@ async function updateProductMarketDataForRegion(regionId: number, id: number, in
const existingSkus = await db.query.productSkus.findMany({ const existingSkus = await db.query.productSkus.findMany({
where: eq(productSkus.productId, id), where: eq(productSkus.productId, id),
columns: { id: true }, columns: { id: true },
with: { marketStats: true },
}) })
const existingSkuIdSet = new Set(existingSkus.map((s) => s.id)) 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) => { await db.transaction(async (tx) => {
for (const sku of skus) { for (const sku of skus) {
if (sku?.id == null || !existingSkuIdSet.has(sku.id)) continue if (sku?.id == null || !existingSkuIdSet.has(sku.id)) continue
@ -621,9 +713,10 @@ export async function updateProduct(regionId: number | null, id: number, input:
const existingSkus = await db.query.productSkus.findMany({ const existingSkus = await db.query.productSkus.findMany({
where: eq(productSkus.productId, id), 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( await assertSkuIdsInRegion(
db, db,
@ -632,38 +725,24 @@ export async function updateProduct(regionId: number | null, id: number, input:
'Combo SKU' 'Combo SKU'
) )
// Only the flag this caller can actually write counts: the superadmin owns // Only a false -> true transition suspends; the admin form re-sends the flag
// the structural flag, a region owns its market row. // 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) => { const skusBeingSuspended = skus.filter((sku: any) => {
if (sku.id == null || !existingSkuIdSet.has(sku.id)) return false if (sku.id == null) return false
return regionId == null const existing = existingById.get(sku.id)
? sku.isSuspended === true if (!existing) return false
: sku.isSuspendedInRegion === true if (regionId == null) return sku.isSuspended === true && !existing.isSuspended
return (
sku.isSuspendedInRegion === true &&
!marketStatsForRegion(existing.marketStats, regionId)?.isSuspendedInRegion
)
}) })
if (skusBeingSuspended.length > 0) { await assertNoActiveComboMembers(
const suspendingIds = skusBeingSuspended.map((sku: any) => sku.id) skusBeingSuspended.map((sku: any) => Number(sku.id)),
const comboMemberships = await db.query.productCombos.findMany({ regionId
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 { try {

View file

@ -19,6 +19,13 @@ import type {
// Bounds are ordered by numeric priority ascending (lower number = higher precedence). // Bounds are ordered by numeric priority ascending (lower number = higher precedence).
const priorityOrder = sql`CAST(${regionBounds.priority} AS REAL) ASC` 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 * 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 * visited, so a Polygon and a MultiPolygon are both handled (the client never
@ -224,31 +231,39 @@ export async function createRegionWithBounds(
0 0
) )
const inserted = await tx const boundValues = input.bounds.map((bound, index) => {
.insert(regionBounds) const center =
.values( index === firstPriorityIndex && input.center != null
input.bounds.map((bound, index) => { ? input.center
const center = : boundCenter(bound.geojson)
index === firstPriorityIndex && input.center != null return {
? input.center regionId: region.id,
: boundCenter(bound.geojson) description: bound.description ?? null,
return { geojson: bound.geojson,
regionId: region.id, priority: String(bound.priority),
description: bound.description ?? null, centerLat: center?.lat ?? null,
geojson: bound.geojson, centerLng: center?.lng ?? null,
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() await tx.insert(regionConsts).values(defaultRegionRows(region.id)).onConflictDoNothing()
const boundRows = inserted.flatMap((bound) => defaultBoundRows(region.id, bound.id)) const boundRows = inserted.flatMap((bound) => defaultBoundRows(region.id, bound.id))
if (boundRows.length > 0) { for (let i = 0; i < boundRows.length; i += BOUND_CONST_INSERT_CHUNK_SIZE) {
await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing() 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 // Seed this region with every global SKU's market-stats row, copied from

View file

@ -61,7 +61,12 @@ export async function getProductAvailability(regionId: number): Promise<UserSlot
// Global products (null region) are servable in every region. // Global products (null region) are servable in every region.
return productRegionId === regionId || productRegionId == null 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) => ({ .map((stat) => ({
id: stat.skuId, id: stat.skuId,
isOutOfStock: stat.isOutOfStock, isOutOfStock: stat.isOutOfStock,