Files
Medasset_ai/frontend/src/pages/ReportDetailPage.tsx
T

1077 lines
39 KiB
TypeScript

import { useState, useMemo } from "react";
import { useParams, Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import type { ColumnDef } from "@tanstack/react-table";
import {
ResponsiveContainer,
BarChart,
Bar,
PieChart,
Pie,
Cell,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from "recharts";
import {
ArrowLeft,
FileSpreadsheet,
Printer,
HelpCircle,
AlertCircle,
Lock,
RotateCcw,
Filter,
} from "lucide-react";
import {
REPORT_CATALOG,
fetchReport,
exportReport,
type ReportKey,
type ReportFilterParams,
} from "@/api/reports";
import { departmentsApi, vendorsApi } from "@/api/masters";
import { ApiError } from "@/api/client";
import { useAuthStore } from "@/hooks/useAuth";
import { formatDateTime } from "@/lib/format";
import { DataTable } from "@/components/DataTable";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { toast } from "@/lib/toast";
function currentMonthStr(): string {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}
function humanizeSummaryKey(key: string): string {
const SPECIAL: Record<string, string> = {
total_assets: "Total Assets",
total_complaints: "Total Complaints",
total_downtime_minutes: "Downtime (Mins)",
downtime_formatted: "Total Downtime",
downtime_days_count: "Distinct Downtime Days",
total_scheduled_minutes: "Scheduled Mins",
total_uptime_minutes: "Uptime (Mins)",
uptime_formatted: "Total Uptime",
downtime_pct: "Downtime %",
downtime_vs_uptime_pct: "Downtime vs Uptime %",
scheduled_hours_per_day: "Scheduled Hrs/Day",
downtime_end_milestone: "Downtime Milestone",
departments_count: "Departments",
total_under_repair: "Under Repair",
total_outstanding_complaints: "Outstanding Complaints",
total_visits: "Total Visits",
departments_visited: "Departments Visited",
total_equipment_checked: "Equipment Checked",
linked_complaints_count: "Linked Complaints",
open_count: "Open",
in_progress_count: "In Progress",
closed_count: "Closed",
critical_count: "Critical",
avg_response_minutes: "Avg Response (Mins)",
planned_count: "Planned",
completed_count: "Completed",
upcoming_count: "Upcoming",
due_count: "Due",
overdue_count: "Overdue",
rescheduled_count: "Rescheduled",
compliance_pct: "Compliance %",
total_records: "Total Records",
active_contracts: "Active Contracts",
expiring_contracts: "Expiring Contracts",
expired_contracts: "Expired Contracts",
active_warranties: "Active Warranties",
expiring_warranties: "Expiring Warranties",
total_items: "Total Items",
on_demo_count: "On Demo",
returned_count: "Returned",
};
return (
SPECIAL[key] ??
key
.replace(/_/g, " ")
.replace(/\b\w/g, (c) => c.toUpperCase())
);
}
function computeUptimePct(record: Record<string, unknown>): string {
const upRaw = record.total_uptime_minutes ?? record.uptime_seconds;
const downRaw = record.total_downtime_minutes ?? record.downtime_seconds;
if (upRaw != null && downRaw != null) {
const up = Number(upRaw);
const down = Number(downRaw);
const total = up + down;
if (Number.isFinite(total) && total > 0) {
return `${((up / total) * 100).toFixed(1)} %`;
}
}
if (record.downtime_pct != null) {
const dtPct = Number(record.downtime_pct);
if (Number.isFinite(dtPct)) {
return `${Math.max(0, 100 - dtPct).toFixed(1)} %`;
}
}
return "—";
}
export function ReportDetailPage() {
const { reportKey } = useParams<{ reportKey: string }>();
const user = useAuthStore((s) => s.user);
const role = user?.role;
const isDeptUser = role === "department_user";
const meta = REPORT_CATALOG.find((r) => r.key === reportKey);
const key = meta?.key as ReportKey | undefined;
const isForbidden = Boolean(role && meta?.hiddenForRoles?.includes(role));
// Tailored filter state
const [month, setMonth] = useState(currentMonthStr());
const [dateFrom, setDateFrom] = useState("");
const [dateTo, setDateTo] = useState("");
const [dueFrom, setDueFrom] = useState("");
const [dueTo, setDueTo] = useState("");
const [departmentId, setDepartmentId] = useState("");
const [priority, setPriority] = useState("");
const [callStatus, setCallStatus] = useState("");
const [serviceMode, setServiceMode] = useState("");
const [agencyId, setAgencyId] = useState("");
const [supplierId, setSupplierId] = useState("");
const [statusFilter, setStatusFilter] = useState("");
const [recordKind, setRecordKind] = useState("all");
const [contractType, setContractType] = useState("");
const [formulaOpen, setFormulaOpen] = useState(false);
const [exporting, setExporting] = useState<"xlsx" | "csv" | null>(null);
const filterParams: ReportFilterParams = useMemo(() => {
if (!key) return {};
const p: ReportFilterParams = {};
if (!isDeptUser && departmentId) p.department_id = Number(departmentId);
switch (key) {
case "monthly-maintenance":
case "monthly-department":
if (month) p.month = month;
break;
case "daily-visit":
if (dateFrom) p.date_from = dateFrom;
if (dateTo) p.date_to = dateTo;
break;
case "breakdown-complaints":
if (dateFrom) p.date_from = dateFrom;
if (dateTo) p.date_to = dateTo;
if (priority) p.priority = priority;
if (callStatus) p.call_status = callStatus;
break;
case "pm-compliance":
if (dateFrom || dateTo) {
if (dateFrom) p.date_from = dateFrom;
if (dateTo) p.date_to = dateTo;
} else if (month) {
p.month = month;
}
if (serviceMode) p.service_mode = serviceMode;
break;
case "calibration-due":
if (dueFrom) p.due_from = dueFrom;
if (dueTo) p.due_to = dueTo;
if (agencyId) p.agency_id = Number(agencyId);
if (statusFilter) p.status = statusFilter;
break;
case "contracts-warranty":
if (recordKind) p.record_kind = recordKind;
if (statusFilter) p.status = statusFilter;
if (contractType) p.contract_type = contractType;
break;
case "demo-equipment":
if (supplierId) p.supplier_id = Number(supplierId);
if (statusFilter) p.status = statusFilter;
if (dateFrom) p.date_from = dateFrom;
if (dateTo) p.date_to = dateTo;
break;
}
return p;
}, [
key,
isDeptUser,
departmentId,
month,
dateFrom,
dateTo,
dueFrom,
dueTo,
priority,
callStatus,
serviceMode,
agencyId,
supplierId,
statusFilter,
recordKind,
contractType,
]);
const activeFiltersCount = useMemo(() => {
let count = 0;
if (departmentId) count++;
if (month && month !== currentMonthStr()) count++;
if (dateFrom || dateTo) count++;
if (dueFrom || dueTo) count++;
if (priority) count++;
if (callStatus) count++;
if (serviceMode) count++;
if (agencyId) count++;
if (supplierId) count++;
if (statusFilter) count++;
if (recordKind && recordKind !== "all") count++;
if (contractType) count++;
return count;
}, [
departmentId,
month,
dateFrom,
dateTo,
dueFrom,
dueTo,
priority,
callStatus,
serviceMode,
agencyId,
supplierId,
statusFilter,
recordKind,
contractType,
]);
function handleResetFilters() {
setMonth(currentMonthStr());
setDateFrom("");
setDateTo("");
setDueFrom("");
setDueTo("");
setDepartmentId("");
setPriority("");
setCallStatus("");
setServiceMode("");
setAgencyId("");
setSupplierId("");
setStatusFilter("");
setRecordKind("all");
setContractType("");
}
const deptsQuery = useQuery({
queryKey: ["departments", "active-only"],
queryFn: () => departmentsApi.list(false),
enabled: Boolean(key) && !isDeptUser && !isForbidden,
});
const vendorsQuery = useQuery({
queryKey: ["vendors", "active-only"],
queryFn: () => vendorsApi.list(false),
enabled:
Boolean(key) &&
(key === "calibration-due" || key === "demo-equipment") &&
!isForbidden,
});
const reportQuery = useQuery({
queryKey: ["report", key, filterParams],
queryFn: () => fetchReport(key!, filterParams),
enabled: Boolean(key) && !isForbidden,
});
const report = reportQuery.data;
const columns: ColumnDef<Record<string, unknown>, unknown>[] = useMemo(() => {
if (!report) return [];
const baseCols: ColumnDef<Record<string, unknown>, unknown>[] = report.columns.map(
(col) => ({
id: col.key,
accessorFn: (row) => row[col.key],
header: col.label,
cell: ({ getValue }) => {
const val = getValue();
if (val === null || val === undefined || val === "") return "—";
if (typeof val === "boolean") return val ? "Yes" : "No";
return String(val);
},
})
);
if (
key === "monthly-maintenance" &&
!report.columns.some((c) => c.key === "uptime_pct")
) {
const uptimePctCol: ColumnDef<Record<string, unknown>, unknown> = {
id: "uptime_pct",
accessorFn: (row) => computeUptimePct(row),
header: "Uptime %",
cell: ({ getValue }) => (
<span className="font-semibold text-emerald-700 whitespace-nowrap">
{String(getValue() ?? "—")}
</span>
),
};
const dtPctIdx = baseCols.findIndex((c) => c.id === "downtime_pct");
if (dtPctIdx >= 0) {
baseCols.splice(dtPctIdx, 0, uptimePctCol);
} else {
baseCols.push(uptimePctCol);
}
}
return baseCols;
}, [report, key]);
async function handleExport(format: "xlsx" | "csv") {
if (!key) return;
setExporting(format);
try {
await exportReport(key, format, filterParams);
toast.success(`Exported ${key}.${format}`);
} catch (err) {
toast.error(
err instanceof ApiError ? err.detail : `Failed to export ${format.toUpperCase()}`
);
} finally {
setExporting(null);
}
}
if (!meta || !key) {
return (
<div className="max-w-lg mx-auto mt-12 bg-white border border-gray-200 rounded-xl p-6 text-center space-y-3">
<AlertCircle className="h-8 w-8 text-amber-500 mx-auto" />
<h2 className="text-lg font-semibold text-gray-900">Report Not Found</h2>
<p className="text-sm text-gray-500">
Unknown report key: <span className="font-mono">{reportKey}</span>
</p>
<Link to="/reports">
<Button variant="outline">Back to Reports</Button>
</Link>
</div>
);
}
if (isForbidden) {
return (
<div className="max-w-lg mx-auto mt-12 bg-white border border-red-200 rounded-xl p-6 text-center space-y-3">
<Lock className="h-8 w-8 text-red-500 mx-auto" />
<h2 className="text-lg font-semibold text-gray-900">Access Restricted</h2>
<p className="text-sm text-gray-600">
{meta.title} is available only to System Administrators, Biomedical Engineers, and Management.
</p>
<Link to="/reports">
<Button variant="outline">Back to Reports</Button>
</Link>
</div>
);
}
const departments = deptsQuery.data?.items ?? [];
const allVendors = vendorsQuery.data?.items ?? [];
const agencies = allVendors.filter(
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
);
const suppliers = allVendors.filter((v) => v.vendor_type === "supplier");
const pieData =
key === "monthly-maintenance" && report
? [
{
name: "Uptime (hrs)",
value: Math.round((Number(report.summary.total_uptime_minutes ?? 0) / 60) * 100) / 100,
color: "#22c55e",
},
{
name: "Downtime (hrs)",
value: Math.round((Number(report.summary.total_downtime_minutes ?? 0) / 60) * 100) / 100,
color: "#ef4444",
},
]
: [];
return (
<div className="space-y-5">
{/* Print-Only Official Hospital Letterhead & Scope */}
<div className="print-only mb-4 border-b-2 border-[#102C52] pb-3">
<div className="flex items-start justify-between">
<div className="flex items-center gap-3.5">
<img
src="/logo.jpg"
alt="XYZ Hospital"
className="h-14 w-14 object-contain"
/>
<div>
<div className="text-base font-extrabold text-[#102C52] tracking-tight">
XYZ HOSPITAL
</div>
<div className="text-[11px] font-semibold text-gray-800">
NABH Accredited Tertiary Care Hospital &bull; Department of Clinical Engineering
</div>
<div className="text-[10px] text-gray-500">
27, Sadashiv Peth, Pune, Maharashtra 411030 &bull; Tel: +91 20 6609 6000
</div>
</div>
</div>
<div className="text-right text-[10px] text-gray-600 space-y-0.5 border-l border-gray-200 pl-3">
<div className="font-bold text-[#102C52] uppercase tracking-wider">
Audit &amp; Operational Record
</div>
<div>
<strong>Ref:</strong> XYZ-BME-{key?.toUpperCase() ?? "REP"}
</div>
<div>
<strong>Date:</strong> {formatDateTime(new Date().toISOString())} IST
</div>
{user?.name && (
<div>
<strong>Generated by:</strong> {user.name} ({user.role?.replace(/_/g, " ").toUpperCase()})
</div>
)}
</div>
</div>
{/* Print Filter / Scope summary bar */}
<div className="mt-2.5 pt-2 border-t border-gray-200 flex flex-wrap items-center justify-between text-[10px] text-gray-700 bg-gray-50 px-3 py-1.5 rounded">
<div className="flex items-center gap-4 flex-wrap">
<div>
<span className="text-gray-500">Report:</span>{" "}
<strong>{report?.title ?? meta.title}</strong>
</div>
{month && (
<div>
<span className="text-gray-500">Period:</span> <strong>{month}</strong>
</div>
)}
{dateFrom && (
<div>
<span className="text-gray-500">From:</span> <strong>{dateFrom}</strong>
</div>
)}
{dateTo && (
<div>
<span className="text-gray-500">To:</span> <strong>{dateTo}</strong>
</div>
)}
<div>
<span className="text-gray-500">Department:</span>{" "}
<strong>
{departmentId
? departments.find((d) => String(d.id) === departmentId)?.name ?? departmentId
: isDeptUser && user?.department_name
? user.department_name
: "All Departments"}
</strong>
</div>
{priority && (
<div>
<span className="text-gray-500">Priority:</span>{" "}
<strong>{priority.toUpperCase()}</strong>
</div>
)}
{callStatus && (
<div>
<span className="text-gray-500">Status:</span>{" "}
<strong>{callStatus.toUpperCase()}</strong>
</div>
)}
</div>
<div className="font-semibold text-gray-900">
Total Records: {report?.rows?.length ?? 0}
</div>
</div>
</div>
{/* Screen Header */}
<div className="no-print flex flex-wrap items-start justify-between gap-4 bg-white border border-gray-200 rounded-xl p-5 shadow-sm">
<div>
<div className="flex items-center gap-2 mb-2">
<Link
to="/reports"
className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-500 hover:text-[#1e3a8a] transition-colors"
>
<ArrowLeft className="h-3.5 w-3.5" />
All Reports
</Link>
<span className="text-gray-300">&bull;</span>
<Badge variant="outline" className="text-[10px] bg-blue-50/60 text-[#1e3a8a] border-blue-200">
{meta.category}
</Badge>
</div>
<h1 className="text-2xl font-bold text-gray-900 tracking-tight">
{report?.title ?? meta.title}
</h1>
<p className="text-sm text-gray-500 mt-1 max-w-2xl leading-relaxed">{meta.description}</p>
</div>
<div className="flex flex-wrap items-center gap-2.5 pt-1">
{key === "monthly-maintenance" && report?.formula_info && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setFormulaOpen((o) => !o)}
className="border-blue-200 text-[#1e3a8a] hover:bg-blue-50 font-medium"
>
<HelpCircle className="h-4 w-4 mr-1.5 text-[#1e3a8a]" />
How this is calculated
</Button>
)}
<Button
type="button"
size="sm"
loading={exporting === "xlsx"}
onClick={() => handleExport("xlsx")}
className="bg-emerald-700 hover:bg-emerald-800 text-white shadow-sm font-medium"
>
<FileSpreadsheet className="h-4 w-4 mr-1.5" />
Export Excel (.xlsx)
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => window.print()}
className="border-gray-300 hover:bg-gray-50 text-gray-700 shadow-sm font-medium"
title="Generates an executive A4 landscape PDF report with official hospital sign-off"
>
<Printer className="h-4 w-4 mr-1.5 text-[#1e3a8a]" />
Print A4 / PDF
</Button>
</div>
</div>
{/* Formula Info Popover / Panel for Monthly Maintenance */}
{key === "monthly-maintenance" && formulaOpen && report?.formula_info && (
<div
role="region"
aria-label="Calculation Formula Explanation"
className="bg-blue-50 border border-blue-200 rounded-xl p-4 text-xs text-blue-950 space-y-2 print-break-inside-avoid"
>
<div className="font-semibold text-sm text-[#1e3a8a] flex items-center gap-1.5">
<HelpCircle className="h-4 w-4" />
Uptime &amp; Downtime Calculation Methodology
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
<div className="bg-white/80 rounded-md p-2 border border-blue-100">
<span className="text-gray-500">Scheduled Hours / Day:</span>{" "}
<strong>{report.formula_info.scheduled_hours_per_day} hrs</strong>
</div>
<div className="bg-white/80 rounded-md p-2 border border-blue-100">
<span className="text-gray-500">Days in Month:</span>{" "}
<strong>{report.formula_info.days_in_month} days</strong>
</div>
<div className="bg-white/80 rounded-md p-2 border border-blue-100">
<span className="text-gray-500">Downtime End Milestone:</span>{" "}
<strong className="font-mono">{report.formula_info.downtime_end_milestone}</strong>
</div>
</div>
<ul className="list-disc pl-5 space-y-1">
<li>
<strong>Uptime Formula:</strong> {report.formula_info.uptime_formula}
</li>
<li>
<strong>Downtime Formula:</strong> {report.formula_info.downtime_formula}
</li>
<li>
<strong>Month-Boundary Clipping:</strong> Each breakdown is clipped to the selected
calendar month in IST (<code>[month_start_IST, next_month_start_IST)</code>), and
distinct calendar downtime days count unique dates covered by those intervals.
</li>
</ul>
</div>
)}
{/* Tailored Filter Bar */}
<div className="no-print bg-white border border-gray-200 rounded-xl p-4 shadow-sm space-y-3">
<div className="flex items-center justify-between border-b border-gray-100 pb-2.5">
<div className="flex items-center gap-2">
<Filter className="h-4 w-4 text-[#1e3a8a]" />
<span className="text-xs font-semibold text-gray-800 uppercase tracking-wider">
Report Parameters &amp; Scope
</span>
{activeFiltersCount > 0 && (
<Badge variant="info" className="text-[10px] px-2 py-0.5">
{activeFiltersCount} active filter{activeFiltersCount > 1 ? "s" : ""}
</Badge>
)}
</div>
{activeFiltersCount > 0 && (
<button
type="button"
onClick={handleResetFilters}
className="text-xs text-gray-500 hover:text-red-600 flex items-center gap-1 transition-colors font-medium"
>
<RotateCcw className="h-3.5 w-3.5" />
Reset filters
</button>
)}
</div>
<div className="flex flex-wrap items-end gap-3.5 pt-0.5">
{(key === "monthly-maintenance" ||
key === "monthly-department" ||
key === "pm-compliance") && (
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Month
</label>
<input
type="month"
aria-label="Month"
value={month}
onChange={(e) => setMonth(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
/>
</div>
)}
{(key === "daily-visit" ||
key === "breakdown-complaints" ||
key === "pm-compliance" ||
key === "demo-equipment") && (
<>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
From Date
</label>
<input
type="date"
aria-label="From Date"
value={dateFrom}
onChange={(e) => setDateFrom(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
/>
</div>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
To Date
</label>
<input
type="date"
aria-label="To Date"
value={dateTo}
onChange={(e) => setDateTo(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
/>
</div>
</>
)}
{key === "calibration-due" && (
<>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Due From
</label>
<input
type="date"
aria-label="Due From"
value={dueFrom}
onChange={(e) => setDueFrom(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
/>
</div>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Due To
</label>
<input
type="date"
aria-label="Due To"
value={dueTo}
onChange={(e) => setDueTo(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
/>
</div>
</>
)}
{!isDeptUser && (
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Department
</label>
<select
aria-label="Department"
value={departmentId}
onChange={(e) => setDepartmentId(e.target.value)}
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>
</div>
)}
{key === "breakdown-complaints" && (
<>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Priority
</label>
<select
aria-label="Priority"
value={priority}
onChange={(e) => setPriority(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Priorities</option>
<option value="critical">Critical</option>
<option value="non_critical">Non-Critical</option>
</select>
</div>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Call Status
</label>
<select
aria-label="Call Status"
value={callStatus}
onChange={(e) => setCallStatus(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Statuses</option>
<option value="open">Open</option>
<option value="in_progress">In Progress</option>
<option value="closed">Closed</option>
</select>
</div>
</>
)}
{key === "pm-compliance" && (
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Service Mode
</label>
<select
aria-label="Service Mode"
value={serviceMode}
onChange={(e) => setServiceMode(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Modes</option>
<option value="in_house">In-House</option>
<option value="outsourced">Outsourced</option>
</select>
</div>
)}
{key === "calibration-due" && (
<>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Calibration Agency
</label>
<select
aria-label="Calibration Agency"
value={agencyId}
onChange={(e) => setAgencyId(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Agencies</option>
{(agencies.length ? agencies : allVendors).map((v) => (
<option key={v.id} value={String(v.id)}>
{v.name}
</option>
))}
</select>
</div>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Status
</label>
<select
aria-label="Calibration Status"
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Statuses</option>
<option value="upcoming">Upcoming</option>
<option value="due">Due</option>
<option value="overdue">Overdue</option>
<option value="completed">Completed</option>
</select>
</div>
</>
)}
{key === "contracts-warranty" && (
<>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Record Kind
</label>
<select
aria-label="Record Kind"
value={recordKind}
onChange={(e) => setRecordKind(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="all">Contracts &amp; Warranties</option>
<option value="contracts">Contracts Only</option>
<option value="warranties">Warranties Only</option>
</select>
</div>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Contract Type
</label>
<select
aria-label="Contract Type"
value={contractType}
onChange={(e) => setContractType(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Types</option>
<option value="AMC">AMC</option>
<option value="CMC">CMC</option>
</select>
</div>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Status
</label>
<select
aria-label="Coverage Status"
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Statuses</option>
<option value="active">Active</option>
<option value="expiring">Expiring</option>
<option value="expired">Expired</option>
<option value="superseded">Superseded</option>
</select>
</div>
</>
)}
{key === "demo-equipment" && (
<>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Supplier
</label>
<select
aria-label="Supplier"
value={supplierId}
onChange={(e) => setSupplierId(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Suppliers</option>
{(suppliers.length ? suppliers : allVendors).map((v) => (
<option key={v.id} value={String(v.id)}>
{v.name}
</option>
))}
</select>
</div>
<div>
<label className="block text-[11px] font-medium text-gray-600 mb-1">
Status
</label>
<select
aria-label="Demo Status"
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Statuses</option>
<option value="on_demo">On Demo</option>
<option value="overdue_return">Overdue Return</option>
<option value="returned">Returned</option>
</select>
</div>
</>
)}
</div>
</div>
{/* Summary Strip */}
{report && (
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 print-break-inside-avoid">
{key === "monthly-maintenance" && (
<div className="bg-white border border-emerald-300 border-t-4 border-t-emerald-600 rounded-xl p-3.5 shadow-sm">
<div className="text-[11px] font-semibold text-emerald-800 uppercase tracking-wider">
Uptime %
</div>
<div className="text-2xl font-black text-emerald-900 mt-1 truncate">
{computeUptimePct(report.summary)}
</div>
<div className="text-[10px] text-emerald-700 mt-0.5">Hospital Availability</div>
</div>
)}
{Object.entries(report.summary).map(([sKey, sVal]) => {
const isNegative = sKey.includes("downtime") || sKey.includes("overdue") || sKey.includes("under_repair");
const isPositive = sKey.includes("uptime") || sKey.includes("compliance") || sKey.includes("completed");
const borderTopColor = isNegative
? "border-t-rose-500"
: isPositive
? "border-t-emerald-500"
: "border-t-[#1e3a8a]";
return (
<div
key={sKey}
className={cn(
"bg-white border border-gray-200 border-t-4 rounded-xl p-3.5 shadow-sm",
borderTopColor
)}
>
<div className="text-[11px] font-medium text-gray-500 truncate">
{humanizeSummaryKey(sKey)}
</div>
<div className="text-xl font-bold text-gray-900 mt-1 truncate">
{String(sVal)}
</div>
</div>
);
})}
</div>
)}
{/* Monthly Maintenance Charts */}
{key === "monthly-maintenance" &&
report?.chart_data &&
report.chart_data.length > 0 && (
<div className="grid grid-cols-1 lg:grid-cols-12 gap-4 print-break-inside-avoid">
<div className="lg:col-span-8 bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
<h2 className="text-sm font-semibold text-gray-800 mb-3">
Department Uptime vs Downtime (Hours)
</h2>
<div className="h-64">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={report.chart_data}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis dataKey="department" tick={{ fontSize: 11 }} />
<YAxis tick={{ fontSize: 11 }} />
<Tooltip
contentStyle={{
backgroundColor: "#ffffff",
borderColor: "#cbd5e1",
borderRadius: "8px",
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",
fontSize: "12px",
}}
/>
<Legend wrapperStyle={{ fontSize: "12px", paddingTop: "8px" }} />
<Bar
dataKey="uptime_hours"
name="Uptime (hrs)"
fill="#10b981"
radius={[4, 4, 0, 0]}
/>
<Bar
dataKey="downtime_hours"
name="Downtime (hrs)"
fill="#f43f5e"
radius={[4, 4, 0, 0]}
/>
</BarChart>
</ResponsiveContainer>
</div>
</div>
<div className="lg:col-span-4 bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
<h2 className="text-sm font-semibold text-gray-800 mb-3">
Hospital Uptime Share
</h2>
<div className="h-64">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={pieData}
dataKey="value"
nameKey="name"
cx="50%"
cy="50%"
innerRadius={48}
outerRadius={78}
>
{pieData.map((entry, idx) => (
<Cell key={idx} fill={entry.color} />
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: "#ffffff",
borderColor: "#cbd5e1",
borderRadius: "8px",
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",
fontSize: "12px",
}}
/>
<Legend wrapperStyle={{ fontSize: "12px", paddingTop: "8px" }} />
</PieChart>
</ResponsiveContainer>
</div>
</div>
</div>
)}
{/* Report DataTable */}
<DataTable
data={report?.rows ?? []}
columns={columns}
loading={reportQuery.isLoading}
globalFilterPlaceholder="Quick filter report rows..."
emptyMessage="No rows match the selected report filters."
/>
{/* Hospital Tripartite Sign-off Block (Print / PDF Only) */}
<div className="print-only mt-8 pt-4 border-t-2 border-gray-300 print-break-inside-avoid">
<div className="flex items-center justify-between text-[10px] font-bold uppercase tracking-wider text-gray-700 mb-4">
<span>Hospital Engineering Audit &amp; Verification Sign-off (NABH Chapter FMS)</span>
<span>XYZ Hospital</span>
</div>
<div className="grid grid-cols-3 gap-5 text-[10px]">
<div className="border border-gray-300 rounded p-3 space-y-4 bg-gray-50/50">
<div className="font-bold text-gray-800">1. PREPARED BY</div>
<div className="h-9 border-b border-dashed border-gray-400"></div>
<div className="space-y-0.5 text-gray-600">
<div>Name: {user?.name || "Biomedical Engineer"}</div>
<div>Role: {user?.role?.replace(/_/g, " ").toUpperCase() || "BIOMEDICAL"}</div>
<div>Date: {new Date().toLocaleDateString("en-IN")}</div>
</div>
</div>
<div className="border border-gray-300 rounded p-3 space-y-4 bg-gray-50/50">
<div className="font-bold text-gray-800">2. VERIFIED BY</div>
<div className="h-9 border-b border-dashed border-gray-400"></div>
<div className="space-y-0.5 text-gray-600">
<div>Name: __________________________</div>
<div>Role: HOD / Biomedical In-Charge</div>
<div>Date: ____ / ____ / ________</div>
</div>
</div>
<div className="border border-gray-300 rounded p-3 space-y-4 bg-gray-50/50">
<div className="font-bold text-gray-800">3. APPROVED BY</div>
<div className="h-9 border-b border-dashed border-gray-400"></div>
<div className="space-y-0.5 text-gray-600">
<div>Name: __________________________</div>
<div>Role: Medical Superintendent / Director</div>
<div>Date: ____ / ____ / ________</div>
</div>
</div>
</div>
<div className="mt-4 pt-2 border-t border-gray-200 text-[9px] text-gray-500 flex items-center justify-between">
<span>Official Hospital Record &bull; XYZ Hospital &bull; Confidential &bull; Retain for 7 Years</span>
<span>AMS Portal Generated &bull; NABH Compliant</span>
</div>
</div>
</div>
);
}