/** * Cart screen — coupon application and the discount calculation. * * components/cart-page.tsx owns the coupon picker and re-derives the discount * (percentage capped by maxValue, flat capped by maxValue / the item total) before * the checkout URL is built. The checkout page that consumes `&coupons=` can't be * mounted in this environment (it spins with a non-empty cart), so the maths is * pinned here, where the numbers are rendered in the bill. * * 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 { Alert } from 'react-native' import { fireEvent, screen, waitFor } from '@testing-library/react-native' import dayjs from 'dayjs' import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual' import CartPage from '@/components/cart-page' import { resetStorage, setupApiMocks } from '../mocks/api' import { authMock, resetAuthMock } from '../mocks/auth' import { routerMock } from '../mocks/router' import { renderWithProviders } from '../helpers/render' const PRODUCT_ID = 2 // Chicken Breast 500 g, price 215 const SLOT_ID = 1849 const TOTAL = 430 // 2 x 215 const COUPON_ID = 77 const futureSlot = () => ({ id: SLOT_ID, deliveryTime: dayjs().add(3, 'hour').toISOString(), freezeTime: dayjs().add(2, 'hour').toISOString(), }) const coupon = (over: Record = {}) => ({ id: COUPON_ID, couponCode: 'SAVE10', discountPercent: null, flatDiscount: null, maxValue: null, minOrder: null, usages: [], maxLimitForUser: null, exclusiveApply: false, ...over, }) /** Mount the cart with one line (2 x 215) and the given eligible coupons. */ async function mountCart(coupons: unknown[]) { setupApiMocks({ procedures: { 'user.cart.getCartSlots': { [PRODUCT_ID]: [futureSlot()] }, 'user.coupon.getEligible': { data: coupons }, }, }) await StorageServiceCasual.setItem( 'cart_items', JSON.stringify([ { id: 1, skuId: PRODUCT_ID, quantity: 2, slotId: SLOT_ID, addedAt: new Date().toISOString(), }, ]) ) renderWithProviders() await waitFor(() => expect(screen.getByText('Chicken Breast 500 g')).toBeVisible()) expect(screen.getByText('Offers & Coupons')).toBeVisible() } /** Open the coupon dropdown and pick the single option. */ async function selectCoupon() { fireEvent.press(screen.getByText('Select a coupon')) await waitFor(() => expect(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}`)).toBeVisible() ) fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}`)) } describe('Cart coupon application', () => { beforeEach(async () => { resetAuthMock() authMock.user = { id: 1 } await resetStorage() jest.spyOn(Alert, 'alert').mockImplementation(() => {}) }) it('shows the item total and free delivery before a coupon is applied', async () => { await mountCart([coupon({ discountPercent: '10' })]) // Without a discount the cart is above the threshold, so Item Total and To Pay // are both ₹430 and the delivery fee is waived. expect(screen.getAllByText(`₹${TOTAL}`).length).toBeGreaterThan(0) expect(screen.queryByText('Product Discount')).toBeNull() expect(screen.getByText('Free')).toBeVisible() }) it('offers the coupon with its computed saving', async () => { await mountCart([coupon({ discountPercent: '10' })]) fireEvent.press(screen.getByText('Select a coupon')) // 10% of 430 = 43. await waitFor(() => expect(screen.getAllByText(/Save ₹43/).length).toBeGreaterThan(0)) }) it('applies a percentage discount and shows the applied code', async () => { await mountCart([coupon({ discountPercent: '10' })]) await selectCoupon() expect(screen.getByText('Product Discount')).toBeVisible() expect(screen.getByText('-₹43')).toBeVisible() expect(screen.getByText('Coupon Applied')).toBeVisible() expect(screen.getByText('SAVE10')).toBeVisible() // 430 - 43 = 387, still above the threshold. expect(screen.getByText('₹387')).toBeVisible() }) it('caps a percentage discount at maxValue', async () => { await mountCart([coupon({ discountPercent: '50', maxValue: '50' })]) await selectCoupon() // 50% of 430 = 215, capped at 50. expect(screen.getByText('-₹50')).toBeVisible() expect(screen.getByText('₹380')).toBeVisible() }) it('applies a flat discount', async () => { await mountCart([coupon({ flatDiscount: '100' })]) await selectCoupon() expect(screen.getByText('-₹100')).toBeVisible() expect(screen.getByText('₹330')).toBeVisible() }) it('never discounts below zero — a flat discount larger than the cart is capped at the item total', async () => { await mountCart([coupon({ flatDiscount: '1000' })]) await selectCoupon() // min(1000, 430) = 430: the discount equals the item total, not the coupon value. expect(screen.getByText('-₹430')).toBeVisible() }) it('re-adds the delivery fee when the discount drops the total below the threshold', async () => { await mountCart([coupon({ flatDiscount: '200' })]) await selectCoupon() // 430 - 200 = 230 < 249 -> +15 delivery. expect(screen.getByText('-₹200')).toBeVisible() expect(screen.getByText('₹245')).toBeVisible() expect(screen.queryByText('Free')).toBeNull() }) it('removes the coupon and the discount again', async () => { await mountCart([coupon({ discountPercent: '10' })]) await selectCoupon() expect(screen.getByText('-₹43')).toBeVisible() fireEvent.press(screen.getByText('Remove coupons')) expect(screen.queryByText('Product Discount')).toBeNull() expect(screen.queryByText('Coupon Applied')).toBeNull() expect(screen.getAllByText(`₹${TOTAL}`).length).toBeGreaterThan(0) }) it('lists a min-order coupon as ineligible and does not apply it', async () => { await mountCart([coupon({ discountPercent: '10', minOrder: '1000' })]) fireEvent.press(screen.getByText('Select a coupon')) await waitFor(() => expect(screen.getAllByText(/Min order ₹1000/).length).toBeGreaterThan(0) ) fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}`)) expect(screen.queryByText('Product Discount')).toBeNull() expect(screen.queryByText('Coupon Applied')).toBeNull() }) it('expands a product-specific coupon to list the products it applies to', async () => { // Product 2 = Chicken Breast 500 g, product 4 = Mutton (both in the fixture // catalog, neither needs to be in the cart). await mountCart([coupon({ discountPercent: '10', skuIds: [2, 4] })]) fireEvent.press(screen.getByText('Select a coupon')) await waitFor(() => expect(screen.getByText('Applies to 2 products')).toBeVisible() ) // Collapsed by default. expect(screen.queryByText('Mutton')).toBeNull() fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail`)) expect(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail-list`)).toBeVisible() expect(screen.getByText('Mutton')).toBeVisible() // Product 2 is already rendered by the cart line above, so count the occurrences. expect(screen.getAllByText('Chicken Breast 500 g').length).toBeGreaterThan(1) // Expanding must not select the coupon (the selected-coupon chip appears only // when it is actually applied). expect(screen.queryByTestId('coupon-chip-SAVE10')).toBeNull() // Pressing the trigger again collapses it. fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail`)) expect(screen.queryByText('Mutton')).toBeNull() }) it('collapses the previously expanded coupon and keeps unresolved targets visible', async () => { await mountCart([ coupon({ id: COUPON_ID, discountPercent: '10', skuIds: [2] }), // 999999 is not in the catalog (e.g. a suspended SKU): it still gets a row. coupon({ id: 78, couponCode: 'MUTTON20', discountPercent: '20', skuIds: [999999] }), ]) fireEvent.press(screen.getByText('Select a coupon')) // One product each, so both triggers read "1 product". await waitFor(() => expect(screen.getAllByText('Applies to 1 product').length).toBe(2) ) fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail`)) expect(screen.getAllByText('Chicken Breast 500 g').length).toBeGreaterThan(1) // Opening the second coupon's list closes the first one. fireEvent.press(screen.getByTestId('coupon-dropdown-option-78-detail')) expect(screen.getByText('Product unavailable · #999999')).toBeVisible() expect(screen.queryByTestId(`coupon-dropdown-option-${COUPON_ID}-detail-list`)).toBeNull() }) it('hides a coupon that has hit its per-user usage limit', async () => { await mountCart([ coupon({ discountPercent: '10', maxLimitForUser: 1, usages: [{ id: 1 }] }), ]) expect(screen.getByText('No coupons available')).toBeVisible() expect(screen.getByText('No coupons available for this order')).toBeVisible() }) it('drops the discount when a quantity change takes the cart below the minOrder', async () => { // Seeded at 2 x 215 = 430, so the minOrder-300 coupon is eligible when selected. await mountCart([coupon({ flatDiscount: '50', minOrder: '300' })]) await selectCoupon() expect(screen.getByText('-₹50')).toBeVisible() // Drop to 1 x 215 = 215 < 300 -> the coupon no longer qualifies. fireEvent.press(screen.getByTestId('cart-item-1-decrement')) await waitFor(() => expect(screen.queryByText('Product Discount')).toBeNull()) expect(screen.queryByText('Coupon Applied')).toBeNull() expect(screen.getByTestId('cart-item-1-value')).toHaveTextContent('1') }) it('sends the selected coupon id to checkout', async () => { await mountCart([coupon({ discountPercent: '10' })]) await selectCoupon() fireEvent.press(screen.getByTestId('checkout-button')) await waitFor(() => expect(routerMock.push).toHaveBeenCalledWith( expect.stringContaining(`&coupons=${COUPON_ID}`) ) ) }) })