From 0b0f550eff36acbc4e84f06c605537bc44a47b9d Mon Sep 17 00:00:00 2001 From: Atharv1705 Date: Thu, 12 Nov 2026 14:49:52 +0530 Subject: [PATCH] phase-7: 8 operational reports, excel and csv exports, and print styles --- README.md | 3 +- backend/app/main.py | 2 + backend/app/routers/__init__.py | 2 + backend/app/routers/reports.py | 87 ++ backend/app/services/exports.py | 108 +++ backend/app/services/reports_service.py | 990 +++++++++++++++++++++++ backend/app/services/settings_service.py | 10 + backend/tests/test_reports.py | 244 ++++++ frontend/src/App.tsx | 4 +- frontend/src/api/reports.ts | 143 ++++ frontend/src/index.css | 41 + frontend/src/pages/ReportDetailPage.tsx | 804 ++++++++++++++++++ frontend/src/pages/ReportsPage.tsx | 90 +++ frontend/src/test/reports.test.tsx | 184 +++++ frontend/src/test/smoke.test.tsx | 6 +- frontend/tsconfig.tsbuildinfo | 2 +- 16 files changed, 2714 insertions(+), 6 deletions(-) create mode 100644 backend/app/routers/reports.py create mode 100644 backend/app/services/exports.py create mode 100644 backend/app/services/reports_service.py create mode 100644 backend/tests/test_reports.py create mode 100644 frontend/src/api/reports.ts create mode 100644 frontend/src/pages/ReportDetailPage.tsx create mode 100644 frontend/src/pages/ReportsPage.tsx create mode 100644 frontend/src/test/reports.test.tsx diff --git a/README.md b/README.md index 0758e69..3f3dbb6 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ cd backend | mgmt@poona.demo | Demo@123 | Management | | coord@poona.demo | Demo@123 | Coordinator | -## What exists now (Phase 6) +## What exists now (Phase 7) - Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules - JWT authentication (`/api/auth/login`, `/api/auth/me`), RBAC permission matrix for 5 roles, and Quick Demo Login - Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users) @@ -73,6 +73,7 @@ cd backend - Department Visits (`/visits`): biomedical/admin round logs with management read access (403 for `department_user` and `coordinator`), department-filtered multi-asset checklist, observations, and complaint creation/linking (`POST /api/visits/:id/link-complaint`) - Alert Engine, Scheduler & Notifications (`/notifications` + TopBar Bell & Calibration Login Pop-up): APScheduler `06:00 Asia/Kolkata` daily job using short-lived `get_scheduler_db()`, deduplicated 7-type alerts (`amc_expiry`, `calibration_due`, `pm_due`, `insurance_expiry`, `warranty_expiry`, `demo_overdue`, `critical_complaint`) evaluated against `effective_today()`/`effective_now_utc()`, per-user `NotificationRead` state with `department_user` entity-department filtering, 60s bell polling with live toast alerts, and once-per-login `CalibrationReminderModal` - Hospital Operations Dashboard (`/`): role-aware `department_scope` banner, 7 clickable KPI cards, 4 Recharts visualizations (Complaints by Status, Complaints by Department, 6-month `clip_downtime_to_month` Downtime Trend, PM Planned vs Completed), `"Needs Attention"` red alerts panel, and `"Recent Complaints"` table +- 8 Operational Reports & Exports (`/reports` & `/reports/:reportKey`): Monthly Maintenance (with `clip_downtime_to_month` uptime/downtime hours, `"How this is calculated"` `formula_info` panel, and Recharts BarChart + PieChart), Monthly Department, Daily Department Visit (403 for `department_user` & `coordinator`), Breakdown & Complaints, PM Compliance, Calibration Due, AMC/CMC & Warranty, and Demo Equipment reports; tailored filters, styled openpyxl Excel (`.xlsx`) & UTF-8 BOM CSV (`.csv`) exports (`/api/reports/{report_key}/export`), and A4 `@media print` styles (`no-print` / `print-header`) - Reusable `AssetPicker` (`/api/assets/lookup`) with warranty/condemned status badges - Secure Document Attachments (`/api/attachments`: JPG/PNG/PDF validation with magic-byte check, 10 MB limit, authenticated preview/download, role-based upload/delete) - Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data diff --git a/backend/app/main.py b/backend/app/main.py index 740a7e2..feda783 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -25,6 +25,7 @@ from .routers import ( masters, notifications, pm, + reports, settings, users, visits, @@ -124,3 +125,4 @@ app.include_router(demo_equipment.router, prefix="/api") app.include_router(visits.router, prefix="/api") app.include_router(notifications.router, prefix="/api") app.include_router(dashboard.router, prefix="/api") +app.include_router(reports.router, prefix="/api") diff --git a/backend/app/routers/__init__.py b/backend/app/routers/__init__.py index efcb2ca..a16718c 100644 --- a/backend/app/routers/__init__.py +++ b/backend/app/routers/__init__.py @@ -12,6 +12,7 @@ from . import ( masters, notifications, pm, + reports, settings, users, visits, @@ -32,6 +33,7 @@ __all__ = [ "masters", "notifications", "pm", + "reports", "settings", "users", "visits", diff --git a/backend/app/routers/reports.py b/backend/app/routers/reports.py new file mode 100644 index 0000000..2e402e0 --- /dev/null +++ b/backend/app/routers/reports.py @@ -0,0 +1,87 @@ +from datetime import date +from typing import Any, Literal + +from fastapi import APIRouter, Depends, Query +from fastapi.responses import StreamingResponse +from sqlalchemy.orm import Session + +from ..core.db import get_db +from ..core.deps import get_current_user +from ..models import User +from ..services.exports import build_csv, build_xlsx +from ..services.reports_service import generate_report + +router = APIRouter(prefix="/reports", tags=["reports"]) + + +def _report_params( + month: str | None = Query(None), + date_from: date | None = Query(None), + date_to: date | None = Query(None), + due_from: date | None = Query(None), + due_to: date | None = Query(None), + department_id: int | None = Query(None), + asset_id: int | None = Query(None), + priority: str | None = Query(None), + call_status: str | None = Query(None), + assigned_to_id: int | None = Query(None), + service_mode: str | None = Query(None), + agency_id: int | None = Query(None), + status: str | None = Query(None), + record_kind: str | None = Query(None), + contract_type: str | None = Query(None), + supplier_id: int | None = Query(None), +) -> dict[str, Any]: + return { + "month": month, + "date_from": date_from, + "date_to": date_to, + "due_from": due_from, + "due_to": due_to, + "department_id": department_id, + "asset_id": asset_id, + "priority": priority, + "call_status": call_status, + "assigned_to_id": assigned_to_id, + "service_mode": service_mode, + "agency_id": agency_id, + "status": status, + "record_kind": record_kind, + "contract_type": contract_type, + "supplier_id": supplier_id, + } + + +@router.get("/{report_key}") +def get_report( + report_key: str, + params: dict[str, Any] = Depends(_report_params), + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +): + return generate_report(db, current_user, report_key, params) + + +@router.get("/{report_key}/export") +def export_report( + report_key: str, + format: Literal["xlsx", "csv"] = Query("xlsx"), + params: dict[str, Any] = Depends(_report_params), + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +): + payload = generate_report(db, current_user, report_key, params) + if format == "csv": + buf = build_csv(payload) + media_type = "text/csv; charset=utf-8" + else: + buf = build_xlsx(payload) + media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + + return StreamingResponse( + buf, + media_type=media_type, + headers={ + "Content-Disposition": f'attachment; filename="{report_key}.{format}"', + }, + ) diff --git a/backend/app/services/exports.py b/backend/app/services/exports.py new file mode 100644 index 0000000..7de5971 --- /dev/null +++ b/backend/app/services/exports.py @@ -0,0 +1,108 @@ +import csv +from io import BytesIO, StringIO +from typing import Any +from openpyxl import Workbook +from openpyxl.styles import Alignment, Font, PatternFill +from openpyxl.utils import get_column_letter + +from ..core.time_utils import format_datetime, utc_now + + +def _format_filters_echo(filters_applied: dict[str, Any]) -> str: + if not filters_applied: + return "None" + return ", ".join(f"{k}={v}" for k, v in filters_applied.items()) + + +def _format_summary_echo(summary: dict[str, Any]) -> str: + if not summary: + return "" + return " | ".join(f"{k.replace('_', ' ').title()}: {v}" for k, v in summary.items()) + + +def build_xlsx(report_payload: dict[str, Any]) -> BytesIO: + wb = Workbook() + ws = wb.active + ws.title = report_payload["title"][:31] + + title_text = f"Poona Hospital & Research Centre \u2014 {report_payload['title']}" + meta_text = ( + f"Generated: {format_datetime(utc_now())} IST | " + f"Filters: {_format_filters_echo(report_payload.get('filters_applied', {}))}" + ) + summary_text = _format_summary_echo(report_payload.get("summary", {})) + + ws.cell(row=1, column=1, value=title_text).font = Font(name="Calibri", size=14, bold=True, color="0F172A") + ws.cell(row=2, column=1, value=meta_text).font = Font(name="Calibri", size=10, color="475569") + ws.cell(row=3, column=1, value=summary_text).font = Font(name="Calibri", size=10, bold=True, color="1E3A8A") + + columns: list[dict[str, str]] = report_payload.get("columns", []) + rows: list[dict[str, Any]] = report_payload.get("rows", []) + + header_fill = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid") + header_font = Font(name="Calibri", size=11, bold=True, color="FFFFFF") + + header_row = 5 + col_widths: list[int] = [] + for c_idx, col in enumerate(columns, start=1): + cell = ws.cell(row=header_row, column=c_idx, value=col["label"]) + cell.fill = header_fill + cell.font = header_font + cell.alignment = Alignment(horizontal="left", vertical="center") + col_widths.append(len(str(col["label"]))) + + ws.freeze_panes = "A6" + + for r_offset, row_data in enumerate(rows): + excel_row = header_row + 1 + r_offset + for c_idx, col in enumerate(columns, start=1): + val = row_data.get(col["key"]) + if isinstance(val, bool): + val = "Yes" if val else "No" + ws.cell(row=excel_row, column=c_idx, value=val) + val_len = len(str(val)) if val is not None else 0 + if val_len > col_widths[c_idx - 1]: + col_widths[c_idx - 1] = val_len + + for c_idx, width in enumerate(col_widths, start=1): + ws.column_dimensions[get_column_letter(c_idx)].width = min(45, max(12, width + 3)) + + buf = BytesIO() + wb.save(buf) + buf.seek(0) + return buf + + +def build_csv(report_payload: dict[str, Any]) -> BytesIO: + sio = StringIO() + writer = csv.writer(sio) + + writer.writerow([f"Poona Hospital & Research Centre - {report_payload['title']}"]) + writer.writerow( + [ + f"Generated: {format_datetime(utc_now())} IST", + f"Filters: {_format_filters_echo(report_payload.get('filters_applied', {}))}", + ] + ) + summary_text = _format_summary_echo(report_payload.get("summary", {})) + if summary_text: + writer.writerow([f"Summary: {summary_text}"]) + writer.writerow([]) + + columns: list[dict[str, str]] = report_payload.get("columns", []) + rows: list[dict[str, Any]] = report_payload.get("rows", []) + + writer.writerow([col["label"] for col in columns]) + for row_data in rows: + out_row = [] + for col in columns: + val = row_data.get(col["key"]) + if isinstance(val, bool): + val = "Yes" if val else "No" + out_row.append("" if val is None else val) + writer.writerow(out_row) + + data = sio.getvalue().encode("utf-8-sig") + buf = BytesIO(data) + buf.seek(0) + return buf diff --git a/backend/app/services/reports_service.py b/backend/app/services/reports_service.py new file mode 100644 index 0000000..2a53d38 --- /dev/null +++ b/backend/app/services/reports_service.py @@ -0,0 +1,990 @@ +import calendar +from datetime import date, datetime, time, timedelta, timezone +import re +from typing import Any, Callable, Optional +from fastapi import HTTPException, status +from sqlalchemy.orm import Session, joinedload + +from ..core.time_utils import ( + KOLKATA, + add_months, + effective_now_utc, + effective_today, + format_date, + format_datetime, + format_duration, +) +from ..models import ( + Asset, + CalibrationPlan, + CalibrationRecord, + Complaint, + Contract, + DemoEquipment, + Department, + DepartmentVisit, + PMRecord, + PMSchedule, + User, + Warranty, +) +from .attachment_service import get_attachment_counts +from .calculations import ( + clip_downtime_to_month, + compute_downtime_minutes, + compute_response_time_minutes, + compute_schedule_status, + coverage_status, +) +from .permissions import Role +from .settings_service import get_setting_value + +_MONTH_RE = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$") + + +def _parse_month(month_str: Optional[str], fallback_today: date) -> tuple[str, int, int]: + clean = month_str.strip() if month_str and month_str.strip() else fallback_today.strftime("%Y-%m") + match = _MONTH_RE.fullmatch(clean) + if not match: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="month must be in YYYY-MM format.", + ) + return clean, int(match.group(1)), int(match.group(2)) + + +def _scoped_dept_id(user: User, requested_dept_id: Optional[int]) -> Optional[int]: + if user.role == Role.department_user.value: + return user.department_id + return requested_dept_id + + +def _clean_filters(**kwargs: Any) -> dict[str, Any]: + out: dict[str, Any] = {} + for k, v in kwargs.items(): + if v is None or v == "": + continue + out[k] = str(v) if isinstance(v, date) else v + return out + + +def _build_monthly_maintenance( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + eff_now = effective_now_utc(db) + month_str, year, month = _parse_month(params.get("month"), today) + dept_id = _scoped_dept_id(user, params.get("department_id")) + asset_id = params.get("asset_id") + + days_in_month = calendar.monthrange(year, month)[1] + sched_hours = int(get_setting_value(db, "scheduled_hours_per_day", 24)) + milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at")) + sched_mins_per_asset = days_in_month * sched_hours * 60 + + dept_q = db.query(Department).filter(Department.is_active.is_(True)) + if dept_id is not None: + dept_q = dept_q.filter(Department.id == dept_id) + departments = dept_q.order_by(Department.name.asc()).all() + dept_by_id = {d.id: d for d in departments} + + asset_q = db.query(Asset).filter(Asset.status != "condemned") + if dept_id is not None: + asset_q = asset_q.filter(Asset.department_id == dept_id) + if asset_id is not None: + asset_q = asset_q.filter(Asset.id == asset_id) + assets = asset_q.all() + + asset_count_by_dept: dict[int, int] = {} + for a in assets: + asset_count_by_dept[a.department_id] = asset_count_by_dept.get(a.department_id, 0) + 1 + if a.department_id not in dept_by_id: + dept_obj = db.query(Department).filter(Department.id == a.department_id).first() + if dept_obj: + dept_by_id[dept_obj.id] = dept_obj + + cmp_q = db.query(Complaint).join(Asset, Complaint.asset_id == Asset.id).options(joinedload(Complaint.asset)) + if dept_id is not None: + cmp_q = cmp_q.filter(Asset.department_id == dept_id) + if asset_id is not None: + cmp_q = cmp_q.filter(Complaint.asset_id == asset_id) + complaints = cmp_q.all() + + dt_mins_by_dept: dict[int, int] = {} + cmp_count_by_dept: dict[int, int] = {} + dates_by_dept: dict[int, set[date]] = {} + overall_dates: set[date] = set() + overall_complaints = 0 + + for c in complaints: + end_map = { + "attended_at": c.attended_at, + "restored_at": c.restored_at, + "closed_at": c.closed_at, + } + end_dt = end_map.get(milestone) or eff_now + mins, dates = clip_downtime_to_month(c.registered_at, end_dt, year, month) + if mins > 0 or len(dates) > 0: + did = c.asset.department_id + dt_mins_by_dept[did] = dt_mins_by_dept.get(did, 0) + mins + cmp_count_by_dept[did] = cmp_count_by_dept.get(did, 0) + 1 + dates_by_dept.setdefault(did, set()).update(dates) + overall_dates.update(dates) + overall_complaints += 1 + + rows: list[dict[str, Any]] = [] + chart_data: list[dict[str, Any]] = [] + ordered_dept_ids = sorted(dept_by_id.keys(), key=lambda did: dept_by_id[did].name) + + for did in ordered_dept_ids: + dept = dept_by_id[did] + a_cnt = asset_count_by_dept.get(did, 0) + if asset_id is not None and a_cnt == 0 and cmp_count_by_dept.get(did, 0) == 0: + continue + c_cnt = cmp_count_by_dept.get(did, 0) + dt_mins = dt_mins_by_dept.get(did, 0) + dt_days = len(dates_by_dept.get(did, set())) + sched_mins = a_cnt * sched_mins_per_asset + up_mins = max(0, sched_mins - dt_mins) + dt_pct = round(dt_mins / sched_mins * 100, 2) if sched_mins > 0 else 0.0 + rows.append( + { + "department_id": did, + "department_name": dept.name, + "asset_count": a_cnt, + "complaint_count": c_cnt, + "total_downtime_minutes": dt_mins, + "downtime_formatted": format_duration(dt_mins), + "downtime_days_count": dt_days, + "scheduled_minutes": sched_mins, + "total_uptime_minutes": up_mins, + "uptime_formatted": format_duration(up_mins), + "downtime_pct": dt_pct, + } + ) + chart_data.append( + { + "department": dept.name, + "downtime_hours": round(dt_mins / 60.0, 2), + "uptime_hours": round(up_mins / 60.0, 2), + } + ) + + total_assets = sum(r["asset_count"] for r in rows) + total_dt_mins = sum(r["total_downtime_minutes"] for r in rows) + total_sched_mins = sum(r["scheduled_minutes"] for r in rows) + total_up_mins = max(0, total_sched_mins - total_dt_mins) + total_dt_pct = round(total_dt_mins / total_sched_mins * 100, 2) if total_sched_mins > 0 else 0.0 + dt_vs_up_pct = round(total_dt_mins / total_up_mins * 100, 2) if total_up_mins > 0 else 0.0 + + return { + "report_key": "monthly-maintenance", + "title": "Monthly Maintenance Summary", + "filters_applied": _clean_filters(month=month_str, department_id=dept_id, asset_id=asset_id), + "formula_info": { + "scheduled_hours_per_day": sched_hours, + "downtime_end_milestone": milestone, + "days_in_month": days_in_month, + "uptime_formula": ( + f"max(0, (non_condemned_assets * {days_in_month} * {sched_hours} * 60) - total_downtime_minutes)" + ), + "downtime_formula": ( + f"Sum of breakdown intervals [registered_at -> {milestone} or effective_now] clipped to " + f"{month_str} (Asia/Kolkata); downtime_days_count is distinct calendar days with any breakdown." + ), + }, + "summary": { + "total_assets": total_assets, + "total_complaints": overall_complaints, + "total_downtime_minutes": total_dt_mins, + "downtime_formatted": format_duration(total_dt_mins), + "downtime_days_count": len(overall_dates), + "total_scheduled_minutes": total_sched_mins, + "total_uptime_minutes": total_up_mins, + "uptime_formatted": format_duration(total_up_mins), + "downtime_pct": total_dt_pct, + "downtime_vs_uptime_pct": dt_vs_up_pct, + "scheduled_hours_per_day": sched_hours, + "downtime_end_milestone": milestone, + }, + "columns": [ + {"key": "department_name", "label": "Department"}, + {"key": "asset_count", "label": "Assets"}, + {"key": "complaint_count", "label": "Breakdowns"}, + {"key": "downtime_formatted", "label": "Downtime"}, + {"key": "downtime_days_count", "label": "Downtime Days"}, + {"key": "uptime_formatted", "label": "Uptime"}, + {"key": "downtime_pct", "label": "Downtime %"}, + ], + "rows": rows, + "chart_data": chart_data, + } + + +def _build_monthly_department( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + month_str, year, month = _parse_month(params.get("month"), today) + dept_id = _scoped_dept_id(user, params.get("department_id")) + + month_start = date(year, month, 1) + next_month_start = add_months(month_start, 1) + + dept_q = db.query(Department).filter(Department.is_active.is_(True)) + if dept_id is not None: + dept_q = dept_q.filter(Department.id == dept_id) + departments = dept_q.order_by(Department.name.asc()).all() + + assets = db.query(Asset).all() + open_complaints = ( + db.query(Complaint) + .join(Asset, Complaint.asset_id == Asset.id) + .options(joinedload(Complaint.asset)) + .filter(Complaint.call_status != "closed") + .all() + ) + visits = ( + db.query(DepartmentVisit) + .filter( + DepartmentVisit.visit_date >= month_start, + DepartmentVisit.visit_date < next_month_start, + ) + .order_by(DepartmentVisit.visit_date.desc(), DepartmentVisit.id.desc()) + .all() + ) + + rows: list[dict[str, Any]] = [] + for d in departments: + d_assets = [a for a in assets if a.department_id == d.id] + d_cmps = [c for c in open_complaints if c.asset.department_id == d.id] + d_visits = [v for v in visits if v.department_id == d.id] + notes = "; ".join( + f"[{format_date(v.visit_date)}] {v.observations.strip()}" + for v in d_visits + if v.observations and v.observations.strip() + ) + rows.append( + { + "department_id": d.id, + "department_name": d.name, + "total_assets": len(d_assets), + "under_repair_count": sum(1 for a in d_assets if a.status == "under_repair"), + "out_of_service_count": sum(1 for a in d_assets if a.status == "out_of_service"), + "outstanding_complaints_count": len(d_cmps), + "critical_open_count": sum(1 for c in d_cmps if c.priority == "critical"), + "visits_this_month": len(d_visits), + "latest_requirements_notes": notes or "\u2014", + } + ) + + return { + "report_key": "monthly-department", + "title": "Monthly Department Report", + "filters_applied": _clean_filters(month=month_str, department_id=dept_id), + "summary": { + "departments_count": len(rows), + "total_under_repair": sum(r["under_repair_count"] for r in rows), + "total_outstanding_complaints": sum(r["outstanding_complaints_count"] for r in rows), + "total_visits": sum(r["visits_this_month"] for r in rows), + }, + "columns": [ + {"key": "department_name", "label": "Department"}, + {"key": "total_assets", "label": "Total Assets"}, + {"key": "under_repair_count", "label": "Under Repair"}, + {"key": "out_of_service_count", "label": "Out of Service"}, + {"key": "outstanding_complaints_count", "label": "Open Complaints"}, + {"key": "critical_open_count", "label": "Critical Open"}, + {"key": "visits_this_month", "label": "Visits"}, + {"key": "latest_requirements_notes", "label": "Visit Observations / Requirements"}, + ], + "rows": rows, + } + + +def _build_daily_visit( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + if user.role in (Role.department_user.value, Role.coordinator.value): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Insufficient permissions to access Daily Department Visit Report.", + ) + + date_from = params.get("date_from") + date_to = params.get("date_to") + dept_id = params.get("department_id") + + query = db.query(DepartmentVisit).options( + joinedload(DepartmentVisit.department), + joinedload(DepartmentVisit.visited_by), + joinedload(DepartmentVisit.assets), + joinedload(DepartmentVisit.complaints), + ) + if dept_id is not None: + query = query.filter(DepartmentVisit.department_id == dept_id) + if date_from is not None: + query = query.filter(DepartmentVisit.visit_date >= date_from) + if date_to is not None: + query = query.filter(DepartmentVisit.visit_date <= date_to) + + visits = query.order_by(DepartmentVisit.visit_date.desc(), DepartmentVisit.id.desc()).all() + rows: list[dict[str, Any]] = [] + depts_visited: set[int] = set() + total_eq_checked = 0 + total_linked = 0 + + for v in visits: + depts_visited.add(v.department_id) + eq_list = ", ".join(f"{a.asset_code} ({a.name})" for a in v.assets) + cmp_list = ", ".join(c.complaint_no for c in v.complaints) + total_eq_checked += len(v.assets) + total_linked += len(v.complaints) + rows.append( + { + "id": v.id, + "visit_date": format_date(v.visit_date), + "department_name": v.department.name if v.department else "\u2014", + "visited_by_name": v.visited_by.name if v.visited_by else "\u2014", + "equipment_checked_count": len(v.assets), + "equipment_checked": eq_list or "\u2014", + "observations": v.observations or "\u2014", + "linked_complaints_count": len(v.complaints), + "linked_complaints": cmp_list or "\u2014", + } + ) + + return { + "report_key": "daily-visit", + "title": "Daily Department Visit Report", + "filters_applied": _clean_filters(date_from=date_from, date_to=date_to, department_id=dept_id), + "summary": { + "total_visits": len(rows), + "departments_visited": len(depts_visited), + "total_equipment_checked": total_eq_checked, + "linked_complaints_count": total_linked, + }, + "columns": [ + {"key": "visit_date", "label": "Visit Date"}, + {"key": "department_name", "label": "Department"}, + {"key": "visited_by_name", "label": "Visited By"}, + {"key": "equipment_checked_count", "label": "Assets Checked"}, + {"key": "equipment_checked", "label": "Equipment Checked"}, + {"key": "observations", "label": "Observations"}, + {"key": "linked_complaints_count", "label": "Linked Count"}, + {"key": "linked_complaints", "label": "Linked Complaints"}, + ], + "rows": rows, + } + + +def _build_breakdown_complaints( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + dept_id = _scoped_dept_id(user, params.get("department_id")) + date_from = params.get("date_from") + date_to = params.get("date_to") + asset_id = params.get("asset_id") + priority = params.get("priority") + call_status = params.get("call_status") + assigned_to_id = params.get("assigned_to_id") + + response_start = str(get_setting_value(db, "response_start", "registered_at")) + milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at")) + eff_now = effective_now_utc(db) + + query = ( + db.query(Complaint) + .join(Asset, Complaint.asset_id == Asset.id) + .options( + joinedload(Complaint.asset).joinedload(Asset.department), + ) + ) + if dept_id is not None: + query = query.filter(Asset.department_id == dept_id) + if asset_id is not None: + query = query.filter(Complaint.asset_id == asset_id) + if priority: + query = query.filter(Complaint.priority == priority) + if call_status: + query = query.filter(Complaint.call_status == call_status) + if assigned_to_id is not None: + query = query.filter(Complaint.assigned_to_id == assigned_to_id) + if date_from is not None: + dt_from_utc = KOLKATA.localize(datetime.combine(date_from, time(0, 0, 0))).astimezone(timezone.utc) + query = query.filter(Complaint.registered_at >= dt_from_utc) + if date_to is not None: + dt_to_utc = KOLKATA.localize( + datetime.combine(date_to + timedelta(days=1), time(0, 0, 0)) + ).astimezone(timezone.utc) + query = query.filter(Complaint.registered_at < dt_to_utc) + + complaints = query.order_by(Complaint.registered_at.desc(), Complaint.id.desc()).all() + assigned_ids = {c.assigned_to_id for c in complaints if c.assigned_to_id is not None} + user_name_by_id: dict[int, str] = {} + if assigned_ids: + user_name_by_id = { + u.id: u.name for u in db.query(User).filter(User.id.in_(assigned_ids)).all() + } + + rows: list[dict[str, Any]] = [] + rt_values: list[int] = [] + total_dt = 0 + + for c in complaints: + rt = compute_response_time_minutes(c.registered_at, c.received_at, c.attended_at, response_start) + if rt is not None: + rt_values.append(rt) + dt_mins, ongoing = compute_downtime_minutes( + c.registered_at, + c.attended_at, + c.restored_at, + c.closed_at, + milestone=milestone, + now_utc=eff_now, + ) + total_dt += dt_mins + rows.append( + { + "complaint_no": c.complaint_no, + "asset_code": c.asset.asset_code, + "asset_name": c.asset.name, + "department_name": c.asset.department.name if c.asset.department else "\u2014", + "priority": c.priority, + "call_status": c.call_status, + "registered_at": format_datetime(c.registered_at), + "assigned_to_name": user_name_by_id.get(c.assigned_to_id, "\u2014") if c.assigned_to_id else "\u2014", + "response_time_minutes": rt, + "response_time_formatted": format_duration(rt), + "downtime_minutes": dt_mins, + "downtime_formatted": format_duration(dt_mins), + "downtime_is_ongoing": ongoing, + "action_taken": c.action_taken or "\u2014", + "closed_at": format_datetime(c.closed_at) or "\u2014", + "closure_remarks": c.closure_remarks or "\u2014", + } + ) + + avg_rt = round(sum(rt_values) / len(rt_values), 1) if rt_values else 0.0 + return { + "report_key": "breakdown-complaints", + "title": "Breakdown / Complaint Report", + "filters_applied": _clean_filters( + date_from=date_from, + date_to=date_to, + department_id=dept_id, + asset_id=asset_id, + priority=priority, + call_status=call_status, + assigned_to_id=assigned_to_id, + ), + "summary": { + "total_complaints": len(rows), + "open_count": sum(1 for c in complaints if c.call_status == "open"), + "in_progress_count": sum(1 for c in complaints if c.call_status == "in_progress"), + "closed_count": sum(1 for c in complaints if c.call_status == "closed"), + "critical_count": sum(1 for c in complaints if c.priority == "critical"), + "avg_response_minutes": avg_rt, + "total_downtime_minutes": total_dt, + }, + "columns": [ + {"key": "complaint_no", "label": "Complaint No"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "priority", "label": "Priority"}, + {"key": "call_status", "label": "Status"}, + {"key": "registered_at", "label": "Registered At"}, + {"key": "assigned_to_name", "label": "Assigned To"}, + {"key": "response_time_formatted", "label": "Response Time"}, + {"key": "downtime_formatted", "label": "Downtime"}, + {"key": "action_taken", "label": "Action Taken"}, + {"key": "closed_at", "label": "Closed At"}, + {"key": "closure_remarks", "label": "Closure Remarks"}, + ], + "rows": rows, + } + + +def _build_pm_compliance( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + dept_id = _scoped_dept_id(user, params.get("department_id")) + month_param = params.get("month") + date_from = params.get("date_from") + date_to = params.get("date_to") + asset_id = params.get("asset_id") + service_mode = params.get("service_mode") + + inhouse_lead = int(get_setting_value(db, "pm_inhouse_lead_days", 15)) + outsourced_lead = int(get_setting_value(db, "pm_outsourced_lead_days", 15)) + red_days = int(get_setting_value(db, "red_threshold_days", 7)) + + query = ( + db.query(PMRecord) + .join(PMSchedule, PMRecord.schedule_id == PMSchedule.id) + .join(Asset, PMRecord.asset_id == Asset.id) + .options( + joinedload(PMRecord.asset).joinedload(Asset.department), + joinedload(PMRecord.schedule).joinedload(PMSchedule.provider), + ) + ) + if dept_id is not None: + query = query.filter(Asset.department_id == dept_id) + if asset_id is not None: + query = query.filter(PMRecord.asset_id == asset_id) + if service_mode: + query = query.filter(PMSchedule.service_mode == service_mode) + + clean_month: str | None = None + if month_param and str(month_param).strip(): + clean_month, y, m = _parse_month(month_param, today) + m_start = date(y, m, 1) + m_end = add_months(m_start, 1) + query = query.filter(PMRecord.planned_date >= m_start, PMRecord.planned_date < m_end) + else: + if date_from is not None: + query = query.filter(PMRecord.planned_date >= date_from) + if date_to is not None: + query = query.filter(PMRecord.planned_date <= date_to) + + records = query.order_by(PMRecord.planned_date.asc(), PMRecord.id.asc()).all() + rows: list[dict[str, Any]] = [] + counts = {"completed": 0, "upcoming": 0, "due": 0, "overdue": 0, "rescheduled": 0} + + for rec in records: + sched = rec.schedule + mode = sched.service_mode + lead = inhouse_lead if mode == "in_house" else outsourced_lead + if rec.status in ("completed", "rescheduled"): + st = rec.status + else: + st, _ = compute_schedule_status(rec.planned_date, None, today, lead, red_days) + counts[st] = counts.get(st, 0) + 1 + team_or_provider = ( + sched.responsible_team + if mode == "in_house" + else (sched.provider.name if sched.provider else "\u2014") + ) + rows.append( + { + "planned_date": format_date(rec.planned_date), + "asset_code": rec.asset.asset_code, + "asset_name": rec.asset.name, + "department_name": rec.asset.department.name if rec.asset.department else "\u2014", + "service_mode": mode, + "team_or_provider": team_or_provider or "\u2014", + "status": st, + "completed_date": format_date(rec.completed_date) or "\u2014", + "service_details": rec.service_details or "\u2014", + "remarks": rec.remarks or "\u2014", + } + ) + + planned_count = len(rows) + compliance_pct = round(counts["completed"] / planned_count * 100, 2) if planned_count > 0 else 0.0 + return { + "report_key": "pm-compliance", + "title": "PM Compliance Report", + "filters_applied": _clean_filters( + month=clean_month, + date_from=date_from, + date_to=date_to, + department_id=dept_id, + asset_id=asset_id, + service_mode=service_mode, + ), + "summary": { + "planned_count": planned_count, + "completed_count": counts["completed"], + "upcoming_count": counts["upcoming"], + "due_count": counts["due"], + "overdue_count": counts["overdue"], + "rescheduled_count": counts["rescheduled"], + "compliance_pct": compliance_pct, + }, + "columns": [ + {"key": "planned_date", "label": "Planned Date"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "service_mode", "label": "Service Mode"}, + {"key": "team_or_provider", "label": "Team / Provider"}, + {"key": "status", "label": "Status"}, + {"key": "completed_date", "label": "Completed Date"}, + {"key": "service_details", "label": "Service Details"}, + {"key": "remarks", "label": "Remarks"}, + ], + "rows": rows, + } + + +def _build_calibration_due( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + dept_id = _scoped_dept_id(user, params.get("department_id")) + due_from = params.get("due_from") + due_to = params.get("due_to") + asset_id = params.get("asset_id") + agency_id = params.get("agency_id") + status_filter = params.get("status") + + cal_lead = int(get_setting_value(db, "calibration_lead_days", 15)) + red_days = int(get_setting_value(db, "red_threshold_days", 7)) + + query = ( + db.query(CalibrationRecord) + .join(CalibrationPlan, CalibrationRecord.plan_id == CalibrationPlan.id) + .join(Asset, CalibrationRecord.asset_id == Asset.id) + .options( + joinedload(CalibrationRecord.asset).joinedload(Asset.department), + joinedload(CalibrationRecord.agency), + joinedload(CalibrationRecord.plan), + ) + ) + if dept_id is not None: + query = query.filter(Asset.department_id == dept_id) + if asset_id is not None: + query = query.filter(CalibrationRecord.asset_id == asset_id) + if agency_id is not None: + query = query.filter(CalibrationRecord.agency_id == agency_id) + if due_from is not None: + query = query.filter(CalibrationRecord.due_date >= due_from) + if due_to is not None: + query = query.filter(CalibrationRecord.due_date <= due_to) + + records = query.order_by(CalibrationRecord.due_date.asc(), CalibrationRecord.id.asc()).all() + rows: list[dict[str, Any]] = [] + counts = {"upcoming": 0, "due": 0, "overdue": 0, "completed": 0} + + for rec in records: + if rec.status == "completed": + st = "completed" + else: + st, _ = compute_schedule_status(rec.due_date, None, today, cal_lead, red_days) + if status_filter and st != status_filter: + continue + counts[st] = counts.get(st, 0) + 1 + rows.append( + { + "due_date": format_date(rec.due_date), + "asset_code": rec.asset.asset_code, + "asset_name": rec.asset.name, + "department_name": rec.asset.department.name if rec.asset.department else "\u2014", + "agency_name": rec.agency.name if rec.agency else "\u2014", + "frequency_months": rec.plan.frequency_months if rec.plan else 0, + "status": st, + "completed_date": format_date(rec.completed_date) or "\u2014", + "certificate_no": rec.certificate_no or "\u2014", + "remarks": rec.remarks or "\u2014", + } + ) + + return { + "report_key": "calibration-due", + "title": "Calibration Due Report", + "filters_applied": _clean_filters( + due_from=due_from, + due_to=due_to, + department_id=dept_id, + asset_id=asset_id, + agency_id=agency_id, + status=status_filter, + ), + "summary": { + "total_records": len(rows), + "upcoming_count": counts["upcoming"], + "due_count": counts["due"], + "overdue_count": counts["overdue"], + "completed_count": counts["completed"], + }, + "columns": [ + {"key": "due_date", "label": "Due Date"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "agency_name", "label": "Agency"}, + {"key": "frequency_months", "label": "Freq (Mo)"}, + {"key": "status", "label": "Status"}, + {"key": "completed_date", "label": "Completed Date"}, + {"key": "certificate_no", "label": "Certificate No"}, + {"key": "remarks", "label": "Remarks"}, + ], + "rows": rows, + } + + +def _build_contracts_warranty( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + dept_id = _scoped_dept_id(user, params.get("department_id")) + asset_id = params.get("asset_id") + record_kind = params.get("record_kind") or "all" + status_filter = params.get("status") + contract_type = params.get("contract_type") + + con_lead = int( + get_setting_value( + db, + "amc_cmc_lead_days", + get_setting_value(db, "contract_expiry_alert_days", 30), + ) + ) + war_lead = int( + get_setting_value( + db, + "warranty_lead_days", + get_setting_value(db, "warranty_expiry_alert_days", 30), + ) + ) + red_days = int(get_setting_value(db, "red_threshold_days", 7)) + + rows: list[dict[str, Any]] = [] + con_counts = {"active": 0, "expiring": 0, "expired": 0} + war_counts = {"active": 0, "expiring": 0, "expired": 0} + + if record_kind in ("all", "contracts"): + cq = ( + db.query(Contract) + .join(Asset, Contract.asset_id == Asset.id) + .options(joinedload(Contract.asset).joinedload(Asset.department), joinedload(Contract.provider)) + ) + if status_filter != "superseded": + cq = cq.filter(Contract.is_superseded.is_(False)) + if dept_id is not None: + cq = cq.filter(Asset.department_id == dept_id) + if asset_id is not None: + cq = cq.filter(Contract.asset_id == asset_id) + if contract_type: + cq = cq.filter(Contract.contract_type == contract_type) + contracts = cq.order_by(Contract.end_date.asc(), Contract.id.desc()).all() + con_att = get_attachment_counts(db, "contract", [c.id for c in contracts]) + for c in contracts: + if c.is_superseded: + st = "superseded" + else: + st, _ = coverage_status(c.start_date, c.end_date, today, con_lead, red_days) + if status_filter and st != status_filter: + continue + if st in con_counts: + con_counts[st] += 1 + rows.append( + { + "record_kind": "Contract", + "asset_code": c.asset.asset_code, + "asset_name": c.asset.name, + "department_name": c.asset.department.name if c.asset.department else "\u2014", + "type_or_duration": c.contract_type, + "provider_name": c.provider.name if c.provider else "\u2014", + "start_date": format_date(c.start_date), + "end_date": format_date(c.end_date), + "days_to_expiry": (c.end_date - today).days, + "status": st, + "attachment_count": con_att.get(c.id, 0), + } + ) + + if record_kind in ("all", "warranties") and not contract_type: + wq = ( + db.query(Warranty) + .join(Asset, Warranty.asset_id == Asset.id) + .options(joinedload(Warranty.asset).joinedload(Asset.department), joinedload(Warranty.provider)) + ) + if dept_id is not None: + wq = wq.filter(Asset.department_id == dept_id) + if asset_id is not None: + wq = wq.filter(Warranty.asset_id == asset_id) + warranties = wq.order_by(Warranty.end_date.asc(), Warranty.id.desc()).all() + war_att = get_attachment_counts(db, "warranty", [w.id for w in warranties]) + for w in warranties: + st, _ = coverage_status(w.start_date, w.end_date, today, war_lead, red_days) + if status_filter and st != status_filter: + continue + if st in war_counts: + war_counts[st] += 1 + rows.append( + { + "record_kind": "Warranty", + "asset_code": w.asset.asset_code, + "asset_name": w.asset.name, + "department_name": w.asset.department.name if w.asset.department else "\u2014", + "type_or_duration": f"{w.duration_months} mo", + "provider_name": w.provider.name if w.provider else "\u2014", + "start_date": format_date(w.start_date), + "end_date": format_date(w.end_date), + "days_to_expiry": (w.end_date - today).days, + "status": st, + "attachment_count": war_att.get(w.id, 0), + } + ) + + return { + "report_key": "contracts-warranty", + "title": "AMC / CMC & Warranty Report", + "filters_applied": _clean_filters( + department_id=dept_id, + asset_id=asset_id, + record_kind=record_kind, + status=status_filter, + contract_type=contract_type, + ), + "summary": { + "total_records": len(rows), + "active_contracts": con_counts["active"], + "expiring_contracts": con_counts["expiring"], + "expired_contracts": con_counts["expired"], + "active_warranties": war_counts["active"], + "expiring_warranties": war_counts["expiring"], + }, + "columns": [ + {"key": "record_kind", "label": "Kind"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "type_or_duration", "label": "Type / Duration"}, + {"key": "provider_name", "label": "Provider"}, + {"key": "start_date", "label": "Start Date"}, + {"key": "end_date", "label": "End Date"}, + {"key": "days_to_expiry", "label": "Days Left"}, + {"key": "status", "label": "Status"}, + {"key": "attachment_count", "label": "Files"}, + ], + "rows": rows, + } + + +def _build_demo_equipment( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + dept_id = _scoped_dept_id(user, params.get("department_id")) + supplier_id = params.get("supplier_id") + status_filter = params.get("status") + date_from = params.get("date_from") + date_to = params.get("date_to") + + query = db.query(DemoEquipment).options( + joinedload(DemoEquipment.supplier), + joinedload(DemoEquipment.department), + joinedload(DemoEquipment.location), + ) + if dept_id is not None: + query = query.filter(DemoEquipment.department_id == dept_id) + if supplier_id is not None: + query = query.filter(DemoEquipment.supplier_id == supplier_id) + if date_from is not None: + query = query.filter(DemoEquipment.expected_return_date >= date_from) + if date_to is not None: + query = query.filter(DemoEquipment.expected_return_date <= date_to) + + items = query.order_by(DemoEquipment.expected_return_date.asc(), DemoEquipment.id.desc()).all() + rows: list[dict[str, Any]] = [] + counts = {"on_demo": 0, "overdue_return": 0, "returned": 0} + + for d in items: + if d.actual_return_date is not None: + st = "returned" + days_rem = (d.expected_return_date - d.actual_return_date).days + elif d.expected_return_date < today: + st = "overdue_return" + days_rem = (d.expected_return_date - today).days + else: + st = "on_demo" + days_rem = (d.expected_return_date - today).days + + if status_filter and st != status_filter: + continue + counts[st] = counts.get(st, 0) + 1 + rows.append( + { + "name": d.name, + "equipment_type": d.equipment_type, + "supplier_name": d.supplier.name if d.supplier else "\u2014", + "department_name": d.department.name if d.department else "\u2014", + "location_name": d.location.name if d.location else "\u2014", + "start_date": format_date(d.start_date), + "expected_return_date": format_date(d.expected_return_date), + "actual_return_date": format_date(d.actual_return_date) or "\u2014", + "status": st, + "days_remaining": days_rem, + "remarks": d.remarks or "\u2014", + } + ) + + return { + "report_key": "demo-equipment", + "title": "Demo Equipment Report", + "filters_applied": _clean_filters( + department_id=dept_id, + supplier_id=supplier_id, + status=status_filter, + date_from=date_from, + date_to=date_to, + ), + "summary": { + "total_items": len(rows), + "on_demo_count": counts["on_demo"], + "overdue_count": counts["overdue_return"], + "returned_count": counts["returned"], + }, + "columns": [ + {"key": "name", "label": "Equipment Name"}, + {"key": "equipment_type", "label": "Type / Model"}, + {"key": "supplier_name", "label": "Supplier"}, + {"key": "department_name", "label": "Department"}, + {"key": "location_name", "label": "Location"}, + {"key": "start_date", "label": "Start Date"}, + {"key": "expected_return_date", "label": "Expected Return"}, + {"key": "actual_return_date", "label": "Actual Return"}, + {"key": "status", "label": "Status"}, + {"key": "days_remaining", "label": "Days Remaining"}, + {"key": "remarks", "label": "Remarks"}, + ], + "rows": rows, + } + + +REPORT_BUILDERS: dict[str, Callable[[Session, User, dict[str, Any]], dict[str, Any]]] = { + "monthly-maintenance": _build_monthly_maintenance, + "monthly-department": _build_monthly_department, + "daily-visit": _build_daily_visit, + "breakdown-complaints": _build_breakdown_complaints, + "pm-compliance": _build_pm_compliance, + "calibration-due": _build_calibration_due, + "contracts-warranty": _build_contracts_warranty, + "demo-equipment": _build_demo_equipment, +} + + +def generate_report( + db: Session, + user: User, + report_key: str, + params: dict[str, Any], +) -> dict[str, Any]: + builder = REPORT_BUILDERS.get(report_key) + if builder is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Unknown report key '{report_key}'.", + ) + return builder(db, user, params) diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.py index 9cc2058..4725fa5 100644 --- a/backend/app/services/settings_service.py +++ b/backend/app/services/settings_service.py @@ -227,6 +227,16 @@ SETTINGS_SCHEMA: list[dict[str, Any]] = [ "max": 60, "options": None, }, + { + "key": "scheduled_hours_per_day", + "type": "int", + "default": 24, + "label": "Scheduled Equipment Hours Per Day", + "description": "Scheduled daily operating hours per asset used for Monthly Maintenance uptime/downtime calculations.", + "min": 1, + "max": 24, + "options": None, + }, ] SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA} diff --git a/backend/tests/test_reports.py b/backend/tests/test_reports.py new file mode 100644 index 0000000..59a8514 --- /dev/null +++ b/backend/tests/test_reports.py @@ -0,0 +1,244 @@ +import csv +from datetime import datetime, timezone +from io import BytesIO, StringIO + +import openpyxl +import pytest + +from app.core.time_utils import KOLKATA +from app.models import Asset, Category, Complaint, Department, Location, User +from app.seed.seed import seed_database + + +ALL_REPORT_KEYS = [ + "monthly-maintenance", + "monthly-department", + "daily-visit", + "breakdown-complaints", + "pm-compliance", + "calibration-due", + "contracts-warranty", + "demo-equipment", +] + + +@pytest.fixture(scope="module", autouse=True) +def seeded_phase7_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("phase7_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def test_all_eight_reports_accessible_for_management_and_admin(client): + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + admin_headers = _auth_headers(client, "admin@poona.demo") + + for headers in (mgmt_headers, admin_headers): + for key in ALL_REPORT_KEYS: + res = client.get(f"/api/reports/{key}", headers=headers) + assert res.status_code == 200, f"{key} failed: {res.text}" + body = res.json() + assert body["report_key"] == key + assert body["title"] + assert isinstance(body["filters_applied"], dict) + assert isinstance(body["summary"], dict) + assert isinstance(body["columns"], list) and len(body["columns"]) > 0 + assert isinstance(body["rows"], list) + + missing = client.get("/api/reports/non-existent-report", headers=admin_headers) + assert missing.status_code == 404 + + +def test_daily_visit_rbac_and_department_user_scoping(client, db): + dept_headers = _auth_headers(client, "dept@poona.demo") + coord_headers = _auth_headers(client, "coord@poona.demo") + bio_headers = _auth_headers(client, "bio@poona.demo") + + # daily-visit is forbidden for department_user and coordinator (JSON + export) + for headers in (dept_headers, coord_headers): + assert client.get("/api/reports/daily-visit", headers=headers).status_code == 403 + assert client.get("/api/reports/daily-visit/export?format=xlsx", headers=headers).status_code == 403 + + # Allowed for biomedical engineer + assert client.get("/api/reports/daily-visit", headers=bio_headers).status_code == 200 + + # Department user attempting to pass another department_id is still scoped to own department + dept_user = db.query(User).filter(User.email == "dept@poona.demo").first() + other_dept = db.query(Department).filter(Department.id != dept_user.department_id).first() + assert dept_user is not None and dept_user.department_id is not None + assert other_dept is not None + + for key in [k for k in ALL_REPORT_KEYS if k != "daily-visit"]: + res = client.get( + f"/api/reports/{key}?department_id={other_dept.id}", + headers=dept_headers, + ) + assert res.status_code == 200, f"{key} failed for dept user: {res.text}" + body = res.json() + if "department_id" in body["filters_applied"]: + assert body["filters_applied"]["department_id"] == dept_user.department_id + + maint = client.get( + f"/api/reports/monthly-maintenance?department_id={other_dept.id}", + headers=dept_headers, + ).json() + assert len(maint["rows"]) == 1 + assert maint["rows"][0]["department_id"] == dept_user.department_id + + +def test_monthly_maintenance_three_complaint_reconciliation(client, db): + admin_headers = _auth_headers(client, "admin@poona.demo") + admin_user = db.query(User).filter(User.email == "admin@poona.demo").first() + category = db.query(Category).first() + location = db.query(Location).first() + assert admin_user is not None and category is not None and location is not None + + # Create isolated department with 2 non-condemned assets so calculation is deterministic + dept = Department(name="Reconciliation Test Unit", code="REC-TEST-01", is_active=True) + db.add(dept) + db.flush() + + asset1 = Asset( + asset_code="REC-AST-001", + serial_no="REC-SN-001", + name="Reconciliation Monitor 1", + category_id=category.id, + department_id=dept.id, + location_id=location.id, + status="in_service", + criticality="critical", + ) + asset2 = Asset( + asset_code="REC-AST-002", + serial_no="REC-SN-002", + name="Reconciliation Monitor 2", + category_id=category.id, + department_id=dept.id, + location_id=location.id, + status="in_service", + criticality="non_critical", + ) + db.add_all([asset1, asset2]) + db.flush() + + # 3 fixed complaints for March 2027 (31 days * 24h * 60m = 44640 mins/asset -> 89280 total): + # 1) Crosses month boundary: Feb 28 22:00 IST -> Mar 01 04:00 IST => 240 mins in March, day Mar 01 + # 2) Mid-month: Mar 10 10:00 IST -> Mar 10 13:30 IST => 210 mins, day Mar 10 + # 3) Distinct day: Mar 20 09:00 IST -> Mar 20 10:15 IST => 75 mins, day Mar 20 + # Expected total downtime = 525 mins, downtime days = 3, uptime = 88755 mins + complaints = [ + Complaint( + complaint_no="REC-CMP-001", + asset_id=asset1.id, + description="Month boundary downtime test", + priority="critical", + registered_at=KOLKATA.localize(datetime(2027, 2, 28, 22, 0)).astimezone(timezone.utc), + restored_at=KOLKATA.localize(datetime(2027, 3, 1, 4, 0)).astimezone(timezone.utc), + registered_by_id=admin_user.id, + received_by_id=admin_user.id, + call_status="closed", + ), + Complaint( + complaint_no="REC-CMP-002", + asset_id=asset1.id, + description="Mid-month downtime test", + priority="non_critical", + registered_at=KOLKATA.localize(datetime(2027, 3, 10, 10, 0)).astimezone(timezone.utc), + restored_at=KOLKATA.localize(datetime(2027, 3, 10, 13, 30)).astimezone(timezone.utc), + registered_by_id=admin_user.id, + received_by_id=admin_user.id, + call_status="closed", + ), + Complaint( + complaint_no="REC-CMP-003", + asset_id=asset2.id, + description="Third distinct day downtime test", + priority="non_critical", + registered_at=KOLKATA.localize(datetime(2027, 3, 20, 9, 0)).astimezone(timezone.utc), + restored_at=KOLKATA.localize(datetime(2027, 3, 20, 10, 15)).astimezone(timezone.utc), + registered_by_id=admin_user.id, + received_by_id=admin_user.id, + call_status="closed", + ), + ] + db.add_all(complaints) + db.commit() + + res = client.get( + f"/api/reports/monthly-maintenance?month=2027-03&department_id={dept.id}", + headers=admin_headers, + ) + assert res.status_code == 200, res.text + payload = res.json() + + summary = payload["summary"] + assert summary["total_assets"] == 2 + assert summary["total_complaints"] == 3 + assert summary["total_downtime_minutes"] == 525 + assert summary["downtime_days_count"] == 3 + assert summary["total_scheduled_minutes"] == 89280 + assert summary["total_uptime_minutes"] == 88755 + assert summary["downtime_pct"] == round(525 / 89280 * 100, 2) + + assert len(payload["rows"]) == 1 + row = payload["rows"][0] + assert row["department_name"] == "Reconciliation Test Unit" + assert row["asset_count"] == 2 + assert row["complaint_count"] == 3 + assert row["total_downtime_minutes"] == 525 + assert row["downtime_days_count"] == 3 + assert row["scheduled_minutes"] == 89280 + assert row["total_uptime_minutes"] == 88755 + + +def test_report_exports_xlsx_and_csv(client): + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + + # Excel export + xlsx_res = client.get( + "/api/reports/monthly-maintenance/export?format=xlsx&month=2027-03", + headers=mgmt_headers, + ) + assert xlsx_res.status_code == 200 + assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"] + assert 'filename="monthly-maintenance.xlsx"' in xlsx_res.headers["content-disposition"] + + wb = openpyxl.load_workbook(BytesIO(xlsx_res.content)) + ws = wb.active + assert "Poona Hospital" in str(ws["A1"].value) + assert "Generated:" in str(ws["A2"].value) + assert "Filters:" in str(ws["A2"].value) + assert "Total Downtime Minutes: 525" in str(ws["A3"].value) + assert ws.freeze_panes == "A6" + assert ws.cell(row=5, column=1).value == "Department" + assert "1E3A8A" in str(ws.cell(row=5, column=1).fill.start_color.rgb) + assert ws.max_row >= 6 + + # CSV export + csv_res = client.get( + "/api/reports/breakdown-complaints/export?format=csv", + headers=mgmt_headers, + ) + assert csv_res.status_code == 200 + assert "text/csv" in csv_res.headers["content-type"] + assert 'filename="breakdown-complaints.csv"' in csv_res.headers["content-disposition"] + assert csv_res.content.startswith(b"\xef\xbb\xbf") + + decoded = csv_res.content.decode("utf-8-sig") + parsed = list(csv.reader(StringIO(decoded))) + assert len(parsed) >= 5 + assert "Poona Hospital" in parsed[0][0] + assert parsed[4][0] == "Complaint No" + + # Unsupported export format rejected + bad_fmt = client.get( + "/api/reports/monthly-maintenance/export?format=pdf", + headers=mgmt_headers, + ) + assert bad_fmt.status_code == 422 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 146f4f7..843fb80 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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() { } /> } /> + } /> } /> ; + formula_info?: FormulaInfo | null; + summary: Record; + columns: ReportColumn[]; + rows: Record[]; + 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; + +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(`/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); +} diff --git a/frontend/src/index.css b/frontend/src/index.css index f897e49..b4bd94d 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -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; + } +} diff --git a/frontend/src/pages/ReportDetailPage.tsx b/frontend/src/pages/ReportDetailPage.tsx new file mode 100644 index 0000000..4762813 --- /dev/null +++ b/frontend/src/pages/ReportDetailPage.tsx @@ -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 = { + 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, 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 ( +
+ +

