/** * Checkout page — coupon application and the discount calculation. * * The coupon arrives the way the cart passes it (`?coupons=`), so these cases * exercise the real maths in components/checkout-page.tsx (discountAmount / finalTotal / * deliveryCharge) and the bill rendered by PaymentAndOrderComponent. This branch was * unreachable until the Rules-of-Hooks fix: the page threw * as soon as the cart resolved to slotted items. * * Cart: 2 x product 2 @ 215 = 430. Consts: freeDeliveryThreshold 249, deliveryCharge 15 — * the item total clears the threshold, so a large enough discount drops it back under and * re-adds the fee. */ jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) import React from 'react' import { fireEvent, screen, waitFor } from '@testing-library/react-native' import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual' import CheckoutPage from '@/components/checkout-page' import { resetStorage, setupApiMocks } from '../mocks/api' import { authMock, resetAuthMock } from '../mocks/auth' import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures' import { routerMock, searchParamsMock } from '../mocks/router' import { renderWithProviders } from '../helpers/render' const PRODUCT_ID = 2 // Chicken Breast 500 g, price 215 const SLOT_ID = 1849 const CART_ITEM_ID = 1 const TOTAL = 430 // 2 x 215 const COUPON_ID = 77 const coupon = (over: Record = {}) => ({ id: COUPON_ID, couponCode: 'SAVE10', discountPercent: null, flatDiscount: null, maxValue: null, minOrder: null, usages: [], maxLimitForUser: null, exclusiveApply: false, ...over, }) const ADDRESSES = { data: [ { id: 1, name: 'Home', phone: '9876543210', addressLine1: '12 Main Road', addressLine2: 'Apt 4', city: 'Hyderabad', state: 'Telangana', isDefault: true, }, ], } const PLACE_ORDER_OK = { data: [{ id: 99, isCod: true }] } /** * Mount checkout with one line (2 x 215) and the given eligible coupons. * `couponsParam` mirrors what the cart puts in the checkout URL. */ async function mountCheckout(coupons: unknown[], couponsParam: number | null = COUPON_ID) { const api = setupApiMocks({ procedures: { 'user.slots.getSlots': { slots: [] }, 'user.address.getUserAddresses': ADDRESSES, 'user.coupon.getEligible': { data: coupons }, 'user.order.placeOrder': PLACE_ORDER_OK, }, }) await StorageServiceCasual.setItem( 'cart_items', JSON.stringify([ { id: CART_ITEM_ID, skuId: PRODUCT_ID, quantity: 2, slotId: SLOT_ID, addedAt: new Date().toISOString(), }, ]) ) // The cart builds this as ":". searchParamsMock.current = { slots: `${SLOT_ID}:${CART_ITEM_ID}`, ...(couponsParam ? { coupons: String(couponsParam) } : {}), } renderWithProviders() await waitFor(() => expect(screen.getByText('To Pay')).toBeVisible()) // Item Total; with no discount To Pay reads the same, so match either. expect(screen.getAllByText(`₹${TOTAL}`).length).toBeGreaterThan(0) return api } describe('Checkout coupon discount calculation', () => { beforeEach(async () => { resetAuthMock() authMock.user = { id: 1 } await resetStorage() searchParamsMock.current = {} }) it('applies a percentage discount to the item total', async () => { await mountCheckout([coupon({ discountPercent: '10' })]) // 10% of 430 = 43; 430 - 43 = 387, still above the 249 threshold -> free delivery. expect(screen.getByText('Product Discount')).toBeVisible() expect(screen.getByText('-₹43')).toBeVisible() expect(screen.getByText('₹387')).toBeVisible() expect(screen.getByText('Free')).toBeVisible() // 43 discount + 10 market-price saving (product 2: 220 market vs 215 paid, x2) // + the 15 delivery fee the discount earned back. expect(screen.getByText('You saved ₹68 on this order')).toBeVisible() }) it('caps a percentage discount at maxValue', async () => { await mountCheckout([coupon({ discountPercent: '50', maxValue: '50' })]) // 50% of 430 = 215, capped at 50. expect(screen.getByText('-₹50')).toBeVisible() expect(screen.getByText('₹380')).toBeVisible() }) it('applies a flat discount', async () => { await mountCheckout([coupon({ flatDiscount: '100' })]) expect(screen.getByText('-₹100')).toBeVisible() expect(screen.getByText('₹330')).toBeVisible() }) it('caps a flat discount at maxValue', async () => { await mountCheckout([coupon({ flatDiscount: '200', maxValue: '150' })]) expect(screen.getByText('-₹150')).toBeVisible() expect(screen.getByText('₹280')).toBeVisible() }) it('never discounts below zero — capped at the item total', async () => { await mountCheckout([coupon({ flatDiscount: '1000' })]) // min(1000, 430) = 430: the discount equals the item total, not the coupon value. // (To Pay would also read ₹15, the same as the delivery fee, so it is not asserted here.) expect(screen.getByText('-₹430')).toBeVisible() }) it('charges delivery again when the discount drops the total below the threshold', async () => { await mountCheckout([coupon({ flatDiscount: '200' })]) // 430 - 200 = 230 < 249 -> +15 delivery, and the nudge asks for the remainder. expect(screen.getByText('-₹200')).toBeVisible() expect(screen.getByText('₹245')).toBeVisible() expect(screen.getByText('Add products worth ₹19 for free delivery')).toBeVisible() }) it('does not apply a coupon whose minOrder is not met, even from the URL', async () => { // The id comes straight from ?coupons=, but the eligibility flag is honoured, so a // coupon the cart cannot use is ignored rather than silently discounted. await mountCheckout([coupon({ flatDiscount: '50', minOrder: '1000' })]) expect(screen.queryByText('Product Discount')).toBeNull() expect(screen.getByText('Free')).toBeVisible() }) it('ignores a coupon that has hit its per-user usage limit', async () => { // Usage-limit coupons are filtered out of the eligible list entirely. await mountCheckout([ coupon({ flatDiscount: '50', maxLimitForUser: 1, usages: [{ id: 1 }] }), ]) expect(screen.queryByText('Product Discount')).toBeNull() }) it('shows no discount when the URL carries no coupon', async () => { await mountCheckout([coupon({ discountPercent: '10' })], null) expect(screen.queryByText('Product Discount')).toBeNull() expect(screen.getByText('Free')).toBeVisible() }) it('sends the selected coupon id with the order', async () => { const api = await mountCheckout([coupon({ discountPercent: '10' })]) fireEvent.press(screen.getByTestId('place-order-button')) await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder')) expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toMatchObject({ selectedItems: [{ skuId: PRODUCT_ID, quantity: 2, slotId: SLOT_ID }], addressId: 1, couponIds: [COUPON_ID], paymentMethod: 'cod', }) await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith( './order-success?orderId=99&totalAmount=387' ) ) }) })