freshyo/apps/backend/tests/api/coupon-math.test.ts
2026-10-15 20:31:20 +05:30

264 lines
8.9 KiB
TypeScript

/**
* Coupon discount maths at placeOrder time.
*
* The discount is computed server-side in placeOrderUtil
* (apps/backend/src/trpc/apis/user-apis/apis/order.ts) and persisted to
* orders.totalAmount. These tests read the order row returned by placeOrder
* (totalAmount is the stored string).
*
* The backend mirrors the customer app's model: coupons discount the goods
* subtotal and delivery is decided on the post-discount total. Multiple coupons
* stack sequentially in the order they are applied, each rounded to the nearest
* rupee. Remaining KNOWN BUGS are pinned here (negative totals for >=100%
* coupons). See tests/BUGS.md.
*/
import { apiClient, captureError, uniqueSuffix } from '../helpers/api'
import { asNumber, getConstants } from '../helpers/consts'
import {
createFutureSlot,
createStoreWithSku,
registerUserWithAddress,
} from '../helpers/fixtures'
import { staffSession } from '../helpers/sessions'
type OrderRow = { id: number; totalAmount: string; slotId: number | null }
type Placed = { success: boolean; data: OrderRow[] }
const couponCode = () =>
`CM${uniqueSuffix()}`.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 20)
/** price 5 is used so quantities map straight onto the totals below. */
const UNIT_PRICE = 5
describe('coupon discount maths', () => {
let admin: ReturnType<typeof apiClient>
let userToken = ''
let addressId = 0
let skuId = 0
let slotId = 0
let secondSlotId = 0
let roundingSkuId = 0
let roundingSlotId = 0
let deliveryCharge = 0
let freeDeliveryThreshold = 0
beforeAll(async () => {
const staff = await staffSession()
admin = apiClient(staff.token)
const store = await createStoreWithSku({ price: UNIT_PRICE })
const slot = await createFutureSlot([store.skuId])
const second = await createFutureSlot([store.skuId], {
deliveryInHours: 6,
freezeInHours: 5,
})
// A second store at 333 so 3 units = 999 exercises float maths.
const rounding = await createStoreWithSku({ price: 333 })
const roundingSlot = await createFutureSlot([rounding.skuId])
const buyer = await registerUserWithAddress()
const consts = await getConstants()
userToken = buyer.token
addressId = buyer.addressId
skuId = store.skuId
slotId = slot.slotId
secondSlotId = second.slotId
roundingSkuId = rounding.skuId
roundingSlotId = roundingSlot.slotId
deliveryCharge = asNumber(consts.deliveryCharge)
freeDeliveryThreshold = asNumber(consts.freeDeliveryThreshold)
// The totals below assume these thresholds.
expect(freeDeliveryThreshold).toBeGreaterThan(UNIT_PRICE)
expect(freeDeliveryThreshold).toBeLessThan(500)
})
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]
}
const place = (
items: { skuId: number; quantity: number; slotId: number | null }[],
couponId?: number | number[]
): Promise<Placed> =>
apiClient(userToken).user.order.placeOrder.mutate({
selectedItems: items,
addressId,
regionId: 1,
paymentMethod: 'cod',
...(couponId != null
? { couponIds: Array.isArray(couponId) ? couponId : [couponId] }
: {}),
}) as unknown as Promise<Placed>
const total = (res: Placed) => parseFloat(res.data[0].totalAmount)
it('applies an uncapped percentage discount', async () => {
const coupon = await createCoupon({ discountPercent: 10 })
const res = await place([{ skuId, quantity: 100, slotId }], coupon.id)
// 500 >= freeDeliveryThreshold -> free delivery; 10% of 500 = 50.
expect(total(res)).toBe(450)
})
it('caps a percentage discount at maxValue', async () => {
const coupon = await createCoupon({ discountPercent: 50, maxValue: 100 })
const res = await place([{ skuId, quantity: 100, slotId }], coupon.id)
// min(50% of 500 = 250, maxValue 100) = 100.
expect(total(res)).toBe(400)
})
it('caps a flat discount at maxValue', async () => {
const coupon = await createCoupon({ flatDiscount: 200, maxValue: 30 })
const res = await place([{ skuId, quantity: 100, slotId }], coupon.id)
// min(flat 200, maxValue 30) = 30.
expect(total(res)).toBe(470)
})
/**
* KNOWN BUG: the percentage branch caps at `maxValue * proportion` or
* Infinity and never at orderTotal, so a >=100% coupon drives totalAmount to
* zero or negative. The flat branch does cap at the order total.
*/
it('pins: a 150% coupon produces a negative total', async () => {
const coupon = await createCoupon({ discountPercent: 150 })
const res = await place([{ skuId, quantity: 100, slotId }], coupon.id)
// 500 - 150% (750) = -250.
expect(total(res)).toBeLessThan(0)
})
it('a 100% coupon zeroes the goods but delivery still applies', async () => {
const coupon = await createCoupon({ discountPercent: 100 })
const res = await place([{ skuId, quantity: 100, slotId }], coupon.id)
// Goods 500 - 100% = 0; 0 is below the free-delivery threshold, so the
// delivery charge is added on top (matching the customer app).
expect(total(res)).toBe(deliveryCharge)
})
it('accepts a cart exactly at the coupon minOrder and rejects below it', async () => {
const coupon = await createCoupon({ flatDiscount: 10, minOrder: 500 })
// 100 * 5 = 500 == minOrder -> the guard is `minOrder > total`, so it passes.
const ok = await place([{ skuId, quantity: 100, slotId }], coupon.id)
expect(ok.success).toBe(true)
expect(total(ok)).toBe(490)
// 99 * 5 = 495 < 500 -> rejected.
const error = await captureError(() =>
place([{ skuId, quantity: 99, slotId }], coupon.id)
)
expect(error.message).toMatch(/minimum requirement/i)
})
it('applies a percentage coupon to the goods subtotal only', async () => {
const coupon = await createCoupon({ discountPercent: 10 })
// 1 * 5 = 5; 10% off the goods = 4.5. Delivery is decided on 4.5, which is
// below the free-delivery threshold, so the charge is added on top.
const res = await place([{ skuId, quantity: 1, slotId }], coupon.id)
expect(total(res)).toBeCloseTo(UNIT_PRICE * 0.9 + deliveryCharge, 6)
})
it('splits a flat discount across slots by orderGroupProportion', async () => {
const coupon = await createCoupon({ flatDiscount: 20 })
const res = await place(
[
{ skuId, quantity: 40, slotId }, // 200
{ skuId, quantity: 60, slotId: secondSlotId }, // 300
],
coupon.id
)
// 500 >= freeDeliveryThreshold -> no delivery, so both sub-orders are the plain
// subtotal. Proportions 0.4 / 0.6 -> discounts 8 / 12.
const totals = res.data
.map((order) => parseFloat(order.totalAmount))
.sort((a, b) => a - b)
expect(totals).toEqual([192, 288])
expect(totals[0] + totals[1]).toBe(480)
})
it('rounds the discount to the nearest rupee', async () => {
const coupon = await createCoupon({ discountPercent: 15 })
const res = await place(
[{ skuId: roundingSkuId, quantity: 3, slotId: roundingSlotId }],
coupon.id
)
// 999 - round(15% of 999 = 149.85) = 999 - 150 = 849.
expect(total(res)).toBe(849)
})
it('stacks multiple coupons sequentially in the order applied', async () => {
const tenPct = await createCoupon({ discountPercent: 10 })
const flat100 = await createCoupon({ flatDiscount: 100 })
// 200 * 5 = 1000. Above the free-delivery threshold, so delivery is free.
// 10% first: -100 -> 900; then flat 100 -> 800.
const pctThenFlat = await place(
[{ skuId, quantity: 200, slotId }],
[tenPct.id, flat100.id]
)
expect(total(pctThenFlat)).toBe(800)
// Same two coupons, reversed: flat 100 first -> 900; then 10% of 900 = 90 -> 810.
const flatThenPct = await place(
[{ skuId, quantity: 200, slotId }],
[flat100.id, tenPct.id]
)
expect(total(flatThenPct)).toBe(810)
})
it('enforces maxLimitForUser', async () => {
const coupon = await createCoupon({ flatDiscount: 5, maxLimitForUser: 1 })
await place([{ skuId, quantity: 100, slotId }], coupon.id)
const error = await captureError(() =>
place([{ skuId, quantity: 100, slotId }], coupon.id)
)
expect(error.message).toMatch(/usage limit/i)
})
it('rejects an expired coupon at order time', async () => {
const coupon = await createCoupon({
flatDiscount: 5,
validTill: new Date(Date.now() - 3600_000).toISOString(),
})
const error = await captureError(() =>
place([{ skuId, quantity: 100, slotId }], coupon.id)
)
expect(error.message).toMatch(/expired/i)
})
it('rejects an unknown coupon id', async () => {
const error = await captureError(() =>
place([{ skuId, quantity: 100, slotId }], 99_999_999)
)
expect(error.message).toMatch(/invalid coupon/i)
})
})