Report Not Found

+

+ Unknown report key: {reportKey} +

+ + + +
+ ); + } + + if (isForbidden) { + return ( +
+ +

Access Restricted

+

+ {meta.title} is available only to System Administrators, Biomedical Engineers, and Management. +

+ + + +
+ ); + } + + 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 ( +
+ {/* Print-Only Letterhead */} +
+
+ Poona Hospital and Research Centre +
+
+ Poona Hospital & Research Centre +
+
+ Asset Management & Maintenance — {report?.title ?? meta.title} +
+
+
+
+
Printed: {formatDateTime(new Date().toISOString())} IST
+ {user?.name &&
Generated by: {user.name}
} +
+
+ + {/* Screen Header */} +
+
+ + + All Reports + +

+ {report?.title ?? meta.title} +

+

{meta.description}

+
+ +
+ {key === "monthly-maintenance" && report?.formula_info && ( + + )} + + + +
+
+ + {/* Formula Info Popover / Panel for Monthly Maintenance */} + {key === "monthly-maintenance" && formulaOpen && report?.formula_info && ( +
+
+ + Uptime & Downtime Calculation Methodology +
+
+
+ Scheduled Hours / Day:{" "} + {report.formula_info.scheduled_hours_per_day} hrs +
+
+ Days in Month:{" "} + {report.formula_info.days_in_month} days +
+
+ Downtime End Milestone:{" "} + {report.formula_info.downtime_end_milestone} +
+
+
    +
  • + Uptime Formula: {report.formula_info.uptime_formula} +
  • +
  • + Downtime Formula: {report.formula_info.downtime_formula} +
  • +
  • + Month-Boundary Clipping: Each breakdown is clipped to the selected + calendar month in IST ([month_start_IST, next_month_start_IST)), and + distinct calendar downtime days count unique dates covered by those intervals. +
  • +
+
+ )} + + {/* Tailored Filter Bar */} +
+ {(key === "monthly-maintenance" || + key === "monthly-department" || + key === "pm-compliance") && ( +
+ + setMonth(e.target.value)} + className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white" + /> +
+ )} + + {(key === "daily-visit" || + key === "breakdown-complaints" || + key === "pm-compliance" || + key === "demo-equipment") && ( + <> +
+ + setDateFrom(e.target.value)} + className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white" + /> +
+
+ + setDateTo(e.target.value)} + className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white" + /> +
+ + )} + + {key === "calibration-due" && ( + <> +
+ + setDueFrom(e.target.value)} + className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white" + /> +
+
+ + setDueTo(e.target.value)} + className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white" + /> +
+ + )} + + {!isDeptUser && ( +
+ + +
+ )} + + {key === "breakdown-complaints" && ( + <> +
+ + +
+
+ + +
+ + )} + + {key === "pm-compliance" && ( +
+ + +
+ )} + + {key === "calibration-due" && ( + <> +
+ + +
+
+ + +
+ + )} + + {key === "contracts-warranty" && ( + <> +
+ + +
+
+ + +
+
+ + +
+ + )} + + {key === "demo-equipment" && ( + <> +
+ + +
+
+ + +
+ + )} +
+ + {/* Summary Strip */} + {report && ( +
+ {Object.entries(report.summary).map(([sKey, sVal]) => ( +
+
+ {humanizeSummaryKey(sKey)} +
+
+ {String(sVal)} +
+
+ ))} +
+ )} + + {/* Monthly Maintenance Charts */} + {key === "monthly-maintenance" && + report?.chart_data && + report.chart_data.length > 0 && ( +
+
+

+ Department Uptime vs Downtime (Hours) +

+
+ + + + + + + + + + + +
+
+ +
+

+ Hospital Uptime Share +

+
+ + + + {pieData.map((entry, idx) => ( + + ))} + + + + + +
+
+
+ )} + + {/* Report DataTable */} + +
+ ); +} diff --git a/frontend/src/pages/ReportsPage.tsx b/frontend/src/pages/ReportsPage.tsx new file mode 100644 index 0000000..e9d81bc --- /dev/null +++ b/frontend/src/pages/ReportsPage.tsx @@ -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> = { + "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 ( +
+
+
+

Reports & Exports

+

+ Operational reports with live filters, Excel (.xlsx) & CSV downloads, and A4 print layout +

+
+ {role === "department_user" && user?.department_name && ( + + Department Scope: {user.department_name} + + )} +
+ +
+ {visibleReports.map((report) => { + const Icon = REPORT_ICONS[report.key] ?? BarChart3; + return ( + +
+
+
+ +
+ + {report.category} + +
+
+

+ {report.title} +

+

+ {report.description} +

+
+
+ +
+ Open Report + +
+ + ); + })} +
+
+ ); +} diff --git a/frontend/src/test/reports.test.tsx b/frontend/src/test/reports.test.tsx new file mode 100644 index 0000000..741eb99 --- /dev/null +++ b/frontend/src/test/reports.test.tsx @@ -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("recharts"); + return { + ...actual, + ResponsiveContainer: ({ children }: { children: React.ReactNode }) => ( +
{children}
+ ), + }; +}); + +function renderWithRouter(ui: React.ReactNode, initialEntries = ["/"]) { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + {ui} + + ); +} + +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(); + 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( + + + + + + ); + + 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( + + } /> + , + ["/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) + ); + }); + }); +}); diff --git a/frontend/src/test/smoke.test.tsx b/frontend/src/test/smoke.test.tsx index c53c71b..c48e607 100644 --- a/frontend/src/test/smoke.test.tsx +++ b/frontend/src/test/smoke.test.tsx @@ -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( ); 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", () => { diff --git a/frontend/tsconfig.tsbuildinfo b/frontend/tsconfig.tsbuildinfo index 75cbeea..12acecd 100644 --- a/frontend/tsconfig.tsbuildinfo +++ b/frontend/tsconfig.tsbuildinfo @@ -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/dashboard.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/notifications.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/calibrationremindermodal.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/toastprovider.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/dashboardpage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/notificationspage.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/phase6-modules.test.tsx","./src/test/pm-page.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"} \ No newline at end of file +{"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/dashboard.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/notifications.ts","./src/api/phase5.ts","./src/api/pm.ts","./src/api/reports.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/calibrationremindermodal.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/toastprovider.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/dashboardpage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/notificationspage.tsx","./src/pages/pmpage.tsx","./src/pages/reportdetailpage.tsx","./src/pages/reportspage.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/phase6-modules.test.tsx","./src/test/pm-page.test.tsx","./src/test/reports.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"} \ No newline at end of file