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), )