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
+2
View File
@@ -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")
+2
View File
@@ -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",
+87
View File
@@ -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}"',
},
)
+108
View File
@@ -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
+990
View File
@@ -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)
+10
View File
@@ -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}
+244
View File
@@ -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