phase-3: breakdown and complaint register with calculations and permissions
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user