This commit is contained in:
shafi54 2026-10-10 10:53:08 +05:30
parent 9ab47b32c4
commit 07f6a261a4
6 changed files with 110 additions and 18 deletions

View file

@ -15,6 +15,7 @@ import {
getUserOrderCount,
getUserOrdersWithRelations,
getUserSlotCapacityStatus,
getUserDeliverySlotById,
getEffectiveRegionSettings,
getEffectiveBoundId,
getRegionSettingsForBound,
@ -116,6 +117,24 @@ const placeOrderUtil = async (params: {
throw new ApiError(`Product ${item.skuId} not found`, 400);
}
// SEC-04: the SKU must belong to the region being ordered into. A product
// with no region is treated as not available anywhere.
if ((product.product?.regionId ?? null) !== params.regionId) {
throw new ApiError(
`Product ${item.skuId} is not available in this region`,
409
);
}
// SEC-05: never sell a deleted, out-of-stock or suspended product.
if (
product.isDeleted ||
product.isOutOfStock ||
product.marketStats?.isSuspended
) {
throw new ApiError(`Product ${item.skuId} is unavailable`, 400);
}
if (!ordersBySlot.has(item.slotId)) {
ordersBySlot.set(item.slotId, []);
}
@ -131,6 +150,48 @@ const placeOrderUtil = async (params: {
}
}
// SEC-05 / SL-04: validate every scheduled slot (existence, region, active
// state, freeze/delivery time) and that it actually carries the ordered SKUs.
if (!params.isFlash) {
for (const [slotId, items] of ordersBySlot) {
if (slotId == null) {
throw new ApiError("A delivery slot is required for scheduled orders", 400);
}
const slot = await getUserDeliverySlotById(slotId);
if (!slot) {
throw new ApiError("Selected delivery slot not found", 400);
}
if (slot.regionId !== params.regionId) {
throw new ApiError("Selected delivery slot belongs to a different region", 409);
}
if (!slot.isActive) {
throw new ApiError("Selected delivery slot is not available", 400);
}
const now = Date.now();
if (slot.freezeTime.getTime() <= now) {
throw new ApiError("Selected delivery slot is closed for orders", 400);
}
if (slot.deliveryTime.getTime() <= now) {
throw new ApiError("Selected delivery slot has already passed", 400);
}
const slotSkuIds = new Set(slot.skuIds ?? []);
for (const item of items) {
if (!slotSkuIds.has(item.skuId)) {
throw new ApiError(
`Product ${item.skuId} is not available in the selected delivery slot`,
400
);
}
}
}
}
let totalAmount = 0;
for (const [slotId, items] of ordersBySlot) {
const orderTotal = items.reduce(

View file

@ -199,6 +199,11 @@ test.)
**Pinned by:** `tests/api/place-order-edge-cases.test.ts`.
> **Fixed (FC-03/SEC-05):** `placeOrderUtil` now rejects a product that is
> `isDeleted`, `isOutOfStock` or `isSuspended` (400 "… is unavailable"). The
> cross-region-SKU case (FC-02/SEC-04) is rejected too: the SKU's product
> `regionId` must equal the order region (409).
### 14. An empty `selectedItems` list fails with a raw DB error
There is no `.min(1)` on `selectedItems`, so an empty list reaches Drizzle, which
@ -222,6 +227,12 @@ accepted.
**Pinned by:** `tests/api/place-order-edge-cases.test.ts`.
> **Fixed (FC-03/SEC-05, FC-13/SL-04):** `placeOrderUtil` now requires a
> non-null `slotId` for scheduled orders and validates the slot: it must exist,
> belong to the order region (409), be `isActive`, have `freezeTime > now` and
> `deliveryTime > now`, and carry every ordered `skuId` in `slot.skuIds` (400
> otherwise).
### 17. No idempotency
Two identical `placeOrder` calls create two orders (`orderGroupId` is

View file

@ -2,9 +2,9 @@
* placeOrder guard/behaviour coverage that the existing suites do not reach:
* stock, quantity, slot validity, flash pricing, suspension and double-submit.
*
* Several are known gaps (out-of-stock is orderable, empty carts are accepted,
* no quantity cap, no slot validity beyond capacity) and are pinned here.
* See tests/BUGS.md.
* Guards now enforced by placeOrderUtil (region, stock, slot state/membership)
* are asserted as rejections. Remaining gaps (empty carts, no quantity cap, no
* idempotency) are still pinned as known bugs. See tests/BUGS.md.
*/
import { apiClient, captureError } from '../helpers/api'
@ -59,6 +59,7 @@ describe('placeOrder edge cases', () => {
apiClient(userToken).user.order.placeOrder.mutate({
selectedItems: [{ skuId, quantity: 1, slotId }],
addressId,
regionId: 1,
paymentMethod: 'cod',
...over,
})
@ -75,14 +76,16 @@ describe('placeOrder edge cases', () => {
}
describe('stock', () => {
it('pins: an out-of-stock product is still orderable', async () => {
it('rejects an out-of-stock product', async () => {
const store = await createStoreWithSku({ price: 100 })
const slot = await createFutureSlot([store.skuId])
await admin.admin.product.toggleOutOfStock.mutate({ id: store.productId })
try {
const res = await place({ selectedItems: [{ skuId: store.skuId, quantity: 1, slotId: slot.slotId }] })
expect(res.success).toBe(true)
const error = await captureError(() =>
place({ selectedItems: [{ skuId: store.skuId, quantity: 1, slotId: slot.slotId }] })
)
expect(error.message).toMatch(/unavailable/i)
} finally {
await admin.admin.product.toggleOutOfStock.mutate({ id: store.productId })
}
@ -105,8 +108,8 @@ describe('placeOrder edge cases', () => {
})
})
describe('slot validity gaps', () => {
it('pins: an inactive slot is accepted', async () => {
describe('slot validity', () => {
it('rejects an inactive slot', async () => {
const created = await admin.admin.slots.createSlot.mutate({
deliveryTime: new Date(Date.now() + 3 * 3600_000).toISOString(),
freezeTime: new Date(Date.now() + 2 * 3600_000).toISOString(),
@ -114,11 +117,13 @@ describe('placeOrder edge cases', () => {
skuIds: [skuId],
})
const res = await place({ selectedItems: [{ skuId, quantity: 1, slotId: created.slot.id }] })
expect(res.success).toBe(true)
const error = await captureError(() =>
place({ selectedItems: [{ skuId, quantity: 1, slotId: created.slot.id }] })
)
expect(error.message).toMatch(/not available/i)
})
it('pins: a slot whose delivery time has passed is accepted', async () => {
it('rejects a slot whose freeze/delivery time has passed', async () => {
const created = await admin.admin.slots.createSlot.mutate({
deliveryTime: new Date(Date.now() - 3600_000).toISOString(),
freezeTime: new Date(Date.now() - 2 * 3600_000).toISOString(),
@ -126,17 +131,21 @@ describe('placeOrder edge cases', () => {
skuIds: [skuId],
})
const res = await place({ selectedItems: [{ skuId, quantity: 1, slotId: created.slot.id }] })
expect(res.success).toBe(true)
const error = await captureError(() =>
place({ selectedItems: [{ skuId, quantity: 1, slotId: created.slot.id }] })
)
expect(error.message).toMatch(/closed for orders/i)
})
it('pins: a slot that does not carry the ordered SKU is accepted', async () => {
it('rejects a slot that does not carry the ordered SKU', async () => {
const slotWithOtherSku = await createFutureSlot([otherSkuId])
const res = await place({
selectedItems: [{ skuId, quantity: 1, slotId: slotWithOtherSku.slotId }],
})
expect(res.success).toBe(true)
const error = await captureError(() =>
place({
selectedItems: [{ skuId, quantity: 1, slotId: slotWithOtherSku.slotId }],
})
)
expect(error.message).toMatch(/not available in the selected/i)
})
})

View file

@ -150,6 +150,7 @@ export async function ensureUserAddress(): Promise<{ addressId: number; created:
if (first) return { addressId: first.id, created: false }
const created = await client.user.address.createAddress.mutate({
regionId: 1,
name: 'API Test Address',
phone: '9999999999',
addressLine1: '1 API Test Street',
@ -183,6 +184,7 @@ export async function registerUserWithAddress(): Promise<{
const client = apiClient(token)
const created = await client.user.address.createAddress.mutate({
regionId: 1,
name: 'API Test Address',
phone: '9999999999',
addressLine1: '1 API Test Street',

View file

@ -218,6 +218,7 @@ export {
// User Slots
getActiveSlotsList as getUserActiveSlotsList,
getProductAvailability as getUserProductAvailability,
getDeliverySlotById as getUserDeliverySlotById,
} from './src/user-apis/slots'
export {

View file

@ -26,6 +26,14 @@ export async function getActiveSlotsList(regionId: number): Promise<UserDelivery
return slots.map(mapSlot)
}
/** Raw delivery-slot row (region, state, freeze/delivery time, skuIds). */
export async function getDeliverySlotById(slotId: number): Promise<SlotRow | null> {
const slot = await db.query.deliverySlotInfo.findFirst({
where: eq(deliverySlotInfo.id, slotId),
})
return slot ?? null
}
export async function getProductAvailability(regionId: number): Promise<UserSlotAvailability[]> {
const stats = await db.query.productMarketStats.findMany({
where: eq(productMarketStats.isSuspended, false),