/** * 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, }) const SECOND_SKU_ID = 4 // Mutton, price 839 /** Mount the cart with one line (2 x 215), optionally a second (1 x 839). */ async function mountCart(coupons: unknown[], withSecondLine = false) { setupApiMocks({ procedures: { 'user.cart.getCartSlots': { [PRODUCT_ID]: [futureSlot()], ...(withSecondLine ? { [SECOND_SKU_ID]: [futureSlot()] } : {}), }, 'user.coupon.getEligible': { data: coupons }, }, }) const lines = [ { id: 1, skuId: PRODUCT_ID, quantity: 2, slotId: SLOT_ID, addedAt: new Date().toISOString(), }, ] if (withSecondLine) { lines.push({ id: 2, skuId: SECOND_SKU_ID, quantity: 1, slotId: SLOT_ID, addedAt: new Date().toISOString(), }) } await StorageServiceCasual.setItem('cart_items', JSON.stringify(lines)) 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('measures minOrder on the coupon-targeted items, not the whole cart', async () => { // Cart = 430 (2 x 215) + 839 (1 x Mutton) = 1269. The coupon only targets the // 430 line and needs 500: measured against the whole cart it would look // eligible, which is exactly what the backend refuses at placeOrder. await mountCart([coupon({ discountPercent: '10', skuIds: [PRODUCT_ID], minOrder: '500' })], true) fireEvent.press(screen.getByText('Select a coupon')) await waitFor(() => expect(screen.getAllByText(/Add ₹70 more to use this coupon/).length).toBeGreaterThan(0) ) }) it('reports missing targets ahead of minOrder', async () => { // Target set matches nothing in the cart and minOrder is above the whole cart: // "no applicable items" is the truthful reason, not "add ₹N more". await mountCart([coupon({ discountPercent: '10', skuIds: [999999], minOrder: '2000' })], true) fireEvent.press(screen.getByText('Select a coupon')) await waitFor(() => expect(screen.getAllByText(/No applicable items in your cart/).length).toBeGreaterThan(0) ) expect(screen.queryByText(/Add ₹/)).toBeNull() }) it('shows a per-product breakdown for a product-specific coupon', async () => { // 2 x 215 (targeted) + 1 x 839 (Mutton, not targeted): the coupon is 10% of the // 430 targeted line only, so its whole discount lands on product 2. await mountCart([coupon({ discountPercent: '10', skuIds: [PRODUCT_ID] })], true) await selectCoupon() // The bill line for the coupon: 10% of 430. expect(screen.getByText('-₹43')).toBeVisible() fireEvent.press(screen.getByTestId(`coupon-breakdown-${COUPON_ID}`)) expect(screen.getByTestId('coupon-breakdown-dialog')).toBeVisible() expect(screen.getByText('Product discount')).toBeVisible() // Only the targeted product gets a row… expect(screen.getByTestId(`coupon-breakdown-row-${PRODUCT_ID}`)).toBeVisible() expect(screen.queryByTestId(`coupon-breakdown-row-${SECOND_SKU_ID}`)).toBeNull() // …and its share is the coupon's whole discount, shown twice: the row and the // "total from this coupon" line below it. expect(screen.getAllByText('−₹43').length).toBe(2) fireEvent.press(screen.getByText('Close')) expect(screen.queryByTestId('coupon-breakdown-dialog')).toBeNull() }) it('offers no breakdown for a coupon that applies to the whole cart', async () => { await mountCart([coupon({ discountPercent: '10' })], true) await selectCoupon() expect(screen.getByTestId(`coupon-chip-SAVE10`)).toBeVisible() expect(screen.queryByTestId(`coupon-breakdown-${COUPON_ID}`)).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}`) ) ) }) })