/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 14.1 — Complaints (`tests/pages/complaints.test.tsx`). * * The complaints fixture is DB-shaped; the `admin.complaint.getAll` procedure * flattens each row to {text, userName, userMobile, status, images, response}. * Tests build that page shape locally (see COMPLAINT_PAGE_*). * * Harness workaround (reported): the shared trpc mock pins `hasNextPage=false` * and hands back a throw-away `fetchNextPage`/`refetch`, so pagination and * refresh rows cannot be observed. This file wraps the same procedure registry * locally and exposes those two spies without touching the harness. */ import React from 'react' import { Alert, FlatList, Image, Modal, RefreshControl } from 'react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native' import Complaints from '@/app/(drawer)/dashboard/complaints/index' import { renderWithProviders, flush } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { lastMutationInput, procedureMutationCalls, setProcedure, } from '../mocks/trpc-client' import { router } from '../mocks/expo-router-mock' jest.mock('../mocks/trpc-client', () => { const actual = jest.requireActual('../mocks/trpc-client') const paginationState = { fetchingNextPage: false } const fetchNextPage = jest.fn() const refetch = jest.fn(async () => ({ data: undefined })) const nodeFor = (path: string) => path.split('.').reduce((node: any, key: string) => node[key], actual.trpc) const wrap = (path: string): any => new Proxy( {}, { get(_target, prop) { if (typeof prop !== 'string') return undefined if ( !path && (prop === 'Provider' || prop === 'createClient' || prop === 'useUtils' || prop === 'useContext') ) { return actual.trpc[prop] } if (prop === 'useInfiniteQuery' && path === 'admin.complaint.getAll') { return (input: any, options: any) => { const result = nodeFor(path).useInfiniteQuery(input, options) const pages = result.data?.pages ?? [] const lastPage = pages[pages.length - 1] return { ...result, refetch, fetchNextPage, hasNextPage: Boolean(lastPage?.nextCursor), isFetchingNextPage: paginationState.fetchingNextPage, } } } if (prop === 'useQuery' || prop === 'useMutation' || prop === 'useInfiniteQuery') { return nodeFor(path)[prop] } return wrap(path ? `${path}.${prop}` : prop) }, } ) return { ...actual, trpc: wrap(''), __paginationState: paginationState, __fetchNextPage: fetchNextPage, __refetch: refetch, } }) // Focus simulation: the shared @react-navigation mock never re-runs the focus // effect, so `useMarkDataFetchers` can never be observed. This local mock keeps // the real module and adds a manual `__triggerFocus`. jest.mock('@react-navigation/native', () => { const actual = jest.requireActual('@react-navigation/native') const ReactActual = jest.requireActual('react') const listeners = new Set<() => void>() const useFocusEffect = (callback: () => void | (() => void)) => { ReactActual.useEffect(() => { const run = () => { callback() } listeners.add(run) run() return () => { listeners.delete(run) } // eslint-disable-next-line react-hooks/exhaustive-deps }, [callback]) } return { ...actual, useFocusEffect, __triggerFocus: () => listeners.forEach((listener) => listener()), } }) const trpcMock = require('../mocks/trpc-client') as any const navMock = require('@react-navigation/native') as any const COMPLAINT = (over: Record = {}) => ({ id: 1, userId: 5, userName: 'Test User', userMobile: '9876543210', orderId: 11, regionId: 1, text: 'Late delivery', status: 'pending', images: [] as string[], response: null as string | null, createdAt: new Date().toISOString(), ...over, }) const COMPLAINT_PENDING = COMPLAINT() const COMPLAINT_RESOLVED = COMPLAINT({ id: 2, orderId: null, text: 'App issue', status: 'resolved', images: ['issue.jpg'], response: 'We fixed it', }) function setComplaintPages(pages: Array<{ complaints: any[]; nextCursor?: number }>) { setProcedure('admin.complaint.getAll', { data: { pages } }) } function renderComplaints() { return renderWithProviders(, { auth: 'in' }) } describe('Complaints (ACOMPUI-01..16)', () => { let alertSpy: jest.SpyInstance beforeEach(() => { resetAllMocks() alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) }) afterEach(() => alertSpy?.mockRestore()) it('ACOMPUI-01: shows "Loading complaints..." while the query is pending', () => { setProcedure('admin.complaint.getAll', { mode: 'pending' }) const view = renderComplaints() expect(view.getByText('Loading complaints...')).toBeTruthy() }) it('ACOMPUI-02: a failed query shows Error + Retry and Retry refetches', async () => { setProcedure('admin.complaint.getAll', { mode: 'error', error: new Error('boom') }) const view = renderComplaints() await flush() expect(view.getByText('Error')).toBeTruthy() expect(view.getByText('boom')).toBeTruthy() fireEvent.press(view.getByText('Retry')) expect(trpcMock.__refetch).toHaveBeenCalled() }) it('ACOMPUI-03: an empty page renders the empty copy', async () => { setComplaintPages([{ complaints: [] }]) const view = renderComplaints() await flush() expect(view.getByText('No complaints')).toBeTruthy() expect(view.getByText('All complaints will appear here')).toBeTruthy() }) it('ACOMPUI-04: a card shows id, user, order, text, status, images and response', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING, COMPLAINT_RESOLVED] }]) const view = renderComplaints() await flush() expect(view.getByText('Complaint #1')).toBeTruthy() expect(view.getByText('Late delivery')).toBeTruthy() expect(view.getAllByText('Test User').length).toBeGreaterThanOrEqual(1) expect(view.getByText('Order #11')).toBeTruthy() expect(view.getByText('Pending')).toBeTruthy() expect(view.getByText('Attached Images:')).toBeTruthy() expect(view.getByText('App issue')).toBeTruthy() expect(view.getByText('Resolved')).toBeTruthy() expect(view.getByText('Admin Reply')).toBeTruthy() expect(view.getByText('We fixed it')).toBeTruthy() expect(view.UNSAFE_getAllByType(Image).some((image) => image.props.source?.uri === 'issue.jpg')).toBe(true) }) it('ACOMPUI-05: a pending complaint shows the Pending status + resolve button', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) const view = renderComplaints() await flush() expect(view.getByText('Pending')).toBeTruthy() expect(view.getByText('Resolve Complaint')).toBeTruthy() }) it('ACOMPUI-06: a resolved complaint shows the Resolved status and hides resolve', async () => { setComplaintPages([{ complaints: [COMPLAINT_RESOLVED] }]) const view = renderComplaints() await flush() expect(view.getByText('Resolved')).toBeTruthy() expect(view.queryByText('Resolve Complaint')).toBeNull() }) it('ACOMPUI-07: pressing the user opens the user detail route', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) const view = renderComplaints() await flush() fireEvent.press(view.getByText('Test User')) expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5') }) it('ACOMPUI-08: pressing the order opens the order detail route', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) const view = renderComplaints() await flush() fireEvent.press(view.getByText('Order #11')) expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders/order-details/11') }) it('ACOMPUI-09: Mark resolved opens the confirmation dialog with a comment field', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) const view = renderComplaints() await flush() fireEvent.press(view.getByText('Resolve Complaint')) expect(view.getByText('Add admin notes for this resolution:')).toBeTruthy() expect(view.getByPlaceholderText('Add a comment...')).toBeTruthy() expect(view.getByText('Resolve')).toBeTruthy() expect(view.getByText('Cancel')).toBeTruthy() }) it('ACOMPUI-10: an empty comment still submits (server min(1) is the only guard)', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) const view = renderComplaints() await flush() fireEvent.press(view.getByText('Resolve Complaint')) fireEvent.press(view.getByText('Resolve')) await flush(2) expect(lastMutationInput('admin.complaint.resolve')).toEqual({ id: '1', response: '' }) expect(procedureMutationCalls('admin.complaint.resolve')).toHaveLength(1) }) it('ACOMPUI-11: resolving sends the comment, alerts success and refetches', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) const view = renderComplaints() await flush() fireEvent.press(view.getByText('Resolve Complaint')) fireEvent.changeText(view.getByPlaceholderText('Add a comment...'), 'Fixed') fireEvent.press(view.getByText('Resolve')) await flush(2) expect(lastMutationInput('admin.complaint.resolve')).toEqual({ id: '1', response: 'Fixed' }) expect(alertSpy).toHaveBeenCalledWith('Success', 'Complaint marked as resolved') expect(trpcMock.__refetch).toHaveBeenCalled() expect(view.queryByText('Add admin notes for this resolution:')).toBeNull() }) it('ACOMPUI-12: a failed resolve alerts the error and closes the dialog', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) setProcedure('admin.complaint.resolve', { mode: 'error', error: new Error('nope') }) const view = renderComplaints() await flush() fireEvent.press(view.getByText('Resolve Complaint')) fireEvent.changeText(view.getByPlaceholderText('Add a comment...'), 'Fixed') fireEvent.press(view.getByText('Resolve')) await flush(2) expect(alertSpy).toHaveBeenCalledWith('Error', 'nope') expect(view.queryByText('Add admin notes for this resolution:')).toBeNull() }) it('ACOMPUI-13: end of list calls fetchNextPage and the appended page is rendered', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING], nextCursor: 1 }]) const view = renderComplaints() await flush() expect(view.getByText('Complaint #1')).toBeTruthy() const list = view.UNSAFE_getByType(FlatList) await act(async () => { list.props.onEndReached?.({ distanceFromEnd: 0 }) }) expect(trpcMock.__fetchNextPage).toHaveBeenCalled() // The harness mock never appends; feed the second page directly and assert // it is flattened into the same list (deduped by id). await act(async () => { setComplaintPages([ { complaints: [COMPLAINT_PENDING, COMPLAINT_RESOLVED], nextCursor: undefined }, ]) }) await flush() expect(view.getByText('Complaint #1')).toBeTruthy() expect(view.getByText('Complaint #2')).toBeTruthy() }) it('ACOMPUI-14: pull-to-refresh triggers the shared refresh (query cache clear)', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) const view = renderComplaints() await flush() const clearSpy = jest.spyOn(view.queryClient, 'clear') const refresh = view.UNSAFE_getByType(RefreshControl) await act(async () => { refresh.props.onRefresh?.() }) expect(clearSpy).toHaveBeenCalled() }) it('ACOMPUI-15: the marked data fetcher refetches on the next focus', async () => { setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) renderComplaints() await flush() expect(trpcMock.__refetch).not.toHaveBeenCalled() await act(async () => { navMock.__triggerFocus() }) await flush() expect(trpcMock.__refetch).toHaveBeenCalled() }) it('ACOMPUI-16: pressing an attached image opens the image viewer', async () => { setComplaintPages([{ complaints: [COMPLAINT_RESOLVED] }]) const view = renderComplaints() await flush() const image = view .UNSAFE_getAllByType(Image) .find((node) => node.props.source?.uri === 'issue.jpg') expect(image).toBeTruthy() fireEvent.press(image as any) await waitFor(() => { expect(view.UNSAFE_getAllByType(Modal).some((modal) => modal.props.visible === true)).toBe(true) }) }) })