freshyo/apps/admin-ui/tests/screens/order-details.test.tsx
2026-10-13 18:11:25 +05:30

277 lines
9.1 KiB
TypeScript

/**
* Order details (app/(drawer)/dashboard/manage-orders/order-details/[id].tsx) —
* detail rendering, packaging toggles, delivery-charge removal, cancellation
* and navigation.
*
* NOTE: the "Initiate Refund" / "Generate Refund Coupon" action block is
* commented out in the source (lines ~697-769) and the state setters that open
* those dialogs are never invoked, so those two mutations are not reachable
* through the UI and cannot be integration-tested.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import OrderDetails from '@/app/(drawer)/dashboard/manage-orders/order-details/[id]'
import { setupApiMocks, resetStorage } from '../mocks/api'
import { resetStaffAuthMock } from '../mocks/staff-auth'
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
import { renderWithProviders } from '../helpers/render'
const makeDetails = (overrides: Record<string, unknown> = {}) => ({
id: 11,
readableId: 11,
userId: 5,
customerName: 'Alice',
customerEmail: 'alice@example.com',
customerMobile: '9999999999',
address: {
name: 'Alice',
line1: '12 Main St',
line2: null,
city: 'City',
state: 'State',
phone: '9876543210',
},
slotInfo: { time: '2026-01-02T10:00:00.000Z', sequence: null },
isCod: false,
isOnlinePayment: true,
totalAmount: 500,
deliveryCharge: 20,
adminNotes: 'handle with care',
userNotes: null,
createdAt: '2026-01-01T10:00:00.000Z',
status: 'pending',
isPackaged: false,
isDelivered: false,
items: [
{
id: 101,
name: 'Chicken',
amount: 200,
isPackaged: false,
isPackageVerified: false,
quantity: '2',
price: '100',
productSize: 1,
unit: 'kg',
},
],
payment: null,
paymentInfo: null,
cancelReason: null,
cancellationReviewed: false,
isRefundDone: false,
refundStatus: null,
refundAmount: null,
couponData: null,
couponCode: null,
couponDescription: null,
discountAmount: 0,
orderStatus: null,
refundRecord: null,
isFlashDelivery: false,
...overrides,
})
const procedures = (overrides: Record<string, unknown> = {}) => ({
'admin.order.getOrderDetails': makeDetails(),
'admin.order.updateOrderItemPackaging': { success: true, updated: true },
'admin.order.removeDeliveryCharge': { message: 'removed' },
'admin.order.cancelOrder': { success: true, message: 'cancelled' },
'admin.user.getUserIncidents': { incidents: [] },
...overrides,
})
const renderDetails = (overrides: Record<string, unknown> = {}) => {
const { fetchMock } = setupApiMocks({ procedures: procedures(overrides) })
renderWithProviders(<OrderDetails />)
return { fetchMock }
}
describe('Order details', () => {
beforeEach(async () => {
resetStaffAuthMock()
await resetStorage()
resetRouterMock()
searchParamsMock.current = { id: '11' }
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows a loading message while the order is pending', () => {
renderDetails()
expect(screen.getByText('Loading order details...')).toBeVisible()
})
it('queries the order with the route id', async () => {
const { fetchMock } = renderDetails()
await waitFor(() => expect(screen.getByText('#11')).toBeVisible())
expect(lastProcedureInput(fetchMock, 'admin.order.getOrderDetails')).toEqual({ orderId: 11 })
})
it('renders the order, customer, items and totals', async () => {
renderDetails()
await waitFor(() => expect(screen.getByText('#11')).toBeVisible())
expect(screen.getByText('Alice')).toBeVisible()
expect(screen.getByText('9999999999')).toBeVisible()
expect(screen.getByText('Chicken')).toBeVisible()
expect(screen.getByText('Subtotal (1 items)')).toBeVisible()
expect(screen.getByText('handle with care')).toBeVisible()
expect(screen.getByText('Manage Orders')).toBeVisible()
})
it('renders an error state with a back action when the order is missing', async () => {
renderDetails({ 'admin.order.getOrderDetails': null })
await waitFor(() => expect(screen.getByText('Oops!')).toBeVisible())
expect(screen.getByText('Failed to load order details')).toBeVisible()
fireEvent.press(screen.getByText('Go Back'))
expect(routerMock.back).toHaveBeenCalled()
})
it('toggles item packaged state', async () => {
const { fetchMock } = renderDetails()
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
fireEvent.press(screen.getAllByText('Packaged').pop()!)
await waitFor(() =>
expect(lastProcedureInput(fetchMock, 'admin.order.updateOrderItemPackaging')).toEqual({
orderItemId: 101,
isPackaged: true,
})
)
})
it('toggles item verified state', async () => {
const { fetchMock } = renderDetails()
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
fireEvent.press(screen.getByText('Pkg Verified'))
await waitFor(() =>
expect(lastProcedureInput(fetchMock, 'admin.order.updateOrderItemPackaging')).toEqual({
orderItemId: 101,
isPackageVerified: true,
})
)
})
it('removes the delivery charge after confirmation', async () => {
const { fetchMock } = renderDetails()
await waitFor(() => expect(screen.getByText('Remove')).toBeVisible())
fireEvent.press(screen.getByText('Remove'))
const call = (Alert.alert as jest.Mock).mock.calls.find((c) => c[0] === 'Remove Delivery Cost')
expect(call).toBeTruthy()
const buttons = call![2] as { text: string; onPress?: () => void }[]
await act(async () => {
buttons.find((b) => b.text === 'Remove')!.onPress?.()
})
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.order.removeDeliveryCharge'))
expect(lastProcedureInput(fetchMock, 'admin.order.removeDeliveryCharge')).toEqual({ orderId: 11 })
})
it('opens the cancel order dialog', async () => {
renderDetails()
await waitFor(() => expect(screen.getByText('Cancel Order')).toBeVisible())
fireEvent.press(screen.getByText('Cancel Order'))
expect(await screen.findByPlaceholderText('Enter reason for cancellation...')).toBeVisible()
})
it('renders the cancellation reason and hides the cancel button when cancelled', async () => {
renderDetails({
'admin.order.getOrderDetails': makeDetails({
status: 'cancelled',
cancelReason: 'Customer requested',
}),
})
await waitFor(() => expect(screen.getByText('Cancellation Reason')).toBeVisible())
expect(screen.getByText('Customer requested')).toBeVisible()
expect(screen.queryByText('Cancel Order')).toBeNull()
})
it('renders the flash delivery notice', async () => {
renderDetails({
'admin.order.getOrderDetails': makeDetails({ isFlashDelivery: true }),
})
await waitFor(() => expect(screen.getByText('1 Hr Delivery Order')).toBeVisible())
expect(screen.getByText(/high-priority flash delivery order/)).toBeVisible()
})
it('renders the applied coupon block', async () => {
renderDetails({
'admin.order.getOrderDetails': makeDetails({
couponCode: 'SAVE50',
couponDescription: 'Flat ₹50 off',
discountAmount: 50,
}),
})
await waitFor(() => expect(screen.getByText('Coupon Applied')).toBeVisible())
expect(screen.getByText('SAVE50')).toBeVisible()
expect(screen.getAllByText('-₹50').length).toBeGreaterThan(0)
})
it('renders the refund coupon block when one exists', async () => {
renderDetails({
'admin.order.getOrderDetails': makeDetails({
couponCode: 'REF10',
couponData: { couponCode: 'REF10', couponDescription: '', discountAmount: 100 },
orderStatus: {
id: 1,
orderTime: '2026-01-01T10:00:00.000Z',
userId: 5,
orderId: 11,
isPackaged: false,
isDelivered: false,
isCancelled: true,
cancelReason: 'x',
isCancelledByAdmin: true,
paymentStatus: 'success',
cancellationUserNotes: null,
cancellationAdminNotes: null,
cancellationReviewed: false,
cancellationReviewedAt: null,
refundCouponId: 9,
},
}),
})
await waitFor(() => expect(screen.getByText('Refund Coupon')).toBeVisible())
expect(screen.getByText('₹100')).toBeVisible()
})
it('navigates to user management from customer details', async () => {
renderDetails()
await waitFor(() => expect(screen.getByText('Customer Details')).toBeVisible())
fireEvent.press(screen.getByText('Customer Details'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5')
})
it('navigates back to Manage Orders from the bottom bar', async () => {
renderDetails()
await waitFor(() => expect(screen.getByText('Manage Orders')).toBeVisible())
fireEvent.press(screen.getByText('Manage Orders'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders')
})
})