freshyo/apps/backend/tests/api/order-lifecycle-gaps.test.ts
2026-10-17 12:07:20 +05:30

212 lines
7 KiB
TypeScript

/**
* Order lifecycle gaps: coupon-usage rollback, first-order-only poisoning,
* cancel error swallowing and the (missing) status transition guards.
*
* Known bugs are pinned — see tests/BUGS.md.
*/
import { apiClient, captureError, uniqueSuffix } from '../helpers/api'
import {
createFutureSlot,
createStoreWithSku,
registerUserWithAddress,
} from '../helpers/fixtures'
import { staffSession } from '../helpers/sessions'
const couponCode = () =>
`LC${uniqueSuffix()}`.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 20)
describe('order lifecycle gaps', () => {
let admin: ReturnType<typeof apiClient>
let userToken = ''
let addressId = 0
let skuId = 0
let slotId = 0
beforeAll(async () => {
const staff = await staffSession()
admin = apiClient(staff.token)
const store = await createStoreWithSku({ price: 100 })
const slot = await createFutureSlot([store.skuId])
const buyer = await registerUserWithAddress()
userToken = buyer.token
addressId = buyer.addressId
skuId = store.skuId
slotId = slot.slotId
})
const place = (couponId?: number) =>
apiClient(userToken).user.order.placeOrder.mutate({
selectedItems: [{ skuId, quantity: 1, slotId }],
addressId,
regionId: 1,
...(couponId ? { couponIds: [couponId] } : {}),
})
const cancel = (id: number, reason = 'lifecycle test') =>
apiClient(userToken).user.order.cancelOrder.mutate({ id, reason })
const createCoupon = async (over: Record<string, unknown> = {}) => {
const created = await admin.admin.coupon.create.mutate({
couponCode: couponCode(),
minOrder: 1,
isApplyForAll: true,
validTill: new Date(Date.now() + 24 * 3600_000).toISOString(),
...over,
})
return created[0]
}
it('releases the coupon usage when the (only) order is cancelled', async () => {
const coupon = await createCoupon({ flatDiscount: 5, maxLimitForUser: 1 })
const placed = await place(coupon.id)
await cancel(placed.data[0].id)
// The usage row is deleted once every sibling order is cancelled, so the
// (now unused) coupon is spendable again.
const again = await place(coupon.id)
expect(again.success).toBe(true)
})
it('does not poison an isFirstOrderOnly coupon when the first order is cancelled', async () => {
const buyer = await registerUserWithAddress()
const coupon = await createCoupon({ flatDiscount: 5, isFirstOrderOnly: true })
// First order, then immediately cancelled.
const first = await apiClient(buyer.token).user.order.placeOrder.mutate({
selectedItems: [{ skuId, quantity: 1, slotId }],
addressId: buyer.addressId,
regionId: 1,
})
await apiClient(buyer.token).user.order.cancelOrder.mutate({
id: first.data[0].id,
reason: 'changed mind',
})
// countEffectiveOrders ignores cancelled orders, so the user is still a
// first-order customer and the coupon applies.
const res = await apiClient(buyer.token).user.order.placeOrder.mutate({
selectedItems: [{ skuId, quantity: 1, slotId }],
addressId: buyer.addressId,
regionId: 1,
couponIds: [coupon.id],
})
expect(res.success).toBe(true)
})
it('keeps the coupon while a sibling order survives, releasing only when all are cancelled', async () => {
const buyer = await registerUserWithAddress()
const secondSlot = await createFutureSlot([skuId])
const coupon = await createCoupon({ flatDiscount: 5, maxLimitForUser: 1 })
const placed = await apiClient(buyer.token).user.order.placeOrder.mutate({
selectedItems: [
{ skuId, quantity: 1, slotId },
{ skuId, quantity: 1, slotId: secondSlot.slotId },
],
addressId: buyer.addressId,
regionId: 1,
couponIds: [coupon.id],
})
expect(placed.data).toHaveLength(2)
const placeAgain = () =>
apiClient(buyer.token).user.order.placeOrder.mutate({
selectedItems: [{ skuId, quantity: 1, slotId }],
addressId: buyer.addressId,
regionId: 1,
couponIds: [coupon.id],
})
// Cancel one sibling: the coupon stays attached to the surviving order.
await apiClient(buyer.token).user.order.cancelOrder.mutate({
id: placed.data[0].id,
reason: 'partial',
})
const stillUsed = await captureError(() => placeAgain())
expect(stillUsed.message).toMatch(/usage limit/i)
// Cancel the last sibling: now the coupon is released.
await apiClient(buyer.token).user.order.cancelOrder.mutate({
id: placed.data[1].id,
reason: 'rest',
})
const again = await placeAgain()
expect(again.success).toBe(true)
})
it('applies an isFirstOrderOnly coupon to a genuinely new user', async () => {
const buyer = await registerUserWithAddress()
const coupon = await createCoupon({ flatDiscount: 5, isFirstOrderOnly: true })
const res = await apiClient(buyer.token).user.order.placeOrder.mutate({
selectedItems: [{ skuId, quantity: 1, slotId }],
addressId: buyer.addressId,
couponIds: [coupon.id],
})
expect(res.success).toBe(true)
})
it('pins: cancelling an already-cancelled order reports a generic message', async () => {
const placed = await place()
const orderId = placed.data[0].id
await cancel(orderId)
const error = await captureError(() => cancel(orderId))
// The specific "already cancelled" 400 is masked by cancelOrder's catch.
expect(error.message).toMatch(/failed to cancel order/i)
})
it('propagates the specific notes guard for a cancelled order', async () => {
const placed = await place()
const orderId = placed.data[0].id
await cancel(orderId)
const error = await captureError(() =>
apiClient(userToken).user.order.updateUserNotes.mutate({
id: orderId,
userNotes: 'too late',
})
)
// updateUserNotes has no catch, so the real message survives.
expect(error.message).toMatch(/cannot update notes for cancelled order/i)
})
it('pins: a cancelled order can still be marked delivered (no transition guard)', async () => {
const placed = await place()
const orderId = placed.data[0].id
await cancel(orderId)
const res = await admin.admin.order.updateDelivered.mutate({
orderId: String(orderId),
isDelivered: true,
})
expect(res.success).toBe(true)
})
it('pins: delivered is reversible', async () => {
const placed = await place()
const orderId = placed.data[0].id
await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: true })
const res = await admin.admin.order.updateDelivered.mutate({
orderId: String(orderId),
isDelivered: false,
})
expect(res.success).toBe(true)
})
it('rejects a user cancellation of a delivered order', async () => {
const placed = await place()
const orderId = placed.data[0].id
await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: true })
const error = await captureError(() => cancel(orderId))
expect(error.message).toMatch(/failed to cancel order/i)
})
})