phase-7: 8 operational reports, excel and csv exports, and print styles

This commit is contained in:
Atharv1705
2026-11-12 14:49:52 +05:30
parent aec1b6ad41
commit 0b0f550eff
16 changed files with 2714 additions and 6 deletions
+3 -1
View File
@@ -19,7 +19,8 @@ import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
import { VisitsPage } from "@/pages/VisitsPage";
import { DashboardPage } from "@/pages/DashboardPage";
import { NotificationsPage } from "@/pages/NotificationsPage";
import { ReportsPage } from "@/pages/stubs";
import { ReportsPage } from "@/pages/ReportsPage";
import { ReportDetailPage } from "@/pages/ReportDetailPage";
import { ToastProvider } from "@/components/ToastProvider";
import { useAuthStore } from "@/hooks/useAuth";
import { can, type Capability } from "@/lib/permissions";
@@ -99,6 +100,7 @@ function AppRoutes() {
}
/>
<Route path="/reports" element={<ReportsPage />} />
<Route path="/reports/:reportKey" element={<ReportDetailPage />} />
<Route path="/notifications" element={<NotificationsPage />} />
<Route
path="/masters"
+143
View File
@@ -0,0 +1,143 @@
import { api } from "./client";
import type { Role } from "@/lib/permissions";
export type ReportKey =
| "monthly-maintenance"
| "monthly-department"
| "daily-visit"
| "breakdown-complaints"
| "pm-compliance"
| "calibration-due"
| "contracts-warranty"
| "demo-equipment";
export interface ReportColumn {
key: string;
label: string;
}
export interface FormulaInfo {
scheduled_hours_per_day: number;
downtime_end_milestone: string;
days_in_month: number;
uptime_formula: string;
downtime_formula: string;
}
export interface ReportChartPoint {
department: string;
downtime_hours: number;
uptime_hours: number;
}
export interface ReportPayload {
report_key: ReportKey | string;
title: string;
filters_applied: Record<string, string | number | null>;
formula_info?: FormulaInfo | null;
summary: Record<string, string | number>;
columns: ReportColumn[];
rows: Record<string, unknown>[];
chart_data?: ReportChartPoint[] | null;
}
export interface ReportMeta {
key: ReportKey;
title: string;
description: string;
category: string;
hiddenForRoles?: Role[];
}
export const REPORT_CATALOG: ReportMeta[] = [
{
key: "monthly-maintenance",
title: "Monthly Maintenance Summary",
description:
"Department-wise uptime vs downtime, clipped breakdown hours, distinct downtime days, and availability %.",
category: "Maintenance & Uptime",
},
{
key: "monthly-department",
title: "Monthly Department Report",
description:
"Asset health counts, under-repair equipment, outstanding complaints, visit counts, and requirement notes per department.",
category: "Department Operations",
},
{
key: "daily-visit",
title: "Daily Department Visit Report",
description:
"Daily biomedical round logs, equipment checked, observations, and linked breakdown complaints.",
category: "Department Operations",
hiddenForRoles: ["department_user", "coordinator"],
},
{
key: "breakdown-complaints",
title: "Breakdown / Complaint Report",
description:
"Full breakdown register with response time, total downtime, ongoing status, action taken, and closure remarks.",
category: "Breakdowns",
},
{
key: "pm-compliance",
title: "PM Compliance Report",
description:
"Planned vs completed preventive maintenance schedules across in-house and outsourced teams with compliance %.",
category: "Compliance & Schedules",
},
{
key: "calibration-due",
title: "Calibration Due Report",
description:
"Calibration status, due/completed dates, agencies, certificate numbers, and overdue tracking.",
category: "Compliance & Schedules",
},
{
key: "contracts-warranty",
title: "AMC / CMC & Warranty Report",
description:
"Active, expiring, expired, and superseded AMC/CMC contracts and equipment warranties with days to expiry.",
category: "Commercial & Coverage",
},
{
key: "demo-equipment",
title: "Demo Equipment Report",
description:
"Supplier trial equipment register highlighting expected return dates, returned units, and overdue days.",
category: "Commercial & Coverage",
},
];
export type ReportFilterParams = Record<string, string | number | undefined>;
function buildQuery(params: ReportFilterParams): string {
const sp = new URLSearchParams();
for (const [k, v] of Object.entries(params)) {
if (v === undefined || v === "") continue;
sp.set(k, String(v));
}
const qs = sp.toString();
return qs ? `?${qs}` : "";
}
export function fetchReport(key: ReportKey, params: ReportFilterParams = {}) {
return api.get<ReportPayload>(`/reports/${key}${buildQuery(params)}`);
}
export async function exportReport(
key: ReportKey,
format: "xlsx" | "csv",
params: ReportFilterParams = {}
) {
const qs = buildQuery({ ...params, format });
const { blob } = await api.downloadBlob(`/reports/${key}/export${qs}`);
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${key}.${format}`;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 10_000);
}
+41
View File
@@ -10,3 +10,44 @@
@apply bg-gray-50 text-gray-900 antialiased;
}
}
@media print {
@page {
size: A4 landscape;
margin: 12mm;
}
aside,
header,
.no-print {
display: none !important;
}
body {
background: #ffffff !important;
color: #111827 !important;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
main {
padding: 0 !important;
overflow: visible !important;
}
table {
border-collapse: collapse !important;
width: 100% !important;
}
th,
td {
border: 1px solid #d1d5db !important;
font-size: 10px !important;
padding: 4px 6px !important;
}
.print-break-inside-avoid {
break-inside: avoid;
}
}
+804
View File
@@ -0,0 +1,804 @@
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,
Download,
FileSpreadsheet,
Printer,
HelpCircle,
AlertCircle,
Lock,
} 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 { toast } from "@/components/ToastProvider";
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())
);
}
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 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 [];
return 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);
},
}));
}, [report]);
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 Letterhead */}
<div className="hidden print:flex items-center justify-between border-b-2 border-[#1e3a8a] pb-3 mb-4">
<div className="flex items-center gap-3">
<img
src="/logo.jpg"
alt="Poona Hospital and Research Centre"
className="h-12 w-12 object-contain"
/>
<div>
<div className="text-base font-bold text-[#1e3a8a]">
Poona Hospital &amp; Research Centre
</div>
<div className="text-xs text-gray-600">
Asset Management &amp; Maintenance — {report?.title ?? meta.title}
</div>
</div>
</div>
<div className="text-right text-[11px] text-gray-500">
<div>Printed: {formatDateTime(new Date().toISOString())} IST</div>
{user?.name && <div>Generated by: {user.name}</div>}
</div>
</div>
{/* Screen Header */}
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<Link
to="/reports"
className="no-print inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-800 mb-1"
>
<ArrowLeft className="h-4 w-4" />
All Reports
</Link>
<h1 className="text-2xl font-bold text-gray-900">
{report?.title ?? meta.title}
</h1>
<p className="text-sm text-gray-500 mt-0.5">{meta.description}</p>
</div>
<div className="no-print flex flex-wrap items-center gap-2">
{key === "monthly-maintenance" && report?.formula_info && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setFormulaOpen((o) => !o)}
>
<HelpCircle className="h-4 w-4 mr-1.5 text-[#1e3a8a]" />
How this is calculated
</Button>
)}
<Button
type="button"
variant="outline"
size="sm"
loading={exporting === "csv"}
onClick={() => handleExport("csv")}
>
<Download className="h-4 w-4 mr-1.5" />
Export CSV (.csv)
</Button>
<Button
type="button"
size="sm"
loading={exporting === "xlsx"}
onClick={() => handleExport("xlsx")}
>
<FileSpreadsheet className="h-4 w-4 mr-1.5" />
Export Excel (.xlsx)
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => window.print()}
>
<Printer className="h-4 w-4 mr-1.5" />
Print A4
</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-lg p-3.5 flex flex-wrap items-end gap-3">
{(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>
{/* Summary Strip */}
{report && (
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2.5 print-break-inside-avoid">
{Object.entries(report.summary).map(([sKey, sVal]) => (
<div
key={sKey}
className="bg-white border border-gray-200 rounded-lg p-3"
>
<div className="text-[11px] font-medium text-gray-500">
{humanizeSummaryKey(sKey)}
</div>
<div className="text-lg font-bold text-gray-900 mt-0.5 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 />
<Legend />
<Bar
dataKey="uptime_hours"
name="Uptime (hrs)"
fill="#22c55e"
radius={[4, 4, 0, 0]}
/>
<Bar
dataKey="downtime_hours"
name="Downtime (hrs)"
fill="#ef4444"
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 />
<Legend />
</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."
/>
</div>
);
}
+90
View File
@@ -0,0 +1,90 @@
import { Link } from "react-router-dom";
import {
BarChart3,
Building2,
ClipboardCheck,
AlertTriangle,
CalendarCheck,
Gauge,
FileSpreadsheet,
Truck,
ArrowRight,
} from "lucide-react";
import { REPORT_CATALOG, type ReportKey } from "@/api/reports";
import { useAuthStore } from "@/hooks/useAuth";
import { Badge } from "@/components/ui/badge";
const REPORT_ICONS: Record<ReportKey, React.ComponentType<{ className?: string }>> = {
"monthly-maintenance": BarChart3,
"monthly-department": Building2,
"daily-visit": ClipboardCheck,
"breakdown-complaints": AlertTriangle,
"pm-compliance": CalendarCheck,
"calibration-due": Gauge,
"contracts-warranty": FileSpreadsheet,
"demo-equipment": Truck,
};
export function ReportsPage() {
const user = useAuthStore((s) => s.user);
const role = user?.role;
const visibleReports = REPORT_CATALOG.filter(
(r) => !role || !r.hiddenForRoles?.includes(role)
);
return (
<div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-gray-900">Reports &amp; Exports</h1>
<p className="text-sm text-gray-500 mt-0.5">
Operational reports with live filters, Excel (.xlsx) &amp; CSV downloads, and A4 print layout
</p>
</div>
{role === "department_user" && user?.department_name && (
<Badge variant="info">
Department Scope: {user.department_name}
</Badge>
)}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
{visibleReports.map((report) => {
const Icon = REPORT_ICONS[report.key] ?? BarChart3;
return (
<Link
key={report.key}
to={`/reports/${report.key}`}
className="group bg-white border border-gray-200 rounded-xl p-5 shadow-sm hover:shadow-md hover:border-[#1e3a8a]/40 transition-all flex flex-col justify-between"
>
<div className="space-y-3">
<div className="flex items-start justify-between gap-2">
<div className="h-10 w-10 rounded-lg bg-blue-50 border border-blue-100 flex items-center justify-center text-[#1e3a8a]">
<Icon className="h-5 w-5" />
</div>
<Badge variant="outline" className="text-[10px]">
{report.category}
</Badge>
</div>
<div>
<h2 className="text-base font-semibold text-gray-900 group-hover:text-[#1e3a8a] transition-colors">
{report.title}
</h2>
<p className="text-xs text-gray-600 mt-1 leading-relaxed">
{report.description}
</p>
</div>
</div>
<div className="mt-4 pt-3 border-t border-gray-100 flex items-center justify-between text-xs font-medium text-[#1e3a8a]">
<span>Open Report</span>
<ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5" />
</div>
</Link>
);
})}
</div>
</div>
);
}
+184
View File
@@ -0,0 +1,184 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReportsPage } from "@/pages/ReportsPage";
import { ReportDetailPage } from "@/pages/ReportDetailPage";
import * as reportsApi from "@/api/reports";
import { departmentsApi } from "@/api/masters";
import { useAuthStore } from "@/hooks/useAuth";
vi.mock("recharts", async () => {
const actual = await vi.importActual<typeof import("recharts")>("recharts");
return {
...actual,
ResponsiveContainer: ({ children }: { children: React.ReactNode }) => (
<div style={{ width: 600, height: 240 }}>{children}</div>
),
};
});
function renderWithRouter(ui: React.ReactNode, initialEntries = ["/"]) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={qc}>
<MemoryRouter initialEntries={initialEntries}>{ui}</MemoryRouter>
</QueryClientProvider>
);
}
describe("Phase 7 Reports", () => {
beforeEach(() => {
vi.restoreAllMocks();
vi.spyOn(departmentsApi, "list").mockResolvedValue({
items: [{ id: 1, name: "ICU", code: "ICU", description: null, is_active: true }],
total: 1,
});
});
it("ReportsPage renders all 8 reports for management and hides Daily Department Visit Report for department_user", () => {
useAuthStore.setState({
user: {
id: 5,
email: "mgmt@poona.org",
name: "Director",
role: "management",
department_id: null,
department_name: null,
is_active: true,
},
token: "t-mgmt",
});
const { rerender } = renderWithRouter(<ReportsPage />);
expect(screen.getByText("Monthly Maintenance Summary")).toBeInTheDocument();
expect(screen.getByText("Daily Department Visit Report")).toBeInTheDocument();
expect(screen.getByText("Demo Equipment Report")).toBeInTheDocument();
useAuthStore.setState({
user: {
id: 3,
email: "icu@poona.org",
name: "ICU Nurse",
role: "department_user",
department_id: 1,
department_name: "ICU",
is_active: true,
},
token: "t-dept",
});
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
rerender(
<QueryClientProvider client={qc}>
<MemoryRouter>
<ReportsPage />
</MemoryRouter>
</QueryClientProvider>
);
expect(screen.getByText("Monthly Maintenance Summary")).toBeInTheDocument();
expect(
screen.queryByText("Daily Department Visit Report")
).not.toBeInTheDocument();
});
it("ReportDetailPage renders Monthly Maintenance summary, How this is calculated popover, and Export Excel button", async () => {
useAuthStore.setState({
user: {
id: 5,
email: "mgmt@poona.org",
name: "Director",
role: "management",
department_id: null,
department_name: null,
is_active: true,
},
token: "t-mgmt",
});
vi.spyOn(reportsApi, "fetchReport").mockResolvedValue({
report_key: "monthly-maintenance",
title: "Monthly Maintenance Summary",
filters_applied: { month: "2026-11" },
formula_info: {
scheduled_hours_per_day: 24,
downtime_end_milestone: "restored_at",
days_in_month: 30,
uptime_formula: "Scheduled Minutes - Clipped Downtime Minutes",
downtime_formula: "Sum of breakdown intervals clipped to month in IST",
},
summary: {
total_assets: 10,
total_complaints: 3,
downtime_formatted: "1d 2h 0m",
downtime_days_count: 3,
uptime_formatted: "298d 22h 0m",
downtime_pct: 0.36,
},
columns: [
{ key: "department_name", label: "Department" },
{ key: "asset_count", label: "Assets" },
{ key: "downtime_formatted", label: "Downtime" },
{ key: "downtime_pct", label: "Downtime %" },
],
rows: [
{
department_name: "ICU",
asset_count: 10,
downtime_formatted: "1d 2h 0m",
downtime_pct: 0.36,
},
],
chart_data: [
{ department: "ICU", downtime_hours: 26, uptime_hours: 7174 },
],
});
const exportSpy = vi
.spyOn(reportsApi, "exportReport")
.mockResolvedValue(undefined);
renderWithRouter(
<Routes>
<Route path="/reports/:reportKey" element={<ReportDetailPage />} />
</Routes>,
["/reports/monthly-maintenance"]
);
await waitFor(() => {
expect(
screen.getByRole("heading", { name: /Monthly Maintenance Summary/i })
).toBeInTheDocument();
expect(screen.getByText("Distinct Downtime Days")).toBeInTheDocument();
expect(screen.getByRole("cell", { name: "ICU" })).toBeInTheDocument();
});
const formulaBtn = screen.getByRole("button", {
name: /How this is calculated/i,
});
fireEvent.click(formulaBtn);
await waitFor(() => {
expect(
screen.getByText(/Uptime & Downtime Calculation Methodology/i)
).toBeInTheDocument();
expect(screen.getByText(/24 hrs/i)).toBeInTheDocument();
expect(screen.getByText(/30 days/i)).toBeInTheDocument();
expect(screen.getByText("restored_at")).toBeInTheDocument();
});
const exportXlsxBtn = screen.getByRole("button", {
name: /Export Excel \(\.xlsx\)/i,
});
fireEvent.click(exportXlsxBtn);
await waitFor(() => {
expect(exportSpy).toHaveBeenCalledWith(
"monthly-maintenance",
"xlsx",
expect.any(Object)
);
});
});
});
+3 -3
View File
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { Sidebar } from "@/components/layout/Sidebar";
import { ReportsPage } from "@/pages/stubs";
import { ReportsPage } from "@/pages/ReportsPage";
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
import { useAuthStore } from "@/hooks/useAuth";
@@ -100,14 +100,14 @@ describe("Phase 1 Frontend Smoke Tests", () => {
expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument();
});
it("renders ReportsPage stub coming in Phase 7", () => {
it("renders ReportsPage catalog cards", () => {
render(
<MemoryRouter>
<ReportsPage />
</MemoryRouter>
);
expect(screen.getByText("Reports & Exports")).toBeInTheDocument();
expect(screen.getByText(/Coming in Phase 7/i)).toBeInTheDocument();
expect(screen.getByText("Monthly Maintenance Summary")).toBeInTheDocument();
});
it("renders DataTableDemoPage with mock rows", () => {