import { useState, useEffect, useMemo } from "react"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import type { ColumnDef } from "@tanstack/react-table"; import { Plus, Paperclip, Pencil, Trash2, CornerDownLeft, Search, AlertCircle, } from "lucide-react"; import { demoEquipmentApi, type DemoEquipmentItem } from "@/api/phase5"; import { departmentsApi, locationsApi, vendorsApi } from "@/api/masters"; import { ApiError } from "@/api/client"; import { useAuthStore } from "@/hooks/useAuth"; import { can } from "@/lib/permissions"; import { formatDate } from "@/lib/format"; import { DataTable } from "@/components/DataTable"; import { Button } from "@/components/ui/button"; import { Modal } from "@/components/ui/dialog"; import { DemoStatusBadge } from "@/components/StatusBadge"; import { Attachments } from "@/components/Attachments"; import { ConfirmDialog } from "@/components/ConfirmDialog"; import { toast } from "@/components/ToastProvider"; type ViewTab = "active" | "returned" | "all"; 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 DemoEquipmentPage() { const qc = useQueryClient(); const role = useAuthStore((s) => s.user?.role); const isDeptUser = role === "department_user"; const canManage = can(role, "manage_demo_equipment"); const [viewTab, setViewTab] = useState("active"); const [q, setQ] = useState(""); const [supplierId, setSupplierId] = useState(""); const [departmentId, setDepartmentId] = useState(""); const [dateFrom, setDateFrom] = useState(""); const [dateTo, setDateTo] = useState(""); const [formOpen, setFormOpen] = useState(false); const [editing, setEditing] = useState(null); const [returnTarget, setReturnTarget] = useState(null); const [attachTarget, setAttachTarget] = useState(null); const [deleteTarget, setDeleteTarget] = useState(null); const deptsQuery = useQuery({ queryKey: ["departments", "active-only"], queryFn: () => departmentsApi.list(false), enabled: !isDeptUser, }); const locationsQuery = useQuery({ queryKey: ["locations", "active-only"], queryFn: () => locationsApi.list(false), }); const vendorsQuery = useQuery({ queryKey: ["vendors", "active-only"], queryFn: () => vendorsApi.list(false), }); const demoQuery = useQuery({ queryKey: [ "demo-equipment", viewTab, q, supplierId, departmentId, dateFrom, dateTo, ], queryFn: () => demoEquipmentApi.list({ q: q.trim() || undefined, supplier_id: supplierId ? Number(supplierId) : undefined, department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined, status: viewTab === "returned" ? "returned" : undefined, date_from: dateFrom || undefined, date_to: dateTo || undefined, page_size: 200, }), }); const deleteMutation = useMutation({ mutationFn: (id: number) => demoEquipmentApi.remove(id), onSuccess: () => { setDeleteTarget(null); qc.invalidateQueries({ queryKey: ["demo-equipment"] }); toast.success("Demo equipment entry deleted"); }, onError: (err) => { toast.error(err instanceof ApiError ? err.detail : "Failed to delete demo entry"); }, }); const items = useMemo(() => { const raw = demoQuery.data?.items ?? []; if (viewTab === "active") { return raw.filter((item) => item.status !== "returned"); } if (viewTab === "returned") { return raw.filter((item) => item.status === "returned"); } return raw; }, [demoQuery.data?.items, viewTab]); const departments = deptsQuery.data?.items ?? []; const locations = locationsQuery.data?.items ?? []; const allVendors = vendorsQuery.data?.items ?? []; const suppliers = allVendors.filter((v) => v.vendor_type === "supplier"); const supplierOptions = suppliers.length ? suppliers : allVendors; const columns: ColumnDef[] = [ { id: "equipment", accessorFn: (r) => `${r.name} ${r.equipment_type ?? ""}`, header: "Equipment", cell: ({ row }) => (
{row.original.name}
{row.original.equipment_type && (
{row.original.equipment_type}
)}
), }, { accessorKey: "supplier_name", header: "Supplier", cell: ({ getValue }) => (getValue() as string | null) || "—", }, { id: "dept_loc", accessorFn: (r) => `${r.department_name ?? ""} ${r.location_name ?? ""}`, header: "Department / Location", cell: ({ row }) => (
{row.original.department_name || "—"}
{row.original.location_name && (
{row.original.location_name}
)}
), }, { accessorKey: "start_date", header: "Start Date", cell: ({ getValue }) => ( {formatDate(getValue() as string)} ), }, { accessorKey: "expected_return_date", header: "Expected Return", cell: ({ row }) => ( {formatDate(row.original.expected_return_date)} ), }, { accessorKey: "actual_return_date", header: "Actual Return", cell: ({ getValue }) => ( {formatDate(getValue() as string | null)} ), }, { id: "status", accessorKey: "status", header: "Status", cell: ({ row }) => ( ), }, { id: "attachments", header: "Docs", enableSorting: false, enableColumnFilter: false, cell: ({ row }) => ( ), }, ...(canManage ? [ { id: "actions", header: "Actions", enableSorting: false, enableColumnFilter: false, cell: ({ row }: { row: { original: DemoEquipmentItem } }) => (
{row.original.status !== "returned" && ( )}
), } satisfies ColumnDef, ] : []), ]; return (

Demo Equipment Register

Monitor supplier trial equipment, expected return dates, and overdue alerts

{canManage && ( )}
{/* View Tabs */}
{( [ { key: "active", label: "Active & Overdue" }, { key: "returned", label: "Returned History" }, { key: "all", label: "All" }, ] as { key: ViewTab; label: string }[] ).map((t) => ( ))}
{/* Filters */}
setQ(e.target.value)} placeholder="Search equipment name, type, remarks..." className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md" />
{!isDeptUser && ( )} setDateFrom(e.target.value)} className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md" /> setDateTo(e.target.value)} className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md" />
setFormOpen(false)} editing={editing} suppliers={supplierOptions} departments={departments} locations={locations} /> setReturnTarget(null)} item={returnTarget} /> !o && setAttachTarget(null)} title={`Documents — ${attachTarget?.name ?? ""}`} className="max-w-xl" > {attachTarget && ( )} !o && setDeleteTarget(null)} title="Delete Demo Equipment Entry" message={`Are you sure you want to delete "${deleteTarget?.name ?? "this demo entry"}"?`} confirmLabel="Delete" variant="danger" loading={deleteMutation.isPending} onConfirm={() => { if (deleteTarget) deleteMutation.mutate(deleteTarget.id); }} />
); } function DemoFormModal({ open, onClose, editing, suppliers, departments, locations, }: { open: boolean; onClose: () => void; editing: DemoEquipmentItem | null; suppliers: Array<{ id: number; name: string }>; departments: Array<{ id: number; name: string }>; locations: Array<{ id: number; department_id: number; name: string }>; }) { const qc = useQueryClient(); const [name, setName] = useState(""); const [equipmentType, setEquipmentType] = useState(""); const [supplierId, setSupplierId] = useState(""); const [departmentId, setDepartmentId] = useState(""); const [locationId, setLocationId] = useState(""); const [startDate, setStartDate] = useState(""); const [expectedReturnDate, setExpectedReturnDate] = useState(""); const [remarks, setRemarks] = useState(""); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); useEffect(() => { if (!open) return; setError(null); if (editing) { setName(editing.name); setEquipmentType(editing.equipment_type ?? ""); setSupplierId(String(editing.supplier_id)); setDepartmentId(String(editing.department_id)); setLocationId(editing.location_id ? String(editing.location_id) : ""); setStartDate(editing.start_date); setExpectedReturnDate(editing.expected_return_date); setRemarks(editing.remarks ?? ""); } else { const today = new Date(); const plus14 = new Date(today); plus14.setDate(plus14.getDate() + 14); setName(""); setEquipmentType(""); setSupplierId(""); setDepartmentId(""); setLocationId(""); setStartDate(today.toISOString().slice(0, 10)); setExpectedReturnDate(plus14.toISOString().slice(0, 10)); setRemarks(""); } }, [open, editing]); const deptLocations = locations.filter( (l) => !departmentId || l.department_id === Number(departmentId) ); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setSubmitting(true); setError(null); try { const payload = { name: name.trim(), equipment_type: equipmentType.trim(), supplier_id: Number(supplierId), department_id: Number(departmentId), location_id: locationId ? Number(locationId) : null, start_date: startDate, expected_return_date: expectedReturnDate, remarks: remarks.trim() || null, }; if (editing) { await demoEquipmentApi.update(editing.id, payload); } else { await demoEquipmentApi.create(payload); } await qc.invalidateQueries({ queryKey: ["demo-equipment"] }); onClose(); } catch (err) { setError(err instanceof ApiError ? err.detail : "Failed to save demo equipment."); } finally { setSubmitting(false); } } return ( !o && onClose()} title={editing ? `Edit Demo Equipment — ${editing.name}` : "Log Demo Equipment"} className="max-w-xl" > {error && (
{error}
)}
setName(e.target.value)} placeholder="e.g. Portable Ultrasound Demo Unit" className={inputCls} />
setEquipmentType(e.target.value)} placeholder="e.g. Diagnostic Imaging" className={inputCls} />
setStartDate(e.target.value)} className={inputCls} />
setExpectedReturnDate(e.target.value)} className={inputCls} />