/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 8.1 — Coupon list (`tests/pages/coupons.test.tsx`). */ import React from 'react' import { Alert, DeviceEventEmitter, FlatList } from 'react-native' import { fireEvent, act, waitFor } from '@testing-library/react-native' import { BottomDropdown } from 'common-ui' import { MaterialCommunityIcons } from '@expo/vector-icons' import Coupons from '@/app/(drawer)/dashboard/coupons/index' import { renderWithProviders, renderAndFlush, flush } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { setProcedure, lastMutationInput, procedureMutationCalls, lastProcedureInput, procedureQueryCalls, } from '../mocks/trpc-client' import { router } from '../mocks/expo-router-mock' import { COUPON_1, COUPON_GLOBAL, COUPON_EXPIRED, COUPON_INVALIDATED, COUPONS, } from '../fixtures' const HOUR = 60 * 60 * 1000 const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString() function response(coupons: any[]) { return { coupons, count: coupons.length, nextCursor: undefined } } // Each network response is one infinite-query page; React Query assembles the // `pages` array itself. function page(coupons: any[]) { return response(coupons) } type View = Awaited> function renderCoupons() { return renderAndFlush(, { auth: false }) } async function openReserved(view: View) { fireEvent.press(view.getByLabelText('Reserved')) await flush(2) } function selectStatusFilter(view: View, values: string[], index = 0) { const dropdowns = view.UNSAFE_getAllByType(BottomDropdown) const dropdown = dropdowns[index < 0 ? dropdowns.length - 1 : index] act(() => { dropdown.props.onValueChange(values) }) } describe('Coupons list (ACOUPUI-01..30)', () => { let alertSpy: jest.SpyInstance beforeEach(() => { resetAllMocks() alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) }) afterEach(() => alertSpy?.mockRestore()) it('ACOUPUI-01: renders the General and Reserved tabs', async () => { setProcedure('admin.coupon.getAll', { data: page(COUPONS) }) const view = await renderCoupons() expect(view.getAllByText('General').length).toBeGreaterThan(0) expect(view.getAllByText('Reserved').length).toBeGreaterThan(0) expect(view.getByText('SAVE10')).toBeTruthy() }) it('ACOUPUI-02: shows the General loading state', () => { setProcedure('admin.coupon.getAll', { mode: 'pending' }) const view = renderWithProviders(, { auth: false }) expect(view.getByText('Loading Coupons...')).toBeTruthy() }) it('ACOUPUI-03: shows the General error state and retries', async () => { setProcedure('admin.coupon.getAll', { mode: 'error', error: new Error('boom') }) const view = await renderCoupons() expect(view.getByText('Failed to load coupons')).toBeTruthy() const calls = procedureQueryCalls('admin.coupon.getAll').length fireEvent.press(view.getByText('Retry')) await waitFor(() => expect(procedureQueryCalls('admin.coupon.getAll').length).toBe(calls + 1) ) expect(view.getByText('Failed to load coupons')).toBeTruthy() }) it('ACOUPUI-04: shows the empty General state', async () => { setProcedure('admin.coupon.getAll', { data: page([]) }) const view = await renderCoupons() expect(view.getByText('No Coupons Found')).toBeTruthy() expect(view.queryByText('Clear Search')).toBeNull() }) it('ACOUPUI-05: empty search results reveal Clear Search, which resets the query', async () => { setProcedure('admin.coupon.getAll', { data: page([]) }) const view = await renderCoupons() fireEvent.changeText(view.getByPlaceholderText('Search coupons...'), 'missing') await waitFor(() => expect(lastProcedureInput('admin.coupon.getAll')).toEqual({ limit: 20, search: 'missing', direction: 'forward', }) ) expect(view.getByText('No Coupons Found')).toBeTruthy() expect(view.getByText('Clear Search')).toBeTruthy() fireEvent.press(view.getByText('Clear Search')) await waitFor(() => expect(view.getByPlaceholderText('Search coupons...').props.value).toBe('')) // Clearing returns to the unfiltered query (already cached from the first render). expect(procedureQueryCalls('admin.coupon.getAll')).toContainEqual({ limit: 20, search: '', direction: 'forward', }) }) it('ACOUPUI-06: renders the coupon card fields', async () => { setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) }) const view = await renderCoupons() expect(view.getByText('SAVE10')).toBeTruthy() expect(view.getByText('ID: 21')).toBeTruthy() expect(view.getByText('Active')).toBeTruthy() expect(view.getByText('Discount: 10% off')).toBeTruthy() expect(view.getByText('Min Order: None')).toBeTruthy() expect(view.getByText('Max: ₹50')).toBeTruthy() expect(view.getByText('Valid Till: No expiry')).toBeTruthy() expect(view.getByText(/Target: All Users/)).toBeTruthy() }) it('ACOUPUI-07: an active coupon shows Active', async () => { setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) }) const view = await renderCoupons() expect(view.getByText('Active')).toBeTruthy() }) it('ACOUPUI-08: an expired coupon shows Expired', async () => { setProcedure('admin.coupon.getAll', { data: page([COUPON_EXPIRED]) }) const view = await renderCoupons() expect(view.getByText('Expired')).toBeTruthy() expect(view.getByText('OLD')).toBeTruthy() }) it('ACOUPUI-09: an invalidated coupon shows Inactive', async () => { setProcedure('admin.coupon.getAll', { data: page([COUPON_INVALIDATED]) }) const view = await renderCoupons() expect(view.getByText('Inactive')).toBeTruthy() expect(view.getByText('DEAD')).toBeTruthy() }) it('ACOUPUI-10: a global coupon is read-only and explains why', async () => { setProcedure('admin.coupon.getAll', { data: page([COUPON_GLOBAL]) }) const view = await renderCoupons() expect(view.getByText('GLOBAL10')).toBeTruthy() expect(view.getByText('Global')).toBeTruthy() expect( view.getByText('Applies to all regions — created and managed by the superadmin.') ).toBeTruthy() expect(view.queryByText('Edit')).toBeNull() expect(view.queryByText('Delete')).toBeNull() }) it('ACOUPUI-11: shows N Users vs All Users for the target audience', async () => { setProcedure('admin.coupon.getAll', { data: page([ { ...COUPON_1, id: 31, couponCode: 'USERS', isApplyForAll: false, applicableUsers: [{ id: 5 }, { id: 6 }] }, ]), }) const view = await renderCoupons() expect(view.getByText(/Target: 2 Users/)).toBeTruthy() view.unmount() setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) }) const allView = await renderCoupons() expect(allView.getByText(/Target: All Users/)).toBeTruthy() }) it('ACOUPUI-12: hides the Products line when no SKUs are targeted', async () => { const view = await renderCoupons() expect(view.queryByText(/Products: \d+ selected/)).toBeNull() const withSkus = { ...COUPON_1, id: 32, couponCode: 'SKU10', skuIds: [11, 12] } setProcedure('admin.coupon.getAll', { data: page([withSkus]) }) view.unmount() const skuView = await renderCoupons() expect(skuView.getByText(/Products: 2 selected/)).toBeTruthy() }) it('ACOUPUI-13: Edit opens the coupon edit route', async () => { setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) }) const view = await renderCoupons() fireEvent.press(view.getByText('Edit')) expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/edit/21') }) it('ACOUPUI-13B: View details opens the coupon detail route', async () => { setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) }) const view = await renderCoupons() fireEvent.press(view.getByTestId('coupon-view-21')) expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/detail/21') }) it('ACOUPUI-14: Delete asks for confirmation and Cancel makes no API call', async () => { setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) }) const view = await renderCoupons() fireEvent.press(view.getByText('Delete')) expect(alertSpy).toHaveBeenCalledWith( 'Delete Coupon', 'Are you sure you want to delete this coupon?', expect.any(Array) ) const buttons = alertSpy.mock.calls[0][2] await act(async () => { buttons[0].onPress?.() }) expect(procedureMutationCalls('admin.coupon.delete')).toHaveLength(0) }) it('ACOUPUI-15: confirming Delete calls the mutation and reports success', async () => { setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) }) const view = await renderCoupons() fireEvent.press(view.getByText('Delete')) const buttons = alertSpy.mock.calls[0][2] await act(async () => { await buttons[1].onPress() }) await waitFor(() => expect(lastMutationInput('admin.coupon.delete')).toEqual({ id: 21 })) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Coupon deleted successfully') ) }) it('ACOUPUI-16: a failed delete shows an error alert', async () => { setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) }) setProcedure('admin.coupon.delete', { mode: 'error', error: new Error('nope') }) const view = await renderCoupons() fireEvent.press(view.getByText('Delete')) const buttons = alertSpy.mock.calls[0][2] await act(async () => { await buttons[1].onPress() }) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'nope')) }) it('ACOUPUI-17: the status filter narrows the list to active/expired/inactive', async () => { setProcedure('admin.coupon.getAll', { data: page(COUPONS) }) const view = await renderCoupons() selectStatusFilter(view, ['active']) expect(view.queryByText('OLD')).toBeNull() expect(view.queryByText('DEAD')).toBeNull() expect(view.getByText('SAVE10')).toBeTruthy() selectStatusFilter(view, ['expired']) expect(view.getByText('OLD')).toBeTruthy() expect(view.queryByText('SAVE10')).toBeNull() selectStatusFilter(view, ['inactive']) expect(view.getByText('DEAD')).toBeTruthy() expect(view.queryByText('OLD')).toBeNull() }) it('ACOUPUI-18: typing a search sends the query to the API', async () => { const view = await renderCoupons() fireEvent.changeText(view.getByPlaceholderText('Search coupons...'), 'SAVE') await waitFor(() => expect(lastProcedureInput('admin.coupon.getAll')).toEqual({ limit: 20, search: 'SAVE', direction: 'forward', }) ) }) it('ACOUPUI-19: reaching the end never duplicates rows', async () => { setProcedure('admin.coupon.getAll', { data: page(COUPONS) }) const view = await renderCoupons() const list = view.UNSAFE_getAllByType(FlatList)[0] await act(async () => { list.props.onEndReached?.() }) await flush() expect(view.getAllByText('SAVE10')).toHaveLength(1) expect(view.getAllByText('GLOBAL10')).toHaveLength(1) expect(COUPONS.every((coupon) => view.queryByText(coupon.couponCode))).toBe(true) }) it('ACOUPUI-20: a manual refresh keeps the list rendered', async () => { setProcedure('admin.coupon.getAll', { data: page(COUPONS) }) const view = await renderCoupons() const calls = procedureQueryCalls('admin.coupon.getAll').length await act(async () => { DeviceEventEmitter.emit('refresh_event') }) await waitFor(() => expect(procedureQueryCalls('admin.coupon.getAll').length).toBeGreaterThan(calls) ) expect(view.getByText('SAVE10')).toBeTruthy() expect(view.queryByText('Failed to load coupons')).toBeNull() }) it('ACOUPUI-21: the Add FAB opens the create route', async () => { const view = await renderCoupons() const icon = view .UNSAFE_getAllByType(MaterialCommunityIcons) .find((node: any) => node.props.name === 'plus') fireEvent.press(icon!) expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/create') }) it('ACOUPUI-22: shows the Reserved loading state', async () => { setProcedure('admin.coupon.getReservedCoupons', { mode: 'pending' }) const view = await renderCoupons() await openReserved(view) expect(view.getByText('Loading Reserved Coupons...')).toBeTruthy() }) it('ACOUPUI-23: shows the Reserved error state and retries', async () => { setProcedure('admin.coupon.getReservedCoupons', { mode: 'error', error: new Error('boom') }) const view = await renderCoupons() await openReserved(view) expect(view.getByText('Failed to load reserved coupons')).toBeTruthy() fireEvent.press(view.getByText('Retry')) await flush() expect(view.getByText('Failed to load reserved coupons')).toBeTruthy() }) it('ACOUPUI-24: shows the empty Reserved state', async () => { setProcedure('admin.coupon.getReservedCoupons', { data: page([]) }) const view = await renderCoupons() await openReserved(view) expect(await view.findByText('No Reserved Coupons Found')).toBeTruthy() }) it('ACOUPUI-25: renders the reserved coupon card fields', async () => { setProcedure('admin.coupon.getReservedCoupons', { data: page([ { ...COUPON_1, id: 25, couponCode: 'RES10', secretCode: 'SECRET123', isRedeemed: false, creator: { name: 'Admin One' }, }, ]), }) const view = await renderCoupons() await openReserved(view) expect(await view.findByText('SECRET123')).toBeTruthy() expect(view.getByText('Coupon: RES10')).toBeTruthy() expect(view.getByText('Active')).toBeTruthy() expect(view.getByText('Discount: 10% off')).toBeTruthy() expect(view.getByText('Valid Till: No expiry')).toBeTruthy() expect(view.getByText(/Created by: Admin One/)).toBeTruthy() }) it('ACOUPUI-26: reserved active/expired/redeemed statuses render', async () => { setProcedure('admin.coupon.getReservedCoupons', { data: page([ { ...COUPON_1, id: 41, couponCode: 'ACT', secretCode: 'ACTIVE1', isRedeemed: false, creator: { name: 'Admin One' } }, { ...COUPON_1, id: 42, couponCode: 'EXP', secretCode: 'EXPIRED1', isRedeemed: false, validTill: iso(-HOUR), creator: { name: 'Admin One' }, }, { ...COUPON_1, id: 43, couponCode: 'RED', secretCode: 'REDEEMED1', isRedeemed: true, creator: { name: 'Admin One' } }, ]), }) const view = await renderCoupons() await openReserved(view) expect(await view.findByText('ACTIVE1')).toBeTruthy() expect(view.getByText('EXPIRED1')).toBeTruthy() expect(view.getByText('REDEEMED1')).toBeTruthy() expect(view.getByText('Expired')).toBeTruthy() expect(view.getByText('Redeemed')).toBeTruthy() }) it('ACOUPUI-27: a redeemed coupon shows who redeemed it and when', async () => { setProcedure('admin.coupon.getReservedCoupons', { data: page([ { ...COUPON_1, id: 44, couponCode: 'RED2', secretCode: 'REDEEMED2', isRedeemed: true, redeemedAt: iso(0), redeemedUser: { name: 'Test User', mobile: '9876543210' }, creator: { name: 'Admin One' }, }, ]), }) const view = await renderCoupons() await openReserved(view) expect(await view.findByText(/Redeemed by: Test User \(9876543210\)/)).toBeTruthy() expect(view.getByText(/Redeemed on:/)).toBeTruthy() }) it('ACOUPUI-28: a reserved coupon shows its creator', async () => { setProcedure('admin.coupon.getReservedCoupons', { data: page([ { ...COUPON_1, id: 45, couponCode: 'CRE', secretCode: 'CREATOR1', creator: { name: 'Admin Two' } }, ]), }) const view = await renderCoupons() await openReserved(view) expect(await view.findByText(/Created by: Admin Two/)).toBeTruthy() }) it('ACOUPUI-29: the reserved status filter narrows the list', async () => { setProcedure('admin.coupon.getReservedCoupons', { data: page([ { ...COUPON_1, id: 51, couponCode: 'A', secretCode: 'ACTIVE9', isRedeemed: false, creator: { name: 'Admin One' } }, { ...COUPON_1, id: 52, couponCode: 'E', secretCode: 'OLD9', isRedeemed: false, validTill: iso(-HOUR), creator: { name: 'Admin One' }, }, { ...COUPON_1, id: 53, couponCode: 'R', secretCode: 'RED9', isRedeemed: true, creator: { name: 'Admin One' } }, ]), }) const view = await renderCoupons() await openReserved(view) expect(await view.findByText('ACTIVE9')).toBeTruthy() selectStatusFilter(view, ['redeemed'], -1) expect(view.getByText('RED9')).toBeTruthy() expect(view.queryByText('OLD9')).toBeNull() expect(view.queryByText('ACTIVE9')).toBeNull() selectStatusFilter(view, ['expired'], -1) expect(view.getByText('OLD9')).toBeTruthy() expect(view.queryByText('RED9')).toBeNull() }) it('ACOUPUI-30: reserved search/filter/refresh keeps the list consistent', async () => { setProcedure('admin.coupon.getReservedCoupons', { data: page([ { ...COUPON_1, id: 61, couponCode: 'SEARCH', secretCode: 'SEARCH1', creator: { name: 'Admin One' } }, ]), }) const view = await renderCoupons() await openReserved(view) expect(await view.findByText('SEARCH1')).toBeTruthy() fireEvent.changeText(view.getByPlaceholderText('Search reserved coupons...'), 'SEARCH') await waitFor(() => expect(lastProcedureInput('admin.coupon.getReservedCoupons')).toEqual({ limit: 20, search: 'SEARCH', direction: 'forward', }) ) selectStatusFilter(view, ['active'], -1) expect(view.getByText('SEARCH1')).toBeTruthy() await act(async () => { DeviceEventEmitter.emit('refresh_event') }) await flush(2) expect(view.getAllByText('SEARCH1')).toHaveLength(1) }) })