/** * Delivery sequences * (app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx) — slot * picker, unassigned/all-users filtering, assigning & unassigning orders, * packaged/delivered toggles, notes, cancel and order intents. * * NOTE: the "save sequence" FAB only appears after a drag (`hasSequenceChanged`). * The mocked draggable list never fires onDragEnd on its own, but the prop is * still on the rendered element and can be invoked through * UNSAFE_getByType(...).props.onDragEnd({ data }) inside act(), which is how the * reorder-save path (`handleSaveSequence`) is covered below. Assignment changes * persist via updateDeliverySequence directly. */ jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) import React from 'react' import { Alert, Linking } from 'react-native' import { act, fireEvent, screen, waitFor } from '@testing-library/react-native' import dayjs from 'dayjs' import MaterialIcons from '@expo/vector-icons/MaterialIcons' import Entypo from '@expo/vector-icons/Entypo' import Ionicons from '@expo/vector-icons/Ionicons' import DeliverySequences from '@/app/(drawer)/dashboard/manage-orders/delivery-sequences' import { setupApiMocks, resetStorage } from '../mocks/api' import { resetStaffAuthMock } from '../mocks/staff-auth' import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router' import { lastProcedureInput, procCount } from '../mocks/procedures' import { refreshHooks, resetRefreshHooks } from '../mocks/refresh' import { renderWithProviders } from '../helpers/render' const SLOTS = [ { id: 3, deliveryTime: '2026-01-01T09:00:00.000Z' }, { id: 4, deliveryTime: '2026-01-02T09:00:00.000Z' }, ] const LABEL_3 = dayjs(SLOTS[0].deliveryTime).format('ddd DD MMM, h:mm a') const LABEL_4 = dayjs(SLOTS[1].deliveryTime).format('ddd DD MMM, h:mm a') const slotOrder = (overrides: Record = {}) => ({ id: 21, readableId: 21, customerName: 'Bob', address: '12 Main St, Phone: 9876543210', addressId: 5, latitude: null, longitude: null, totalAmount: 300, items: [], deliveryTime: null, status: 'pending', isPackaged: false, isDelivered: false, slotId: 3, adminNotes: 'fragile', userNotes: null, ...overrides, }) const defaultProcedures = (overrides: Record = {}) => ({ 'admin.slots.getAll': { slots: SLOTS, count: 2 }, 'admin.order.getSlotOrders': { success: true, data: [slotOrder()] }, 'admin.slots.getDeliverySequence': { deliverySequence: {} }, 'admin.staffUser.getStaff': { staff: [{ id: 7, name: 'Ravi' }, { id: 8, name: 'Sita' }] }, 'admin.slots.updateDeliverySequence': { slot: { id: 3, deliverySequence: {} }, message: 'ok' }, 'admin.order.updatePackaged': { success: true, userId: 1 }, 'admin.order.updateDelivered': { success: true, userId: 1 }, 'admin.order.updateNotes': { id: 21 }, 'admin.order.cancelOrder': { success: true, message: 'cancelled' }, 'admin.order.updateAddressCoords': { success: true }, ...overrides, }) const renderScreen = (overrides: Record = {}) => { const { fetchMock } = setupApiMocks({ procedures: defaultProcedures(overrides) }) // `view` is returned so tests can reach props of the mocked DraggableFlatList // (its `onDragEnd` prop is not fired by the mock component itself). const view = renderWithProviders() return { fetchMock, view } } const openOrderMenu = async () => { const dots = screen.UNSAFE_getAllByType(Entypo)[0] fireEvent.press(dots) await screen.findByText('Select an action to perform') } const openUserDropdown = async () => { fireEvent.press(await screen.findByText('Unassigned')) await screen.findByText('All Users') } const toggleMenuResponder = async (name: 'square-outline' | 'checkbox') => { const icon = screen.UNSAFE_getAllByType(Ionicons).find((node) => node.props.name === name)! fireEvent(icon, 'responderEnd', { stopPropagation: jest.fn() }) } const openAssignDropdown = async () => { const icon = screen .UNSAFE_getAllByType(MaterialIcons) .find((node) => node.props.name === 'person-add')! fireEvent.press(icon) await screen.findByText('Assign To') } describe('Delivery sequences', () => { beforeEach(async () => { resetStaffAuthMock() await resetStorage() resetRouterMock() resetRefreshHooks() searchParamsMock.current = { slotId: '3' } jest.spyOn(Alert, 'alert').mockImplementation(() => {}) jest.spyOn(Linking, 'openURL').mockResolvedValue(true) }) it('shows a loading message while slots load', () => { renderScreen() expect(screen.getByText('Loading slots...')).toBeVisible() }) it('reports when there are no slots', async () => { renderScreen({ 'admin.slots.getAll': { slots: [], count: 0 } }) expect(await screen.findByText('No slots available')).toBeVisible() }) it('auto-selects the first slot and prompts when no slot is given', async () => { searchParamsMock.current = {} renderScreen() expect( await screen.findByText('No slot selected. Please select a slot to view delivery sequence.') ).toBeVisible() await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith( '/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=3' ) ) }) it('queries slot orders and sequence with the route slot id', async () => { const { fetchMock } = renderScreen() await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) expect(lastProcedureInput(fetchMock, 'admin.order.getSlotOrders')).toEqual({ slotId: '3' }) expect(lastProcedureInput(fetchMock, 'admin.slots.getDeliverySequence')).toEqual({ id: '3' }) }) it('renders the order card details', async () => { renderScreen() await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) expect(screen.getByText('₹300')).toBeVisible() expect(screen.getByText('fragile')).toBeVisible() }) it('renders an empty state when there are no orders', async () => { renderScreen({ 'admin.order.getSlotOrders': { success: true, data: [] } }) expect(await screen.findByText('No orders found for this slot')).toBeVisible() }) it('filters to a user with no sequence and reports empty', async () => { renderScreen() await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) await openUserDropdown() fireEvent.press(screen.getByText('Ravi')) expect(await screen.findByText('No orders found for this slot')).toBeVisible() }) it('shows assignment info in the All Users view', async () => { renderScreen({ 'admin.slots.getDeliverySequence': { deliverySequence: { '7': [21] } } }) await openUserDropdown() fireEvent.press(screen.getByText('All Users')) expect(await screen.findByText('Assigned to')).toBeVisible() expect(screen.getByText('Ravi')).toBeVisible() expect(screen.getByText('#21')).toBeVisible() }) it('assigns selected orders to a user', async () => { const { fetchMock } = renderScreen() await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) fireEvent.press(screen.getAllByRole('checkbox')[0]) await openAssignDropdown() fireEvent.press(screen.getByText('Ravi')) await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.slots.updateDeliverySequence')).toEqual({ id: 3, deliverySequence: { '7': [21] }, }) ) }) it('unassigns selected orders from all users', async () => { const { fetchMock } = renderScreen({ 'admin.slots.getDeliverySequence': { deliverySequence: { '7': [21] } }, }) await openUserDropdown() fireEvent.press(screen.getByText('All Users')) await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) fireEvent.press(screen.getAllByRole('checkbox')[0]) await openAssignDropdown() fireEvent.press(screen.getByText('None')) await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.slots.updateDeliverySequence')).toEqual({ id: 3, deliverySequence: { '7': [] }, }) ) }) it('marks an order packaged from the options menu', async () => { const { fetchMock } = renderScreen({ 'admin.order.getSlotOrders': { success: true, data: [slotOrder({ isDelivered: true })] }, }) await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) const beforeOrders = procCount(fetchMock, 'admin.order.getSlotOrders') const beforeSequence = procCount(fetchMock, 'admin.slots.getDeliverySequence') await openOrderMenu() await toggleMenuResponder('square-outline') await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.order.updatePackaged')).toEqual({ orderId: '21', isPackaged: true, })) // onSuccess refetches both the slot orders and the delivery sequence. await waitFor(() => { expect(procCount(fetchMock, 'admin.order.getSlotOrders')).toBeGreaterThan(beforeOrders) expect(procCount(fetchMock, 'admin.slots.getDeliverySequence')).toBeGreaterThan(beforeSequence) }) }) it('marks an order delivered from the options menu', async () => { const { fetchMock } = renderScreen({ 'admin.order.getSlotOrders': { success: true, data: [slotOrder({ isPackaged: true })] }, }) await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) await openOrderMenu() await toggleMenuResponder('square-outline') await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.order.updateDelivered')).toEqual({ orderId: '21', isDelivered: true, })) }) it('saves admin notes from the options menu', async () => { const { fetchMock } = renderScreen() await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) await openOrderMenu() fireEvent.press(screen.getByText('Admin Notes')) fireEvent.changeText( await screen.findByPlaceholderText('Enter notes for this order...'), 'fragile item' ) fireEvent.press(screen.getByText('Save Notes')) await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.order.updateNotes')).toEqual({ orderId: 21, adminNotes: 'fragile item', }) ) }) it('opens the cancel dialog from the options menu', async () => { renderScreen() await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) await openOrderMenu() fireEvent.press(screen.getByText('Cancel Order')) expect(await screen.findByPlaceholderText('Enter reason for cancellation...')).toBeVisible() }) it('navigates to order details from View Details', async () => { renderScreen() await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) await openOrderMenu() fireEvent.press(screen.getByText('View Details')) expect(routerMock.push).toHaveBeenCalledWith( '/(drawer)/dashboard/manage-orders/order-details/21' ) }) it('switches slots through the slot picker', async () => { renderScreen() await waitFor(() => expect(screen.getByText(LABEL_3)).toBeVisible()) fireEvent.press(screen.getByText(LABEL_3)) fireEvent.press(await screen.findByText(LABEL_4)) expect(routerMock.replace).toHaveBeenCalledWith( '/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=4' ) }) it('opens a Google Maps link for orders with coordinates', async () => { renderScreen({ 'admin.order.getSlotOrders': { success: true, data: [slotOrder({ latitude: 16.75, longitude: 78.0 })], }, }) await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) const mapIcon = screen .UNSAFE_getAllByType(MaterialIcons) .find((node) => node.props.name === 'map')! fireEvent.press(mapIcon) expect(Linking.openURL).toHaveBeenCalledWith('https://www.google.com/maps?q=16.75,78') }) it('goes back from the header', async () => { renderScreen() await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) fireEvent.press(screen.getByLabelText('Go back')) expect(routerMock.back).toHaveBeenCalled() }) it('refetches orders and sequence after saving a reordered sequence', async () => { const { fetchMock, view } = renderScreen({ 'admin.order.getSlotOrders': { success: true, data: [slotOrder({ id: 21, readableId: 21 }), slotOrder({ id: 22, readableId: 22 })], }, 'admin.slots.getDeliverySequence': { deliverySequence: { '7': [21, 22] } }, }) // A real user must be selected: handleDragEnd/handleSaveSequence no-op for // the Unassigned (-1) view. await openUserDropdown() fireEvent.press(screen.getByText('Ravi')) await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) const beforeOrders = procCount(fetchMock, 'admin.order.getSlotOrders') const beforeSequence = procCount(fetchMock, 'admin.slots.getDeliverySequence') // The mocked list renders its data but never drags by itself. const list = view.UNSAFE_getByType(require('react-native-draggable-flatlist').default) act(() => { list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] }) }) fireEvent.press(await screen.findByLabelText('Save sequence')) // handleSaveSequence's onSuccess refetches both the slot orders and the // delivery sequence. await waitFor(() => { expect(procCount(fetchMock, 'admin.order.getSlotOrders')).toBeGreaterThan(beforeOrders) expect(procCount(fetchMock, 'admin.slots.getDeliverySequence')).toBeGreaterThan(beforeSequence) }) }) it('refetches on mark-data-fetchers', async () => { const { fetchMock } = renderScreen() await waitFor(() => expect(screen.getByText('#21')).toBeVisible()) const before = procCount(fetchMock, 'admin.order.getSlotOrders') refreshHooks.markDataFetchers?.() await waitFor(() => expect(procCount(fetchMock, 'admin.order.getSlotOrders')).toBeGreaterThan(before) ) }) })