phase-3: breakdown and complaint register with calculations and permissions
This commit is contained in:
@@ -9,9 +9,10 @@ import { MastersPage } from "@/pages/MastersPage";
|
||||
import { SettingsPage } from "@/pages/SettingsPage";
|
||||
import { AssetsPage } from "@/pages/AssetsPage";
|
||||
import { AssetDetailPage } from "@/pages/AssetDetailPage";
|
||||
import { ComplaintsPage } from "@/pages/ComplaintsPage";
|
||||
import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage";
|
||||
import {
|
||||
DashboardPage,
|
||||
ComplaintsPage,
|
||||
PMPage,
|
||||
CalibrationPage,
|
||||
ContractsPage,
|
||||
@@ -84,6 +85,7 @@ function AppRoutes() {
|
||||
<Route path="/assets" element={<AssetsPage />} />
|
||||
<Route path="/assets/:id" element={<AssetDetailPage />} />
|
||||
<Route path="/complaints" element={<ComplaintsPage />} />
|
||||
<Route path="/complaints/:id" element={<ComplaintDetailPage />} />
|
||||
<Route path="/pm" element={<PMPage />} />
|
||||
<Route path="/calibration" element={<CalibrationPage />} />
|
||||
<Route path="/contracts" element={<ContractsPage />} />
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { api } from "./client";
|
||||
import type { AssetCriticality, AssetStatus } from "./assets";
|
||||
|
||||
export type CallStatus = "open" | "in_progress" | "closed";
|
||||
|
||||
export type TimestampField =
|
||||
| "registered_at"
|
||||
| "received_at"
|
||||
| "attended_at"
|
||||
| "restored_at"
|
||||
| "closed_at"
|
||||
| "ce_attended_at";
|
||||
|
||||
export interface ComplaintItem {
|
||||
id: number;
|
||||
complaint_no: string;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
asset_status: AssetStatus | string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
location_name: string | null;
|
||||
description: string;
|
||||
breakdown_details: string | null;
|
||||
priority: AssetCriticality | string;
|
||||
notes: string | null;
|
||||
registered_at: string;
|
||||
registered_by_id: number;
|
||||
registered_by_name: string | null;
|
||||
received_by_id: number | null;
|
||||
received_by_name: string | null;
|
||||
received_at: string | null;
|
||||
assigned_to_id: number | null;
|
||||
assigned_to_name: string | null;
|
||||
assigned_at: string | null;
|
||||
attended_by_id: number | null;
|
||||
attended_by_name: string | null;
|
||||
attended_at: string | null;
|
||||
restored_at: string | null;
|
||||
closed_by_id: number | null;
|
||||
closed_by_name: string | null;
|
||||
closed_at: string | null;
|
||||
call_status: CallStatus;
|
||||
closure_remarks: string | null;
|
||||
action_taken: string | null;
|
||||
root_cause: string | null;
|
||||
corrective_action: string | null;
|
||||
lessons_learned: string | null;
|
||||
ce_name: string | null;
|
||||
ce_attended_at: string | null;
|
||||
ce_action_taken: string | null;
|
||||
spare_required: boolean;
|
||||
spare_details: string | null;
|
||||
spare_cost_estimate: number | null;
|
||||
response_time_minutes: number | null;
|
||||
downtime_minutes: number;
|
||||
downtime_is_ongoing: boolean;
|
||||
downtime_end_milestone: string;
|
||||
response_start_setting: string;
|
||||
ce_response_time_minutes: number | null;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ComplaintEventItem {
|
||||
id: number;
|
||||
complaint_id: number;
|
||||
event_type: string;
|
||||
from_value: string | null;
|
||||
to_value: string | null;
|
||||
by_user_id: number | null;
|
||||
by_user_name: string | null;
|
||||
at: string;
|
||||
note: string | null;
|
||||
}
|
||||
|
||||
export interface ComplaintListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
call_status?: CallStatus | "";
|
||||
priority?: AssetCriticality | "";
|
||||
assigned_to_id?: number;
|
||||
closure_state?: "open_only" | "closed_only" | "";
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface ComplaintCreatePayload {
|
||||
asset_id: number;
|
||||
description: string;
|
||||
breakdown_details?: string | null;
|
||||
priority: AssetCriticality;
|
||||
notes?: string | null;
|
||||
received_by_id?: number | null;
|
||||
}
|
||||
|
||||
export interface ComplaintUpdatePayload {
|
||||
description?: string;
|
||||
breakdown_details?: string | null;
|
||||
priority?: AssetCriticality;
|
||||
notes?: string | null;
|
||||
action_taken?: string | null;
|
||||
root_cause?: string | null;
|
||||
corrective_action?: string | null;
|
||||
lessons_learned?: string | null;
|
||||
ce_name?: string | null;
|
||||
ce_attended_at?: string | null;
|
||||
ce_action_taken?: string | null;
|
||||
spare_required?: boolean;
|
||||
spare_details?: string | null;
|
||||
spare_cost_estimate?: number | null;
|
||||
}
|
||||
|
||||
export const complaintsApi = {
|
||||
list: (params: ComplaintListParams = {}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.department_id) qs.set("department_id", String(params.department_id));
|
||||
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
|
||||
if (params.call_status) qs.set("call_status", params.call_status);
|
||||
if (params.priority) qs.set("priority", params.priority);
|
||||
if (params.assigned_to_id) qs.set("assigned_to_id", String(params.assigned_to_id));
|
||||
if (params.closure_state) qs.set("closure_state", params.closure_state);
|
||||
if (params.date_from) qs.set("date_from", params.date_from);
|
||||
if (params.date_to) qs.set("date_to", params.date_to);
|
||||
qs.set("page", String(params.page ?? 1));
|
||||
qs.set("page_size", String(params.page_size ?? 200));
|
||||
return api.get<{ items: ComplaintItem[]; total: number }>(`/complaints?${qs.toString()}`);
|
||||
},
|
||||
create: (data: ComplaintCreatePayload) => api.post<ComplaintItem>("/complaints", data),
|
||||
get: (id: number) => api.get<ComplaintItem>(`/complaints/${id}`),
|
||||
events: (id: number) =>
|
||||
api.get<{ items: ComplaintEventItem[]; total: number }>(`/complaints/${id}/events`),
|
||||
update: (id: number, data: ComplaintUpdatePayload) =>
|
||||
api.patch<ComplaintItem>(`/complaints/${id}`, data),
|
||||
assign: (id: number, data: { assigned_to_id: number; note?: string }) =>
|
||||
api.post<ComplaintItem>(`/complaints/${id}/assign`, data),
|
||||
attend: (id: number, data: { attended_by_id?: number; note?: string } = {}) =>
|
||||
api.post<ComplaintItem>(`/complaints/${id}/attend`, data),
|
||||
restore: (id: number, data: { note?: string } = {}) =>
|
||||
api.post<ComplaintItem>(`/complaints/${id}/restore`, data),
|
||||
close: (id: number, data: { closure_remarks?: string } = {}) =>
|
||||
api.post<ComplaintItem>(`/complaints/${id}/close`, data),
|
||||
reopen: (id: number, data: { reason: string }) =>
|
||||
api.post<ComplaintItem>(`/complaints/${id}/reopen`, data),
|
||||
correctTimestamp: (
|
||||
id: number,
|
||||
data: { field: TimestampField; new_value: string; reason: string }
|
||||
) => api.post<ComplaintItem>(`/complaints/${id}/correct-timestamp`, data),
|
||||
};
|
||||
@@ -154,3 +154,20 @@ export const usersApi = {
|
||||
) => api.patch<MasterUser>(`/users/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/users/${id}`),
|
||||
};
|
||||
|
||||
export interface UserLookupItem {
|
||||
id: number;
|
||||
name: string;
|
||||
role: Role;
|
||||
department_id: number | null;
|
||||
}
|
||||
|
||||
export async function fetchUsersLookup(): Promise<{ items: UserLookupItem[]; total: number }> {
|
||||
const res = await api.get<UserLookupItem[] | { items: UserLookupItem[]; total: number }>(
|
||||
"/users/lookup"
|
||||
);
|
||||
if (Array.isArray(res)) {
|
||||
return { items: res, total: res.length };
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ interface DataTableProps<TData> {
|
||||
emptyAction?: React.ReactNode;
|
||||
globalFilterPlaceholder?: string;
|
||||
onRowClick?: (row: TData) => void;
|
||||
getRowClassName?: (row: TData) => string;
|
||||
exportFilename?: string;
|
||||
}
|
||||
|
||||
@@ -52,6 +53,7 @@ export function DataTable<TData>({
|
||||
emptyAction,
|
||||
globalFilterPlaceholder = "Search...",
|
||||
onRowClick,
|
||||
getRowClassName,
|
||||
exportFilename = "export",
|
||||
}: DataTableProps<TData>) {
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
@@ -203,6 +205,7 @@ export function DataTable<TData>({
|
||||
key={row.id}
|
||||
className={cn(
|
||||
"hover:bg-blue-50/50 transition-colors",
|
||||
getRowClassName?.(row.original),
|
||||
onRowClick && "cursor-pointer"
|
||||
)}
|
||||
onClick={() => onRowClick?.(row.original)}
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { AlertCircle, Clock, Paperclip, X } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { validateAttachmentFile } from "@/components/Attachments";
|
||||
import { ApiError } from "@/api/client";
|
||||
import type { AssetLookupItem, AssetCriticality } from "@/api/assets";
|
||||
import { complaintsApi } from "@/api/complaints";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import { fetchUsersLookup } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
const complaintSchema = z.object({
|
||||
description: z.string().trim().min(1, "Problem description is required"),
|
||||
breakdown_details: z.string().optional(),
|
||||
priority: z.enum(["critical", "non_critical"]),
|
||||
notes: z.string().optional(),
|
||||
received_by_id: z.string().optional(),
|
||||
});
|
||||
|
||||
type ComplaintFormValues = z.infer<typeof complaintSchema>;
|
||||
|
||||
interface RaiseComplaintModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const inputCls =
|
||||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||||
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
|
||||
|
||||
export function RaiseComplaintModal({ open, onClose }: RaiseComplaintModalProps) {
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const isDeptUser = user?.role === "department_user";
|
||||
|
||||
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
|
||||
const [files, setFiles] = useState<File[]>([]);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
|
||||
const usersQuery = useQuery({
|
||||
queryKey: ["users-lookup"],
|
||||
queryFn: fetchUsersLookup,
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<ComplaintFormValues>({
|
||||
resolver: zodResolver(complaintSchema),
|
||||
defaultValues: {
|
||||
description: "",
|
||||
breakdown_details: "",
|
||||
priority: "non_critical",
|
||||
notes: "",
|
||||
received_by_id: user?.id ? String(user.id) : "",
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setSelectedAsset(null);
|
||||
setFiles([]);
|
||||
setServerError(null);
|
||||
reset({
|
||||
description: "",
|
||||
breakdown_details: "",
|
||||
priority: "non_critical",
|
||||
notes: "",
|
||||
received_by_id: user?.id ? String(user.id) : "",
|
||||
});
|
||||
}, [open, user?.id, reset]);
|
||||
|
||||
function handleFilePick(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const picked = Array.from(e.target.files ?? []);
|
||||
e.target.value = "";
|
||||
for (const f of picked) {
|
||||
const err = validateAttachmentFile(f);
|
||||
if (err) {
|
||||
setServerError(`${f.name}: ${err}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setServerError(null);
|
||||
setFiles((prev) => [...prev, ...picked]);
|
||||
}
|
||||
|
||||
async function onSubmit(values: ComplaintFormValues) {
|
||||
if (!selectedAsset) {
|
||||
setServerError("Please select an asset first.");
|
||||
return;
|
||||
}
|
||||
setServerError(null);
|
||||
try {
|
||||
const created = await complaintsApi.create({
|
||||
asset_id: selectedAsset.id,
|
||||
description: values.description.trim(),
|
||||
breakdown_details: values.breakdown_details?.trim() || null,
|
||||
priority: values.priority as AssetCriticality,
|
||||
notes: values.notes?.trim() || null,
|
||||
received_by_id: values.received_by_id ? Number(values.received_by_id) : null,
|
||||
});
|
||||
|
||||
for (const file of files) {
|
||||
await attachmentsApi.upload("complaint", created.id, file);
|
||||
}
|
||||
|
||||
await qc.invalidateQueries({ queryKey: ["complaints"] });
|
||||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
onClose();
|
||||
navigate(`/complaints/${created.id}`);
|
||||
} catch (err) {
|
||||
setServerError(err instanceof ApiError ? err.detail : "Failed to register complaint.");
|
||||
}
|
||||
}
|
||||
|
||||
const users = usersQuery.data?.items ?? [];
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Raise Breakdown / Complaint"
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{serverError && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{serverError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>Select Asset *</label>
|
||||
<AssetPicker
|
||||
selectedAsset={selectedAsset}
|
||||
onSelect={setSelectedAsset}
|
||||
departmentId={isDeptUser ? user?.department_id ?? undefined : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 rounded-md bg-gray-50 border border-gray-200 px-3 py-2 text-xs text-gray-600">
|
||||
<Clock className="h-4 w-4 text-gray-400 shrink-0" />
|
||||
<span>Registered At: Auto-captured by server on submit</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Priority *</label>
|
||||
<select {...register("priority")} className={inputCls}>
|
||||
<option value="non_critical">Non-Critical</option>
|
||||
<option value="critical">Critical (Emergency / Life Support)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Received By</label>
|
||||
<select {...register("received_by_id")} className={inputCls}>
|
||||
<option value="">Current User</option>
|
||||
{users.map((u) => (
|
||||
<option key={u.id} value={String(u.id)}>
|
||||
{u.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Complaint Description *</label>
|
||||
<textarea
|
||||
{...register("description")}
|
||||
rows={2}
|
||||
placeholder="Brief summary of the breakdown or issue..."
|
||||
className={inputCls}
|
||||
/>
|
||||
{errors.description && (
|
||||
<p className="text-xs text-red-600 mt-1">{errors.description.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Breakdown Details</label>
|
||||
<textarea
|
||||
{...register("breakdown_details")}
|
||||
rows={2}
|
||||
placeholder="Error codes, observed symptoms, clinical impact..."
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Additional Notes</label>
|
||||
<input
|
||||
{...register("notes")}
|
||||
placeholder="Optional caller contact or bay number..."
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Multi-file photo/PDF picker */}
|
||||
<div>
|
||||
<label className={labelCls}>Photos / Supporting Documents (Optional)</label>
|
||||
<label className="inline-flex items-center gap-2 px-3 py-2 rounded-md border border-gray-300 bg-white hover:bg-gray-50 text-xs font-medium text-gray-700 cursor-pointer">
|
||||
<Paperclip className="h-3.5 w-3.5" />
|
||||
Attach JPG, PNG, or PDF (max 10 MB each)
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept=".jpg,.jpeg,.png,.pdf"
|
||||
onChange={handleFilePick}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
{files.length > 0 && (
|
||||
<ul className="mt-2 space-y-1">
|
||||
{files.map((f, idx) => (
|
||||
<li
|
||||
key={`${f.name}-${idx}`}
|
||||
className="flex items-center justify-between text-xs bg-gray-50 border border-gray-200 rounded px-2.5 py-1.5"
|
||||
>
|
||||
<span className="truncate">{f.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setFiles((prev) => prev.filter((_, i) => i !== idx))}
|
||||
className="text-gray-400 hover:text-red-600 ml-2"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting}>
|
||||
Submit Complaint
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
CheckCircle2,
|
||||
Wrench,
|
||||
AlertTriangle,
|
||||
AlertCircle,
|
||||
Ban,
|
||||
Clock,
|
||||
ShieldAlert,
|
||||
@@ -199,3 +200,48 @@ export function CriticalityBadge({
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CallStatusBadge({
|
||||
status,
|
||||
className,
|
||||
}: {
|
||||
status: "open" | "in_progress" | "closed" | string;
|
||||
className?: string;
|
||||
}) {
|
||||
const map: Record<string, { label: string; cls: string; icon: React.ReactNode }> = {
|
||||
open: {
|
||||
label: "Open",
|
||||
cls: "bg-red-100 text-red-800 border border-red-200",
|
||||
icon: <AlertCircle className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
in_progress: {
|
||||
label: "In Progress",
|
||||
cls: "bg-amber-100 text-amber-800 border border-amber-200",
|
||||
icon: <Clock className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
closed: {
|
||||
label: "Closed",
|
||||
cls: "bg-green-100 text-green-800 border border-green-200",
|
||||
icon: <CheckCircle2 className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
};
|
||||
|
||||
const cfg = map[status] ?? {
|
||||
label: status,
|
||||
cls: "bg-gray-100 text-gray-700 border border-gray-200",
|
||||
icon: <MinusCircle className="h-3 w-3 shrink-0" />,
|
||||
};
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",
|
||||
cfg.cls,
|
||||
className
|
||||
)}
|
||||
>
|
||||
{cfg.icon}
|
||||
<span>{cfg.label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -89,7 +89,6 @@ const ROLE_CAPABILITIES: Record<Role, ReadonlySet<Capability>> = {
|
||||
coordinator: new Set<Capability>([
|
||||
"edit_asset_contracts_only",
|
||||
"view_assets",
|
||||
"raise_complaint",
|
||||
"handle_complaint",
|
||||
"view_pm",
|
||||
"manage_calibration_contracts",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,331 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Plus, Search } from "lucide-react";
|
||||
import {
|
||||
complaintsApi,
|
||||
type ComplaintItem,
|
||||
type CallStatus,
|
||||
} from "@/api/complaints";
|
||||
import type { AssetCriticality } from "@/api/assets";
|
||||
import { departmentsApi, fetchUsersLookup } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDateTime, formatDuration } from "@/lib/format";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { CallStatusBadge, CriticalityBadge } from "@/components/StatusBadge";
|
||||
import { RaiseComplaintModal } from "@/components/RaiseComplaintModal";
|
||||
|
||||
const CALL_STATUS_CHIPS: { value: CallStatus | ""; label: string }[] = [
|
||||
{ value: "", label: "All Calls" },
|
||||
{ value: "open", label: "Open" },
|
||||
{ value: "in_progress", label: "In Progress" },
|
||||
{ value: "closed", label: "Closed" },
|
||||
];
|
||||
|
||||
export function ComplaintsPage() {
|
||||
const navigate = useNavigate();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const role = user?.role;
|
||||
const isDeptUser = role === "department_user";
|
||||
const canRaise = can(role, "raise_complaint");
|
||||
|
||||
const [q, setQ] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState<string>("");
|
||||
const [callStatus, setCallStatus] = useState<CallStatus | "">("");
|
||||
const [priority, setPriority] = useState<AssetCriticality | "">("");
|
||||
const [assignedToId, setAssignedToId] = useState<string>("");
|
||||
const [closureState, setClosureState] = useState<"open_only" | "closed_only" | "">("");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
const [raiseOpen, setRaiseOpen] = useState(false);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
enabled: !isDeptUser,
|
||||
});
|
||||
|
||||
const usersQuery = useQuery({
|
||||
queryKey: ["users-lookup"],
|
||||
queryFn: fetchUsersLookup,
|
||||
});
|
||||
|
||||
const complaintsQuery = useQuery({
|
||||
queryKey: [
|
||||
"complaints",
|
||||
q,
|
||||
departmentId,
|
||||
callStatus,
|
||||
priority,
|
||||
assignedToId,
|
||||
closureState,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
],
|
||||
queryFn: () =>
|
||||
complaintsApi.list({
|
||||
q: q.trim() || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
call_status: callStatus || undefined,
|
||||
priority: priority || undefined,
|
||||
assigned_to_id: assignedToId ? Number(assignedToId) : undefined,
|
||||
closure_state: closureState || undefined,
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const columns: ColumnDef<ComplaintItem, unknown>[] = [
|
||||
{
|
||||
accessorKey: "complaint_no",
|
||||
header: "Complaint No",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="font-mono font-semibold text-[#1e3a8a] whitespace-nowrap">
|
||||
{String(getValue())}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "asset_display",
|
||||
accessorFn: (row) => `${row.asset_code} ${row.asset_name}`,
|
||||
header: "Asset",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<div className="min-w-36">
|
||||
<div className="font-mono text-xs text-[#1e3a8a] font-medium">
|
||||
{row.original.asset_code}
|
||||
</div>
|
||||
<div className="text-xs text-gray-800 truncate">{row.original.asset_name}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "department_name",
|
||||
header: "Department",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "priority",
|
||||
header: "Priority",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => <CriticalityBadge criticality={String(getValue())} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "call_status",
|
||||
header: "Call Status",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => <CallStatusBadge status={String(getValue())} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "assigned_to_name",
|
||||
header: "Assigned To",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "Unassigned",
|
||||
},
|
||||
{
|
||||
accessorKey: "registered_at",
|
||||
header: "Registered At",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap text-xs">{formatDateTime(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "response_time_minutes",
|
||||
header: "Response Time",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap text-xs font-medium">
|
||||
{formatDuration(getValue() as number | null)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "downtime_minutes",
|
||||
header: "Downtime",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-1.5 whitespace-nowrap">
|
||||
<span className="text-xs font-semibold text-gray-900">
|
||||
{formatDuration(row.original.downtime_minutes)}
|
||||
</span>
|
||||
{row.original.downtime_is_ongoing && (
|
||||
<Badge variant="danger" className="text-[10px] px-1.5 py-0">
|
||||
Ongoing
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "closed_at",
|
||||
header: "Closed At",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap text-xs">
|
||||
{formatDateTime(getValue() as string | null)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
const techUsers = (usersQuery.data?.items ?? []).filter(
|
||||
(u) => u.role === "biomedical" || u.role === "system_admin"
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Breakdown & Complaint Register</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
{isDeptUser && user?.department_name
|
||||
? `Complaints for ${user.department_name}`
|
||||
: "Track breakdown calls, response times, downtime, and technical resolution"}
|
||||
</p>
|
||||
</div>
|
||||
{canRaise && (
|
||||
<Button onClick={() => setRaiseOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Raise Complaint
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 space-y-3">
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<span className="text-xs font-medium text-gray-500 mr-1">Call Status:</span>
|
||||
{CALL_STATUS_CHIPS.map((chip) => (
|
||||
<button
|
||||
key={chip.value || "all"}
|
||||
type="button"
|
||||
onClick={() => setCallStatus(chip.value)}
|
||||
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||
callStatus === chip.value
|
||||
? "bg-[#1e3a8a] text-white"
|
||||
: "bg-gray-50 border border-gray-200 text-gray-700 hover:bg-gray-100"
|
||||
}`}
|
||||
>
|
||||
{chip.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-2.5">
|
||||
<div className="relative lg:col-span-2">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Search complaint no, asset, description..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!isDeptUser && (
|
||||
<select
|
||||
value={departmentId}
|
||||
onChange={(e) => setDepartmentId(e.target.value)}
|
||||
aria-label="Filter by Department"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Departments</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={String(d.id)}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
|
||||
<select
|
||||
value={priority}
|
||||
onChange={(e) => setPriority(e.target.value as AssetCriticality | "")}
|
||||
aria-label="Filter by Priority"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Priorities</option>
|
||||
<option value="critical">Critical</option>
|
||||
<option value="non_critical">Non-Critical</option>
|
||||
</select>
|
||||
|
||||
<select
|
||||
value={assignedToId}
|
||||
onChange={(e) => setAssignedToId(e.target.value)}
|
||||
aria-label="Filter by Assigned To"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Assignees</option>
|
||||
{techUsers.map((u) => (
|
||||
<option key={u.id} value={String(u.id)}>
|
||||
{u.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<select
|
||||
value={closureState}
|
||||
onChange={(e) =>
|
||||
setClosureState(e.target.value as "open_only" | "closed_only" | "")
|
||||
}
|
||||
aria-label="Filter by Closure State"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Closure States</option>
|
||||
<option value="open_only">Unclosed Only</option>
|
||||
<option value="closed_only">Closed Only</option>
|
||||
</select>
|
||||
|
||||
<div className="flex items-center gap-1.5 lg:col-span-2">
|
||||
<input
|
||||
type="date"
|
||||
aria-label="From date"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(e.target.value)}
|
||||
className="flex-1 px-2 py-1 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
<span className="text-xs text-gray-400">to</span>
|
||||
<input
|
||||
type="date"
|
||||
aria-label="To date"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
className="flex-1 px-2 py-1 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={complaintsQuery.data?.items ?? []}
|
||||
columns={columns}
|
||||
loading={complaintsQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter loaded table..."
|
||||
exportFilename="poona-hospital-complaints"
|
||||
emptyMessage="No complaints match the current filters."
|
||||
onRowClick={(row) => navigate(`/complaints/${row.id}`)}
|
||||
getRowClassName={(row) =>
|
||||
row.call_status === "open"
|
||||
? "bg-red-50/35"
|
||||
: row.call_status === "in_progress"
|
||||
? "bg-amber-50/35"
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
|
||||
{canRaise && (
|
||||
<RaiseComplaintModal open={raiseOpen} onClose={() => setRaiseOpen(false)} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -36,13 +36,6 @@ export const DashboardPage = () => (
|
||||
</div>
|
||||
</StubPage>
|
||||
);
|
||||
export const ComplaintsPage = () => (
|
||||
<StubPage
|
||||
title="Breakdown & Complaint Register"
|
||||
phase={3}
|
||||
description="Full complaint lifecycle with response time and downtime tracking."
|
||||
/>
|
||||
);
|
||||
export const PMPage = () => (
|
||||
<StubPage title="Preventive Maintenance" phase={4} description="PM schedules and calendar view." />
|
||||
);
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage";
|
||||
import { complaintsApi, type ComplaintItem } from "@/api/complaints";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import * as mastersApi from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
const MOCK_COMPLAINT: ComplaintItem = {
|
||||
id: 42,
|
||||
complaint_no: "CMP-2026-0042",
|
||||
asset_id: 1,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "Ventilator",
|
||||
asset_status: "under_repair",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
location_name: "ICU Bay 1",
|
||||
description: "Oxygen sensor alarm",
|
||||
breakdown_details: "Sensor failing calibration check",
|
||||
priority: "critical",
|
||||
notes: null,
|
||||
registered_at: "2026-11-11T06:00:00Z",
|
||||
registered_by_id: 3,
|
||||
registered_by_name: "ICU Nurse",
|
||||
received_by_id: 2,
|
||||
received_by_name: "Bio Eng",
|
||||
received_at: "2026-11-11T06:00:00Z",
|
||||
assigned_to_id: 2,
|
||||
assigned_to_name: "Bio Eng",
|
||||
assigned_at: "2026-11-11T06:10:00Z",
|
||||
attended_by_id: 2,
|
||||
attended_by_name: "Bio Eng",
|
||||
attended_at: "2026-11-11T06:25:00Z",
|
||||
restored_at: null,
|
||||
closed_by_id: null,
|
||||
closed_by_name: null,
|
||||
closed_at: null,
|
||||
call_status: "in_progress",
|
||||
closure_remarks: null,
|
||||
action_taken: "Replaced flow sensor",
|
||||
root_cause: "Sensor drift",
|
||||
corrective_action: "Calibration scheduled",
|
||||
lessons_learned: null,
|
||||
ce_name: null,
|
||||
ce_attended_at: null,
|
||||
ce_action_taken: null,
|
||||
spare_required: true,
|
||||
spare_details: "O2 cell",
|
||||
spare_cost_estimate: 4500,
|
||||
response_time_minutes: 25,
|
||||
downtime_minutes: 1420,
|
||||
downtime_is_ongoing: true,
|
||||
downtime_end_milestone: "restored_at",
|
||||
response_start_setting: "registered_at",
|
||||
ce_response_time_minutes: null,
|
||||
updated_at: "2026-11-11T06:30:00Z",
|
||||
};
|
||||
|
||||
function renderPage() {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter initialEntries={["/complaints/42"]}>
|
||||
<Routes>
|
||||
<Route path="/complaints/:id" element={<ComplaintDetailPage />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("ComplaintDetailPage", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.spyOn(complaintsApi, "get").mockResolvedValue(MOCK_COMPLAINT);
|
||||
vi.spyOn(complaintsApi, "events").mockResolvedValue({ items: [], total: 0 });
|
||||
vi.spyOn(attachmentsApi, "list").mockResolvedValue({ items: [], total: 0 });
|
||||
vi.spyOn(mastersApi, "fetchUsersLookup").mockResolvedValue({
|
||||
items: [{ id: 2, name: "Bio Eng", role: "biomedical", department_id: null }],
|
||||
total: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("renders technical section read-only with Lock banner for department_user and displays downtime metrics", async () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 3,
|
||||
name: "ICU Nurse",
|
||||
email: "dept@poona.demo",
|
||||
role: "department_user",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
is_active: true,
|
||||
},
|
||||
token: "t",
|
||||
hydrating: false,
|
||||
});
|
||||
|
||||
renderPage();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("CMP-2026-0042")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(
|
||||
screen.getByText(/Restricted: Editable by Biomedical team only/i)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /Save Technical Details/i })).not.toBeInTheDocument();
|
||||
|
||||
// Downtime formatting (1420 mins = 23h 40m) + total mins + Ongoing + milestone
|
||||
expect(screen.getByText("23h 40m")).toBeInTheDocument();
|
||||
expect(screen.getByText("1,420 mins")).toBeInTheDocument();
|
||||
expect(screen.getByText("Ongoing")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Downtime ends at: restored_at/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders editable technical section for biomedical role", async () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 2,
|
||||
name: "Bio Eng",
|
||||
email: "bio@poona.demo",
|
||||
role: "biomedical",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "t",
|
||||
hydrating: false,
|
||||
});
|
||||
|
||||
renderPage();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("CMP-2026-0042")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(
|
||||
screen.queryByText(/Restricted: Editable by Biomedical team only/i)
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: /Save Technical Details/i })
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue("Replaced flow sensor")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,7 @@ describe("permissions.can()", () => {
|
||||
// coordinator
|
||||
expect(can("coordinator", "edit_asset_contracts_only")).toBe(true);
|
||||
expect(can("coordinator", "create_edit_assets")).toBe(false);
|
||||
expect(can("coordinator", "raise_complaint")).toBe(false);
|
||||
expect(can("coordinator", "handle_complaint")).toBe(true);
|
||||
expect(can("coordinator", "manage_calibration_contracts")).toBe(true);
|
||||
expect(can("coordinator", "manage_demo_equipment")).toBe(true);
|
||||
|
||||
Reference in New Issue
Block a user