phase-5: contracts, warranties, insurance, demo equipment, and department visits
This commit is contained in:
@@ -13,12 +13,12 @@ import { ComplaintsPage } from "@/pages/ComplaintsPage";
|
||||
import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage";
|
||||
import { PMPage } from "@/pages/PMPage";
|
||||
import { CalibrationPage } from "@/pages/CalibrationPage";
|
||||
import { ContractsPage } from "@/pages/ContractsPage";
|
||||
import { InsurancePage } from "@/pages/InsurancePage";
|
||||
import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
|
||||
import { VisitsPage } from "@/pages/VisitsPage";
|
||||
import {
|
||||
DashboardPage,
|
||||
ContractsPage,
|
||||
InsurancePage,
|
||||
DemoEquipmentPage,
|
||||
VisitsPage,
|
||||
ReportsPage,
|
||||
NotificationsPage,
|
||||
} from "@/pages/stubs";
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
import { api } from "./client";
|
||||
import type { AlertSeverity, CoverageStatus } from "./assets";
|
||||
|
||||
export type ContractStatus = CoverageStatus | "superseded";
|
||||
export type DemoStatus = "on_demo" | "overdue_return" | "returned";
|
||||
|
||||
export interface ContractItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
contract_type: string;
|
||||
provider_id: number;
|
||||
provider_name: string | null;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_period_text: string | null;
|
||||
renewed_from_id: number | null;
|
||||
is_superseded: boolean;
|
||||
status: ContractStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_to_expiry: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ContractListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
provider_id?: number;
|
||||
contract_type?: string;
|
||||
status?: string;
|
||||
include_superseded?: boolean;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface ContractCreatePayload {
|
||||
asset_id: number;
|
||||
contract_type: string;
|
||||
provider_id: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_period_text?: string | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface ContractRenewPayload {
|
||||
contract_type?: string;
|
||||
provider_id?: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_period_text?: string | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface WarrantyItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
duration_months: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
provider_id: number | null;
|
||||
provider_name: string | null;
|
||||
status: CoverageStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_to_expiry: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface WarrantyListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
status?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface WarrantyCreatePayload {
|
||||
asset_id: number;
|
||||
duration_months: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
provider_id?: number | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface InsuranceItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
insurer_id: number;
|
||||
insurer_name: string | null;
|
||||
policy_no: string;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_amount: number | null;
|
||||
status: CoverageStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_to_expiry: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface InsuranceListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
insurer_id?: number;
|
||||
status?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface InsuranceCreatePayload {
|
||||
asset_id: number;
|
||||
insurer_id: number;
|
||||
policy_no: string;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_amount?: number | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface DemoEquipmentItem {
|
||||
id: number;
|
||||
name: string;
|
||||
equipment_type: string;
|
||||
supplier_id: number;
|
||||
supplier_name: string | null;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
location_id: number | null;
|
||||
location_name: string | null;
|
||||
start_date: string;
|
||||
expected_return_date: string;
|
||||
actual_return_date: string | null;
|
||||
status: DemoStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_remaining: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface DemoListParams {
|
||||
q?: string;
|
||||
supplier_id?: number;
|
||||
department_id?: number;
|
||||
status?: string;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface DemoCreatePayload {
|
||||
name: string;
|
||||
equipment_type: string;
|
||||
supplier_id: number;
|
||||
department_id: number;
|
||||
location_id?: number | null;
|
||||
start_date: string;
|
||||
expected_return_date: string;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface VisitAssetBrief {
|
||||
id: number;
|
||||
asset_code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface VisitComplaintBrief {
|
||||
id: number;
|
||||
complaint_no: string;
|
||||
call_status: string;
|
||||
priority: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface VisitItem {
|
||||
id: number;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
visited_by_id: number;
|
||||
visited_by_name: string | null;
|
||||
visit_date: string;
|
||||
observations: string;
|
||||
assets: VisitAssetBrief[];
|
||||
complaints: VisitComplaintBrief[];
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface VisitListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
visited_by_id?: number;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface VisitCreatePayload {
|
||||
department_id: number;
|
||||
visit_date: string;
|
||||
observations: string;
|
||||
asset_ids?: number[];
|
||||
complaint_ids?: number[];
|
||||
}
|
||||
|
||||
function toQS(params: Record<string, string | number | boolean | undefined>): string {
|
||||
const sp = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v === undefined || v === "") continue;
|
||||
sp.set(k, String(v));
|
||||
}
|
||||
const s = sp.toString();
|
||||
return s ? `?${s}` : "";
|
||||
}
|
||||
|
||||
export const contractsApi = {
|
||||
list: (params: ContractListParams = {}) =>
|
||||
api.get<{ items: ContractItem[]; total: number }>(
|
||||
`/contracts${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: ContractCreatePayload) => api.post<ContractItem>("/contracts", data),
|
||||
update: (id: number, data: Partial<ContractCreatePayload>) =>
|
||||
api.patch<ContractItem>(`/contracts/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/contracts/${id}`),
|
||||
renew: (id: number, data: ContractRenewPayload) =>
|
||||
api.post<{ old_contract: ContractItem; new_contract: ContractItem }>(
|
||||
`/contracts/${id}/renew`,
|
||||
data
|
||||
),
|
||||
history: (assetId: number) =>
|
||||
api.get<{ items: ContractItem[] }>(`/contracts/history/${assetId}`),
|
||||
};
|
||||
|
||||
export const warrantiesApi = {
|
||||
list: (params: WarrantyListParams = {}) =>
|
||||
api.get<{ items: WarrantyItem[]; total: number }>(
|
||||
`/warranties${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: WarrantyCreatePayload) => api.post<WarrantyItem>("/warranties", data),
|
||||
update: (id: number, data: Partial<WarrantyCreatePayload>) =>
|
||||
api.patch<WarrantyItem>(`/warranties/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/warranties/${id}`),
|
||||
};
|
||||
|
||||
export const insuranceApi = {
|
||||
list: (params: InsuranceListParams = {}) =>
|
||||
api.get<{ items: InsuranceItem[]; total: number }>(
|
||||
`/insurance${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: InsuranceCreatePayload) => api.post<InsuranceItem>("/insurance", data),
|
||||
update: (id: number, data: Partial<InsuranceCreatePayload>) =>
|
||||
api.patch<InsuranceItem>(`/insurance/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/insurance/${id}`),
|
||||
};
|
||||
|
||||
export const demoEquipmentApi = {
|
||||
list: (params: DemoListParams = {}) =>
|
||||
api.get<{ items: DemoEquipmentItem[]; total: number }>(
|
||||
`/demo-equipment${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: DemoCreatePayload) =>
|
||||
api.post<DemoEquipmentItem>("/demo-equipment", data),
|
||||
update: (id: number, data: Partial<DemoCreatePayload>) =>
|
||||
api.patch<DemoEquipmentItem>(`/demo-equipment/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/demo-equipment/${id}`),
|
||||
markReturned: (id: number, data: { actual_return_date: string; remarks?: string | null }) =>
|
||||
api.post<DemoEquipmentItem>(`/demo-equipment/${id}/return`, data),
|
||||
};
|
||||
|
||||
export const visitsApi = {
|
||||
list: (params: VisitListParams = {}) =>
|
||||
api.get<{ items: VisitItem[]; total: number }>(
|
||||
`/visits${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
get: (id: number) => api.get<VisitItem>(`/visits/${id}`),
|
||||
create: (data: VisitCreatePayload) => api.post<VisitItem>("/visits", data),
|
||||
update: (id: number, data: Partial<VisitCreatePayload>) =>
|
||||
api.patch<VisitItem>(`/visits/${id}`, data),
|
||||
linkComplaint: (id: number, complaintId: number) =>
|
||||
api.post<VisitItem>(`/visits/${id}/link-complaint`, { complaint_id: complaintId }),
|
||||
};
|
||||
@@ -3,6 +3,7 @@ import { Search, X, ShieldCheck, Ban } from "lucide-react";
|
||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { CoverageBadge, AssetStatusBadge } from "./StatusBadge";
|
||||
import { InsuranceDrawer } from "./InsuranceDrawer";
|
||||
|
||||
interface AssetPickerProps {
|
||||
selectedAsset: AssetLookupItem | null;
|
||||
@@ -24,6 +25,7 @@ export function AssetPicker({
|
||||
const [results, setResults] = useState<AssetLookupItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [insuranceOpen, setInsuranceOpen] = useState(false);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -148,11 +150,28 @@ export function AssetPicker({
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Insurance</div>
|
||||
<div className="font-medium text-gray-800">
|
||||
{selectedAsset.insurance_summary || selectedAsset.insurance_status || "None"}
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-medium text-gray-800">
|
||||
{selectedAsset.insurance_summary || selectedAsset.insurance_status || "None"}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setInsuranceOpen(true)}
|
||||
className="text-xs font-medium text-[#1e3a8a] hover:underline"
|
||||
>
|
||||
View Insurance
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{insuranceOpen && (
|
||||
<InsuranceDrawer
|
||||
open={insuranceOpen}
|
||||
onClose={() => setInsuranceOpen(false)}
|
||||
assetId={selectedAsset.id}
|
||||
assetLabel={`${selectedAsset.asset_code} — ${selectedAsset.name}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { useEffect } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Link } from "react-router-dom";
|
||||
import { X, ShieldCheck, AlertCircle, ExternalLink } from "lucide-react";
|
||||
import { insuranceApi } from "@/api/phase5";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate, formatINR } from "@/lib/format";
|
||||
import { ExpiryChip } from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface InsuranceDrawerProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
assetId: number | null;
|
||||
assetLabel?: string;
|
||||
}
|
||||
|
||||
export function InsuranceDrawer({
|
||||
open,
|
||||
onClose,
|
||||
assetId,
|
||||
assetLabel,
|
||||
}: InsuranceDrawerProps) {
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const canManage = can(role, "manage_calibration_contracts");
|
||||
|
||||
const policiesQuery = useQuery({
|
||||
queryKey: ["insurance", "asset-drawer", assetId],
|
||||
queryFn: () => insuranceApi.list({ asset_id: assetId!, page_size: 200 }),
|
||||
enabled: open && Boolean(assetId),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") onClose();
|
||||
}
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open || !assetId) return null;
|
||||
|
||||
const policies = policiesQuery.data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex justify-end bg-black/40"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Asset Insurance Policies"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-lg bg-white h-full shadow-2xl border-l border-gray-200 flex flex-col"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 bg-gray-50">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-gray-900">
|
||||
<ShieldCheck className="h-4 w-4 text-[#1e3a8a] shrink-0" />
|
||||
<span>Asset Insurance</span>
|
||||
</div>
|
||||
{assetLabel && (
|
||||
<p className="text-xs text-gray-500 truncate mt-0.5">{assetLabel}</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Close insurance drawer"
|
||||
className="p-1.5 rounded-md text-gray-500 hover:text-gray-800 hover:bg-gray-200"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-5 space-y-4">
|
||||
{policiesQuery.isLoading ? (
|
||||
<div className="space-y-3">
|
||||
<div className="h-28 bg-gray-100 rounded-lg animate-pulse" />
|
||||
<div className="h-28 bg-gray-100 rounded-lg animate-pulse" />
|
||||
</div>
|
||||
) : policiesQuery.isError ? (
|
||||
<div className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 p-3 text-sm text-red-700">
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>Failed to load insurance policies for this asset.</span>
|
||||
</div>
|
||||
) : policies.length === 0 ? (
|
||||
<div className="text-center py-10 bg-gray-50 border border-dashed border-gray-200 rounded-lg space-y-2">
|
||||
<ShieldCheck className="h-8 w-8 text-gray-300 mx-auto" />
|
||||
<p className="text-sm font-medium text-gray-700">
|
||||
No insurance policies recorded for this asset.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Policies can be added from the Insurance register.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
policies.map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
className="rounded-lg border border-gray-200 bg-white p-4 space-y-3 shadow-sm"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="font-mono text-sm font-bold text-[#1e3a8a]">
|
||||
{p.policy_no}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600 mt-0.5">
|
||||
{p.insurer_name || `Insurer #${p.insurer_id}`}
|
||||
</div>
|
||||
</div>
|
||||
<ExpiryChip
|
||||
daysToExpiry={p.days_to_expiry}
|
||||
status={p.status}
|
||||
severity={p.severity}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 text-xs bg-gray-50 rounded-md p-2.5 border border-gray-100">
|
||||
<div>
|
||||
<div className="text-gray-500">Start</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{formatDate(p.start_date)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">End</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{formatDate(p.end_date)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Coverage</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{formatINR(p.coverage_amount)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{p.remarks && (
|
||||
<p className="text-xs text-gray-600">
|
||||
<span className="font-medium">Remarks:</span> {p.remarks}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="pt-2 border-t border-gray-100">
|
||||
<div className="text-xs font-semibold text-gray-700 mb-1.5">
|
||||
Policy Certificates & Documents
|
||||
</div>
|
||||
<Attachments
|
||||
entityType="insurance"
|
||||
entityId={p.id}
|
||||
canUpload={canManage}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="px-5 py-3 border-t border-gray-200 bg-gray-50 flex items-center justify-between gap-2">
|
||||
<Link to={`/insurance`} onClick={onClose}>
|
||||
<Button variant="outline" size="sm">
|
||||
<ExternalLink className="h-3.5 w-3.5 mr-1.5" />
|
||||
Open Insurance Register
|
||||
</Button>
|
||||
</Link>
|
||||
<Button variant="outline" size="sm" onClick={onClose}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,8 +10,8 @@ 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 { assetsApi, type AssetLookupItem, type AssetCriticality } from "@/api/assets";
|
||||
import { complaintsApi, type ComplaintItem } from "@/api/complaints";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import { fetchUsersLookup } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
@@ -29,13 +29,24 @@ type ComplaintFormValues = z.infer<typeof complaintSchema>;
|
||||
interface RaiseComplaintModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
initialAssetId?: number | null;
|
||||
initialDescription?: string;
|
||||
onCreated?: (complaint: ComplaintItem) => Promise<void> | void;
|
||||
navigateOnCreate?: boolean;
|
||||
}
|
||||
|
||||
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) {
|
||||
export function RaiseComplaintModal({
|
||||
open,
|
||||
onClose,
|
||||
initialAssetId = null,
|
||||
initialDescription = "",
|
||||
onCreated,
|
||||
navigateOnCreate = true,
|
||||
}: RaiseComplaintModalProps) {
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
@@ -69,17 +80,39 @@ export function RaiseComplaintModal({ open, onClose }: RaiseComplaintModalProps)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setSelectedAsset(null);
|
||||
setFiles([]);
|
||||
setServerError(null);
|
||||
reset({
|
||||
description: "",
|
||||
description: initialDescription,
|
||||
breakdown_details: "",
|
||||
priority: "non_critical",
|
||||
notes: "",
|
||||
received_by_id: user?.id ? String(user.id) : "",
|
||||
});
|
||||
}, [open, user?.id, reset]);
|
||||
if (initialAssetId) {
|
||||
let cancelled = false;
|
||||
assetsApi
|
||||
.get(initialAssetId)
|
||||
.then((a) => {
|
||||
if (cancelled) return;
|
||||
setSelectedAsset({
|
||||
...a,
|
||||
contract_summary: a.contract_type
|
||||
? `${a.contract_type} (${a.contract_status})`
|
||||
: "None",
|
||||
insurance_summary: a.insurance_status || "None",
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setSelectedAsset(null);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
} else {
|
||||
setSelectedAsset(null);
|
||||
}
|
||||
}, [open, user?.id, initialAssetId, initialDescription, reset]);
|
||||
|
||||
function handleFilePick(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const picked = Array.from(e.target.files ?? []);
|
||||
@@ -117,8 +150,13 @@ export function RaiseComplaintModal({ open, onClose }: RaiseComplaintModalProps)
|
||||
|
||||
await qc.invalidateQueries({ queryKey: ["complaints"] });
|
||||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
if (onCreated) {
|
||||
await onCreated(created);
|
||||
}
|
||||
onClose();
|
||||
navigate(`/complaints/${created.id}`);
|
||||
if (navigateOnCreate) {
|
||||
navigate(`/complaints/${created.id}`);
|
||||
}
|
||||
} catch (err) {
|
||||
setServerError(err instanceof ApiError ? err.detail : "Failed to register complaint.");
|
||||
}
|
||||
|
||||
@@ -306,3 +306,120 @@ export function CallStatusBadge({
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function ExpiryChip({
|
||||
daysToExpiry,
|
||||
status,
|
||||
severity,
|
||||
className,
|
||||
}: {
|
||||
daysToExpiry: number;
|
||||
status: string;
|
||||
severity?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
if (status === "superseded") {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-gray-100 text-gray-600 border border-gray-300",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<MinusCircle className="h-3 w-3 shrink-0" />
|
||||
Superseded
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === "expired" || daysToExpiry < 0) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-red-100 text-red-800 border border-red-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<AlertCircle className="h-3 w-3 shrink-0" />
|
||||
Expired
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === "expiring") {
|
||||
const isRed = severity === "red";
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap border",
|
||||
isRed
|
||||
? "bg-red-100 text-red-800 border-red-200"
|
||||
: "bg-amber-100 text-amber-800 border-amber-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Clock className="h-3 w-3 shrink-0" />
|
||||
{daysToExpiry} {daysToExpiry === 1 ? "day" : "days"} left
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-green-100 text-green-800 border border-green-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<CheckCircle2 className="h-3 w-3 shrink-0" />
|
||||
Active
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function DemoStatusBadge({
|
||||
status,
|
||||
daysRemaining,
|
||||
className,
|
||||
}: {
|
||||
status: string;
|
||||
daysRemaining?: number;
|
||||
className?: string;
|
||||
}) {
|
||||
if (status === "returned") {
|
||||
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 bg-green-100 text-green-800 border border-green-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<CheckCircle2 className="h-3 w-3 shrink-0" />
|
||||
Returned
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === "overdue_return") {
|
||||
const overdueDays =
|
||||
daysRemaining != null && daysRemaining < 0 ? Math.abs(daysRemaining) : null;
|
||||
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 bg-red-100 text-red-800 border border-red-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<AlertTriangle className="h-3 w-3 shrink-0" />
|
||||
{overdueDays != null ? `Overdue by ${overdueDays}d` : "Overdue Return"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
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 bg-blue-100 text-blue-800 border border-blue-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Clock className="h-3 w-3 shrink-0" />
|
||||
On Demo
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { AssetFormModal } from "@/components/AssetFormModal";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
import {
|
||||
NewPMScheduleModal,
|
||||
CompletePMModal,
|
||||
@@ -64,6 +65,7 @@ export function AssetDetailPage() {
|
||||
|
||||
const [activeTab, setActiveTab] = useState<DetailTab>("overview");
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [insuranceDrawerOpen, setInsuranceDrawerOpen] = useState(false);
|
||||
const [addCalOpen, setAddCalOpen] = useState(false);
|
||||
const [approveCalOpen, setApproveCalOpen] = useState(false);
|
||||
const [newPMOpen, setNewPMOpen] = useState(false);
|
||||
@@ -169,12 +171,18 @@ export function AssetDetailPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{canEdit && (
|
||||
<Button variant="outline" onClick={() => setEditOpen(true)}>
|
||||
<Pencil className="h-4 w-4 mr-1.5" />
|
||||
Edit Asset
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" onClick={() => setInsuranceDrawerOpen(true)}>
|
||||
<ShieldCheck className="h-4 w-4 mr-1.5" />
|
||||
View Insurance
|
||||
</Button>
|
||||
)}
|
||||
{canEdit && (
|
||||
<Button variant="outline" onClick={() => setEditOpen(true)}>
|
||||
<Pencil className="h-4 w-4 mr-1.5" />
|
||||
Edit Asset
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 pt-3 border-t border-gray-100 text-sm">
|
||||
@@ -625,6 +633,12 @@ export function AssetDetailPage() {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<InsuranceDrawer
|
||||
open={insuranceDrawerOpen}
|
||||
onClose={() => setInsuranceDrawerOpen(false)}
|
||||
assetId={asset.id}
|
||||
assetLabel={`${asset.asset_code} — ${asset.name}`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
CalendarCog,
|
||||
Info,
|
||||
Activity,
|
||||
ShieldCheck,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
complaintsApi,
|
||||
@@ -34,6 +35,7 @@ import {
|
||||
CriticalityBadge,
|
||||
} from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
|
||||
function toDatetimeLocal(iso: string | null | undefined): string {
|
||||
if (!iso) return "";
|
||||
@@ -96,6 +98,7 @@ export function ComplaintDetailPage() {
|
||||
const [tsField, setTsField] = useState<TimestampField>("attended_at");
|
||||
const [tsValue, setTsValue] = useState("");
|
||||
const [tsReason, setTsReason] = useState("");
|
||||
const [insuranceDrawerOpen, setInsuranceDrawerOpen] = useState(false);
|
||||
|
||||
// Technical form state
|
||||
const [actionTaken, setActionTaken] = useState("");
|
||||
@@ -791,11 +794,22 @@ export function ComplaintDetailPage() {
|
||||
<div>Department: {c.department_name || "—"}</div>
|
||||
<div>Location: {c.location_name || "—"}</div>
|
||||
</div>
|
||||
<Link to={`/assets/${c.asset_id}`} className="block pt-1">
|
||||
<Button variant="outline" size="sm" className="w-full">
|
||||
View Asset Record
|
||||
<div className="space-y-2 pt-1">
|
||||
<Link to={`/assets/${c.asset_id}`} className="block">
|
||||
<Button variant="outline" size="sm" className="w-full">
|
||||
View Asset Record
|
||||
</Button>
|
||||
</Link>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() => setInsuranceDrawerOpen(true)}
|
||||
>
|
||||
<ShieldCheck className="h-3.5 w-3.5 mr-1.5" />
|
||||
View Insurance
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl border border-gray-200 p-4 shadow-sm space-y-3">
|
||||
@@ -985,6 +999,13 @@ export function ComplaintDetailPage() {
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
<InsuranceDrawer
|
||||
open={insuranceDrawerOpen}
|
||||
onClose={() => setInsuranceDrawerOpen(false)}
|
||||
assetId={c.asset_id}
|
||||
assetLabel={`${c.asset_code} — ${c.asset_name}`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,703 @@
|
||||
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";
|
||||
|
||||
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<ViewTab>("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<DemoEquipmentItem | null>(null);
|
||||
const [returnTarget, setReturnTarget] = useState<DemoEquipmentItem | null>(null);
|
||||
const [attachTarget, setAttachTarget] = useState<DemoEquipmentItem | null>(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: () => qc.invalidateQueries({ queryKey: ["demo-equipment"] }),
|
||||
});
|
||||
|
||||
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<DemoEquipmentItem, unknown>[] = [
|
||||
{
|
||||
id: "equipment",
|
||||
accessorFn: (r) => `${r.name} ${r.equipment_type ?? ""}`,
|
||||
header: "Equipment",
|
||||
cell: ({ row }) => (
|
||||
<div>
|
||||
<div className="font-medium text-gray-900">{row.original.name}</div>
|
||||
{row.original.equipment_type && (
|
||||
<div className="text-xs text-gray-500">{row.original.equipment_type}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
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 }) => (
|
||||
<div>
|
||||
<div className="text-gray-800">{row.original.department_name || "—"}</div>
|
||||
{row.original.location_name && (
|
||||
<div className="text-xs text-gray-500">{row.original.location_name}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "start_date",
|
||||
header: "Start Date",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "expected_return_date",
|
||||
header: "Expected Return",
|
||||
cell: ({ row }) => (
|
||||
<span
|
||||
className={`whitespace-nowrap ${
|
||||
row.original.status === "overdue_return" ? "font-semibold text-red-700" : ""
|
||||
}`}
|
||||
>
|
||||
{formatDate(row.original.expected_return_date)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "actual_return_date",
|
||||
header: "Actual Return",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string | null)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: "Status",
|
||||
cell: ({ row }) => (
|
||||
<DemoStatusBadge
|
||||
status={row.original.status}
|
||||
daysRemaining={row.original.days_remaining}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "attachments",
|
||||
header: "Docs",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setAttachTarget(row.original)}
|
||||
title="View or upload demo equipment documents"
|
||||
>
|
||||
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||||
<span className="text-xs">{row.original.attachment_count}</span>
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
...(canManage
|
||||
? [
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }: { row: { original: DemoEquipmentItem } }) => (
|
||||
<div className="flex items-center gap-1">
|
||||
{row.original.status !== "returned" && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setReturnTarget(row.original)}
|
||||
>
|
||||
<CornerDownLeft className="h-3.5 w-3.5 mr-1" />
|
||||
Return
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setEditing(row.original);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
aria-label={`Edit demo equipment ${row.original.name}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => {
|
||||
if (window.confirm(`Delete demo entry "${row.original.name}"?`)) {
|
||||
deleteMutation.mutate(row.original.id);
|
||||
}
|
||||
}}
|
||||
aria-label={`Delete demo equipment ${row.original.name}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
} satisfies ColumnDef<DemoEquipmentItem, unknown>,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
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">Demo Equipment Register</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Monitor supplier trial equipment, expected return dates, and overdue alerts
|
||||
</p>
|
||||
</div>
|
||||
{canManage && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Log Demo Equipment
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* View Tabs */}
|
||||
<div className="flex gap-1 border-b border-gray-200">
|
||||
{(
|
||||
[
|
||||
{ key: "active", label: "Active & Overdue" },
|
||||
{ key: "returned", label: "Returned History" },
|
||||
{ key: "all", label: "All" },
|
||||
] as { key: ViewTab; label: string }[]
|
||||
).map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
onClick={() => setViewTab(t.key)}
|
||||
className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
|
||||
viewTab === t.key
|
||||
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||||
: "border-transparent text-gray-500 hover:text-gray-800"
|
||||
}`}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 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 equipment name, type, remarks..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<select
|
||||
value={supplierId}
|
||||
onChange={(e) => setSupplierId(e.target.value)}
|
||||
aria-label="Filter by Supplier"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Suppliers</option>
|
||||
{supplierOptions.map((s) => (
|
||||
<option key={s.id} value={String(s.id)}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{!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>
|
||||
)}
|
||||
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Start Date From"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Start Date To"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={items}
|
||||
columns={columns}
|
||||
loading={demoQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter demo equipment..."
|
||||
exportFilename="demo-equipment"
|
||||
emptyMessage="No demo equipment entries found."
|
||||
/>
|
||||
|
||||
<DemoFormModal
|
||||
open={formOpen}
|
||||
onClose={() => setFormOpen(false)}
|
||||
editing={editing}
|
||||
suppliers={supplierOptions}
|
||||
departments={departments}
|
||||
locations={locations}
|
||||
/>
|
||||
|
||||
<ReturnDemoModal
|
||||
open={Boolean(returnTarget)}
|
||||
onClose={() => setReturnTarget(null)}
|
||||
item={returnTarget}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={Boolean(attachTarget)}
|
||||
onOpenChange={(o) => !o && setAttachTarget(null)}
|
||||
title={`Documents — ${attachTarget?.name ?? ""}`}
|
||||
className="max-w-xl"
|
||||
>
|
||||
{attachTarget && (
|
||||
<Attachments
|
||||
entityType="demo_equipment"
|
||||
entityId={attachTarget.id}
|
||||
canUpload={canManage}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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<string | null>(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 (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? `Edit Demo Equipment — ${editing.name}` : "Log Demo Equipment"}
|
||||
className="max-w-xl"
|
||||
>
|
||||
{error && (
|
||||
<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>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Equipment Name *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g. Portable Ultrasound Demo Unit"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Equipment Type / Model *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={equipmentType}
|
||||
onChange={(e) => setEquipmentType(e.target.value)}
|
||||
placeholder="e.g. Diagnostic Imaging"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Supplier *</label>
|
||||
<select
|
||||
required
|
||||
value={supplierId}
|
||||
onChange={(e) => setSupplierId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select supplier...</option>
|
||||
{suppliers.map((s) => (
|
||||
<option key={s.id} value={String(s.id)}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Department *</label>
|
||||
<select
|
||||
required
|
||||
value={departmentId}
|
||||
onChange={(e) => {
|
||||
setDepartmentId(e.target.value);
|
||||
setLocationId("");
|
||||
}}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select department...</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={String(d.id)}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Location</label>
|
||||
<select
|
||||
value={locationId}
|
||||
onChange={(e) => setLocationId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select location...</option>
|
||||
{deptLocations.map((l) => (
|
||||
<option key={l.id} value={String(l.id)}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div />
|
||||
<div>
|
||||
<label className={labelCls}>Start Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Expected Return Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={expectedReturnDate}
|
||||
onChange={(e) => setExpectedReturnDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
{editing ? "Save Changes" : "Log Demo Equipment"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function ReturnDemoModal({
|
||||
open,
|
||||
onClose,
|
||||
item,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
item: DemoEquipmentItem | null;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [actualReturnDate, setActualReturnDate] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setActualReturnDate(new Date().toISOString().slice(0, 10));
|
||||
setRemarks(item?.remarks ?? "");
|
||||
setError(null);
|
||||
}, [open, item]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!item) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await demoEquipmentApi.markReturned(item.id, {
|
||||
actual_return_date: actualReturnDate,
|
||||
remarks: remarks.trim() || null,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["demo-equipment"] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to mark returned.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Mark Returned — ${item?.name ?? ""}`}
|
||||
>
|
||||
{error && (
|
||||
<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>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>Actual Return Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={actualReturnDate}
|
||||
onChange={(e) => setActualReturnDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Return Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
placeholder="Condition, handover person, gate pass reference..."
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" variant="success" loading={submitting}>
|
||||
Confirm Return
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import {
|
||||
Plus,
|
||||
Paperclip,
|
||||
Pencil,
|
||||
Trash2,
|
||||
ShieldCheck,
|
||||
Search,
|
||||
AlertCircle,
|
||||
} from "lucide-react";
|
||||
import { insuranceApi, type InsuranceItem } from "@/api/phase5";
|
||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||
import { departmentsApi, vendorsApi } from "@/api/masters";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate, formatINR } from "@/lib/format";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { ExpiryChip } from "@/components/StatusBadge";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
|
||||
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";
|
||||
|
||||
const STATUS_CHIPS = [
|
||||
{ key: "", label: "All" },
|
||||
{ key: "active", label: "Active" },
|
||||
{ key: "expiring", label: "Expiring Soon" },
|
||||
{ key: "expired", label: "Expired" },
|
||||
];
|
||||
|
||||
export function InsurancePage() {
|
||||
const qc = useQueryClient();
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const isDeptUser = role === "department_user";
|
||||
const canManage = can(role, "manage_calibration_contracts");
|
||||
|
||||
const [statusFilter, setStatusFilter] = useState("");
|
||||
const [q, setQ] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [insurerId, setInsurerId] = useState("");
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<InsuranceItem | null>(null);
|
||||
const [drawerAsset, setDrawerAsset] = useState<{
|
||||
assetId: number;
|
||||
label: string;
|
||||
} | null>(null);
|
||||
const [attachPolicy, setAttachPolicy] = useState<InsuranceItem | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
enabled: !isDeptUser,
|
||||
});
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
});
|
||||
|
||||
const policiesQuery = useQuery({
|
||||
queryKey: ["insurance", q, departmentId, insurerId, statusFilter],
|
||||
queryFn: () =>
|
||||
insuranceApi.list({
|
||||
q: q.trim() || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
insurer_id: insurerId ? Number(insurerId) : undefined,
|
||||
status: statusFilter || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => insuranceApi.remove(id),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["insurance"] });
|
||||
qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
},
|
||||
});
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
const allVendors = vendorsQuery.data?.items ?? [];
|
||||
const insurers = allVendors.filter((v) => v.vendor_type === "insurer");
|
||||
const insurerOptions = insurers.length ? insurers : allVendors;
|
||||
|
||||
const columns: ColumnDef<InsuranceItem, unknown>[] = [
|
||||
{
|
||||
id: "asset",
|
||||
accessorFn: (r) => `${r.asset_code} ${r.asset_name}`,
|
||||
header: "Asset",
|
||||
cell: ({ row }) => (
|
||||
<Link to={`/assets/${row.original.asset_id}`} className="hover:underline">
|
||||
<div className="font-mono text-xs font-semibold text-[#1e3a8a]">
|
||||
{row.original.asset_code}
|
||||
</div>
|
||||
<div className="text-xs text-gray-800">{row.original.asset_name}</div>
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "department_name",
|
||||
header: "Department",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "insurer_name",
|
||||
header: "Insurer",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "policy_no",
|
||||
header: "Policy No",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="font-mono text-xs font-medium">{String(getValue())}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "start_date",
|
||||
header: "Start",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "end_date",
|
||||
header: "End",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "coverage_amount",
|
||||
header: "Coverage",
|
||||
cell: ({ getValue }) => formatINR(getValue() as number | null),
|
||||
},
|
||||
{
|
||||
id: "expiry",
|
||||
accessorFn: (r) => r.days_to_expiry,
|
||||
header: "Status",
|
||||
cell: ({ row }) => (
|
||||
<ExpiryChip
|
||||
daysToExpiry={row.original.days_to_expiry}
|
||||
status={row.original.status}
|
||||
severity={row.original.severity}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "attachments",
|
||||
header: "Docs",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setAttachPolicy(row.original)}
|
||||
title="View or upload policy certificates"
|
||||
>
|
||||
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||||
<span className="text-xs">{row.original.attachment_count}</span>
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
setDrawerAsset({
|
||||
assetId: row.original.asset_id,
|
||||
label: `${row.original.asset_code} — ${row.original.asset_name}`,
|
||||
})
|
||||
}
|
||||
>
|
||||
<ShieldCheck className="h-3.5 w-3.5 mr-1" />
|
||||
Drawer
|
||||
</Button>
|
||||
{canManage && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setEditing(row.original);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
aria-label={`Edit policy ${row.original.policy_no}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => {
|
||||
if (window.confirm(`Delete policy ${row.original.policy_no}?`)) {
|
||||
deleteMutation.mutate(row.original.id);
|
||||
}
|
||||
}}
|
||||
aria-label={`Delete policy ${row.original.policy_no}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
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">Asset Insurance</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Track insurance policies, coverage amounts, expiry alerts, and policy certificates
|
||||
</p>
|
||||
</div>
|
||||
{canManage && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Add Insurance Policy
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 space-y-3">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{STATUS_CHIPS.map((chip) => (
|
||||
<button
|
||||
key={chip.key}
|
||||
type="button"
|
||||
onClick={() => setStatusFilter(chip.key)}
|
||||
className={`px-3 py-1 rounded-full text-xs font-medium border transition-colors ${
|
||||
statusFilter === chip.key
|
||||
? "bg-[#1e3a8a] text-white border-[#1e3a8a]"
|
||||
: "bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-100"
|
||||
}`}
|
||||
>
|
||||
{chip.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2.5">
|
||||
<div className="relative">
|
||||
<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 asset code, name, policy no..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</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={insurerId}
|
||||
onChange={(e) => setInsurerId(e.target.value)}
|
||||
aria-label="Filter by Insurer"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Insurers</option>
|
||||
{insurerOptions.map((v) => (
|
||||
<option key={v.id} value={String(v.id)}>
|
||||
{v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={policiesQuery.data?.items ?? []}
|
||||
columns={columns}
|
||||
loading={policiesQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter insurance policies..."
|
||||
exportFilename="insurance-policies"
|
||||
emptyMessage="No insurance policies match the selected filters."
|
||||
/>
|
||||
|
||||
<InsuranceFormModal
|
||||
open={formOpen}
|
||||
onClose={() => setFormOpen(false)}
|
||||
editing={editing}
|
||||
insurers={insurerOptions}
|
||||
/>
|
||||
|
||||
<InsuranceDrawer
|
||||
open={Boolean(drawerAsset)}
|
||||
onClose={() => setDrawerAsset(null)}
|
||||
assetId={drawerAsset?.assetId ?? null}
|
||||
assetLabel={drawerAsset?.label}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={Boolean(attachPolicy)}
|
||||
onOpenChange={(o) => !o && setAttachPolicy(null)}
|
||||
title={`Policy Documents — ${attachPolicy?.policy_no ?? ""}`}
|
||||
className="max-w-xl"
|
||||
>
|
||||
{attachPolicy && (
|
||||
<Attachments
|
||||
entityType="insurance"
|
||||
entityId={attachPolicy.id}
|
||||
canUpload={canManage}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InsuranceFormModal({
|
||||
open,
|
||||
onClose,
|
||||
editing,
|
||||
insurers,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
editing: InsuranceItem | null;
|
||||
insurers: Array<{ id: number; name: string }>;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
|
||||
const [insurerId, setInsurerId] = useState("");
|
||||
const [policyNo, setPolicyNo] = useState("");
|
||||
const [startDate, setStartDate] = useState("");
|
||||
const [endDate, setEndDate] = useState("");
|
||||
const [coverageAmount, setCoverageAmount] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null);
|
||||
if (editing) {
|
||||
setInsurerId(String(editing.insurer_id));
|
||||
setPolicyNo(editing.policy_no);
|
||||
setStartDate(editing.start_date);
|
||||
setEndDate(editing.end_date);
|
||||
setCoverageAmount(
|
||||
editing.coverage_amount != null ? String(editing.coverage_amount) : ""
|
||||
);
|
||||
setRemarks(editing.remarks ?? "");
|
||||
assetsApi
|
||||
.get(editing.asset_id)
|
||||
.then((a) =>
|
||||
setSelectedAsset({
|
||||
...a,
|
||||
contract_summary: a.contract_type ?? "None",
|
||||
insurance_summary: a.insurance_status,
|
||||
})
|
||||
)
|
||||
.catch(() => setSelectedAsset(null));
|
||||
} else {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const nextYear = new Date();
|
||||
nextYear.setFullYear(nextYear.getFullYear() + 1);
|
||||
setSelectedAsset(null);
|
||||
setInsurerId("");
|
||||
setPolicyNo("");
|
||||
setStartDate(today);
|
||||
setEndDate(nextYear.toISOString().slice(0, 10));
|
||||
setCoverageAmount("");
|
||||
setRemarks("");
|
||||
}
|
||||
}, [open, editing]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!editing && !selectedAsset) {
|
||||
setError("Please select an asset.");
|
||||
return;
|
||||
}
|
||||
if (!insurerId) {
|
||||
setError("Please select an insurer.");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const payload = {
|
||||
insurer_id: Number(insurerId),
|
||||
policy_no: policyNo.trim(),
|
||||
start_date: startDate,
|
||||
end_date: endDate,
|
||||
coverage_amount: coverageAmount.trim() !== "" ? Number(coverageAmount) : null,
|
||||
remarks: remarks.trim() || null,
|
||||
};
|
||||
if (editing) {
|
||||
await insuranceApi.update(editing.id, payload);
|
||||
} else {
|
||||
await insuranceApi.create({
|
||||
asset_id: selectedAsset!.id,
|
||||
...payload,
|
||||
});
|
||||
}
|
||||
await qc.invalidateQueries({ queryKey: ["insurance"] });
|
||||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to save insurance policy.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? `Edit Policy — ${editing.policy_no}` : "Add Insurance Policy"}
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{error && (
|
||||
<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>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>Asset *</label>
|
||||
<AssetPicker
|
||||
selectedAsset={selectedAsset}
|
||||
onSelect={setSelectedAsset}
|
||||
disabled={Boolean(editing)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Insurer *</label>
|
||||
<select
|
||||
required
|
||||
value={insurerId}
|
||||
onChange={(e) => setInsurerId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select insurer...</option>
|
||||
{insurers.map((v) => (
|
||||
<option key={v.id} value={String(v.id)}>
|
||||
{v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Policy Number *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={policyNo}
|
||||
onChange={(e) => setPolicyNo(e.target.value)}
|
||||
placeholder="e.g. POL-MED-2026-001"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Start Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>End Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Coverage Amount (INR)</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step="any"
|
||||
value={coverageAmount}
|
||||
onChange={(e) => setCoverageAmount(e.target.value)}
|
||||
placeholder="e.g. 500000"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
{editing ? "Save Changes" : "Create Policy"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import {
|
||||
Plus,
|
||||
Pencil,
|
||||
AlertTriangle,
|
||||
Search,
|
||||
AlertCircle,
|
||||
CheckSquare,
|
||||
} from "lucide-react";
|
||||
import { visitsApi, type VisitItem } from "@/api/phase5";
|
||||
import { assetsApi } from "@/api/assets";
|
||||
import { departmentsApi } 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 { Badge } from "@/components/ui/badge";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { CallStatusBadge } from "@/components/StatusBadge";
|
||||
import { RaiseComplaintModal } from "@/components/RaiseComplaintModal";
|
||||
|
||||
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 VisitsPage() {
|
||||
const qc = useQueryClient();
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const canManage = can(role, "manage_visits");
|
||||
|
||||
const [q, setQ] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
|
||||
const [visitModalOpen, setVisitModalOpen] = useState(false);
|
||||
const [editingVisit, setEditingVisit] = useState<VisitItem | null>(null);
|
||||
const [complaintVisitTarget, setComplaintVisitTarget] = useState<VisitItem | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
});
|
||||
|
||||
const visitsQuery = useQuery({
|
||||
queryKey: ["visits", q, departmentId, dateFrom, dateTo],
|
||||
queryFn: () =>
|
||||
visitsApi.list({
|
||||
q: q.trim() || undefined,
|
||||
department_id: departmentId ? Number(departmentId) : undefined,
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
|
||||
const columns: ColumnDef<VisitItem, unknown>[] = [
|
||||
{
|
||||
accessorKey: "visit_date",
|
||||
header: "Visit Date",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap font-medium">
|
||||
{formatDate(getValue() as string)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "department_name",
|
||||
header: "Department",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "visited_by_name",
|
||||
header: "Visited By",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
id: "assets",
|
||||
header: "Equipment Checked",
|
||||
enableSorting: false,
|
||||
accessorFn: (r) => r.assets.map((a) => `${a.asset_code} ${a.name}`).join(" "),
|
||||
cell: ({ row }) =>
|
||||
row.original.assets.length === 0 ? (
|
||||
<span className="text-xs text-gray-400">None</span>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-1 max-w-xs">
|
||||
{row.original.assets.map((a) => (
|
||||
<Link
|
||||
key={a.id}
|
||||
to={`/assets/${a.id}`}
|
||||
title={a.name}
|
||||
className="inline-flex items-center px-2 py-0.5 rounded bg-blue-50 text-[#1e3a8a] border border-blue-200 font-mono text-[11px] hover:bg-blue-100"
|
||||
>
|
||||
{a.asset_code}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "observations",
|
||||
header: "Observations",
|
||||
cell: ({ getValue }) => (
|
||||
<p className="text-xs text-gray-800 whitespace-pre-wrap max-w-sm">
|
||||
{String(getValue())}
|
||||
</p>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "complaints",
|
||||
header: "Linked Complaints",
|
||||
enableSorting: false,
|
||||
accessorFn: (r) => r.complaints.map((c) => c.complaint_no).join(" "),
|
||||
cell: ({ row }) =>
|
||||
row.original.complaints.length === 0 ? (
|
||||
<span className="text-xs text-gray-400">—</span>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1">
|
||||
{row.original.complaints.map((c) => (
|
||||
<Link
|
||||
key={c.id}
|
||||
to={`/complaints/${c.id}`}
|
||||
className="inline-flex items-center gap-1.5 text-xs hover:underline"
|
||||
>
|
||||
<span className="font-mono font-semibold text-[#1e3a8a]">
|
||||
{c.complaint_no}
|
||||
</span>
|
||||
<CallStatusBadge status={c.call_status} />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
...(canManage
|
||||
? [
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }: { row: { original: VisitItem } }) => (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setComplaintVisitTarget(row.original)}
|
||||
>
|
||||
<AlertTriangle className="h-3.5 w-3.5 mr-1 text-amber-600" />
|
||||
Raise Complaint
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setEditingVisit(row.original);
|
||||
setVisitModalOpen(true);
|
||||
}}
|
||||
aria-label={`Edit visit ${row.original.id}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
} satisfies ColumnDef<VisitItem, unknown>,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
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">Department Visits</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Daily biomedical rounds, equipment checks, observations, and breakdown escalation
|
||||
</p>
|
||||
</div>
|
||||
{canManage && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditingVisit(null);
|
||||
setVisitModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Log Visit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 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 observations, department, visitor..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Visit Date From"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Visit Date To"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={visitsQuery.data?.items ?? []}
|
||||
columns={columns}
|
||||
loading={visitsQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter visits..."
|
||||
exportFilename="department-visits"
|
||||
emptyMessage="No department visits recorded yet."
|
||||
/>
|
||||
|
||||
{canManage && (
|
||||
<>
|
||||
<VisitFormModal
|
||||
open={visitModalOpen}
|
||||
onClose={() => setVisitModalOpen(false)}
|
||||
editing={editingVisit}
|
||||
departments={departments}
|
||||
onCreatedAndRaise={(created) => setComplaintVisitTarget(created)}
|
||||
/>
|
||||
|
||||
<RaiseComplaintModal
|
||||
open={Boolean(complaintVisitTarget)}
|
||||
onClose={() => setComplaintVisitTarget(null)}
|
||||
initialAssetId={complaintVisitTarget?.assets[0]?.id ?? null}
|
||||
initialDescription={complaintVisitTarget?.observations ?? ""}
|
||||
navigateOnCreate={false}
|
||||
onCreated={async (complaint) => {
|
||||
if (!complaintVisitTarget) return;
|
||||
await visitsApi.linkComplaint(complaintVisitTarget.id, complaint.id);
|
||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function VisitFormModal({
|
||||
open,
|
||||
onClose,
|
||||
editing,
|
||||
departments,
|
||||
onCreatedAndRaise,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
editing: VisitItem | null;
|
||||
departments: Array<{ id: number; name: string }>;
|
||||
onCreatedAndRaise: (visit: VisitItem) => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [visitDate, setVisitDate] = useState("");
|
||||
const [observations, setObservations] = useState("");
|
||||
const [selectedAssetIds, setSelectedAssetIds] = useState<number[]>([]);
|
||||
const [assetSearch, setAssetSearch] = useState("");
|
||||
const [raiseImmediately, setRaiseImmediately] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null);
|
||||
setAssetSearch("");
|
||||
setRaiseImmediately(false);
|
||||
if (editing) {
|
||||
setDepartmentId(String(editing.department_id));
|
||||
setVisitDate(editing.visit_date);
|
||||
setObservations(editing.observations);
|
||||
setSelectedAssetIds(editing.assets.map((a) => a.id));
|
||||
} else {
|
||||
setDepartmentId("");
|
||||
setVisitDate(new Date().toISOString().slice(0, 10));
|
||||
setObservations("");
|
||||
setSelectedAssetIds([]);
|
||||
}
|
||||
}, [open, editing]);
|
||||
|
||||
const deptAssetsQuery = useQuery({
|
||||
queryKey: ["assets", "visit-checklist", departmentId],
|
||||
queryFn: () =>
|
||||
assetsApi.lookup({
|
||||
department_id: departmentId ? Number(departmentId) : undefined,
|
||||
limit: 200,
|
||||
}),
|
||||
enabled: open && Boolean(departmentId),
|
||||
});
|
||||
|
||||
const filteredAssets = useMemo(() => {
|
||||
const list = deptAssetsQuery.data?.items ?? [];
|
||||
const term = assetSearch.trim().toLowerCase();
|
||||
if (!term) return list;
|
||||
return list.filter((a) =>
|
||||
`${a.asset_code} ${a.name} ${a.location_name ?? ""}`
|
||||
.toLowerCase()
|
||||
.includes(term)
|
||||
);
|
||||
}, [deptAssetsQuery.data?.items, assetSearch]);
|
||||
|
||||
function toggleAsset(id: number) {
|
||||
setSelectedAssetIds((prev) =>
|
||||
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!departmentId) {
|
||||
setError("Please select a department.");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (editing) {
|
||||
await visitsApi.update(editing.id, {
|
||||
department_id: Number(departmentId),
|
||||
visit_date: visitDate,
|
||||
observations: observations.trim(),
|
||||
asset_ids: selectedAssetIds,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||
onClose();
|
||||
} else {
|
||||
const created = await visitsApi.create({
|
||||
department_id: Number(departmentId),
|
||||
visit_date: visitDate,
|
||||
observations: observations.trim(),
|
||||
asset_ids: selectedAssetIds,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||
onClose();
|
||||
if (raiseImmediately) {
|
||||
onCreatedAndRaise(created);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to save visit.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? "Edit Department Visit" : "Log Department Visit"}
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{error && (
|
||||
<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>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Department *</label>
|
||||
<select
|
||||
required
|
||||
value={departmentId}
|
||||
onChange={(e) => {
|
||||
setDepartmentId(e.target.value);
|
||||
if (!editing) setSelectedAssetIds([]);
|
||||
}}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select department...</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={String(d.id)}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Visit Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={visitDate}
|
||||
onChange={(e) => setVisitDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<label className="text-sm font-medium text-gray-700 flex items-center gap-1.5">
|
||||
<CheckSquare className="h-4 w-4 text-[#1e3a8a]" />
|
||||
Equipment Checked ({selectedAssetIds.length} selected)
|
||||
</label>
|
||||
{departmentId && (
|
||||
<input
|
||||
type="text"
|
||||
value={assetSearch}
|
||||
onChange={(e) => setAssetSearch(e.target.value)}
|
||||
placeholder="Filter department equipment..."
|
||||
className="px-2.5 py-1 text-xs border border-gray-200 rounded-md w-52"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="max-h-44 overflow-y-auto border border-gray-200 rounded-md divide-y divide-gray-100 bg-gray-50/40">
|
||||
{!departmentId ? (
|
||||
<div className="p-4 text-center text-xs text-gray-400">
|
||||
Select a department to view its equipment checklist.
|
||||
</div>
|
||||
) : deptAssetsQuery.isLoading ? (
|
||||
<div className="p-4 text-center text-xs text-gray-500">
|
||||
Loading department equipment...
|
||||
</div>
|
||||
) : filteredAssets.length === 0 ? (
|
||||
<div className="p-4 text-center text-xs text-gray-400">
|
||||
No matching assets found in this department.
|
||||
</div>
|
||||
) : (
|
||||
filteredAssets.map((a) => (
|
||||
<label
|
||||
key={a.id}
|
||||
className="flex items-center justify-between gap-2 px-3 py-2 text-xs hover:bg-blue-50/50 cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedAssetIds.includes(a.id)}
|
||||
onChange={() => toggleAsset(a.id)}
|
||||
className="h-3.5 w-3.5 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
<span className="font-mono font-semibold text-[#1e3a8a]">
|
||||
{a.asset_code}
|
||||
</span>
|
||||
<span className="text-gray-800 truncate">{a.name}</span>
|
||||
</div>
|
||||
<Badge variant="outline" className="text-[10px] shrink-0">
|
||||
{a.location_name || "—"}
|
||||
</Badge>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Observations *</label>
|
||||
<textarea
|
||||
rows={3}
|
||||
required
|
||||
value={observations}
|
||||
onChange={(e) => setObservations(e.target.value)}
|
||||
placeholder="Round findings, preventive checks, nurse feedback, issues spotted..."
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!editing && (
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={raiseImmediately}
|
||||
onChange={(e) => setRaiseImmediately(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Raise & link a complaint immediately from this observation
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
{editing ? "Save Visit" : raiseImmediately ? "Save & Raise Complaint" : "Save Visit"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -36,18 +36,6 @@ export const DashboardPage = () => (
|
||||
</div>
|
||||
</StubPage>
|
||||
);
|
||||
export const ContractsPage = () => (
|
||||
<StubPage title="Contracts & Warranty" phase={5} description="AMC/CMC contracts and warranty tracking." />
|
||||
);
|
||||
export const InsurancePage = () => (
|
||||
<StubPage title="Insurance" phase={5} description="Insurance policies with expiry alerts." />
|
||||
);
|
||||
export const DemoEquipmentPage = () => (
|
||||
<StubPage title="Demo Equipment Register" phase={5} description="Demo equipment tracking with overdue returns." />
|
||||
);
|
||||
export const VisitsPage = () => (
|
||||
<StubPage title="Department Visits" phase={5} description="Daily department visit reports." />
|
||||
);
|
||||
export const ReportsPage = () => (
|
||||
<StubPage title="Reports & Exports" phase={7} description="8 reports with Excel export." />
|
||||
);
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
import { ContractsPage } from "@/pages/ContractsPage";
|
||||
import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
|
||||
import {
|
||||
insuranceApi,
|
||||
contractsApi,
|
||||
warrantiesApi,
|
||||
demoEquipmentApi,
|
||||
type ContractItem,
|
||||
type DemoEquipmentItem,
|
||||
} from "@/api/phase5";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import { departmentsApi, locationsApi, vendorsApi } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
function renderWithProviders(ui: React.ReactNode) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter>{ui}</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("Phase 5 Modules", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 2,
|
||||
email: "bio@poona.org",
|
||||
name: "Biomed Engineer",
|
||||
role: "biomedical",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "test-token",
|
||||
});
|
||||
|
||||
vi.spyOn(departmentsApi, "list").mockResolvedValue({
|
||||
items: [{ id: 1, name: "ICU", code: "ICU", description: null, is_active: true }],
|
||||
total: 1,
|
||||
});
|
||||
vi.spyOn(locationsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
vi.spyOn(vendorsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
vi.spyOn(attachmentsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("InsuranceDrawer renders policy details for an asset", async () => {
|
||||
vi.spyOn(insuranceApi, "list").mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 10,
|
||||
asset_id: 1,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
insurer_id: 5,
|
||||
insurer_name: "New India Assurance",
|
||||
policy_no: "POL-MED-2026-001",
|
||||
start_date: "2026-01-01",
|
||||
end_date: "2026-12-31",
|
||||
coverage_amount: 850000,
|
||||
status: "expiring",
|
||||
severity: "yellow",
|
||||
days_to_expiry: 18,
|
||||
attachment_count: 1,
|
||||
remarks: "All risk cover",
|
||||
created_at: "2026-01-01T00:00:00Z",
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
renderWithProviders(
|
||||
<InsuranceDrawer
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
assetId={1}
|
||||
assetLabel="PHRC-ICU-0001 — ICU Ventilator"
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("POL-MED-2026-001")).toBeInTheDocument();
|
||||
expect(screen.getByText("New India Assurance")).toBeInTheDocument();
|
||||
expect(screen.getByText("18 days left")).toBeInTheDocument();
|
||||
expect(screen.getByText(/All risk cover/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("ContractsPage renders renewal history with Superseded badge on older contract", async () => {
|
||||
const activeContract: ContractItem = {
|
||||
id: 202,
|
||||
asset_id: 1,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
contract_type: "CMC",
|
||||
provider_id: 3,
|
||||
provider_name: "MedTech Services",
|
||||
start_date: "2026-01-01",
|
||||
end_date: "2026-12-31",
|
||||
coverage_period_text: "1 Year",
|
||||
renewed_from_id: 201,
|
||||
is_superseded: false,
|
||||
status: "active",
|
||||
severity: "ok",
|
||||
days_to_expiry: 120,
|
||||
attachment_count: 0,
|
||||
remarks: "Renewed CMC",
|
||||
created_at: "2026-01-01T00:00:00Z",
|
||||
};
|
||||
|
||||
const oldSupersededContract: ContractItem = {
|
||||
...activeContract,
|
||||
id: 201,
|
||||
contract_type: "AMC",
|
||||
start_date: "2025-01-01",
|
||||
end_date: "2025-12-31",
|
||||
renewed_from_id: null,
|
||||
is_superseded: true,
|
||||
status: "superseded",
|
||||
severity: "ok",
|
||||
days_to_expiry: -30,
|
||||
remarks: "Initial AMC",
|
||||
};
|
||||
|
||||
vi.spyOn(contractsApi, "list").mockResolvedValue({
|
||||
items: [activeContract],
|
||||
total: 1,
|
||||
});
|
||||
vi.spyOn(warrantiesApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
vi.spyOn(contractsApi, "history").mockResolvedValue({
|
||||
items: [activeContract, oldSupersededContract],
|
||||
});
|
||||
|
||||
renderWithProviders(<ContractsPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("PHRC-ICU-0001")).toBeInTheDocument();
|
||||
expect(screen.getByText("MedTech Services")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const historyBtn = screen.getByRole("button", { name: /History/i });
|
||||
fireEvent.click(historyBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/Contract Renewal History — PHRC-ICU-0001/i)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("Superseded")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Renewed from #201/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("DemoEquipmentPage highlights overdue returns", async () => {
|
||||
const overdueItem: DemoEquipmentItem = {
|
||||
id: 301,
|
||||
name: "Portable Ultrasound Demo",
|
||||
equipment_type: "Imaging",
|
||||
supplier_id: 4,
|
||||
supplier_name: "MedEquip India",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
location_id: null,
|
||||
location_name: "ICU Bay 2",
|
||||
start_date: "2026-10-01",
|
||||
expected_return_date: "2026-10-15",
|
||||
actual_return_date: null,
|
||||
status: "overdue_return",
|
||||
severity: "red",
|
||||
days_remaining: -5,
|
||||
attachment_count: 0,
|
||||
remarks: "Pending pickup",
|
||||
created_at: "2026-10-01T00:00:00Z",
|
||||
};
|
||||
|
||||
vi.spyOn(demoEquipmentApi, "list").mockResolvedValue({
|
||||
items: [overdueItem],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
renderWithProviders(<DemoEquipmentPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Portable Ultrasound Demo")).toBeInTheDocument();
|
||||
expect(screen.getByText("Overdue by 5d")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /^Return$/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1 +1 @@
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/pm.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/pmpage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/pm-page.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/phase5.ts","./src/api/pm.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/contractspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/pmpage.tsx","./src/pages/settingspage.tsx","./src/pages/visitspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/phase5-modules.test.tsx","./src/test/pm-page.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
||||
Reference in New Issue
Block a user