freshyo/apps/backend/tests/api/user-coupon.test.ts
2026-10-24 15:19:39 +05:30

367 lines
15 KiB
TypeScript

/**
* UCOUP-01..21 — `user.coupon.*` (catalogue §6.10).
*
* NOTE: the shared `createCoupon` fixture always sends `null` for the optional
* numeric/date columns, which the admin schema (`z.number().optional()`) rejects
* with BAD_REQUEST. These tests therefore use a local helper that only sends the
* fields it needs.
*/
import { apiClient, errorCode, expectTrpcError, uniqueSuffix } from '../helpers/api'
import { staffClient } from '../helpers/sessions'
import {
createCatalogOrderFixture,
placeOrder,
registerThrowawayUser,
} from '../helpers/fixtures'
jest.setTimeout(180_000)
function couponCode(prefix: string): string {
return `${prefix}${uniqueSuffix().replace(/[^a-z0-9]/gi, '').toUpperCase()}`
}
async function createAdminCoupon(opts: Record<string, any> = {}): Promise<any> {
const admin = await staffClient()
const payload: any = { ...opts, couponCode: opts.couponCode ?? couponCode('E2E') }
if (payload.discountPercent == null && payload.flatDiscount == null) payload.flatDiscount = 50
const res: any = await admin.admin.coupon.create.mutate(payload)
return Array.isArray(res) ? res[0] : res?.coupons?.[0]
}
async function createReservedCoupon(opts: Record<string, any> = {}): Promise<any> {
const admin = await staffClient()
const payload: any = { ...opts, couponCode: opts.couponCode ?? couponCode('SEC') }
if (payload.discountPercent == null && payload.flatDiscount == null) payload.flatDiscount = 40
const res: any = await admin.admin.coupon.createReservedCoupon.mutate(payload)
return Array.isArray(res) ? res[0] : res?.coupons?.[0]
}
async function invalidate(couponId: number): Promise<void> {
const admin = await staffClient()
await admin.admin.coupon.delete.mutate({ id: couponId })
}
async function eligible(token: string, regionId = 1): Promise<any> {
return apiClient(token).user.coupon.getEligible.query({ regionId })
}
async function myCoupons(token: string, regionId = 1): Promise<any> {
return apiClient(token).user.coupon.getMyCoupons.query({ regionId })
}
function allMine(mine: any): any[] {
return [...(mine.data.personal ?? []), ...(mine.data.general ?? [])]
}
async function userWithOrder() {
const fixture = await createCatalogOrderFixture({ price: 349 })
const placed = await placeOrder(fixture.user.token, {
addressId: fixture.address.id,
skuId: fixture.product.skuId,
slotId: fixture.slot.slotId,
})
return { ...fixture, orderId: Number(placed[0].id) }
}
/* -------------------------------------------------------------------------- */
/* getEligible */
/* -------------------------------------------------------------------------- */
describe('user.coupon.getEligible (UCOUP-01..07)', () => {
it('UCOUP-01: a general coupon is visible and isFirstOrder is reported', async () => {
const user = await registerThrowawayUser()
const coupon = await createAdminCoupon({ isApplyForAll: true })
const res: any = await eligible(user.token)
expect(res.success).toBe(true)
expect(typeof res.isFirstOrder).toBe('boolean')
expect(res.isFirstOrder).toBe(true)
expect(res.data.some((c: any) => c.id === coupon.id)).toBe(true)
})
it('UCOUP-02: an expired coupon is excluded', async () => {
const user = await registerThrowawayUser()
const coupon = await createAdminCoupon({
isApplyForAll: true,
validTill: '2020-01-01T00:00:00.000Z',
})
const res: any = await eligible(user.token)
expect(res.data.some((c: any) => c.id === coupon.id)).toBe(false)
})
it('UCOUP-03: an invalidated coupon is excluded', async () => {
const user = await registerThrowawayUser()
const coupon = await createAdminCoupon({ isApplyForAll: true })
await invalidate(coupon.id)
const res: any = await eligible(user.token)
expect(res.data.some((c: any) => c.id === coupon.id)).toBe(false)
})
it('UCOUP-04: a coupon whose per-user limit is reached is excluded', async () => {
const fixture = await userWithOrder()
const coupon = await createAdminCoupon({ isApplyForAll: true, maxLimitForUser: 1 })
await placeOrder(fixture.user.token, {
addressId: fixture.address.id,
skuId: fixture.product.skuId,
slotId: fixture.slot.slotId,
couponIds: [coupon.id],
})
const res: any = await eligible(fixture.user.token)
expect(res.data.some((c: any) => c.id === coupon.id)).toBe(false)
})
it("UCOUP-05: another user's personal coupon is excluded, the owner's is not", async () => {
const user = await registerThrowawayUser()
const other = await registerThrowawayUser()
const coupon = await createAdminCoupon({
isUserBased: true,
applicableUsers: [other.userId],
isApplyForAll: false,
})
const mine: any = await eligible(user.token)
expect(mine.data.some((c: any) => c.id === coupon.id)).toBe(false)
const theirs: any = await eligible(other.token)
expect(theirs.data.some((c: any) => c.id === coupon.id)).toBe(true)
})
it('UCOUP-06 (current): min-order / out-of-region coupons are still returned', async () => {
// getEligible deliberately does NOT filter min-order or region: the client
// renders those coupons disabled with a reason. The `regionId` input is not
// used to narrow the result either.
const user = await registerThrowawayUser()
const coupon = await createAdminCoupon({ isApplyForAll: true, minOrder: 10_000_000 })
const region1: any = await eligible(user.token, 1)
expect(region1.data.some((c: any) => c.id === coupon.id)).toBe(true)
const region2: any = await eligible(user.token, 2)
expect(region2.data.some((c: any) => c.id === coupon.id)).toBe(true)
})
it('UCOUP-07 (current): first-order-only is still returned to a non-first user', async () => {
// getEligible does not apply the first-order filter; getMyCoupons does.
const fixture = await userWithOrder()
const coupon = await createAdminCoupon({ isApplyForAll: true, isFirstOrderOnly: true })
const res: any = await eligible(fixture.user.token)
expect(res.isFirstOrder).toBe(false)
expect(res.data.some((c: any) => c.id === coupon.id)).toBe(true)
})
})
/* -------------------------------------------------------------------------- */
/* getMyCoupons */
/* -------------------------------------------------------------------------- */
describe('user.coupon.getMyCoupons (UCOUP-08..12)', () => {
it('UCOUP-08: coupons are split into personal and general buckets', async () => {
const user = await registerThrowawayUser()
const general = await createAdminCoupon({ isApplyForAll: true })
const secret = couponCode('MYC')
await createReservedCoupon({ couponCode: secret })
await apiClient(user.token).user.coupon.redeemReservedCoupon.mutate({ secretCode: secret })
const res: any = await myCoupons(user.token)
expect(res.success).toBe(true)
expect(res.data.personal.some((c: any) => c.code === secret)).toBe(true)
expect(res.data.general.some((c: any) => c.code === general.couponCode)).toBe(true)
})
it('UCOUP-09: a first-order-only coupon is filtered for a non-first user', async () => {
const fixture = await userWithOrder()
const coupon = await createAdminCoupon({ isApplyForAll: true, isFirstOrderOnly: true })
const res: any = await myCoupons(fixture.user.token)
expect(allMine(res).some((c: any) => c.code === coupon.couponCode)).toBe(false)
})
it('UCOUP-10: expired and invalidated coupons are filtered', async () => {
const user = await registerThrowawayUser()
const expired = await createAdminCoupon({
isApplyForAll: true,
validTill: '2020-01-01T00:00:00.000Z',
})
const invalid = await createAdminCoupon({ isApplyForAll: true })
await invalidate(invalid.id)
const res: any = await myCoupons(user.token)
const codes = allMine(res).map((c: any) => c.code)
expect(codes).not.toContain(expired.couponCode)
expect(codes).not.toContain(invalid.couponCode)
})
it('UCOUP-11 (current): a used-up coupon is included with isUsedUp true', async () => {
const fixture = await userWithOrder()
const coupon = await createAdminCoupon({ isApplyForAll: true, maxLimitForUser: 1 })
await placeOrder(fixture.user.token, {
addressId: fixture.address.id,
skuId: fixture.product.skuId,
slotId: fixture.slot.slotId,
couponIds: [coupon.id],
})
const res: any = await myCoupons(fixture.user.token)
const found = allMine(res).find((c: any) => c.code === coupon.couponCode)
expect(found).toBeDefined()
expect(found.isUsedUp).toBe(true)
expect(found.usageCount).toBe(1)
})
it('UCOUP-12 (current): getMyCoupons honours the region input, getEligible ignores it', async () => {
const user = await registerThrowawayUser()
const coupon = await createAdminCoupon({ isApplyForAll: true })
const region1: any = await myCoupons(user.token, 1)
expect(allMine(region1).some((c: any) => c.code === coupon.couponCode)).toBe(true)
const region2: any = await myCoupons(user.token, 2)
expect(allMine(region2).some((c: any) => c.code === coupon.couponCode)).toBe(false)
const eligibleRegion2: any = await eligible(user.token, 2)
expect(eligibleRegion2.data.some((c: any) => c.id === coupon.id)).toBe(true)
})
})
/* -------------------------------------------------------------------------- */
/* redeemReservedCoupon */
/* -------------------------------------------------------------------------- */
describe('user.coupon.redeemReservedCoupon (UCOUP-13..21)', () => {
it('UCOUP-13: a valid secret redeems and the coupon appears as personal', async () => {
const user = await registerThrowawayUser()
const secret = couponCode('RED')
await createReservedCoupon({ couponCode: secret })
const res: any = await apiClient(user.token).user.coupon.redeemReservedCoupon.mutate({
secretCode: secret,
})
expect(res.success).toBe(true)
expect(res.coupon.couponCode).toBe(secret)
const mine: any = await myCoupons(user.token)
expect(mine.data.personal.some((c: any) => c.code === secret)).toBe(true)
})
it('UCOUP-14: an unknown secret is 400', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
() =>
apiClient(user.token).user.coupon.redeemReservedCoupon.mutate({
secretCode: couponCode('NOPE'),
}),
'BAD_REQUEST',
'Invalid or already redeemed'
)
})
it('UCOUP-15: an expired secret is 400', async () => {
const user = await registerThrowawayUser()
const secret = couponCode('EXPR')
await createReservedCoupon({ couponCode: secret, validTill: '2020-01-01T00:00:00.000Z' })
await expectTrpcError(
() => apiClient(user.token).user.coupon.redeemReservedCoupon.mutate({ secretCode: secret }),
'BAD_REQUEST',
'expired'
)
})
it('UCOUP-16: redeeming the same secret twice is 400 the second time', async () => {
const user = await registerThrowawayUser()
const secret = couponCode('TWICE')
await createReservedCoupon({ couponCode: secret })
const first: any = await apiClient(user.token).user.coupon.redeemReservedCoupon.mutate({
secretCode: secret,
})
expect(first.success).toBe(true)
await expectTrpcError(
() => apiClient(user.token).user.coupon.redeemReservedCoupon.mutate({ secretCode: secret }),
'BAD_REQUEST',
'already redeemed'
)
})
it('UCOUP-17: a first-order-only secret is rejected when the user has ordered', async () => {
const fixture = await userWithOrder()
const secret = couponCode('FOSEC')
await createReservedCoupon({ couponCode: secret, isFirstOrderOnly: true })
await expectTrpcError(
() => apiClient(fixture.user.token).user.coupon.redeemReservedCoupon.mutate({ secretCode: secret }),
'BAD_REQUEST',
'first order only'
)
})
it('UCOUP-18: two users racing the same secret — one wins, one is 400', async () => {
const a = await registerThrowawayUser()
const b = await registerThrowawayUser()
const secret = couponCode('RACE')
await createReservedCoupon({ couponCode: secret })
const results = await Promise.allSettled([
apiClient(a.token).user.coupon.redeemReservedCoupon.mutate({ secretCode: secret }),
apiClient(b.token).user.coupon.redeemReservedCoupon.mutate({ secretCode: secret }),
])
const fulfilled = results.filter((r) => r.status === 'fulfilled')
const rejected = results.filter((r) => r.status === 'rejected')
expect(fulfilled).toHaveLength(1)
expect(rejected).toHaveLength(1)
expect(errorCode((rejected[0] as PromiseRejectedResult).reason)).toBe('BAD_REQUEST')
})
it('UCOUP-19: no token is 401', async () => {
await expectTrpcError(
() =>
apiClient().user.coupon.redeemReservedCoupon.mutate({ secretCode: 'ANYTHING' }),
'UNAUTHORIZED'
)
await expectTrpcError(() => apiClient().user.coupon.getEligible.query({}), 'UNAUTHORIZED')
await expectTrpcError(() => apiClient().user.coupon.getMyCoupons.query({}), 'UNAUTHORIZED')
})
it('UCOUP-20 (current): the secret lookup is case-insensitive (input is uppercased)', async () => {
const user = await registerThrowawayUser()
const secret = couponCode('CASE')
await createReservedCoupon({ couponCode: secret })
const res: any = await apiClient(user.token).user.coupon.redeemReservedCoupon.mutate({
secretCode: secret.toLowerCase(),
})
expect(res.success).toBe(true)
expect(res.coupon.couponCode).toBe(secret)
})
it('UCOUP-21: a coupon-code collision does not consume the secret', async () => {
const user = await registerThrowawayUser()
const admin = await staffClient()
const secret = couponCode('COLL')
// Reserved first, then an ordinary coupon takes the same code. The two admin
// create paths only check their own table, so the collision is reachable.
await createReservedCoupon({ couponCode: secret })
await createAdminCoupon({ couponCode: secret, isApplyForAll: true, flatDiscount: 10 })
// The insert hits coupons.coupon_code's unique constraint. The batch must roll
// the claim back, so the redemption fails without burning the secret.
const [outcome] = await Promise.allSettled([
apiClient(user.token).user.coupon.redeemReservedCoupon.mutate({ secretCode: secret }),
])
expect(outcome.status).toBe('rejected')
const reserved: any = await admin.admin.coupon.getReservedCoupons.query({ search: secret })
const row = reserved.coupons.find((entry: any) => entry.secretCode === secret)
expect(row).toBeTruthy()
expect(row.isRedeemed).toBe(false)
expect(row.redeemedBy).toBeNull()
})
})