From de3dcb8c5250c18835b325e357f57bdb6aba5c1d Mon Sep 17 00:00:00 2001 From: DeepnaPooja Date: Wed, 2 Sep 2026 16:30:04 +0530 Subject: [PATCH] Add dialogs and update API for cancel requests --- Distribution/docs/testbug.md | 2 +- .../rides/_components/ride-cancel-dialog.tsx | 132 ++++++++++++++++++ .../rides/_components/ride-close-dialog.tsx | 105 ++++++++++++++ .../_components/ride-edit-driver-sheet.tsx | 115 +++++++++++++++ .../rides/_components/ride-view-sheet.tsx | 75 ++++++++++ .../rides/_components/rides-client.tsx | 86 ++++++++++-- distribution_fe/lib/api/operations.ts | 23 +-- 7 files changed, 511 insertions(+), 27 deletions(-) create mode 100644 distribution_fe/app/(dashboard)/operations/rides/_components/ride-cancel-dialog.tsx create mode 100644 distribution_fe/app/(dashboard)/operations/rides/_components/ride-close-dialog.tsx create mode 100644 distribution_fe/app/(dashboard)/operations/rides/_components/ride-edit-driver-sheet.tsx create mode 100644 distribution_fe/app/(dashboard)/operations/rides/_components/ride-view-sheet.tsx diff --git a/Distribution/docs/testbug.md b/Distribution/docs/testbug.md index 6aa8237..c701303 100644 --- a/Distribution/docs/testbug.md +++ b/Distribution/docs/testbug.md @@ -32,7 +32,6 @@ Running log of backend API failures found during testing and the corresponding f | 25 | Orders (CRUD gap) | Create/Update/Delete endpoints exist and work | Orders page is read-only in the frontend — only list/get are wired up; add Create/Update/Delete UI | 2026-09-02 | | 26 | Pricing → Schemes (unused capability) | Eligibility check, spend/ROI analytics, and apply-scheme-to-order endpoints all exist | None of these are wired into the frontend — only basic scheme CRUD is; add UI for eligibility check, spend/ROI view, and applying a scheme to an order | 2026-09-02 | | 27 | Misc missing Delete actions | Delete/soft-delete endpoints exist for Users, Stores, Price Lists, and Suppliers | No Delete UI wired up for these on their respective pages | 2026-09-02 | -| 29 | Operations → Rides | | Add a View icon to the action column in Operations → Rides table (create-ride backend bug fixed, see Resolved #1) | 2026-09-02 | | 28 | Auth (root cause of #10 and likely others) | The actually-registered middleware is `Distribution/Middleware/AuthMiddleware.cs` (`app.UseMiddleware()` in Program.cs) — a plain, symmetric-key JWT check, NOT the RSA-based `Infra/Authorization/Middleware/AuthMiddleware.cs`/`JwtMiddleware.cs`, which despite their doc comments claiming to be "reference-only," are actually unregistered/dead. The active middleware reads `config["Jwt:Key"]`, but `appsettings.json` only defines `Jwt:PublicKey` (RSA XML, used by AuthHex-issued tokens) — so `Jwt:Key` is always null, the whole validation block is skipped, and `context.User` is never set for ANY request, valid token or not. It also never attaches `role_id`/`role_level`/`username` claims the way the dead Infra middleware does. Net effect: `ICurrentUserService.UserId`/`RoleId` are always null, so every `currentUser.UserId ?? throw new UnauthorizedAccessException()` check fails (this is the actual cause of bug #10, Procurement → Orders) and every permission/role-level check silently fails too | Decision: keep `Distribution/Middleware/AuthMiddleware.cs` (outside Infra) as the one true auth flow going forward; delete the dead unregistered duplicates `Infra/Authorization/Middleware/AuthMiddleware.cs` and `JwtMiddleware.cs`. Then fix the active middleware to validate against `Jwt:PublicKey` (RSA), reject (not silently swallow) invalid/missing tokens, and attach `role_id`/`role_level`/`username` claims from the local User/Role row after validation | 2026-09-02 | ## Resolved @@ -40,6 +39,7 @@ Running log of backend API failures found during testing and the corresponding f | # | Area | Backend API Failure | Frontend Change Needed | Fixed In | Date | |---|------|----------------------|--------------------------|----------|------| | 1 | Operations → Rides (Create Ride) | Create Ride failed with "Vehicle not found" | — | Fixed DTO field naming mismatch | 2026-09-02 | +| 29 | Operations → Rides | Cancel-request API routes mismatched | Added View, Edit, and Cancel icons to Rides table | Fixed API routes + added action icons | 2026-09-02 | ## Implementation Guide diff --git a/distribution_fe/app/(dashboard)/operations/rides/_components/ride-cancel-dialog.tsx b/distribution_fe/app/(dashboard)/operations/rides/_components/ride-cancel-dialog.tsx new file mode 100644 index 0000000..8bfcf52 --- /dev/null +++ b/distribution_fe/app/(dashboard)/operations/rides/_components/ride-cancel-dialog.tsx @@ -0,0 +1,132 @@ +'use client' + +import { useEffect } from 'react' +import { useForm, zodResolver, z } from '@/lib/form' +import { FormField } from '@/components/shared/form-field' +import { Input } from '@/components/ui/input' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from '@/components/ui/dialog' +import { FieldGroup } from '@/components/ui/field' +import { toast } from '@/components/ui/toast' +import { rides as ridesApi, getApiError } from '@/lib/api/index' +import type { RideResponse, CancelRequestType } from '@/types/api' + +const TYPE_OPTIONS: CancelRequestType[] = ['VehicleBreakdown', 'DriverUnavailable', 'RouteIssue', 'Other'] + +const schema = z.object({ + typeCode: z.enum(['VehicleBreakdown', 'DriverUnavailable', 'RouteIssue', 'Other']), + reason: z.string().min(1, 'Reason is required'), +}) + +type FormValues = z.infer + +interface RideCancelDialogProps { + open: boolean + onClose: () => void + onSuccess: () => void + ride: RideResponse | null +} + +export function RideCancelDialog({ open, onClose, onSuccess, ride }: RideCancelDialogProps) { + const form = useForm({ + resolver: zodResolver(schema), + defaultValues: { typeCode: 'Other', reason: '' }, + }) + + useEffect(() => { + if (open) { + form.reset({ typeCode: 'Other', reason: '' }) + } + }, [open]) + + if (!ride) return null + + async function onSubmit(values: FormValues) { + try { + await ridesApi.cancelRequests.raise(ride!.id, values) + toast.add({ title: 'Cancel request raised', type: 'success' }) + onSuccess() + onClose() + } catch (err) { + toast.add({ title: 'Failed to raise cancel request', description: getApiError(err), type: 'error' }) + } + } + + return ( + !v && onClose()}> + + + Cancel Ride + + Raises a cancel request for this ride, subject to supervisor approval. + + + +
+ + ( + + )} + /> + + ( + + )} + /> + + + + + + +
+
+
+ ) +} diff --git a/distribution_fe/app/(dashboard)/operations/rides/_components/ride-close-dialog.tsx b/distribution_fe/app/(dashboard)/operations/rides/_components/ride-close-dialog.tsx new file mode 100644 index 0000000..c4f91df --- /dev/null +++ b/distribution_fe/app/(dashboard)/operations/rides/_components/ride-close-dialog.tsx @@ -0,0 +1,105 @@ +'use client' + +import { useEffect } from 'react' +import { useForm, zodResolver, z } from '@/lib/form' +import { FormField } from '@/components/shared/form-field' +import { Input } from '@/components/ui/input' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from '@/components/ui/dialog' +import { FieldGroup } from '@/components/ui/field' +import { toast } from '@/components/ui/toast' +import { rides as ridesApi, getApiError } from '@/lib/api/index' +import type { RideResponse } from '@/types/api' + +const schema = z.object({ + meterend: z.number().min(0, 'Meter end must be 0 or more'), +}) + +type FormValues = z.infer + +interface RideCloseDialogProps { + open: boolean + onClose: () => void + onSuccess: () => void + ride: RideResponse | null +} + +export function RideCloseDialog({ open, onClose, onSuccess, ride }: RideCloseDialogProps) { + const form = useForm({ + resolver: zodResolver(schema), + defaultValues: { meterend: 0 }, + }) + + useEffect(() => { + if (open && ride) { + form.reset({ meterend: ride.meterstart }) + } + }, [open, ride]) + + if (!ride) return null + + async function onSubmit(values: FormValues) { + try { + await ridesApi.close(ride!.id, values.meterend) + toast.add({ title: 'Ride closed', type: 'success' }) + onSuccess() + onClose() + } catch (err) { + toast.add({ title: 'Failed to close ride', description: getApiError(err), type: 'error' }) + } + } + + return ( + !v && onClose()}> + + + Close Ride + + Enter the final odometer reading to close this ride. + + + +
+ + ( + field.onChange(Number(e.target.value))} + onBlur={field.onBlur} + placeholder="0" + aria-invalid={invalid} + /> + )} + /> + + + + + + +
+
+
+ ) +} diff --git a/distribution_fe/app/(dashboard)/operations/rides/_components/ride-edit-driver-sheet.tsx b/distribution_fe/app/(dashboard)/operations/rides/_components/ride-edit-driver-sheet.tsx new file mode 100644 index 0000000..59c1d4f --- /dev/null +++ b/distribution_fe/app/(dashboard)/operations/rides/_components/ride-edit-driver-sheet.tsx @@ -0,0 +1,115 @@ +'use client' + +import { useEffect, useState } from 'react' +import { useForm, zodResolver, z } from '@/lib/form' +import { FormField } from '@/components/shared/form-field' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from '@/components/ui/dialog' +import { FieldGroup } from '@/components/ui/field' +import { toast } from '@/components/ui/toast' +import { rides as ridesApi, drivers as driversApi, getApiError, getPaginatedItems } from '@/lib/api/index' +import type { RideResponse, DriverProfileResponse } from '@/types/api' + +const schema = z.object({ + driverProfileId: z.string().min(1, 'Driver is required'), +}) + +type FormValues = z.infer + +interface RideEditDriverSheetProps { + open: boolean + onClose: () => void + onSuccess: () => void + ride: RideResponse | null +} + +export function RideEditDriverSheet({ open, onClose, onSuccess, ride }: RideEditDriverSheetProps) { + const [driversList, setDriversList] = useState([]) + + const form = useForm({ + resolver: zodResolver(schema), + defaultValues: { driverProfileId: '' }, + }) + + useEffect(() => { + if (!open || !ride) return + form.reset({ driverProfileId: ride.driverProfileId }) + driversApi.list({ pageSize: 200 }) + .then((res) => setDriversList(getPaginatedItems(res))) + .catch((err) => toast.add({ title: 'Failed to load drivers', description: getApiError(err), type: 'error' })) + }, [open, ride]) + + if (!ride) return null + + async function onSubmit(values: FormValues) { + try { + await ridesApi.assignDriver(ride!.id, values.driverProfileId) + toast.add({ title: 'Driver updated', type: 'success' }) + onSuccess() + onClose() + } catch (err) { + toast.add({ title: 'Failed to update driver', description: getApiError(err), type: 'error' }) + } + } + + return ( + !v && onClose()}> + + + Edit Ride Driver + + Reassign the driver for this ride. Only available while the ride is in Draft status. + + + +
+ + ( + + )} + /> + + + + + + +
+
+
+ ) +} diff --git a/distribution_fe/app/(dashboard)/operations/rides/_components/ride-view-sheet.tsx b/distribution_fe/app/(dashboard)/operations/rides/_components/ride-view-sheet.tsx new file mode 100644 index 0000000..949f0a2 --- /dev/null +++ b/distribution_fe/app/(dashboard)/operations/rides/_components/ride-view-sheet.tsx @@ -0,0 +1,75 @@ +'use client' + +import { Badge } from '@/components/ui/badge' +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog' +import type { RideResponse, RideStatus, RideType } from '@/types/api' + +const RIDE_STATUS_VARIANT: Record = { + Draft: 'secondary', + Open: 'secondary', + Active: 'default', + CancelRequested: 'destructive', + Cancelled: 'destructive', + Closed: 'secondary', +} + +const RIDE_TYPE_VARIANT: Record = { + Delivery: 'default', + Sale: 'secondary', +} + +const fmtDateTime = (v: string | null) => + v + ? new Date(v).toLocaleString('en-GB', { + day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', + }) + : '—' + +interface RideViewSheetProps { + open: boolean + onClose: () => void + ride: RideResponse | null +} + +function Row({ label, value }: { label: string; value: React.ReactNode }) { + return ( +
+ {label} + {value} +
+ ) +} + +export function RideViewSheet({ open, onClose, ride }: RideViewSheetProps) { + if (!ride) return null + + return ( + !v && onClose()}> + + + Ride Details + + +
+ + + + + {ride.rideType}} /> + {ride.status}} /> + + + + + + +
+
+
+ ) +} diff --git a/distribution_fe/app/(dashboard)/operations/rides/_components/rides-client.tsx b/distribution_fe/app/(dashboard)/operations/rides/_components/rides-client.tsx index b650852..8e58ea2 100644 --- a/distribution_fe/app/(dashboard)/operations/rides/_components/rides-client.tsx +++ b/distribution_fe/app/(dashboard)/operations/rides/_components/rides-client.tsx @@ -13,6 +13,10 @@ import { rides as ridesApi, getApiError, getPaginatedItems } from '@/lib/api/ind import type { RideResponse, RideStatus, RideType } from '@/types/api' import { RideSheet } from './ride-sheet' +import { RideViewSheet } from './ride-view-sheet' +import { RideEditDriverSheet } from './ride-edit-driver-sheet' +import { RideCancelDialog } from './ride-cancel-dialog' +import { RideCloseDialog } from './ride-close-dialog' const fmtDate = (v: string) => new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }) @@ -39,6 +43,11 @@ export function RidesClient() { const [pageSize, setPageSize] = useState(20) const [sheetOpen, setSheetOpen] = useState(false) + const [viewOpen, setViewOpen] = useState(false) + const [editDriverOpen, setEditDriverOpen] = useState(false) + const [cancelOpen, setCancelOpen] = useState(false) + const [closeOpen, setCloseOpen] = useState(false) + const [selectedRide, setSelectedRide] = useState(null) const fetchData = useCallback(async (p: number, ps: number) => { setLoading(true) @@ -57,6 +66,21 @@ export function RidesClient() { fetchData(page, pageSize) }, [fetchData, page, pageSize]) + function handleView(row: RideResponse) { + setSelectedRide(row) + setViewOpen(true) + } + + function handleEditDriver(row: RideResponse) { + setSelectedRide(row) + setEditDriverOpen(true) + } + + function handleCancel(row: RideResponse) { + setSelectedRide(row) + setCancelOpen(true) + } + async function handleActivate(row: RideResponse) { try { await ridesApi.activate(row.id) @@ -67,21 +91,9 @@ export function RidesClient() { } } - async function handleClose(row: RideResponse) { - const input = window.prompt('Enter meter end reading:') - if (input === null) return - const meterend = Number(input) - if (isNaN(meterend) || meterend < 0) { - toast.add({ title: 'Invalid meter reading', type: 'error' }) - return - } - try { - await ridesApi.close(row.id, meterend) - toast.add({ title: 'Ride closed', type: 'success' }) - fetchData(page, pageSize) - } catch (err) { - toast.add({ title: 'Failed to close ride', description: getApiError(err), type: 'error' }) - } + function handleClose(row: RideResponse) { + setSelectedRide(row) + setCloseOpen(true) } const tableConfig = useMemo>(() => ({ @@ -136,6 +148,17 @@ export function RidesClient() { ], rowActions: { actions: () => [ + { + action: 'view', + label: 'View ride', + onClick: handleView, + }, + { + action: 'edit', + label: 'Edit driver', + onClick: handleEditDriver, + visible: (target) => target.status === 'Draft', + }, { action: 'activate', label: 'Activate ride', @@ -148,6 +171,12 @@ export function RidesClient() { onClick: handleClose, visible: (target) => target.status === 'Active', }, + { + action: 'cancel', + label: 'Cancel ride', + onClick: handleCancel, + visible: (target) => target.status === 'Active', + }, ], }, }), [pageSize]) @@ -183,6 +212,33 @@ export function RidesClient() { onClose={() => setSheetOpen(false)} onSuccess={() => fetchData(page, pageSize)} /> + + setViewOpen(false)} + ride={selectedRide} + /> + + setEditDriverOpen(false)} + onSuccess={() => fetchData(page, pageSize)} + ride={selectedRide} + /> + + setCancelOpen(false)} + onSuccess={() => fetchData(page, pageSize)} + ride={selectedRide} + /> + + setCloseOpen(false)} + onSuccess={() => fetchData(page, pageSize)} + ride={selectedRide} + /> ) } diff --git a/distribution_fe/lib/api/operations.ts b/distribution_fe/lib/api/operations.ts index 2cead86..e914f63 100644 --- a/distribution_fe/lib/api/operations.ts +++ b/distribution_fe/lib/api/operations.ts @@ -8,7 +8,6 @@ import type { RideType, RideStatus, CancelRequestType, - CancelRequestStatus, LoadingSheetStatus, DeliveryTaskStatus, } from '@/types/api' @@ -38,10 +37,6 @@ export interface CancelRequestBody { reason: string } -export interface CancelRequestReviewBody { - status: CancelRequestStatus -} - export const rides = { list: (params?: RideListParams) => api.get>('/rides', { params }).then(r => r.data), @@ -52,6 +47,9 @@ export const rides = { create: (body: RideBody) => api.post('/rides', body).then(r => r.data), + assignDriver: (id: string, driverProfileId: string) => + api.put(`/rides/${id}/driver`, { driverProfileId }).then(r => r.data), + activate: (id: string) => api.patch(`/rides/${id}/activate`).then(r => r.data), @@ -59,14 +57,17 @@ export const rides = { api.patch(`/rides/${id}/close`, { meterend }).then(r => r.data), cancelRequests: { - list: (rideId: string) => - api.get(`/rides/${rideId}/cancel-requests`).then(r => r.data), + getForRide: (rideId: string) => + api.get(`/rides/${rideId}/cancel-request`).then(r => r.data), - create: (rideId: string, body: CancelRequestBody) => - api.post(`/rides/${rideId}/cancel-requests`, body).then(r => r.data), + raise: (rideId: string, body: CancelRequestBody) => + api.post(`/rides/${rideId}/cancel-request`, body).then(r => r.data), - review: (rideId: string, requestId: string, body: CancelRequestReviewBody) => - api.patch(`/rides/${rideId}/cancel-requests/${requestId}`, body).then(r => r.data), + approve: (requestId: string) => + api.post(`/rides/cancel-requests/${requestId}/approve`).then(r => r.data), + + reject: (requestId: string) => + api.post(`/rides/cancel-requests/${requestId}/reject`).then(r => r.data), }, }