253 lines
7.8 KiB
TypeScript
253 lines
7.8 KiB
TypeScript
/**
|
|
* Coupon UX surfaces: reserved-code redemption, getMyCoupons, the admin create
|
|
* guards and the user-scoping guard at placeOrder.
|
|
*
|
|
* See tests/BUGS.md.
|
|
*/
|
|
|
|
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,
|
|
regionId: 1,
|
|
...(couponId ? { couponIds: [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)
|
|
})
|
|
|
|
it('rejects an expired reserved code', async () => {
|
|
const { secretCode } = await createReserved({
|
|
validTill: new Date(Date.now() - 3600_000).toISOString(),
|
|
})
|
|
|
|
const error = await captureError(() => redeem(userA.token, secretCode))
|
|
expect(error.message).toMatch(/expired/i)
|
|
})
|
|
|
|
it('lets only one of two simultaneous claims win', async () => {
|
|
const { secretCode } = await createReserved()
|
|
|
|
const results = await Promise.allSettled([
|
|
redeem(userA.token, secretCode),
|
|
redeem(userB.token, secretCode),
|
|
])
|
|
|
|
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1)
|
|
})
|
|
|
|
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)
|
|
})
|
|
})
|
|
|
|
it('rejects user B applying a coupon issued to user A', async () => {
|
|
const coupon = await createCoupon({
|
|
isUserBased: true,
|
|
isApplyForAll: false,
|
|
applicableUsers: [userA.userId],
|
|
flatDiscount: 5,
|
|
})
|
|
|
|
// 3 * 100 = 300 >= threshold -> no delivery, isolating the scope check.
|
|
const error = await captureError(() => place(userB, coupon.id, 3))
|
|
expect(error.message).toMatch(/not applicable/i)
|
|
|
|
// The intended user can still spend it.
|
|
const ok = await place(userA, coupon.id, 3)
|
|
expect(ok.success).toBe(true)
|
|
})
|
|
})
|