Files
poona-ams/backend/app/services/reports_service.py
T

1004 lines
39 KiB
Python

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]
obs_notes = "; ".join(
f"[{format_date(v.visit_date)}] {v.observations.strip()}"
for v in d_visits
if v.observations and v.observations.strip()
)
reqs_notes = "; ".join(
f"[{format_date(v.visit_date)}] {v.new_requirements.strip()}"
for v in d_visits
if v.new_requirements and v.new_requirements.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),
"new_equipment_requirements": reqs_notes or "\u2014",
"latest_requirements_notes": obs_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": "new_equipment_requirements", "label": "New Equipment Requirements"},
{"key": "latest_requirements_notes", "label": "Visit Observations"},
],
"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_due_window_days",
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)