phase-4: preventive maintenance and calibration modules
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import calendar
|
||||
from datetime import date, datetime, timezone
|
||||
import json
|
||||
import pytz
|
||||
@@ -56,6 +57,15 @@ def format_date(d: date | None) -> str | None:
|
||||
return d.strftime("%d-%b-%Y")
|
||||
|
||||
|
||||
def add_months(d: date, months: int) -> date:
|
||||
"""Add calendar months to a date, clamping day-of-month to the target month's length."""
|
||||
total_months = (d.year * 12 + (d.month - 1)) + months
|
||||
year, zero_month = divmod(total_months, 12)
|
||||
month = zero_month + 1
|
||||
max_day = calendar.monthrange(year, month)[1]
|
||||
return date(year, month, min(d.day, max_day))
|
||||
|
||||
|
||||
def format_duration(minutes: int | None) -> str:
|
||||
if minutes is None:
|
||||
return "\u2014"
|
||||
|
||||
+3
-1
@@ -7,7 +7,7 @@ from fastapi.responses import JSONResponse
|
||||
from .core.db import SessionLocal, engine
|
||||
from .core.exceptions import CodedHTTPException, coded_http_exception_handler
|
||||
from .models import Base
|
||||
from .routers import assets, attachments, auth, complaints, health, masters, settings, users
|
||||
from .routers import assets, attachments, auth, calibration, complaints, health, masters, pm, settings, users
|
||||
from .services.settings_service import ensure_default_settings
|
||||
|
||||
logging.basicConfig(
|
||||
@@ -63,3 +63,5 @@ app.include_router(users.router, prefix="/api")
|
||||
app.include_router(assets.router, prefix="/api")
|
||||
app.include_router(attachments.router, prefix="/api")
|
||||
app.include_router(complaints.router, prefix="/api")
|
||||
app.include_router(pm.router, prefix="/api")
|
||||
app.include_router(calibration.router, prefix="/api")
|
||||
|
||||
@@ -25,6 +25,7 @@ class CalibrationPlan(Base):
|
||||
|
||||
asset = relationship("Asset")
|
||||
agency = relationship("Vendor")
|
||||
approved_by = relationship("User", foreign_keys=[approved_by_id])
|
||||
|
||||
|
||||
class CalibrationRecord(Base):
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
@@ -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),
|
||||
)
|
||||
@@ -9,6 +9,19 @@ from .assets import (
|
||||
)
|
||||
from .attachments import AttachmentListOut, AttachmentOut
|
||||
from .auth import LoginRequest, TokenResponse, UserOut
|
||||
from .calibration import (
|
||||
CalibrationPlanApproveIn,
|
||||
CalibrationPlanBulkCreateIn,
|
||||
CalibrationPlanBulkOut,
|
||||
CalibrationPlanCreateFromAsset,
|
||||
CalibrationPlanListOut,
|
||||
CalibrationPlanOut,
|
||||
CalibrationPlanUpdateIn,
|
||||
CalibrationRecordCompleteIn,
|
||||
CalibrationRecordCompleteOut,
|
||||
CalibrationRecordListOut,
|
||||
CalibrationRecordOut,
|
||||
)
|
||||
from .complaints import (
|
||||
ComplaintAssignIn,
|
||||
ComplaintAttendIn,
|
||||
@@ -42,6 +55,18 @@ from .masters import (
|
||||
VendorOut,
|
||||
VendorUpdate,
|
||||
)
|
||||
from .pm import (
|
||||
PMRecordCompleteIn,
|
||||
PMRecordCompleteOut,
|
||||
PMRecordListOut,
|
||||
PMRecordOut,
|
||||
PMRecordRescheduleIn,
|
||||
PMRecordRescheduleOut,
|
||||
PMScheduleCreate,
|
||||
PMScheduleListOut,
|
||||
PMScheduleOut,
|
||||
PMScheduleUpdate,
|
||||
)
|
||||
from .settings import DemoDateIn, DemoDateOut, SettingItemOut, SettingsListOut, SettingsUpdateIn
|
||||
|
||||
__all__ = [
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
from datetime import date
|
||||
from typing import Literal, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
CalibrationStatusFilter = Literal["upcoming", "due", "overdue", "completed"]
|
||||
|
||||
|
||||
class CalibrationPlanCreateFromAsset(BaseModel):
|
||||
frequency_months: int = Field(..., ge=1, le=120)
|
||||
calibrations_per_year: Optional[int] = Field(None, ge=1, le=24)
|
||||
agency_id: Optional[int] = None
|
||||
next_due_date: date
|
||||
approve: bool = False
|
||||
|
||||
|
||||
class CalibrationPlanBulkCreateIn(BaseModel):
|
||||
asset_ids: list[int] = Field(..., min_length=1)
|
||||
frequency_months: int = Field(..., ge=1, le=120)
|
||||
calibrations_per_year: Optional[int] = Field(None, ge=1, le=24)
|
||||
agency_id: Optional[int] = None
|
||||
next_due_date: date
|
||||
approve: bool = False
|
||||
|
||||
|
||||
class CalibrationPlanUpdateIn(BaseModel):
|
||||
frequency_months: Optional[int] = Field(None, ge=1, le=120)
|
||||
calibrations_per_year: Optional[int] = Field(None, ge=1, le=24)
|
||||
agency_id: Optional[int] = None
|
||||
next_due_date: Optional[date] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class CalibrationPlanApproveIn(BaseModel):
|
||||
frequency_months: Optional[int] = Field(None, ge=1, le=120)
|
||||
calibrations_per_year: Optional[int] = Field(None, ge=1, le=24)
|
||||
|
||||
|
||||
class CalibrationPlanOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
asset_id: int
|
||||
asset_code: str
|
||||
asset_name: str
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
frequency_months: int
|
||||
calibrations_per_year: int
|
||||
agency_id: Optional[int] = None
|
||||
agency_name: Optional[str] = None
|
||||
approved_by_id: Optional[int] = None
|
||||
approved_by_name: Optional[str] = None
|
||||
approved_on: Optional[date] = None
|
||||
next_due_date: date
|
||||
is_active: bool
|
||||
|
||||
|
||||
class CalibrationPlanListOut(BaseModel):
|
||||
items: list[CalibrationPlanOut]
|
||||
total: int
|
||||
|
||||
|
||||
class CalibrationPlanBulkOut(BaseModel):
|
||||
created: list[CalibrationPlanOut]
|
||||
skipped_asset_ids: list[int]
|
||||
|
||||
|
||||
class CalibrationRecordSummaryCounts(BaseModel):
|
||||
upcoming: int
|
||||
due: int
|
||||
overdue: int
|
||||
completed: int
|
||||
|
||||
|
||||
class CalibrationRecordOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
plan_id: int
|
||||
asset_id: int
|
||||
asset_code: str
|
||||
asset_name: str
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
location_name: Optional[str] = None
|
||||
due_date: date
|
||||
completed_date: Optional[date] = None
|
||||
agency_id: Optional[int] = None
|
||||
agency_name: Optional[str] = None
|
||||
certificate_no: Optional[str] = None
|
||||
remarks: Optional[str] = None
|
||||
status: str
|
||||
severity: str
|
||||
frequency_months: int
|
||||
approved_by_name: Optional[str] = None
|
||||
approved_on: Optional[date] = None
|
||||
|
||||
|
||||
class CalibrationRecordListOut(BaseModel):
|
||||
items: list[CalibrationRecordOut]
|
||||
total: int
|
||||
summary: CalibrationRecordSummaryCounts
|
||||
|
||||
|
||||
class CalibrationRecordCompleteIn(BaseModel):
|
||||
completed_date: date
|
||||
certificate_no: str = Field(..., min_length=1)
|
||||
agency_id: Optional[int] = None
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class CalibrationRecordCompleteOut(BaseModel):
|
||||
completed_record: CalibrationRecordOut
|
||||
next_record: CalibrationRecordOut
|
||||
@@ -0,0 +1,113 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Literal, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
PMServiceMode = Literal["in_house", "outsourced"]
|
||||
PMRecordStatusFilter = Literal["upcoming", "due", "overdue", "completed", "rescheduled"]
|
||||
|
||||
|
||||
class PMScheduleCreate(BaseModel):
|
||||
asset_id: int
|
||||
service_mode: PMServiceMode
|
||||
frequency_months: int = Field(..., ge=1, le=120)
|
||||
responsible_team: Optional[str] = None
|
||||
provider_id: Optional[int] = None
|
||||
contract_id: Optional[int] = None
|
||||
next_planned_date: date
|
||||
|
||||
|
||||
class PMScheduleUpdate(BaseModel):
|
||||
service_mode: Optional[PMServiceMode] = None
|
||||
frequency_months: Optional[int] = Field(None, ge=1, le=120)
|
||||
responsible_team: Optional[str] = None
|
||||
provider_id: Optional[int] = None
|
||||
contract_id: Optional[int] = None
|
||||
next_planned_date: Optional[date] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class PMScheduleOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
asset_id: int
|
||||
asset_code: str
|
||||
asset_name: str
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
location_name: Optional[str] = None
|
||||
service_mode: str
|
||||
frequency_months: int
|
||||
responsible_team: Optional[str] = None
|
||||
provider_id: Optional[int] = None
|
||||
provider_name: Optional[str] = None
|
||||
contract_id: Optional[int] = None
|
||||
contract_summary: Optional[str] = None
|
||||
next_planned_date: date
|
||||
is_active: bool
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class PMScheduleListOut(BaseModel):
|
||||
items: list[PMScheduleOut]
|
||||
total: int
|
||||
|
||||
|
||||
class PMRecordSummaryCounts(BaseModel):
|
||||
upcoming: int
|
||||
due: int
|
||||
overdue: int
|
||||
completed_this_month: int
|
||||
|
||||
|
||||
class PMRecordOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
schedule_id: int
|
||||
asset_id: int
|
||||
asset_code: str
|
||||
asset_name: str
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
location_name: Optional[str] = None
|
||||
service_mode: str
|
||||
responsible_team: Optional[str] = None
|
||||
provider_id: Optional[int] = None
|
||||
provider_name: Optional[str] = None
|
||||
contract_id: Optional[int] = None
|
||||
planned_date: date
|
||||
completed_date: Optional[date] = None
|
||||
status: str
|
||||
severity: str
|
||||
service_details: Optional[str] = None
|
||||
remarks: Optional[str] = None
|
||||
rescheduled_to: Optional[date] = None
|
||||
frequency_months: int
|
||||
|
||||
|
||||
class PMRecordListOut(BaseModel):
|
||||
items: list[PMRecordOut]
|
||||
total: int
|
||||
summary: PMRecordSummaryCounts
|
||||
|
||||
|
||||
class PMRecordCompleteIn(BaseModel):
|
||||
completed_date: date
|
||||
service_details: str = Field(..., min_length=1)
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class PMRecordCompleteOut(BaseModel):
|
||||
completed_record: PMRecordOut
|
||||
next_record: PMRecordOut
|
||||
|
||||
|
||||
class PMRecordRescheduleIn(BaseModel):
|
||||
rescheduled_to: date
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class PMRecordRescheduleOut(BaseModel):
|
||||
rescheduled_record: PMRecordOut
|
||||
next_record: PMRecordOut
|
||||
@@ -187,6 +187,46 @@ SETTINGS_SCHEMA: list[dict[str, Any]] = [
|
||||
"max": None,
|
||||
"options": ["attended_at", "restored_at", "closed_at"],
|
||||
},
|
||||
{
|
||||
"key": "pm_inhouse_lead_days",
|
||||
"type": "int",
|
||||
"default": 15,
|
||||
"label": "In-House PM Lead Days",
|
||||
"description": "Days before planned in-house PM date when status transitions from upcoming to due.",
|
||||
"min": 1,
|
||||
"max": 90,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "pm_outsourced_lead_days",
|
||||
"type": "int",
|
||||
"default": 15,
|
||||
"label": "Outsourced PM Lead Days",
|
||||
"description": "Days before planned outsourced PM date when status transitions from upcoming to due.",
|
||||
"min": 1,
|
||||
"max": 90,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "calibration_lead_days",
|
||||
"type": "int",
|
||||
"default": 15,
|
||||
"label": "Calibration Lead Days",
|
||||
"description": "Days before calibration due date when status transitions from upcoming to due.",
|
||||
"min": 1,
|
||||
"max": 90,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "red_threshold_days",
|
||||
"type": "int",
|
||||
"default": 7,
|
||||
"label": "Critical Alert Threshold Days",
|
||||
"description": "Days remaining at or below which a due schedule alert escalates to critical (red).",
|
||||
"min": 1,
|
||||
"max": 60,
|
||||
"options": None,
|
||||
},
|
||||
]
|
||||
|
||||
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
from datetime import date
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import add_months
|
||||
from app.models import (
|
||||
Asset,
|
||||
CalibrationPlan,
|
||||
CalibrationRecord,
|
||||
Category,
|
||||
Contract,
|
||||
Department,
|
||||
Location,
|
||||
PMRecord,
|
||||
PMSchedule,
|
||||
Vendor,
|
||||
)
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_pm_cal_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("pm_cal_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 _create_test_asset(client, headers, db, code_suffix: str, req_cal: bool = False) -> int:
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
loc = db.query(Location).filter(Location.department_id == icu.id).first()
|
||||
cat = db.query(Category).first()
|
||||
res = client.post(
|
||||
"/api/assets",
|
||||
headers=headers,
|
||||
json={
|
||||
"asset_code": f"PHRC-PMCAL-{code_suffix}",
|
||||
"serial_no": f"SN-PMCAL-{code_suffix}",
|
||||
"name": f"PM Cal Test Unit {code_suffix}",
|
||||
"category_id": cat.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": loc.id,
|
||||
"status": "in_service",
|
||||
"criticality": "critical",
|
||||
"requires_calibration": req_cal,
|
||||
"insurance_applicable": False,
|
||||
},
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
return res.json()["id"]
|
||||
|
||||
|
||||
def test_add_months_clamping_and_db_note_n2(db):
|
||||
assert add_months(date(2026, 1, 31), 1) == date(2026, 2, 28)
|
||||
assert add_months(date(2024, 1, 31), 1) == date(2024, 2, 29)
|
||||
assert add_months(date(2026, 3, 31), 3) == date(2026, 6, 30)
|
||||
assert add_months(date(2026, 10, 15), 4) == date(2027, 2, 15)
|
||||
|
||||
# Note N2: seeded DB never persists 'upcoming', 'due', or 'overdue'
|
||||
bad_cal = (
|
||||
db.query(CalibrationRecord)
|
||||
.filter(CalibrationRecord.status.in_(["upcoming", "due", "overdue"]))
|
||||
.count()
|
||||
)
|
||||
bad_pm = (
|
||||
db.query(PMRecord)
|
||||
.filter(PMRecord.status.in_(["upcoming", "due", "overdue"]))
|
||||
.count()
|
||||
)
|
||||
assert bad_cal == 0
|
||||
assert bad_pm == 0
|
||||
|
||||
|
||||
def test_outsourced_pm_lifecycle_complete_and_reschedule(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
|
||||
provider = db.query(Vendor).filter(Vendor.vendor_type == "service_provider").first()
|
||||
contract = db.query(Contract).filter(Contract.is_superseded.is_(False)).first()
|
||||
asset_id = contract.asset_id
|
||||
|
||||
# Forbidden for department_user and management
|
||||
forbid_res = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"service_mode": "in_house",
|
||||
"frequency_months": 3,
|
||||
"responsible_team": "ICU Bio",
|
||||
"next_planned_date": "2026-06-10",
|
||||
},
|
||||
)
|
||||
assert forbid_res.status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=mgmt_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"service_mode": "in_house",
|
||||
"frequency_months": 3,
|
||||
"responsible_team": "Bio Team",
|
||||
"next_planned_date": "2026-06-10",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# Validation: outsourced requires provider_id
|
||||
bad_out = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"service_mode": "outsourced",
|
||||
"frequency_months": 3,
|
||||
"next_planned_date": "2026-06-10",
|
||||
},
|
||||
)
|
||||
assert bad_out.status_code == 422
|
||||
|
||||
# Create outsourced PM schedule with provider + contract
|
||||
sched_res = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"service_mode": "outsourced",
|
||||
"frequency_months": 3,
|
||||
"provider_id": contract.provider_id or provider.id,
|
||||
"contract_id": contract.id,
|
||||
"next_planned_date": "2026-06-10",
|
||||
},
|
||||
)
|
||||
assert sched_res.status_code == 201, sched_res.text
|
||||
sched = sched_res.json()
|
||||
assert sched["service_mode"] == "outsourced"
|
||||
assert sched["contract_id"] == contract.id
|
||||
assert sched["contract_summary"] is not None
|
||||
|
||||
# Initial PMRecord was created with planned_date=2026-06-10 and DB status=None
|
||||
recs_res = client.get(f"/api/pm/records?schedule_id={sched['id']}", headers=bio_headers)
|
||||
assert recs_res.status_code == 200
|
||||
items = recs_res.json()["items"]
|
||||
assert len(items) == 1
|
||||
first_rec_id = items[0]["id"]
|
||||
assert items[0]["planned_date"] == "2026-06-10"
|
||||
db.expire_all()
|
||||
assert db.query(PMRecord).filter(PMRecord.id == first_rec_id).first().status is None
|
||||
|
||||
# Complete the initial PMRecord on 2026-06-12 -> next planned 2026-09-12
|
||||
comp_res = client.post(
|
||||
f"/api/pm/records/{first_rec_id}/complete",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"completed_date": "2026-06-12",
|
||||
"service_details": "Replaced flow sensor filter and verified pressure calibration.",
|
||||
"remarks": "Vendor engineer visit completed.",
|
||||
},
|
||||
)
|
||||
assert comp_res.status_code == 200, comp_res.text
|
||||
comp_data = comp_res.json()
|
||||
assert comp_data["completed_record"]["status"] == "completed"
|
||||
assert comp_data["completed_record"]["completed_date"] == "2026-06-12"
|
||||
assert comp_data["next_record"]["planned_date"] == "2026-09-12"
|
||||
|
||||
# Re-completing same record -> 400
|
||||
recomp = client.post(
|
||||
f"/api/pm/records/{first_rec_id}/complete",
|
||||
headers=bio_headers,
|
||||
json={"completed_date": "2026-06-13", "service_details": "Duplicate"},
|
||||
)
|
||||
assert recomp.status_code == 400
|
||||
|
||||
# Reschedule the generated next record from 2026-09-12 to 2026-09-25
|
||||
second_rec_id = comp_data["next_record"]["id"]
|
||||
resched_res = client.post(
|
||||
f"/api/pm/records/{second_rec_id}/reschedule",
|
||||
headers=bio_headers,
|
||||
json={"rescheduled_to": "2026-09-25", "remarks": "OT occupied on 12 Sep."},
|
||||
)
|
||||
assert resched_res.status_code == 200, resched_res.text
|
||||
resched_data = resched_res.json()
|
||||
assert resched_data["rescheduled_record"]["status"] == "rescheduled"
|
||||
assert resched_data["rescheduled_record"]["rescheduled_to"] == "2026-09-25"
|
||||
assert resched_data["next_record"]["planned_date"] == "2026-09-25"
|
||||
|
||||
# Verify schedule next_planned_date updated and deactivate schedule works
|
||||
del_res = client.delete(f"/api/pm/schedules/{sched['id']}", headers=bio_headers)
|
||||
assert del_res.status_code == 200
|
||||
assert del_res.json()["is_active"] is False
|
||||
|
||||
|
||||
def test_calibration_plan_approval_permissions_and_completion(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
a1 = _create_test_asset(client, bio_headers, db, "001", req_cal=False)
|
||||
a2 = _create_test_asset(client, bio_headers, db, "002", req_cal=False)
|
||||
a3 = _create_test_asset(client, bio_headers, db, "003", req_cal=True)
|
||||
agency = db.query(Vendor).filter(Vendor.vendor_type == "calibration_agency").first()
|
||||
|
||||
# Biomedical cannot create with approve=True
|
||||
forbid_create_app = client.post(
|
||||
f"/api/calibration/plans/from-asset/{a1}",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"frequency_months": 6,
|
||||
"agency_id": agency.id,
|
||||
"next_due_date": "2026-08-01",
|
||||
"approve": True,
|
||||
},
|
||||
)
|
||||
assert forbid_create_app.status_code == 403
|
||||
assert forbid_create_app.json()["code"] == "FORBIDDEN_CALIBRATION_APPROVAL"
|
||||
|
||||
# Biomedical creates unapproved plan from asset -> sets requires_calibration=True
|
||||
c1 = client.post(
|
||||
f"/api/calibration/plans/from-asset/{a1}",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"frequency_months": 6,
|
||||
"agency_id": agency.id,
|
||||
"next_due_date": "2026-08-01",
|
||||
"approve": False,
|
||||
},
|
||||
)
|
||||
assert c1.status_code == 201, c1.text
|
||||
plan1 = c1.json()
|
||||
assert plan1["calibrations_per_year"] == 2
|
||||
assert plan1["approved_by_id"] is None
|
||||
db.expire_all()
|
||||
assert db.query(Asset).filter(Asset.id == a1).first().requires_calibration is True
|
||||
|
||||
# Duplicate from-asset -> 409 DUPLICATE_CALIBRATION_PLAN
|
||||
dup = client.post(
|
||||
f"/api/calibration/plans/from-asset/{a1}",
|
||||
headers=bio_headers,
|
||||
json={"frequency_months": 6, "next_due_date": "2026-08-01"},
|
||||
)
|
||||
assert dup.status_code == 409
|
||||
assert dup.json()["code"] == "DUPLICATE_CALIBRATION_PLAN"
|
||||
|
||||
# Bulk add with a1 (already has plan) + a2 + a3
|
||||
bulk_res = client.post(
|
||||
"/api/calibration/plans/bulk-from-assets",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_ids": [a1, a2, a3],
|
||||
"frequency_months": 12,
|
||||
"agency_id": agency.id,
|
||||
"next_due_date": "2026-10-15",
|
||||
"approve": False,
|
||||
},
|
||||
)
|
||||
assert bulk_res.status_code == 200, bulk_res.text
|
||||
bulk_json = bulk_res.json()
|
||||
assert [p["asset_id"] for p in bulk_json["created"]] == [a2, a3]
|
||||
assert bulk_json["skipped_asset_ids"] == [a1]
|
||||
|
||||
# Biomedical gets 403 trying to modify frequency or approve; management succeeds (200)
|
||||
bio_freq = client.put(
|
||||
f"/api/calibration/plans/{plan1['id']}",
|
||||
headers=bio_headers,
|
||||
json={"frequency_months": 12},
|
||||
)
|
||||
assert bio_freq.status_code == 403
|
||||
assert bio_freq.json()["code"] == "FORBIDDEN_CALIBRATION_APPROVAL"
|
||||
|
||||
bio_app = client.post(f"/api/calibration/plans/{plan1['id']}/approve", headers=bio_headers)
|
||||
assert bio_app.status_code == 403
|
||||
|
||||
assert client.post(f"/api/calibration/plans/{plan1['id']}/approve", headers=dept_headers).status_code == 403
|
||||
|
||||
mgmt_freq = client.put(
|
||||
f"/api/calibration/plans/{plan1['id']}",
|
||||
headers=mgmt_headers,
|
||||
json={"frequency_months": 4},
|
||||
)
|
||||
assert mgmt_freq.status_code == 200
|
||||
assert mgmt_freq.json()["frequency_months"] == 4
|
||||
assert mgmt_freq.json()["calibrations_per_year"] == 3
|
||||
|
||||
mgmt_app = client.post(
|
||||
f"/api/calibration/plans/{plan1['id']}/approve",
|
||||
headers=mgmt_headers,
|
||||
json={"frequency_months": 6},
|
||||
)
|
||||
assert mgmt_app.status_code == 200, mgmt_app.text
|
||||
assert mgmt_app.json()["frequency_months"] == 6
|
||||
assert mgmt_app.json()["approved_by_name"] is not None
|
||||
assert mgmt_app.json()["approved_on"] is not None
|
||||
|
||||
# Complete calibration record -> creates next record at completed_date + frequency_months and preserves history
|
||||
cal_recs = client.get(f"/api/calibration/records?asset_id={a1}", headers=bio_headers).json()["items"]
|
||||
assert len(cal_recs) == 1
|
||||
rec1_id = cal_recs[0]["id"]
|
||||
|
||||
comp = client.post(
|
||||
f"/api/calibration/records/{rec1_id}/complete",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"completed_date": "2026-08-05",
|
||||
"certificate_no": "NABL-2026-9901",
|
||||
"agency_id": agency.id,
|
||||
"remarks": "All channels within +/-1% tolerance.",
|
||||
},
|
||||
)
|
||||
assert comp.status_code == 200, comp.text
|
||||
comp_json = comp.json()
|
||||
assert comp_json["completed_record"]["status"] == "completed"
|
||||
assert comp_json["completed_record"]["certificate_no"] == "NABL-2026-9901"
|
||||
assert comp_json["next_record"]["due_date"] == "2027-02-05"
|
||||
|
||||
# Both historical and next records exist for asset
|
||||
history = client.get(f"/api/calibration/records?asset_id={a1}", headers=bio_headers).json()
|
||||
assert history["total"] == 2
|
||||
assert history["summary"]["completed"] == 1
|
||||
|
||||
|
||||
def test_demo_clock_transitions_statuses_dynamically_on_read(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
asset_id = _create_test_asset(client, bio_headers, db, "CLK", req_cal=True)
|
||||
agency = db.query(Vendor).filter(Vendor.vendor_type == "calibration_agency").first()
|
||||
|
||||
# Calibration due 2028-06-20; PM planned 2028-06-20 (far future, no interference)
|
||||
cal_plan = client.post(
|
||||
f"/api/calibration/plans/from-asset/{asset_id}",
|
||||
headers=admin_headers,
|
||||
json={
|
||||
"frequency_months": 12,
|
||||
"agency_id": agency.id,
|
||||
"next_due_date": "2028-06-20",
|
||||
"approve": True,
|
||||
},
|
||||
)
|
||||
assert cal_plan.status_code == 201
|
||||
|
||||
pm_sched = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"service_mode": "in_house",
|
||||
"frequency_months": 6,
|
||||
"responsible_team": "Bio Team A",
|
||||
"next_planned_date": "2028-06-20",
|
||||
},
|
||||
)
|
||||
assert pm_sched.status_code == 201
|
||||
|
||||
try:
|
||||
# 1) 2028-05-01 -> 50 days before due -> both 'upcoming' (ok)
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": "2028-05-01"},
|
||||
)
|
||||
cal1 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
pm1 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
ov1 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json()
|
||||
assert cal1["status"] == "upcoming" and cal1["severity"] == "ok"
|
||||
assert pm1["status"] == "upcoming" and pm1["severity"] == "ok"
|
||||
assert ov1["calibration_records"][0]["status"] == "upcoming"
|
||||
assert ov1["pm_records"][0]["status"] == "upcoming"
|
||||
|
||||
# 2) 2028-06-10 -> 10 days before due (<= 15 lead, > 7 red) -> both 'due' (yellow)
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": "2028-06-10"},
|
||||
)
|
||||
cal2 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
pm2 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
ov2 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json()
|
||||
assert cal2["status"] == "due" and cal2["severity"] == "yellow"
|
||||
assert pm2["status"] == "due" and pm2["severity"] == "yellow"
|
||||
assert ov2["calibration_records"][0]["status"] == "due"
|
||||
assert ov2["pm_records"][0]["status"] == "due"
|
||||
|
||||
# 3) 2028-06-15 -> 5 days before due (<= 7 red) -> 'due' (red)
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": "2028-06-15"},
|
||||
)
|
||||
cal3 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
pm3 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
assert cal3["status"] == "due" and cal3["severity"] == "red"
|
||||
assert pm3["status"] == "due" and pm3["severity"] == "red"
|
||||
|
||||
# 4) 2028-06-25 -> 5 days past due -> 'overdue' (red)
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": "2028-06-25"},
|
||||
)
|
||||
cal4 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
pm4 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
ov4 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json()
|
||||
assert cal4["status"] == "overdue" and cal4["severity"] == "red"
|
||||
assert pm4["status"] == "overdue" and pm4["severity"] == "red"
|
||||
assert ov4["calibration_records"][0]["status"] == "overdue"
|
||||
assert ov4["pm_records"][0]["status"] == "overdue"
|
||||
|
||||
# Confirm DB status columns stayed NULL throughout!
|
||||
db.expire_all()
|
||||
assert db.query(CalibrationRecord).filter(CalibrationRecord.asset_id == asset_id).first().status is None
|
||||
assert db.query(PMRecord).filter(PMRecord.asset_id == asset_id).first().status is None
|
||||
finally:
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": None},
|
||||
)
|
||||
Reference in New Issue
Block a user