freshyo/apps/backend/tests/api/coupon-ux.test.ts
2026-10-01 00:33:03 +05:30

251 lines
7.8 KiB
TypeScript

/**
* Coupon UX surfaces: reserved-code redemption, getMyCoupons, the admin create
* guards and the user-scoping bypass at placeOrder.
*
* See tests/BUGS.md for the pinned defects.
*/
import { apiClient, captureError, uniqueSuffix } from '../helpers/api'
import {
createFutureSlot,
createStoreWithSku,
registerUserWithAddress,
} from '../helpers/fixtures'
import { staffSession } from '../helpers/sessions'
const code = (prefix = 'UX') =>
`${prefix}${uniqueSuffix()}`.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 20)
const future = () => new Date(Date.now() + 24 * 3600_000).toISOString()
describe('coupon UX', () => {
let admin: ReturnType<typeof apiClient>
let userA: { token: string; userId: number; addressId: number }
let userB: { token: string; userId: number; addressId: number }
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])
userA = await registerUserWithAddress()
userB = await registerUserWithAddress()
skuId = store.skuId
slotId = slot.slotId
})
const createCoupon = async (over: Record<string, unknown> = {}) => {
const created = await admin.admin.coupon.create.mutate({
couponCode: code(),
minOrder: 1,
isApplyForAll: true,
validTill: future(),
...over,
})
return created[0]
}
const createReserved = async (over: Record<string, unknown> = {}) => {
const reservedCode = code('RSV')
const created = await admin.admin.coupon.createReservedCoupon.mutate({
couponCode: reservedCode,
flatDiscount: 5,
minOrder: 1,
validTill: future(),
...over,
})
return { secretCode: reservedCode, coupon: created[0] }
}
const redeem = (token: string, secretCode: string) =>
apiClient(token).user.coupon.redeemReservedCoupon.mutate({ secretCode })
const place = (
user: { token: string; addressId: number },
couponId?: number,
quantity = 1
) =>
apiClient(user.token).user.order.placeOrder.mutate({
selectedItems: [{ skuId, quantity, slotId }],
addressId: user.addressId,
paymentMethod: 'cod',
...(couponId ? { couponId } : {}),
})
describe('redeemReservedCoupon', () => {
it('redeems a reserved code for the user', async () => {
const { secretCode } = await createReserved()
const res = await redeem(userA.token, secretCode)
expect(res.success).toBe(true)
expect(res.coupon).toBeTruthy()
})
it('rejects a second redemption by the same user', async () => {
const { secretCode } = await createReserved()
await redeem(userA.token, secretCode)
const error = await captureError(() => redeem(userA.token, secretCode))
expect(error.message).toMatch(/already redeemed/i)
})
it('rejects redeeming an unknown code', async () => {
const error = await captureError(() => redeem(userA.token, code('NOPE')))
expect(error.message).toMatch(/invalid|redeemed/i)
})
/**
* KNOWN GAP: redemption does not check validTill (only the placeOrder
* path does), so an already-expired reserved code still redeems.
*/
it('pins: an expired reserved code still redeems', async () => {
const { secretCode } = await createReserved({
validTill: new Date(Date.now() - 3600_000).toISOString(),
})
const res = await redeem(userA.token, secretCode)
expect(res.success).toBe(true)
})
it('rejects an isFirstOrderOnly reserved code for a user with orders', async () => {
await place(userB) // give B an order
const { secretCode } = await createReserved({ isFirstOrderOnly: true })
const error = await captureError(() => redeem(userB.token, secretCode))
expect(error.message).toMatch(/first order only/i)
})
})
describe('getMyCoupons', () => {
it('categorises a user coupon as personal and an apply-for-all as general', async () => {
await createCoupon({
isUserBased: true,
isApplyForAll: false,
applicableUsers: [userA.userId],
flatDiscount: 5,
})
await createCoupon({ isApplyForAll: true, flatDiscount: 5 })
const res = await apiClient(userA.token).user.coupon.getMyCoupons.query()
expect(Array.isArray(res.data.personal)).toBe(true)
expect(Array.isArray(res.data.general)).toBe(true)
expect(res.data.personal.length).toBeGreaterThan(0)
expect(res.data.general.length).toBeGreaterThan(0)
})
it('marks a coupon isUsedUp once maxLimitForUser is reached', async () => {
const coupon = await createCoupon({
isUserBased: true,
isApplyForAll: false,
applicableUsers: [userA.userId],
flatDiscount: 5,
maxLimitForUser: 1,
})
await place(userA, coupon.id)
const res = await apiClient(userA.token).user.coupon.getMyCoupons.query()
const found = res.data.personal.find((c: { id: number }) => c.id === coupon.id)
expect(found).toBeDefined()
expect(found!.isUsedUp).toBe(true)
expect(found!.usageCount).toBe(1)
})
})
describe('admin coupon create guards', () => {
it('rejects both discount types', async () => {
const error = await captureError(() =>
admin.admin.coupon.create.mutate({
couponCode: code(),
discountPercent: 10,
flatDiscount: 5,
isApplyForAll: true,
})
)
expect(error.message).toMatch(/discountPercent or flatDiscount/i)
})
it('rejects a user-based coupon without applicableUsers', async () => {
const error = await captureError(() =>
admin.admin.coupon.create.mutate({
couponCode: code(),
flatDiscount: 5,
isUserBased: true,
})
)
expect(error.message).toMatch(/applicableUsers is required/i)
})
it('rejects a coupon that is both user-based and apply-for-all', async () => {
const error = await captureError(() =>
admin.admin.coupon.create.mutate({
couponCode: code(),
flatDiscount: 5,
isUserBased: true,
isApplyForAll: true,
applicableUsers: [userA.userId],
})
)
expect(error.message).toMatch(/both user-based and apply for all/i)
})
it('rejects a duplicate coupon code', async () => {
const duplicate = code()
await admin.admin.coupon.create.mutate({
couponCode: duplicate,
flatDiscount: 5,
isApplyForAll: true,
})
const error = await captureError(() =>
admin.admin.coupon.create.mutate({
couponCode: duplicate,
flatDiscount: 5,
isApplyForAll: true,
})
)
expect(error.message).toMatch(/already exists/i)
})
it('rejects unknown applicableUsers', async () => {
const error = await captureError(() =>
admin.admin.coupon.create.mutate({
couponCode: code(),
flatDiscount: 5,
isUserBased: true,
applicableUsers: [99_999_999],
})
)
expect(error.message).toMatch(/not found/i)
})
})
/**
* KNOWN BUG: placeOrder's validateAndGetCoupon never checks isUserBased /
* applicableUsers, so user B can spend a coupon that was issued to user A.
* Only the display endpoints filter by applicability. See tests/BUGS.md.
*/
it('pins: user B can apply a coupon issued to user A', async () => {
const coupon = await createCoupon({
isUserBased: true,
isApplyForAll: false,
applicableUsers: [userA.userId],
flatDiscount: 5,
})
// 3 * 100 = 300 >= minOrderValue -> no delivery, so this isolates the
// scoping bypass: 300 - 5 = 295.
const res = await place(userB, coupon.id, 3)
expect(res.success).toBe(true)
expect(parseFloat(res.data[0].totalAmount)).toBe(295)
})
})