/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 13.3 — Delivery sequences * (`tests/pages/delivery-sequences.test.tsx`). */ import React from 'react' import { Alert, DeviceEventEmitter } from 'react-native' import { act, fireEvent } from '@testing-library/react-native' import DraggableFlatList from 'react-native-draggable-flatlist' jest.mock('expo-location', () => ({ requestForegroundPermissionsAsync: jest.fn(async () => ({ status: 'granted' })), getCurrentPositionAsync: jest.fn(async () => ({ coords: { latitude: 12.34, longitude: 56.78 }, })), Accuracy: { High: 6 }, })) import DeliverySequences from '@/app/(drawer)/dashboard/manage-orders/delivery-sequences/index' import { renderWithProviders, flush } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { lastMutationInput, lastProcedureInput, procedureMutationCalls, setProcedure, } from '../mocks/trpc-client' import { router, __setParams } from '../mocks/expo-router-mock' import { SLOT_ORDERS } from '../fixtures' const SLOT_ID = '1849' function slotOrders(orders: any[]) { setProcedure('admin.order.getSlotOrders', { data: { success: true, data: orders } }) } describe('Delivery sequences (ADSEQ-01..20)', () => { let alertSpy: jest.SpyInstance beforeEach(() => { resetAllMocks() // OrderOptionsMenu expects key/value rows from getRegionConstants. setProcedure('admin.region.getRegionConstants', { data: [{ key: 'welcomeMessage', value: 'Welcome' }], }) alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) }) afterEach(() => alertSpy?.mockRestore()) function renderSequences(params: Record = { slotId: SLOT_ID }) { __setParams(params) return renderWithProviders(, { auth: 'in' }) } function selectUser(view: ReturnType, userId: string) { fireEvent.press(view.getByTestId('delivery-sequence-user-dropdown')) fireEvent.press(view.getByTestId(`delivery-sequence-user-dropdown-option-${userId}`)) } it('ADSEQ-01: shows the slots loading copy', () => { setProcedure('admin.slots.getAll', { mode: 'pending' }) const view = renderSequences() expect(view.getByText('Loading slots...')).toBeTruthy() }) it('ADSEQ-02: with no slots shows the empty copy', () => { setProcedure('admin.slots.getAll', { data: { slots: [], count: 0 } }) const view = renderSequences() expect(view.getByText('No slots available')).toBeTruthy() }) it('ADSEQ-03: loads the slot selected through the URL', () => { const view = renderSequences() expect(lastProcedureInput('admin.order.getSlotOrders')).toEqual({ slotId: SLOT_ID }) expect(view.getByTestId('delivery-sequence-slot-dropdown')).toBeTruthy() expect(view.getByText('#101')).toBeTruthy() }) it('ADSEQ-04: with no slotId it replaces the URL with the first slot', async () => { renderSequences({}) await flush(2) expect(router.replace).toHaveBeenCalledWith( '/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=1849', ) }) it('ADSEQ-05: choosing another slot replaces the URL', () => { const view = renderSequences() fireEvent.press(view.getByTestId('delivery-sequence-slot-dropdown')) fireEvent.press(view.getByTestId('delivery-sequence-slot-dropdown-option-1850')) expect(router.replace).toHaveBeenCalledWith( '/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=1850', ) }) it('ADSEQ-06: shows the orders loading copy', () => { setProcedure('admin.order.getSlotOrders', { mode: 'pending' }) const view = renderSequences() expect(view.getByText('Loading orders...')).toBeTruthy() }) it('ADSEQ-07: shows the no-orders copy', () => { slotOrders([]) const view = renderSequences() expect(view.getByText('No orders found for this slot')).toBeTruthy() }) it('ADSEQ-08: renders the slot statistics', () => { const view = renderSequences() // The harness's DraggableFlatList mock renders rows only, so mount the real // ListHeaderComponent (SlotProgress) that the page passes to it. const header = view.UNSAFE_getByType(DraggableFlatList).props.ListHeaderComponent const stats = renderWithProviders(header, { auth: false }) expect(stats.getByText('Slot 1849 Statistics')).toBeTruthy() expect(stats.getByText('Delivered')).toBeTruthy() expect(stats.getByText('Undelivered')).toBeTruthy() expect(stats.getByText('Packaged')).toBeTruthy() expect(stats.getByText('Not Packaged')).toBeTruthy() expect(stats.getAllByText('0')).toHaveLength(2) expect(stats.getAllByText('1')).toHaveLength(2) }) it('ADSEQ-09: the staff filter lists Unassigned, All Users and staff', () => { const view = renderSequences() fireEvent.press(view.getByTestId('delivery-sequence-user-dropdown')) expect(view.getByTestId('delivery-sequence-user-dropdown-option--1')).toBeTruthy() expect(view.getByTestId('delivery-sequence-user-dropdown-option--2')).toBeTruthy() expect(view.getByTestId('delivery-sequence-user-dropdown-option-3')).toBeTruthy() fireEvent.press(view.getByTestId('delivery-sequence-user-dropdown-option--2')) expect(view.getByText('All Users')).toBeTruthy() expect(view.getByText('#101')).toBeTruthy() }) it('ADSEQ-10: dragging changes the local sequence and reveals Save', async () => { setProcedure('admin.slots.getDeliverySequence', { data: { deliverySequence: { 3: [11] } }, }) const view = renderSequences() selectUser(view, '3') const list = view.UNSAFE_getByType(DraggableFlatList) await act(async () => { list.props.onDragEnd({ data: [{ sequenceId: 11 }] }) }) expect(view.getByLabelText('Save sequence')).toBeTruthy() }) it('ADSEQ-11: saving posts the updated delivery sequence', async () => { setProcedure('admin.slots.getDeliverySequence', { data: { deliverySequence: { 3: [11] } }, }) const view = renderSequences() selectUser(view, '3') const list = view.UNSAFE_getByType(DraggableFlatList) await act(async () => { list.props.onDragEnd({ data: [{ sequenceId: 11 }] }) }) fireEvent.press(view.getByLabelText('Save sequence')) await flush(2) expect(lastMutationInput('admin.slots.updateDeliverySequence')).toEqual({ id: 1849, deliverySequence: { 3: [11] }, }) }) it('ADSEQ-12: a successful save shows the success alert', async () => { setProcedure('admin.slots.getDeliverySequence', { data: { deliverySequence: { 3: [11] } }, }) const view = renderSequences() selectUser(view, '3') const list = view.UNSAFE_getByType(DraggableFlatList) await act(async () => { list.props.onDragEnd({ data: [{ sequenceId: 11 }] }) }) fireEvent.press(view.getByLabelText('Save sequence')) await flush(2) expect(alertSpy).toHaveBeenCalledWith('Success', 'Delivery sequence updated successfully') }) it('ADSEQ-13: a failed save shows the error alert', async () => { setProcedure('admin.slots.updateDeliverySequence', { mode: 'error', error: new Error('boom'), }) setProcedure('admin.slots.getDeliverySequence', { data: { deliverySequence: { 3: [11] } }, }) const view = renderSequences() selectUser(view, '3') const list = view.UNSAFE_getByType(DraggableFlatList) await act(async () => { list.props.onDragEnd({ data: [{ sequenceId: 11 }] }) }) fireEvent.press(view.getByLabelText('Save sequence')) await flush(2) expect(alertSpy).toHaveBeenCalledWith( 'Error', 'Failed to update delivery sequence: boom', ) }) it('ADSEQ-14: marking packaged from the order menu calls updatePackaged', async () => { const view = renderSequences() fireEvent.press(view.getByTestId('sequence-menu-11')) fireEvent(view.getByTestId('order-menu-packaged'), 'responderEnd', { stopPropagation: jest.fn(), }) await flush(2) expect(lastMutationInput('admin.order.updatePackaged')).toEqual({ orderId: '11', isPackaged: true, }) }) it('ADSEQ-15: marking delivered from the order menu calls updateDelivered', async () => { const view = renderSequences() fireEvent.press(view.getByTestId('sequence-menu-11')) fireEvent(view.getByTestId('order-menu-delivered'), 'responderEnd', { stopPropagation: jest.fn(), }) await flush(2) expect(lastMutationInput('admin.order.updateDelivered')).toEqual({ orderId: '11', isDelivered: true, }) }) it('ADSEQ-16: Attach Location saves the current coordinates', async () => { const view = renderSequences() fireEvent.press(view.getByTestId('sequence-menu-11')) fireEvent.press(view.getByTestId('order-menu-attach-location')) await flush(3) expect(lastMutationInput('admin.order.updateAddressCoords')).toEqual({ addressId: 11, latitude: 12.34, longitude: 56.78, }) }) it('ADSEQ-17: View Details opens the order detail route', () => { const view = renderSequences() fireEvent.press(view.getByTestId('sequence-menu-11')) fireEvent.press(view.getByTestId('order-menu-view-details')) expect(router.push).toHaveBeenCalledWith( '/(drawer)/dashboard/manage-orders/order-details/11', ) }) it('ADSEQ-18: a flash order is listed like any other order (no flash branch)', () => { slotOrders([{ ...SLOT_ORDERS[0], id: 12, readableId: 102, isFlashDelivery: true }]) const view = renderSequences() expect(view.getByText('#102')).toBeTruthy() expect(view.queryByText('FLASH')).toBeNull() }) it('ADSEQ-19: registers the manual refresh listener and survives a refresh event', async () => { const listenerSpy = jest.spyOn(DeviceEventEmitter, 'addListener') const view = renderSequences() await flush() expect(listenerSpy).toHaveBeenCalledWith('refresh_event', expect.any(Function)) await act(async () => { DeviceEventEmitter.emit('refresh_event') }) await flush() expect(view.getByText('#101')).toBeTruthy() listenerSpy.mockRestore() }) it('ADSEQ-20: with no orders there is no sequence to save', async () => { slotOrders([]) const view = renderSequences() expect(view.getByText('No orders found for this slot')).toBeTruthy() expect(view.queryByLabelText('Save sequence')).toBeNull() expect(procedureMutationCalls('admin.slots.updateDeliverySequence')).toHaveLength(0) }) })