phase-4: preventive maintenance and calibration modules

This commit is contained in:
Atharv1705
2026-11-12 14:16:38 +05:30
parent 905f6735a7
commit d3f22ba444
26 changed files with 5066 additions and 27 deletions
+3 -1
View File
@@ -1,12 +1,14 @@
from . import assets, attachments, auth, complaints, health, masters, settings, users
from . import assets, attachments, auth, calibration, complaints, health, masters, pm, settings, users
__all__ = [
"assets",
"attachments",
"auth",
"calibration",
"complaints",
"health",
"masters",
"pm",
"settings",
"users",
]
+11 -3
View File
@@ -59,9 +59,11 @@ def _lead_settings(db: Session) -> dict[str, int]:
"warranty": int(get_setting_value(db, "warranty_expiry_alert_days")),
"contract": int(get_setting_value(db, "contract_expiry_alert_days")),
"insurance": int(get_setting_value(db, "insurance_expiry_alert_days")),
"calibration": int(get_setting_value(db, "calibration_due_window_days")),
"calibration": int(get_setting_value(db, "calibration_lead_days", 15)),
"pm": int(get_setting_value(db, "pm_due_window_days")),
"red": int(get_setting_value(db, "contract_critical_alert_days")),
"pm_in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)),
"pm_outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
"red": int(get_setting_value(db, "red_threshold_days", 7)),
}
@@ -771,13 +773,19 @@ def get_asset_overview(
pm_rec_rows = (
db.query(PMRecord)
.options(joinedload(PMRecord.schedule))
.filter(PMRecord.asset_id == asset.id)
.order_by(PMRecord.planned_date.desc(), PMRecord.id.desc())
.all()
)
pm_rec_out = []
for r in pm_rec_rows:
st, sev = compute_schedule_status(r.planned_date, r.status, today, leads["pm"], leads["red"])
pm_lead = (
leads["pm_in_house"]
if r.schedule and r.schedule.service_mode == "in_house"
else leads["pm_outsourced"]
)
st, sev = compute_schedule_status(r.planned_date, r.status, today, pm_lead, leads["red"])
pm_rec_out.append(
PMRecordSummaryOut(
id=r.id,
+640
View File
@@ -0,0 +1,640 @@
from datetime import date
from typing import Optional
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
from sqlalchemy import or_
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user, require_roles
from ..core.exceptions import CodedHTTPException
from ..core.time_utils import add_months, effective_today
from ..models import Asset, CalibrationPlan, CalibrationRecord, User, Vendor
from ..schemas.calibration import (
CalibrationPlanApproveIn,
CalibrationPlanBulkCreateIn,
CalibrationPlanBulkOut,
CalibrationPlanCreateFromAsset,
CalibrationPlanListOut,
CalibrationPlanOut,
CalibrationPlanUpdateIn,
CalibrationRecordCompleteIn,
CalibrationRecordCompleteOut,
CalibrationRecordListOut,
CalibrationRecordOut,
CalibrationRecordSummaryCounts,
CalibrationStatusFilter,
)
from ..services.audit import log_audit
from ..services.calculations import compute_schedule_status
from ..services.permissions import Role
from ..services.settings_service import get_setting_value
router = APIRouter(prefix="/calibration", tags=["calibration"])
APPROVER_ROLES = {Role.management.value, Role.system_admin.value, Role.coordinator.value}
def _cal_lead_settings(db: Session) -> dict[str, int]:
return {
"lead": int(get_setting_value(db, "calibration_lead_days", 15)),
"red": int(get_setting_value(db, "red_threshold_days", 7)),
}
def _default_per_year(frequency_months: int) -> int:
return max(1, round(12 / frequency_months))
def _to_plan_out(plan: CalibrationPlan) -> CalibrationPlanOut:
asset = plan.asset
return CalibrationPlanOut(
id=plan.id,
asset_id=plan.asset_id,
asset_code=asset.asset_code,
asset_name=asset.name,
department_id=asset.department_id,
department_name=asset.department.name if asset.department else None,
frequency_months=plan.frequency_months,
calibrations_per_year=plan.calibrations_per_year,
agency_id=plan.agency_id,
agency_name=plan.agency.name if plan.agency else None,
approved_by_id=plan.approved_by_id,
approved_by_name=plan.approved_by.name if plan.approved_by else None,
approved_on=plan.approved_on,
next_due_date=plan.next_due_date,
is_active=plan.is_active,
)
def _to_record_out(
rec: CalibrationRecord,
today: date,
leads: dict[str, int],
) -> CalibrationRecordOut:
asset = rec.asset
plan = rec.plan
if rec.status == "completed":
comp_status, severity = "completed", "ok"
else:
comp_status, severity = compute_schedule_status(
rec.due_date, None, today, leads["lead"], leads["red"]
)
return CalibrationRecordOut(
id=rec.id,
plan_id=rec.plan_id,
asset_id=rec.asset_id,
asset_code=asset.asset_code,
asset_name=asset.name,
department_id=asset.department_id,
department_name=asset.department.name if asset.department else None,
location_name=asset.location.name if asset.location else None,
due_date=rec.due_date,
completed_date=rec.completed_date,
agency_id=rec.agency_id,
agency_name=rec.agency.name if rec.agency else None,
certificate_no=rec.certificate_no,
remarks=rec.remarks,
status=comp_status,
severity=severity,
frequency_months=plan.frequency_months,
approved_by_name=plan.approved_by.name if plan.approved_by else None,
approved_on=plan.approved_on,
)
def _load_plan_with_joins(db: Session, plan_id: int) -> CalibrationPlan | None:
return (
db.query(CalibrationPlan)
.options(
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
joinedload(CalibrationPlan.agency),
joinedload(CalibrationPlan.approved_by),
)
.filter(CalibrationPlan.id == plan_id)
.first()
)
def _load_record_with_joins(db: Session, record_id: int) -> CalibrationRecord | None:
return (
db.query(CalibrationRecord)
.options(
joinedload(CalibrationRecord.asset).joinedload(Asset.department),
joinedload(CalibrationRecord.asset).joinedload(Asset.location),
joinedload(CalibrationRecord.agency),
joinedload(CalibrationRecord.plan).joinedload(CalibrationPlan.approved_by),
)
.filter(CalibrationRecord.id == record_id)
.first()
)
def _create_plan_and_initial_record(
db: Session,
*,
asset: Asset,
frequency_months: int,
calibrations_per_year: Optional[int],
agency_id: Optional[int],
next_due_date: date,
approve: bool,
current_user: User,
today: date,
) -> CalibrationPlan:
asset.requires_calibration = True
asset.updated_by_id = current_user.id
per_year = calibrations_per_year or _default_per_year(frequency_months)
plan = CalibrationPlan(
asset_id=asset.id,
frequency_months=frequency_months,
calibrations_per_year=per_year,
agency_id=agency_id,
approved_by_id=current_user.id if approve else None,
approved_on=today if approve else None,
next_due_date=next_due_date,
is_active=True,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(plan)
db.flush()
initial_rec = CalibrationRecord(
asset_id=asset.id,
plan_id=plan.id,
due_date=next_due_date,
agency_id=agency_id,
status=None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(initial_rec)
db.flush()
log_audit(
db,
entity_type="calibration_plan",
entity_id=plan.id,
action="create",
changes={
"asset_id": asset.id,
"frequency_months": frequency_months,
"calibrations_per_year": per_year,
"next_due_date": str(next_due_date),
"approved": approve,
"initial_record_id": initial_rec.id,
},
user_id=current_user.id,
)
return plan
@router.get("/plans", response_model=CalibrationPlanListOut)
def list_calibration_plans(
q: str = "",
department_id: Optional[int] = None,
agency_id: Optional[int] = None,
is_active: Optional[bool] = None,
page: int = Query(1, ge=1),
page_size: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
query = (
db.query(CalibrationPlan)
.join(Asset, CalibrationPlan.asset_id == Asset.id)
.outerjoin(Vendor, CalibrationPlan.agency_id == Vendor.id)
.options(
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
joinedload(CalibrationPlan.agency),
joinedload(CalibrationPlan.approved_by),
)
)
if current_user.role == Role.department_user.value:
query = query.filter(Asset.department_id == current_user.department_id)
elif department_id is not None:
query = query.filter(Asset.department_id == department_id)
if agency_id is not None:
query = query.filter(CalibrationPlan.agency_id == agency_id)
if is_active is not None:
query = query.filter(CalibrationPlan.is_active.is_(is_active))
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Asset.asset_code.ilike(like),
Asset.name.ilike(like),
Vendor.name.ilike(like),
)
)
total = query.count()
rows = (
query.order_by(CalibrationPlan.next_due_date.asc(), CalibrationPlan.id.asc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return CalibrationPlanListOut(items=[_to_plan_out(p) for p in rows], total=total)
@router.post(
"/plans/from-asset/{asset_id}",
response_model=CalibrationPlanOut,
status_code=status.HTTP_201_CREATED,
)
def create_calibration_plan_from_asset(
asset_id: int,
payload: CalibrationPlanCreateFromAsset,
db: Session = Depends(get_db),
current_user: User = Depends(
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
),
):
asset = db.query(Asset).filter(Asset.id == asset_id).first()
if asset is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
existing = db.query(CalibrationPlan.id).filter(CalibrationPlan.asset_id == asset_id).first()
if existing is not None:
raise CodedHTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Calibration plan already exists for this asset.",
code="DUPLICATE_CALIBRATION_PLAN",
)
if payload.approve and current_user.role not in APPROVER_ROLES:
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only management, system_admin, or coordinator can approve calibration frequency.",
code="FORBIDDEN_CALIBRATION_APPROVAL",
)
if payload.agency_id is not None:
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
today = effective_today(db)
plan = _create_plan_and_initial_record(
db,
asset=asset,
frequency_months=payload.frequency_months,
calibrations_per_year=payload.calibrations_per_year,
agency_id=payload.agency_id,
next_due_date=payload.next_due_date,
approve=payload.approve,
current_user=current_user,
today=today,
)
db.commit()
loaded = _load_plan_with_joins(db, plan.id)
return _to_plan_out(loaded)
@router.post("/plans/bulk-from-assets", response_model=CalibrationPlanBulkOut)
def bulk_create_calibration_plans(
payload: CalibrationPlanBulkCreateIn,
db: Session = Depends(get_db),
current_user: User = Depends(
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
),
):
if payload.approve and current_user.role not in APPROVER_ROLES:
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only management, system_admin, or coordinator can approve calibration frequency.",
code="FORBIDDEN_CALIBRATION_APPROVAL",
)
if payload.agency_id is not None:
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
unique_ids = list(dict.fromkeys(payload.asset_ids))
assets_by_id = {a.id: a for a in db.query(Asset).filter(Asset.id.in_(unique_ids)).all()}
existing_asset_ids = {
row[0]
for row in db.query(CalibrationPlan.asset_id)
.filter(CalibrationPlan.asset_id.in_(unique_ids))
.all()
}
today = effective_today(db)
created_ids: list[int] = []
skipped_ids: list[int] = []
for aid in unique_ids:
asset = assets_by_id.get(aid)
if asset is None or aid in existing_asset_ids:
skipped_ids.append(aid)
continue
plan = _create_plan_and_initial_record(
db,
asset=asset,
frequency_months=payload.frequency_months,
calibrations_per_year=payload.calibrations_per_year,
agency_id=payload.agency_id,
next_due_date=payload.next_due_date,
approve=payload.approve,
current_user=current_user,
today=today,
)
created_ids.append(plan.id)
existing_asset_ids.add(aid)
db.commit()
created_out: list[CalibrationPlanOut] = []
if created_ids:
loaded_plans = (
db.query(CalibrationPlan)
.options(
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
joinedload(CalibrationPlan.agency),
joinedload(CalibrationPlan.approved_by),
)
.filter(CalibrationPlan.id.in_(created_ids))
.all()
)
by_id = {p.id: p for p in loaded_plans}
created_out = [_to_plan_out(by_id[pid]) for pid in created_ids if pid in by_id]
return CalibrationPlanBulkOut(created=created_out, skipped_asset_ids=skipped_ids)
@router.put("/plans/{plan_id}", response_model=CalibrationPlanOut)
def update_calibration_plan(
plan_id: int,
payload: CalibrationPlanUpdateIn,
db: Session = Depends(get_db),
current_user: User = Depends(
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
),
):
plan = db.query(CalibrationPlan).filter(CalibrationPlan.id == plan_id).first()
if plan is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration plan not found.")
data = payload.model_dump(exclude_unset=True)
if current_user.role == Role.biomedical.value:
if (
("frequency_months" in data and data["frequency_months"] is not None)
or ("calibrations_per_year" in data and data["calibrations_per_year"] is not None)
):
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Biomedical users cannot modify calibration frequency; management, coordinator, or system_admin approval is required.",
code="FORBIDDEN_CALIBRATION_APPROVAL",
)
if "agency_id" in data and data["agency_id"] is not None:
if not db.query(Vendor.id).filter(Vendor.id == data["agency_id"]).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
if "frequency_months" in data and data["frequency_months"] is not None and "calibrations_per_year" not in data:
data["calibrations_per_year"] = _default_per_year(data["frequency_months"])
old_due_date = plan.next_due_date
old_agency_id = plan.agency_id
changes: dict[str, dict[str, object]] = {}
for k, v in data.items():
if v is None and k in ("frequency_months", "calibrations_per_year", "next_due_date", "is_active"):
continue
old_val = getattr(plan, k)
if old_val != v:
changes[k] = {"from": old_val, "to": v}
setattr(plan, k, v)
plan.updated_by_id = current_user.id
if plan.next_due_date != old_due_date or plan.agency_id != old_agency_id:
open_rec = (
db.query(CalibrationRecord)
.filter(CalibrationRecord.plan_id == plan.id, CalibrationRecord.status.is_(None))
.order_by(CalibrationRecord.due_date.desc(), CalibrationRecord.id.desc())
.first()
)
if open_rec is not None:
open_rec.due_date = plan.next_due_date
open_rec.agency_id = plan.agency_id
open_rec.updated_by_id = current_user.id
if changes:
log_audit(
db,
entity_type="calibration_plan",
entity_id=plan.id,
action="update",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_plan_with_joins(db, plan.id)
return _to_plan_out(loaded)
@router.post("/plans/{plan_id}/approve", response_model=CalibrationPlanOut)
def approve_calibration_plan(
plan_id: int,
payload: Optional[CalibrationPlanApproveIn] = Body(default=None),
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.management, Role.system_admin, Role.coordinator)),
):
plan = db.query(CalibrationPlan).filter(CalibrationPlan.id == plan_id).first()
if plan is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration plan not found.")
today = effective_today(db)
changes: dict[str, dict[str, object]] = {}
if payload is not None:
if payload.frequency_months is not None and payload.frequency_months != plan.frequency_months:
changes["frequency_months"] = {"from": plan.frequency_months, "to": payload.frequency_months}
plan.frequency_months = payload.frequency_months
if payload.calibrations_per_year is None:
new_per_year = _default_per_year(payload.frequency_months)
if new_per_year != plan.calibrations_per_year:
changes["calibrations_per_year"] = {"from": plan.calibrations_per_year, "to": new_per_year}
plan.calibrations_per_year = new_per_year
if payload.calibrations_per_year is not None and payload.calibrations_per_year != plan.calibrations_per_year:
changes["calibrations_per_year"] = {"from": plan.calibrations_per_year, "to": payload.calibrations_per_year}
plan.calibrations_per_year = payload.calibrations_per_year
plan.approved_by_id = current_user.id
plan.approved_on = today
plan.updated_by_id = current_user.id
changes["approved_by_id"] = {"to": current_user.id}
changes["approved_on"] = {"to": str(today)}
log_audit(
db,
entity_type="calibration_plan",
entity_id=plan.id,
action="approve",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_plan_with_joins(db, plan.id)
return _to_plan_out(loaded)
@router.get("/records", response_model=CalibrationRecordListOut)
def list_calibration_records(
q: str = "",
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
agency_id: Optional[int] = None,
status_filter: Optional[CalibrationStatusFilter] = Query(None, alias="status"),
due_from: Optional[date] = None,
due_to: Optional[date] = None,
page: int = Query(1, ge=1),
page_size: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
today = effective_today(db)
leads = _cal_lead_settings(db)
query = (
db.query(CalibrationRecord)
.join(CalibrationPlan, CalibrationRecord.plan_id == CalibrationPlan.id)
.join(Asset, CalibrationRecord.asset_id == Asset.id)
.outerjoin(Vendor, CalibrationRecord.agency_id == Vendor.id)
.options(
joinedload(CalibrationRecord.asset).joinedload(Asset.department),
joinedload(CalibrationRecord.asset).joinedload(Asset.location),
joinedload(CalibrationRecord.agency),
joinedload(CalibrationRecord.plan).joinedload(CalibrationPlan.approved_by),
)
)
if current_user.role == Role.department_user.value:
query = query.filter(Asset.department_id == current_user.department_id)
elif department_id is not None:
query = query.filter(Asset.department_id == department_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)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Asset.asset_code.ilike(like),
Asset.name.ilike(like),
Vendor.name.ilike(like),
CalibrationRecord.certificate_no.ilike(like),
CalibrationRecord.remarks.ilike(like),
)
)
rows = query.order_by(CalibrationRecord.due_date.asc(), CalibrationRecord.id.asc()).all()
computed_all = [_to_record_out(r, today, leads) for r in rows]
summary = CalibrationRecordSummaryCounts(
upcoming=sum(1 for item in computed_all if item.status == "upcoming"),
due=sum(1 for item in computed_all if item.status == "due"),
overdue=sum(1 for item in computed_all if item.status == "overdue"),
completed=sum(1 for item in computed_all if item.status == "completed"),
)
if status_filter is not None:
filtered = [item for item in computed_all if item.status == status_filter]
else:
filtered = computed_all
total = len(filtered)
start = (page - 1) * page_size
paginated = filtered[start : start + page_size]
return CalibrationRecordListOut(items=paginated, total=total, summary=summary)
@router.post("/records/{record_id}/complete", response_model=CalibrationRecordCompleteOut)
def complete_calibration_record(
record_id: int,
payload: CalibrationRecordCompleteIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
rec = _load_record_with_joins(db, record_id)
if rec is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration record not found.")
if rec.status == "completed":
raise CodedHTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Calibration record is already completed.",
code="INVALID_CALIBRATION_STATUS",
)
clean_cert = payload.certificate_no.strip()
if not clean_cert:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="certificate_no cannot be blank.",
)
if payload.agency_id is not None:
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
rec.agency_id = payload.agency_id
rec.status = "completed"
rec.completed_date = payload.completed_date
rec.certificate_no = clean_cert
rec.remarks = payload.remarks.strip() if payload.remarks and payload.remarks.strip() else None
rec.updated_by_id = current_user.id
plan = rec.plan
next_due = add_months(payload.completed_date, plan.frequency_months)
plan.next_due_date = next_due
plan.updated_by_id = current_user.id
next_rec = CalibrationRecord(
asset_id=plan.asset_id,
plan_id=plan.id,
due_date=next_due,
agency_id=rec.agency_id if rec.agency_id is not None else plan.agency_id,
status=None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(next_rec)
db.flush()
log_audit(
db,
entity_type="calibration_record",
entity_id=rec.id,
action="complete",
changes={
"completed_date": str(payload.completed_date),
"certificate_no": clean_cert,
"next_due_date": str(next_due),
"next_record_id": next_rec.id,
},
user_id=current_user.id,
)
db.commit()
today = effective_today(db)
leads = _cal_lead_settings(db)
loaded_completed = _load_record_with_joins(db, rec.id)
loaded_next = _load_record_with_joins(db, next_rec.id)
return CalibrationRecordCompleteOut(
completed_record=_to_record_out(loaded_completed, today, leads),
next_record=_to_record_out(loaded_next, today, leads),
)
+625
View File
@@ -0,0 +1,625 @@
from datetime import date
import re
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import or_
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user, require_roles
from ..core.exceptions import CodedHTTPException
from ..core.time_utils import add_months, effective_today, format_date
from ..models import Asset, Contract, PMRecord, PMSchedule, User, Vendor
from ..schemas.pm import (
PMRecordCompleteIn,
PMRecordCompleteOut,
PMRecordListOut,
PMRecordOut,
PMRecordRescheduleIn,
PMRecordRescheduleOut,
PMRecordStatusFilter,
PMRecordSummaryCounts,
PMScheduleCreate,
PMScheduleListOut,
PMScheduleOut,
PMScheduleUpdate,
PMServiceMode,
)
from ..services.audit import log_audit
from ..services.calculations import compute_schedule_status
from ..services.permissions import Role
from ..services.settings_service import get_setting_value
router = APIRouter(prefix="/pm", tags=["pm"])
_MONTH_RE = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
def _pm_lead_settings(db: Session) -> dict[str, int]:
return {
"in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)),
"outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
"red": int(get_setting_value(db, "red_threshold_days", 7)),
}
def _to_schedule_out(s: PMSchedule) -> PMScheduleOut:
asset = s.asset
contract_summary = None
if s.contract is not None:
contract_summary = f"{s.contract.contract_type} (till {format_date(s.contract.end_date)})"
return PMScheduleOut(
id=s.id,
asset_id=s.asset_id,
asset_code=asset.asset_code,
asset_name=asset.name,
department_id=asset.department_id,
department_name=asset.department.name if asset.department else None,
location_name=asset.location.name if asset.location else None,
service_mode=s.service_mode,
frequency_months=s.frequency_months,
responsible_team=s.responsible_team,
provider_id=s.provider_id,
provider_name=s.provider.name if s.provider else None,
contract_id=s.contract_id,
contract_summary=contract_summary,
next_planned_date=s.next_planned_date,
is_active=s.is_active,
created_at=s.created_at,
)
def _to_record_out(
rec: PMRecord,
today: date,
leads: dict[str, int],
) -> PMRecordOut:
sched = rec.schedule
asset = rec.asset
mode = sched.service_mode
lead_days = leads["in_house"] if mode == "in_house" else leads["outsourced"]
if rec.status in ("completed", "rescheduled"):
comp_status, severity = rec.status, "ok"
else:
comp_status, severity = compute_schedule_status(
rec.planned_date, None, today, lead_days, leads["red"]
)
return PMRecordOut(
id=rec.id,
schedule_id=rec.schedule_id,
asset_id=rec.asset_id,
asset_code=asset.asset_code,
asset_name=asset.name,
department_id=asset.department_id,
department_name=asset.department.name if asset.department else None,
location_name=asset.location.name if asset.location else None,
service_mode=mode,
responsible_team=sched.responsible_team,
provider_id=sched.provider_id,
provider_name=sched.provider.name if sched.provider else None,
contract_id=sched.contract_id,
planned_date=rec.planned_date,
completed_date=rec.completed_date,
status=comp_status,
severity=severity,
service_details=rec.service_details,
remarks=rec.remarks,
rescheduled_to=rec.rescheduled_to,
frequency_months=sched.frequency_months,
)
def _load_schedule_with_joins(db: Session, schedule_id: int) -> PMSchedule | None:
return (
db.query(PMSchedule)
.options(
joinedload(PMSchedule.asset).joinedload(Asset.department),
joinedload(PMSchedule.asset).joinedload(Asset.location),
joinedload(PMSchedule.provider),
joinedload(PMSchedule.contract),
)
.filter(PMSchedule.id == schedule_id)
.first()
)
def _load_record_with_joins(db: Session, record_id: int) -> PMRecord | None:
return (
db.query(PMRecord)
.options(
joinedload(PMRecord.asset).joinedload(Asset.department),
joinedload(PMRecord.asset).joinedload(Asset.location),
joinedload(PMRecord.schedule).joinedload(PMSchedule.provider),
)
.filter(PMRecord.id == record_id)
.first()
)
def _validate_schedule_fields(
db: Session,
*,
asset_id: int,
service_mode: str,
responsible_team: Optional[str],
provider_id: Optional[int],
contract_id: Optional[int],
) -> tuple[Optional[str], Optional[int], Optional[int]]:
if service_mode == "in_house":
clean_team = responsible_team.strip() if responsible_team else ""
if not clean_team:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="responsible_team is required for in_house PM schedules.",
)
return clean_team, None, None
if provider_id is None:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="provider_id is required for outsourced PM schedules.",
)
provider = db.query(Vendor.id).filter(Vendor.id == provider_id).first()
if provider is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Service provider vendor not found.")
if contract_id is not None:
contract = db.query(Contract).filter(Contract.id == contract_id).first()
if contract is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
if contract.asset_id != asset_id:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Contract does not belong to the selected asset.",
)
clean_team = responsible_team.strip() if responsible_team and responsible_team.strip() else None
return clean_team, provider_id, contract_id
@router.get("/schedules", response_model=PMScheduleListOut)
def list_pm_schedules(
q: str = "",
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
service_mode: Optional[PMServiceMode] = None,
is_active: Optional[bool] = None,
page: int = Query(1, ge=1),
page_size: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
query = (
db.query(PMSchedule)
.join(Asset, PMSchedule.asset_id == Asset.id)
.outerjoin(Vendor, PMSchedule.provider_id == Vendor.id)
.options(
joinedload(PMSchedule.asset).joinedload(Asset.department),
joinedload(PMSchedule.asset).joinedload(Asset.location),
joinedload(PMSchedule.provider),
joinedload(PMSchedule.contract),
)
)
if current_user.role == Role.department_user.value:
query = query.filter(Asset.department_id == current_user.department_id)
elif department_id is not None:
query = query.filter(Asset.department_id == department_id)
if asset_id is not None:
query = query.filter(PMSchedule.asset_id == asset_id)
if service_mode is not None:
query = query.filter(PMSchedule.service_mode == service_mode)
if is_active is not None:
query = query.filter(PMSchedule.is_active.is_(is_active))
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Asset.asset_code.ilike(like),
Asset.name.ilike(like),
PMSchedule.responsible_team.ilike(like),
Vendor.name.ilike(like),
)
)
total = query.count()
rows = (
query.order_by(PMSchedule.next_planned_date.asc(), PMSchedule.id.asc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return PMScheduleListOut(items=[_to_schedule_out(s) for s in rows], total=total)
@router.post("/schedules", response_model=PMScheduleOut, status_code=status.HTTP_201_CREATED)
def create_pm_schedule(
payload: PMScheduleCreate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
asset = db.query(Asset).filter(Asset.id == payload.asset_id).first()
if asset is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
clean_team, provider_id, contract_id = _validate_schedule_fields(
db,
asset_id=asset.id,
service_mode=payload.service_mode,
responsible_team=payload.responsible_team,
provider_id=payload.provider_id,
contract_id=payload.contract_id,
)
schedule = PMSchedule(
asset_id=asset.id,
service_mode=payload.service_mode,
frequency_months=payload.frequency_months,
responsible_team=clean_team,
provider_id=provider_id,
contract_id=contract_id,
next_planned_date=payload.next_planned_date,
is_active=True,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(schedule)
db.flush()
initial_record = PMRecord(
schedule_id=schedule.id,
asset_id=asset.id,
planned_date=payload.next_planned_date,
status=None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(initial_record)
db.flush()
log_audit(
db,
entity_type="pm_schedule",
entity_id=schedule.id,
action="create",
changes={
"asset_id": asset.id,
"service_mode": payload.service_mode,
"frequency_months": payload.frequency_months,
"next_planned_date": str(payload.next_planned_date),
"initial_record_id": initial_record.id,
},
user_id=current_user.id,
)
db.commit()
loaded = _load_schedule_with_joins(db, schedule.id)
return _to_schedule_out(loaded)
@router.patch("/schedules/{schedule_id}", response_model=PMScheduleOut)
def update_pm_schedule(
schedule_id: int,
payload: PMScheduleUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
schedule = db.query(PMSchedule).filter(PMSchedule.id == schedule_id).first()
if schedule is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM schedule not found.")
data = payload.model_dump(exclude_unset=True)
target_mode = data.get("service_mode", schedule.service_mode)
target_team = data.get("responsible_team", schedule.responsible_team)
target_provider = data.get("provider_id", schedule.provider_id)
target_contract = data.get("contract_id", schedule.contract_id)
clean_team, provider_id, contract_id = _validate_schedule_fields(
db,
asset_id=schedule.asset_id,
service_mode=target_mode,
responsible_team=target_team,
provider_id=target_provider,
contract_id=target_contract,
)
data["responsible_team"] = clean_team
data["provider_id"] = provider_id
data["contract_id"] = contract_id
changes: dict[str, dict[str, object]] = {}
old_next_date = schedule.next_planned_date
for k, v in data.items():
old_val = getattr(schedule, k)
if old_val != v:
changes[k] = {"from": old_val, "to": v}
setattr(schedule, k, v)
schedule.updated_by_id = current_user.id
if "next_planned_date" in data and schedule.next_planned_date != old_next_date:
open_rec = (
db.query(PMRecord)
.filter(PMRecord.schedule_id == schedule.id, PMRecord.status.is_(None))
.order_by(PMRecord.planned_date.desc(), PMRecord.id.desc())
.first()
)
if open_rec is not None:
open_rec.planned_date = schedule.next_planned_date
open_rec.updated_by_id = current_user.id
if changes:
log_audit(
db,
entity_type="pm_schedule",
entity_id=schedule.id,
action="update",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_schedule_with_joins(db, schedule.id)
return _to_schedule_out(loaded)
@router.delete("/schedules/{schedule_id}", response_model=PMScheduleOut)
def deactivate_pm_schedule(
schedule_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
schedule = db.query(PMSchedule).filter(PMSchedule.id == schedule_id).first()
if schedule is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM schedule not found.")
if schedule.is_active:
schedule.is_active = False
schedule.updated_by_id = current_user.id
log_audit(
db,
entity_type="pm_schedule",
entity_id=schedule.id,
action="deactivate",
changes={"is_active": {"from": True, "to": False}},
user_id=current_user.id,
)
db.commit()
loaded = _load_schedule_with_joins(db, schedule.id)
return _to_schedule_out(loaded)
@router.get("/records", response_model=PMRecordListOut)
def list_pm_records(
q: str = "",
month: Optional[str] = None,
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
schedule_id: Optional[int] = None,
service_mode: Optional[PMServiceMode] = None,
status_filter: Optional[PMRecordStatusFilter] = Query(None, alias="status"),
page: int = Query(1, ge=1),
page_size: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
today = effective_today(db)
leads = _pm_lead_settings(db)
query = (
db.query(PMRecord)
.join(PMSchedule, PMRecord.schedule_id == PMSchedule.id)
.join(Asset, PMRecord.asset_id == Asset.id)
.outerjoin(Vendor, PMSchedule.provider_id == Vendor.id)
.options(
joinedload(PMRecord.asset).joinedload(Asset.department),
joinedload(PMRecord.asset).joinedload(Asset.location),
joinedload(PMRecord.schedule).joinedload(PMSchedule.provider),
)
)
if current_user.role == Role.department_user.value:
query = query.filter(Asset.department_id == current_user.department_id)
elif department_id is not None:
query = query.filter(Asset.department_id == department_id)
if asset_id is not None:
query = query.filter(PMRecord.asset_id == asset_id)
if schedule_id is not None:
query = query.filter(PMRecord.schedule_id == schedule_id)
if service_mode is not None:
query = query.filter(PMSchedule.service_mode == service_mode)
target_year, target_month = today.year, today.month
if month is not None and month.strip():
m_match = _MONTH_RE.fullmatch(month.strip())
if not m_match:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="month must be in YYYY-MM format.",
)
target_year = int(m_match.group(1))
target_month = int(m_match.group(2))
month_start = date(target_year, target_month, 1)
next_month_start = add_months(month_start, 1)
query = query.filter(
PMRecord.planned_date >= month_start,
PMRecord.planned_date < next_month_start,
)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Asset.asset_code.ilike(like),
Asset.name.ilike(like),
PMSchedule.responsible_team.ilike(like),
Vendor.name.ilike(like),
PMRecord.service_details.ilike(like),
PMRecord.remarks.ilike(like),
)
)
rows = query.order_by(PMRecord.planned_date.asc(), PMRecord.id.asc()).all()
computed_all = [_to_record_out(r, today, leads) for r in rows]
upcoming_cnt = sum(1 for item in computed_all if item.status == "upcoming")
due_cnt = sum(1 for item in computed_all if item.status == "due")
overdue_cnt = sum(1 for item in computed_all if item.status == "overdue")
completed_month_cnt = 0
for item in computed_all:
if item.status == "completed":
ref_date = item.completed_date or item.planned_date
if (ref_date.year == target_year and ref_date.month == target_month) or (
item.planned_date.year == target_year and item.planned_date.month == target_month
):
completed_month_cnt += 1
if status_filter is not None:
filtered = [item for item in computed_all if item.status == status_filter]
else:
filtered = computed_all
total = len(filtered)
start = (page - 1) * page_size
paginated = filtered[start : start + page_size]
return PMRecordListOut(
items=paginated,
total=total,
summary=PMRecordSummaryCounts(
upcoming=upcoming_cnt,
due=due_cnt,
overdue=overdue_cnt,
completed_this_month=completed_month_cnt,
),
)
@router.post("/records/{record_id}/complete", response_model=PMRecordCompleteOut)
def complete_pm_record(
record_id: int,
payload: PMRecordCompleteIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
rec = _load_record_with_joins(db, record_id)
if rec is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM record not found.")
if rec.status in ("completed", "rescheduled"):
raise CodedHTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"PM record is already {rec.status}.",
code="INVALID_PM_STATUS",
)
clean_details = payload.service_details.strip()
if not clean_details:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="service_details cannot be blank.",
)
rec.status = "completed"
rec.completed_date = payload.completed_date
rec.service_details = clean_details
rec.remarks = payload.remarks.strip() if payload.remarks and payload.remarks.strip() else None
rec.updated_by_id = current_user.id
schedule = rec.schedule
next_date = add_months(payload.completed_date, schedule.frequency_months)
schedule.next_planned_date = next_date
schedule.updated_by_id = current_user.id
next_rec = PMRecord(
schedule_id=schedule.id,
asset_id=schedule.asset_id,
planned_date=next_date,
status=None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(next_rec)
db.flush()
log_audit(
db,
entity_type="pm_record",
entity_id=rec.id,
action="complete",
changes={
"completed_date": str(payload.completed_date),
"next_planned_date": str(next_date),
"next_record_id": next_rec.id,
},
user_id=current_user.id,
)
db.commit()
today = effective_today(db)
leads = _pm_lead_settings(db)
loaded_completed = _load_record_with_joins(db, rec.id)
loaded_next = _load_record_with_joins(db, next_rec.id)
return PMRecordCompleteOut(
completed_record=_to_record_out(loaded_completed, today, leads),
next_record=_to_record_out(loaded_next, today, leads),
)
@router.post("/records/{record_id}/reschedule", response_model=PMRecordRescheduleOut)
def reschedule_pm_record(
record_id: int,
payload: PMRecordRescheduleIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
rec = _load_record_with_joins(db, record_id)
if rec is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM record not found.")
if rec.status in ("completed", "rescheduled"):
raise CodedHTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"PM record is already {rec.status}.",
code="INVALID_PM_STATUS",
)
rec.status = "rescheduled"
rec.rescheduled_to = payload.rescheduled_to
rec.remarks = payload.remarks.strip() if payload.remarks and payload.remarks.strip() else None
rec.updated_by_id = current_user.id
schedule = rec.schedule
schedule.next_planned_date = payload.rescheduled_to
schedule.updated_by_id = current_user.id
next_rec = PMRecord(
schedule_id=schedule.id,
asset_id=schedule.asset_id,
planned_date=payload.rescheduled_to,
status=None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(next_rec)
db.flush()
log_audit(
db,
entity_type="pm_record",
entity_id=rec.id,
action="reschedule",
changes={
"rescheduled_to": str(payload.rescheduled_to),
"next_record_id": next_rec.id,
},
user_id=current_user.id,
)
db.commit()
today = effective_today(db)
leads = _pm_lead_settings(db)
loaded_rescheduled = _load_record_with_joins(db, rec.id)
loaded_next = _load_record_with_joins(db, next_rec.id)
return PMRecordRescheduleOut(
rescheduled_record=_to_record_out(loaded_rescheduled, today, leads),
next_record=_to_record_out(loaded_next, today, leads),
)