phase-4: preventive maintenance and calibration modules

This commit is contained in:
Atharv1705
2026-11-12 14:16:38 +05:30
parent 905f6735a7
commit d3f22ba444
26 changed files with 5066 additions and 27 deletions
+3 -1
View File
@@ -58,13 +58,15 @@ cd backend
| mgmt@poona.demo | Demo@123 | Management | | mgmt@poona.demo | Demo@123 | Management |
| coord@poona.demo | Demo@123 | Coordinator | | coord@poona.demo | Demo@123 | Coordinator |
## What exists now (Phase 3) ## What exists now (Phase 4)
- Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules - Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules
- JWT authentication (`/api/auth/login`, `/api/auth/me`), RBAC permission matrix for 5 roles, and Quick Demo Login - JWT authentication (`/api/auth/login`, `/api/auth/me`), RBAC permission matrix for 5 roles, and Quick Demo Login
- Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users) - Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users)
- Typed System Settings (`/settings`) and TopBar "As of Date" Demo Clock (`POST /api/settings/demo-date`) - Typed System Settings (`/settings`) and TopBar "As of Date" Demo Clock (`POST /api/settings/demo-date`)
- Asset Register (`/assets` & `/assets/:id`): full CRUD with duplicate asset code check (`409`), department scoping, coordinator field-level edit restrictions, 8-tab Asset Detail Overview, and audit logging - Asset Register (`/assets` & `/assets/:id`): full CRUD with duplicate asset code check (`409`), department scoping, coordinator field-level edit restrictions, 8-tab Asset Detail Overview, and audit logging
- Breakdown & Complaint Register (`/complaints` & `/complaints/:id`): sequential complaint numbering, `AssetPicker` raise modal with multi-file attachments, response time & ongoing/milestone downtime calculations, assign/attend/restore/close/reopen workflow with asset status sync, event timeline, admin timestamp correction, and role-enforced technical/CE/spares section (`FORBIDDEN_TECHNICAL_FIELDS` 403 + read-only lock banner) - Breakdown & Complaint Register (`/complaints` & `/complaints/:id`): sequential complaint numbering, `AssetPicker` raise modal with multi-file attachments, response time & ongoing/milestone downtime calculations, assign/attend/restore/close/reopen workflow with asset status sync, event timeline, admin timestamp correction, and role-enforced technical/CE/spares section (`FORBIDDEN_TECHNICAL_FIELDS` 403 + read-only lock banner)
- Preventive Maintenance (`/pm`): in-house & outsourced PM schedules (`/api/pm/schedules`), dynamic read-time `upcoming`/`due`/`overdue`/`completed`/`rescheduled` status & severity evaluation against `effective_today()`, KPI summary strip, Table View & 7-column Mon–Sun Month Calendar View, Complete (auto-advancing next cycle via `add_months`) and Reschedule workflows, plus Asset Detail PM tab actions
- Calibration (`/calibration`): single & bulk calibration plan creation (`/api/calibration/plans/from-asset/:assetId`, `/bulk-from-assets`), management/admin/coordinator-gated frequency edit & approval (`FORBIDDEN_CALIBRATION_APPROVAL` 403 for biomedical), dynamic read-time status/severity computation, completion with certificate file upload (`calibration_record` attachments) and auto-generated next due cycle, plus Asset Detail Calibration tab wiring
- Reusable `AssetPicker` (`/api/assets/lookup`) with warranty/condemned status badges - Reusable `AssetPicker` (`/api/assets/lookup`) with warranty/condemned status badges
- Secure Document Attachments (`/api/attachments`: JPG/PNG/PDF validation with magic-byte check, 10 MB limit, authenticated preview/download, role-based upload/delete) - Secure Document Attachments (`/api/attachments`: JPG/PNG/PDF validation with magic-byte check, 10 MB limit, authenticated preview/download, role-based upload/delete)
- Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data - Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data
+10
View File
@@ -1,3 +1,4 @@
import calendar
from datetime import date, datetime, timezone from datetime import date, datetime, timezone
import json import json
import pytz import pytz
@@ -56,6 +57,15 @@ def format_date(d: date | None) -> str | None:
return d.strftime("%d-%b-%Y") 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: def format_duration(minutes: int | None) -> str:
if minutes is None: if minutes is None:
return "\u2014" return "\u2014"
+3 -1
View File
@@ -7,7 +7,7 @@ from fastapi.responses import JSONResponse
from .core.db import SessionLocal, engine from .core.db import SessionLocal, engine
from .core.exceptions import CodedHTTPException, coded_http_exception_handler from .core.exceptions import CodedHTTPException, coded_http_exception_handler
from .models import Base 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 from .services.settings_service import ensure_default_settings
logging.basicConfig( logging.basicConfig(
@@ -63,3 +63,5 @@ app.include_router(users.router, prefix="/api")
app.include_router(assets.router, prefix="/api") app.include_router(assets.router, prefix="/api")
app.include_router(attachments.router, prefix="/api") app.include_router(attachments.router, prefix="/api")
app.include_router(complaints.router, prefix="/api") app.include_router(complaints.router, prefix="/api")
app.include_router(pm.router, prefix="/api")
app.include_router(calibration.router, prefix="/api")
+1
View File
@@ -25,6 +25,7 @@ class CalibrationPlan(Base):
asset = relationship("Asset") asset = relationship("Asset")
agency = relationship("Vendor") agency = relationship("Vendor")
approved_by = relationship("User", foreign_keys=[approved_by_id])
class CalibrationRecord(Base): class CalibrationRecord(Base):
+3 -1
View File
@@ -1,12 +1,14 @@
from . import assets, attachments, auth, complaints, health, masters, settings, users from . import assets, attachments, auth, calibration, complaints, health, masters, pm, settings, users
__all__ = [ __all__ = [
"assets", "assets",
"attachments", "attachments",
"auth", "auth",
"calibration",
"complaints", "complaints",
"health", "health",
"masters", "masters",
"pm",
"settings", "settings",
"users", "users",
] ]
+11 -3
View File
@@ -59,9 +59,11 @@ def _lead_settings(db: Session) -> dict[str, int]:
"warranty": int(get_setting_value(db, "warranty_expiry_alert_days")), "warranty": int(get_setting_value(db, "warranty_expiry_alert_days")),
"contract": int(get_setting_value(db, "contract_expiry_alert_days")), "contract": int(get_setting_value(db, "contract_expiry_alert_days")),
"insurance": int(get_setting_value(db, "insurance_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")), "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 = ( pm_rec_rows = (
db.query(PMRecord) db.query(PMRecord)
.options(joinedload(PMRecord.schedule))
.filter(PMRecord.asset_id == asset.id) .filter(PMRecord.asset_id == asset.id)
.order_by(PMRecord.planned_date.desc(), PMRecord.id.desc()) .order_by(PMRecord.planned_date.desc(), PMRecord.id.desc())
.all() .all()
) )
pm_rec_out = [] pm_rec_out = []
for r in pm_rec_rows: 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( pm_rec_out.append(
PMRecordSummaryOut( PMRecordSummaryOut(
id=r.id, id=r.id,
+640
View File
@@ -0,0 +1,640 @@
from datetime import date
from typing import Optional
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
from sqlalchemy import or_
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user, require_roles
from ..core.exceptions import CodedHTTPException
from ..core.time_utils import add_months, effective_today
from ..models import Asset, CalibrationPlan, CalibrationRecord, User, Vendor
from ..schemas.calibration import (
CalibrationPlanApproveIn,
CalibrationPlanBulkCreateIn,
CalibrationPlanBulkOut,
CalibrationPlanCreateFromAsset,
CalibrationPlanListOut,
CalibrationPlanOut,
CalibrationPlanUpdateIn,
CalibrationRecordCompleteIn,
CalibrationRecordCompleteOut,
CalibrationRecordListOut,
CalibrationRecordOut,
CalibrationRecordSummaryCounts,
CalibrationStatusFilter,
)
from ..services.audit import log_audit
from ..services.calculations import compute_schedule_status
from ..services.permissions import Role
from ..services.settings_service import get_setting_value
router = APIRouter(prefix="/calibration", tags=["calibration"])
APPROVER_ROLES = {Role.management.value, Role.system_admin.value, Role.coordinator.value}
def _cal_lead_settings(db: Session) -> dict[str, int]:
return {
"lead": int(get_setting_value(db, "calibration_lead_days", 15)),
"red": int(get_setting_value(db, "red_threshold_days", 7)),
}
def _default_per_year(frequency_months: int) -> int:
return max(1, round(12 / frequency_months))
def _to_plan_out(plan: CalibrationPlan) -> CalibrationPlanOut:
asset = plan.asset
return CalibrationPlanOut(
id=plan.id,
asset_id=plan.asset_id,
asset_code=asset.asset_code,
asset_name=asset.name,
department_id=asset.department_id,
department_name=asset.department.name if asset.department else None,
frequency_months=plan.frequency_months,
calibrations_per_year=plan.calibrations_per_year,
agency_id=plan.agency_id,
agency_name=plan.agency.name if plan.agency else None,
approved_by_id=plan.approved_by_id,
approved_by_name=plan.approved_by.name if plan.approved_by else None,
approved_on=plan.approved_on,
next_due_date=plan.next_due_date,
is_active=plan.is_active,
)
def _to_record_out(
rec: CalibrationRecord,
today: date,
leads: dict[str, int],
) -> CalibrationRecordOut:
asset = rec.asset
plan = rec.plan
if rec.status == "completed":
comp_status, severity = "completed", "ok"
else:
comp_status, severity = compute_schedule_status(
rec.due_date, None, today, leads["lead"], leads["red"]
)
return CalibrationRecordOut(
id=rec.id,
plan_id=rec.plan_id,
asset_id=rec.asset_id,
asset_code=asset.asset_code,
asset_name=asset.name,
department_id=asset.department_id,
department_name=asset.department.name if asset.department else None,
location_name=asset.location.name if asset.location else None,
due_date=rec.due_date,
completed_date=rec.completed_date,
agency_id=rec.agency_id,
agency_name=rec.agency.name if rec.agency else None,
certificate_no=rec.certificate_no,
remarks=rec.remarks,
status=comp_status,
severity=severity,
frequency_months=plan.frequency_months,
approved_by_name=plan.approved_by.name if plan.approved_by else None,
approved_on=plan.approved_on,
)
def _load_plan_with_joins(db: Session, plan_id: int) -> CalibrationPlan | None:
return (
db.query(CalibrationPlan)
.options(
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
joinedload(CalibrationPlan.agency),
joinedload(CalibrationPlan.approved_by),
)
.filter(CalibrationPlan.id == plan_id)
.first()
)
def _load_record_with_joins(db: Session, record_id: int) -> CalibrationRecord | None:
return (
db.query(CalibrationRecord)
.options(
joinedload(CalibrationRecord.asset).joinedload(Asset.department),
joinedload(CalibrationRecord.asset).joinedload(Asset.location),
joinedload(CalibrationRecord.agency),
joinedload(CalibrationRecord.plan).joinedload(CalibrationPlan.approved_by),
)
.filter(CalibrationRecord.id == record_id)
.first()
)
def _create_plan_and_initial_record(
db: Session,
*,
asset: Asset,
frequency_months: int,
calibrations_per_year: Optional[int],
agency_id: Optional[int],
next_due_date: date,
approve: bool,
current_user: User,
today: date,
) -> CalibrationPlan:
asset.requires_calibration = True
asset.updated_by_id = current_user.id
per_year = calibrations_per_year or _default_per_year(frequency_months)
plan = CalibrationPlan(
asset_id=asset.id,
frequency_months=frequency_months,
calibrations_per_year=per_year,
agency_id=agency_id,
approved_by_id=current_user.id if approve else None,
approved_on=today if approve else None,
next_due_date=next_due_date,
is_active=True,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(plan)
db.flush()
initial_rec = CalibrationRecord(
asset_id=asset.id,
plan_id=plan.id,
due_date=next_due_date,
agency_id=agency_id,
status=None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(initial_rec)
db.flush()
log_audit(
db,
entity_type="calibration_plan",
entity_id=plan.id,
action="create",
changes={
"asset_id": asset.id,
"frequency_months": frequency_months,
"calibrations_per_year": per_year,
"next_due_date": str(next_due_date),
"approved": approve,
"initial_record_id": initial_rec.id,
},
user_id=current_user.id,
)
return plan
@router.get("/plans", response_model=CalibrationPlanListOut)
def list_calibration_plans(
q: str = "",
department_id: Optional[int] = None,
agency_id: Optional[int] = None,
is_active: Optional[bool] = None,
page: int = Query(1, ge=1),
page_size: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
query = (
db.query(CalibrationPlan)
.join(Asset, CalibrationPlan.asset_id == Asset.id)
.outerjoin(Vendor, CalibrationPlan.agency_id == Vendor.id)
.options(
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
joinedload(CalibrationPlan.agency),
joinedload(CalibrationPlan.approved_by),
)
)
if current_user.role == Role.department_user.value:
query = query.filter(Asset.department_id == current_user.department_id)
elif department_id is not None:
query = query.filter(Asset.department_id == department_id)
if agency_id is not None:
query = query.filter(CalibrationPlan.agency_id == agency_id)
if is_active is not None:
query = query.filter(CalibrationPlan.is_active.is_(is_active))
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Asset.asset_code.ilike(like),
Asset.name.ilike(like),
Vendor.name.ilike(like),
)
)
total = query.count()
rows = (
query.order_by(CalibrationPlan.next_due_date.asc(), CalibrationPlan.id.asc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return CalibrationPlanListOut(items=[_to_plan_out(p) for p in rows], total=total)
@router.post(
"/plans/from-asset/{asset_id}",
response_model=CalibrationPlanOut,
status_code=status.HTTP_201_CREATED,
)
def create_calibration_plan_from_asset(
asset_id: int,
payload: CalibrationPlanCreateFromAsset,
db: Session = Depends(get_db),
current_user: User = Depends(
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
),
):
asset = db.query(Asset).filter(Asset.id == asset_id).first()
if asset is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
existing = db.query(CalibrationPlan.id).filter(CalibrationPlan.asset_id == asset_id).first()
if existing is not None:
raise CodedHTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Calibration plan already exists for this asset.",
code="DUPLICATE_CALIBRATION_PLAN",
)
if payload.approve and current_user.role not in APPROVER_ROLES:
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only management, system_admin, or coordinator can approve calibration frequency.",
code="FORBIDDEN_CALIBRATION_APPROVAL",
)
if payload.agency_id is not None:
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
today = effective_today(db)
plan = _create_plan_and_initial_record(
db,
asset=asset,
frequency_months=payload.frequency_months,
calibrations_per_year=payload.calibrations_per_year,
agency_id=payload.agency_id,
next_due_date=payload.next_due_date,
approve=payload.approve,
current_user=current_user,
today=today,
)
db.commit()
loaded = _load_plan_with_joins(db, plan.id)
return _to_plan_out(loaded)
@router.post("/plans/bulk-from-assets", response_model=CalibrationPlanBulkOut)
def bulk_create_calibration_plans(
payload: CalibrationPlanBulkCreateIn,
db: Session = Depends(get_db),
current_user: User = Depends(
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
),
):
if payload.approve and current_user.role not in APPROVER_ROLES:
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only management, system_admin, or coordinator can approve calibration frequency.",
code="FORBIDDEN_CALIBRATION_APPROVAL",
)
if payload.agency_id is not None:
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
unique_ids = list(dict.fromkeys(payload.asset_ids))
assets_by_id = {a.id: a for a in db.query(Asset).filter(Asset.id.in_(unique_ids)).all()}
existing_asset_ids = {
row[0]
for row in db.query(CalibrationPlan.asset_id)
.filter(CalibrationPlan.asset_id.in_(unique_ids))
.all()
}
today = effective_today(db)
created_ids: list[int] = []
skipped_ids: list[int] = []
for aid in unique_ids:
asset = assets_by_id.get(aid)
if asset is None or aid in existing_asset_ids:
skipped_ids.append(aid)
continue
plan = _create_plan_and_initial_record(
db,
asset=asset,
frequency_months=payload.frequency_months,
calibrations_per_year=payload.calibrations_per_year,
agency_id=payload.agency_id,
next_due_date=payload.next_due_date,
approve=payload.approve,
current_user=current_user,
today=today,
)
created_ids.append(plan.id)
existing_asset_ids.add(aid)
db.commit()
created_out: list[CalibrationPlanOut] = []
if created_ids:
loaded_plans = (
db.query(CalibrationPlan)
.options(
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
joinedload(CalibrationPlan.agency),
joinedload(CalibrationPlan.approved_by),
)
.filter(CalibrationPlan.id.in_(created_ids))
.all()
)
by_id = {p.id: p for p in loaded_plans}
created_out = [_to_plan_out(by_id[pid]) for pid in created_ids if pid in by_id]
return CalibrationPlanBulkOut(created=created_out, skipped_asset_ids=skipped_ids)
@router.put("/plans/{plan_id}", response_model=CalibrationPlanOut)
def update_calibration_plan(
plan_id: int,
payload: CalibrationPlanUpdateIn,
db: Session = Depends(get_db),
current_user: User = Depends(
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
),
):
plan = db.query(CalibrationPlan).filter(CalibrationPlan.id == plan_id).first()
if plan is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration plan not found.")
data = payload.model_dump(exclude_unset=True)
if current_user.role == Role.biomedical.value:
if (
("frequency_months" in data and data["frequency_months"] is not None)
or ("calibrations_per_year" in data and data["calibrations_per_year"] is not None)
):
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Biomedical users cannot modify calibration frequency; management, coordinator, or system_admin approval is required.",
code="FORBIDDEN_CALIBRATION_APPROVAL",
)
if "agency_id" in data and data["agency_id"] is not None:
if not db.query(Vendor.id).filter(Vendor.id == data["agency_id"]).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
if "frequency_months" in data and data["frequency_months"] is not None and "calibrations_per_year" not in data:
data["calibrations_per_year"] = _default_per_year(data["frequency_months"])
old_due_date = plan.next_due_date
old_agency_id = plan.agency_id
changes: dict[str, dict[str, object]] = {}
for k, v in data.items():
if v is None and k in ("frequency_months", "calibrations_per_year", "next_due_date", "is_active"):
continue
old_val = getattr(plan, k)
if old_val != v:
changes[k] = {"from": old_val, "to": v}
setattr(plan, k, v)
plan.updated_by_id = current_user.id
if plan.next_due_date != old_due_date or plan.agency_id != old_agency_id:
open_rec = (
db.query(CalibrationRecord)
.filter(CalibrationRecord.plan_id == plan.id, CalibrationRecord.status.is_(None))
.order_by(CalibrationRecord.due_date.desc(), CalibrationRecord.id.desc())
.first()
)
if open_rec is not None:
open_rec.due_date = plan.next_due_date
open_rec.agency_id = plan.agency_id
open_rec.updated_by_id = current_user.id
if changes:
log_audit(
db,
entity_type="calibration_plan",
entity_id=plan.id,
action="update",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_plan_with_joins(db, plan.id)
return _to_plan_out(loaded)
@router.post("/plans/{plan_id}/approve", response_model=CalibrationPlanOut)
def approve_calibration_plan(
plan_id: int,
payload: Optional[CalibrationPlanApproveIn] = Body(default=None),
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.management, Role.system_admin, Role.coordinator)),
):
plan = db.query(CalibrationPlan).filter(CalibrationPlan.id == plan_id).first()
if plan is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration plan not found.")
today = effective_today(db)
changes: dict[str, dict[str, object]] = {}
if payload is not None:
if payload.frequency_months is not None and payload.frequency_months != plan.frequency_months:
changes["frequency_months"] = {"from": plan.frequency_months, "to": payload.frequency_months}
plan.frequency_months = payload.frequency_months
if payload.calibrations_per_year is None:
new_per_year = _default_per_year(payload.frequency_months)
if new_per_year != plan.calibrations_per_year:
changes["calibrations_per_year"] = {"from": plan.calibrations_per_year, "to": new_per_year}
plan.calibrations_per_year = new_per_year
if payload.calibrations_per_year is not None and payload.calibrations_per_year != plan.calibrations_per_year:
changes["calibrations_per_year"] = {"from": plan.calibrations_per_year, "to": payload.calibrations_per_year}
plan.calibrations_per_year = payload.calibrations_per_year
plan.approved_by_id = current_user.id
plan.approved_on = today
plan.updated_by_id = current_user.id
changes["approved_by_id"] = {"to": current_user.id}
changes["approved_on"] = {"to": str(today)}
log_audit(
db,
entity_type="calibration_plan",
entity_id=plan.id,
action="approve",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_plan_with_joins(db, plan.id)
return _to_plan_out(loaded)
@router.get("/records", response_model=CalibrationRecordListOut)
def list_calibration_records(
q: str = "",
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
agency_id: Optional[int] = None,
status_filter: Optional[CalibrationStatusFilter] = Query(None, alias="status"),
due_from: Optional[date] = None,
due_to: Optional[date] = None,
page: int = Query(1, ge=1),
page_size: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
today = effective_today(db)
leads = _cal_lead_settings(db)
query = (
db.query(CalibrationRecord)
.join(CalibrationPlan, CalibrationRecord.plan_id == CalibrationPlan.id)
.join(Asset, CalibrationRecord.asset_id == Asset.id)
.outerjoin(Vendor, CalibrationRecord.agency_id == Vendor.id)
.options(
joinedload(CalibrationRecord.asset).joinedload(Asset.department),
joinedload(CalibrationRecord.asset).joinedload(Asset.location),
joinedload(CalibrationRecord.agency),
joinedload(CalibrationRecord.plan).joinedload(CalibrationPlan.approved_by),
)
)
if current_user.role == Role.department_user.value:
query = query.filter(Asset.department_id == current_user.department_id)
elif department_id is not None:
query = query.filter(Asset.department_id == department_id)
if asset_id is not None:
query = query.filter(CalibrationRecord.asset_id == asset_id)
if agency_id is not None:
query = query.filter(CalibrationRecord.agency_id == agency_id)
if due_from is not None:
query = query.filter(CalibrationRecord.due_date >= due_from)
if due_to is not None:
query = query.filter(CalibrationRecord.due_date <= due_to)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Asset.asset_code.ilike(like),
Asset.name.ilike(like),
Vendor.name.ilike(like),
CalibrationRecord.certificate_no.ilike(like),
CalibrationRecord.remarks.ilike(like),
)
)
rows = query.order_by(CalibrationRecord.due_date.asc(), CalibrationRecord.id.asc()).all()
computed_all = [_to_record_out(r, today, leads) for r in rows]
summary = CalibrationRecordSummaryCounts(
upcoming=sum(1 for item in computed_all if item.status == "upcoming"),
due=sum(1 for item in computed_all if item.status == "due"),
overdue=sum(1 for item in computed_all if item.status == "overdue"),
completed=sum(1 for item in computed_all if item.status == "completed"),
)
if status_filter is not None:
filtered = [item for item in computed_all if item.status == status_filter]
else:
filtered = computed_all
total = len(filtered)
start = (page - 1) * page_size
paginated = filtered[start : start + page_size]
return CalibrationRecordListOut(items=paginated, total=total, summary=summary)
@router.post("/records/{record_id}/complete", response_model=CalibrationRecordCompleteOut)
def complete_calibration_record(
record_id: int,
payload: CalibrationRecordCompleteIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
rec = _load_record_with_joins(db, record_id)
if rec is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration record not found.")
if rec.status == "completed":
raise CodedHTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Calibration record is already completed.",
code="INVALID_CALIBRATION_STATUS",
)
clean_cert = payload.certificate_no.strip()
if not clean_cert:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="certificate_no cannot be blank.",
)
if payload.agency_id is not None:
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
rec.agency_id = payload.agency_id
rec.status = "completed"
rec.completed_date = payload.completed_date
rec.certificate_no = clean_cert
rec.remarks = payload.remarks.strip() if payload.remarks and payload.remarks.strip() else None
rec.updated_by_id = current_user.id
plan = rec.plan
next_due = add_months(payload.completed_date, plan.frequency_months)
plan.next_due_date = next_due
plan.updated_by_id = current_user.id
next_rec = CalibrationRecord(
asset_id=plan.asset_id,
plan_id=plan.id,
due_date=next_due,
agency_id=rec.agency_id if rec.agency_id is not None else plan.agency_id,
status=None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(next_rec)
db.flush()
log_audit(
db,
entity_type="calibration_record",
entity_id=rec.id,
action="complete",
changes={
"completed_date": str(payload.completed_date),
"certificate_no": clean_cert,
"next_due_date": str(next_due),
"next_record_id": next_rec.id,
},
user_id=current_user.id,
)
db.commit()
today = effective_today(db)
leads = _cal_lead_settings(db)
loaded_completed = _load_record_with_joins(db, rec.id)
loaded_next = _load_record_with_joins(db, next_rec.id)
return CalibrationRecordCompleteOut(
completed_record=_to_record_out(loaded_completed, today, leads),
next_record=_to_record_out(loaded_next, today, leads),
)
+625
View File
@@ -0,0 +1,625 @@
from datetime import date
import re
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import or_
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user, require_roles
from ..core.exceptions import CodedHTTPException
from ..core.time_utils import add_months, effective_today, format_date
from ..models import Asset, Contract, PMRecord, PMSchedule, User, Vendor
from ..schemas.pm import (
PMRecordCompleteIn,
PMRecordCompleteOut,
PMRecordListOut,
PMRecordOut,
PMRecordRescheduleIn,
PMRecordRescheduleOut,
PMRecordStatusFilter,
PMRecordSummaryCounts,
PMScheduleCreate,
PMScheduleListOut,
PMScheduleOut,
PMScheduleUpdate,
PMServiceMode,
)
from ..services.audit import log_audit
from ..services.calculations import compute_schedule_status
from ..services.permissions import Role
from ..services.settings_service import get_setting_value
router = APIRouter(prefix="/pm", tags=["pm"])
_MONTH_RE = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
def _pm_lead_settings(db: Session) -> dict[str, int]:
return {
"in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)),
"outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
"red": int(get_setting_value(db, "red_threshold_days", 7)),
}
def _to_schedule_out(s: PMSchedule) -> PMScheduleOut:
asset = s.asset
contract_summary = None
if s.contract is not None:
contract_summary = f"{s.contract.contract_type} (till {format_date(s.contract.end_date)})"
return PMScheduleOut(
id=s.id,
asset_id=s.asset_id,
asset_code=asset.asset_code,
asset_name=asset.name,
department_id=asset.department_id,
department_name=asset.department.name if asset.department else None,
location_name=asset.location.name if asset.location else None,
service_mode=s.service_mode,
frequency_months=s.frequency_months,
responsible_team=s.responsible_team,
provider_id=s.provider_id,
provider_name=s.provider.name if s.provider else None,
contract_id=s.contract_id,
contract_summary=contract_summary,
next_planned_date=s.next_planned_date,
is_active=s.is_active,
created_at=s.created_at,
)
def _to_record_out(
rec: PMRecord,
today: date,
leads: dict[str, int],
) -> PMRecordOut:
sched = rec.schedule
asset = rec.asset
mode = sched.service_mode
lead_days = leads["in_house"] if mode == "in_house" else leads["outsourced"]
if rec.status in ("completed", "rescheduled"):
comp_status, severity = rec.status, "ok"
else:
comp_status, severity = compute_schedule_status(
rec.planned_date, None, today, lead_days, leads["red"]
)
return PMRecordOut(
id=rec.id,
schedule_id=rec.schedule_id,
asset_id=rec.asset_id,
asset_code=asset.asset_code,
asset_name=asset.name,
department_id=asset.department_id,
department_name=asset.department.name if asset.department else None,
location_name=asset.location.name if asset.location else None,
service_mode=mode,
responsible_team=sched.responsible_team,
provider_id=sched.provider_id,
provider_name=sched.provider.name if sched.provider else None,
contract_id=sched.contract_id,
planned_date=rec.planned_date,
completed_date=rec.completed_date,
status=comp_status,
severity=severity,
service_details=rec.service_details,
remarks=rec.remarks,
rescheduled_to=rec.rescheduled_to,
frequency_months=sched.frequency_months,
)
def _load_schedule_with_joins(db: Session, schedule_id: int) -> PMSchedule | None:
return (
db.query(PMSchedule)
.options(
joinedload(PMSchedule.asset).joinedload(Asset.department),
joinedload(PMSchedule.asset).joinedload(Asset.location),
joinedload(PMSchedule.provider),
joinedload(PMSchedule.contract),
)
.filter(PMSchedule.id == schedule_id)
.first()
)
def _load_record_with_joins(db: Session, record_id: int) -> PMRecord | None:
return (
db.query(PMRecord)
.options(
joinedload(PMRecord.asset).joinedload(Asset.department),
joinedload(PMRecord.asset).joinedload(Asset.location),
joinedload(PMRecord.schedule).joinedload(PMSchedule.provider),
)
.filter(PMRecord.id == record_id)
.first()
)
def _validate_schedule_fields(
db: Session,
*,
asset_id: int,
service_mode: str,
responsible_team: Optional[str],
provider_id: Optional[int],
contract_id: Optional[int],
) -> tuple[Optional[str], Optional[int], Optional[int]]:
if service_mode == "in_house":
clean_team = responsible_team.strip() if responsible_team else ""
if not clean_team:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="responsible_team is required for in_house PM schedules.",
)
return clean_team, None, None
if provider_id is None:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="provider_id is required for outsourced PM schedules.",
)
provider = db.query(Vendor.id).filter(Vendor.id == provider_id).first()
if provider is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Service provider vendor not found.")
if contract_id is not None:
contract = db.query(Contract).filter(Contract.id == contract_id).first()
if contract is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
if contract.asset_id != asset_id:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Contract does not belong to the selected asset.",
)
clean_team = responsible_team.strip() if responsible_team and responsible_team.strip() else None
return clean_team, provider_id, contract_id
@router.get("/schedules", response_model=PMScheduleListOut)
def list_pm_schedules(
q: str = "",
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
service_mode: Optional[PMServiceMode] = None,
is_active: Optional[bool] = None,
page: int = Query(1, ge=1),
page_size: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
query = (
db.query(PMSchedule)
.join(Asset, PMSchedule.asset_id == Asset.id)
.outerjoin(Vendor, PMSchedule.provider_id == Vendor.id)
.options(
joinedload(PMSchedule.asset).joinedload(Asset.department),
joinedload(PMSchedule.asset).joinedload(Asset.location),
joinedload(PMSchedule.provider),
joinedload(PMSchedule.contract),
)
)
if current_user.role == Role.department_user.value:
query = query.filter(Asset.department_id == current_user.department_id)
elif department_id is not None:
query = query.filter(Asset.department_id == department_id)
if asset_id is not None:
query = query.filter(PMSchedule.asset_id == asset_id)
if service_mode is not None:
query = query.filter(PMSchedule.service_mode == service_mode)
if is_active is not None:
query = query.filter(PMSchedule.is_active.is_(is_active))
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Asset.asset_code.ilike(like),
Asset.name.ilike(like),
PMSchedule.responsible_team.ilike(like),
Vendor.name.ilike(like),
)
)
total = query.count()
rows = (
query.order_by(PMSchedule.next_planned_date.asc(), PMSchedule.id.asc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return PMScheduleListOut(items=[_to_schedule_out(s) for s in rows], total=total)
@router.post("/schedules", response_model=PMScheduleOut, status_code=status.HTTP_201_CREATED)
def create_pm_schedule(
payload: PMScheduleCreate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
asset = db.query(Asset).filter(Asset.id == payload.asset_id).first()
if asset is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
clean_team, provider_id, contract_id = _validate_schedule_fields(
db,
asset_id=asset.id,
service_mode=payload.service_mode,
responsible_team=payload.responsible_team,
provider_id=payload.provider_id,
contract_id=payload.contract_id,
)
schedule = PMSchedule(
asset_id=asset.id,
service_mode=payload.service_mode,
frequency_months=payload.frequency_months,
responsible_team=clean_team,
provider_id=provider_id,
contract_id=contract_id,
next_planned_date=payload.next_planned_date,
is_active=True,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(schedule)
db.flush()
initial_record = PMRecord(
schedule_id=schedule.id,
asset_id=asset.id,
planned_date=payload.next_planned_date,
status=None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(initial_record)
db.flush()
log_audit(
db,
entity_type="pm_schedule",
entity_id=schedule.id,
action="create",
changes={
"asset_id": asset.id,
"service_mode": payload.service_mode,
"frequency_months": payload.frequency_months,
"next_planned_date": str(payload.next_planned_date),
"initial_record_id": initial_record.id,
},
user_id=current_user.id,
)
db.commit()
loaded = _load_schedule_with_joins(db, schedule.id)
return _to_schedule_out(loaded)
@router.patch("/schedules/{schedule_id}", response_model=PMScheduleOut)
def update_pm_schedule(
schedule_id: int,
payload: PMScheduleUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
schedule = db.query(PMSchedule).filter(PMSchedule.id == schedule_id).first()
if schedule is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM schedule not found.")
data = payload.model_dump(exclude_unset=True)
target_mode = data.get("service_mode", schedule.service_mode)
target_team = data.get("responsible_team", schedule.responsible_team)
target_provider = data.get("provider_id", schedule.provider_id)
target_contract = data.get("contract_id", schedule.contract_id)
clean_team, provider_id, contract_id = _validate_schedule_fields(
db,
asset_id=schedule.asset_id,
service_mode=target_mode,
responsible_team=target_team,
provider_id=target_provider,
contract_id=target_contract,
)
data["responsible_team"] = clean_team
data["provider_id"] = provider_id
data["contract_id"] = contract_id
changes: dict[str, dict[str, object]] = {}
old_next_date = schedule.next_planned_date
for k, v in data.items():
old_val = getattr(schedule, k)
if old_val != v:
changes[k] = {"from": old_val, "to": v}
setattr(schedule, k, v)
schedule.updated_by_id = current_user.id
if "next_planned_date" in data and schedule.next_planned_date != old_next_date:
open_rec = (
db.query(PMRecord)
.filter(PMRecord.schedule_id == schedule.id, PMRecord.status.is_(None))
.order_by(PMRecord.planned_date.desc(), PMRecord.id.desc())
.first()
)
if open_rec is not None:
open_rec.planned_date = schedule.next_planned_date
open_rec.updated_by_id = current_user.id
if changes:
log_audit(
db,
entity_type="pm_schedule",
entity_id=schedule.id,
action="update",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_schedule_with_joins(db, schedule.id)
return _to_schedule_out(loaded)
@router.delete("/schedules/{schedule_id}", response_model=PMScheduleOut)
def deactivate_pm_schedule(
schedule_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
schedule = db.query(PMSchedule).filter(PMSchedule.id == schedule_id).first()
if schedule is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM schedule not found.")
if schedule.is_active:
schedule.is_active = False
schedule.updated_by_id = current_user.id
log_audit(
db,
entity_type="pm_schedule",
entity_id=schedule.id,
action="deactivate",
changes={"is_active": {"from": True, "to": False}},
user_id=current_user.id,
)
db.commit()
loaded = _load_schedule_with_joins(db, schedule.id)
return _to_schedule_out(loaded)
@router.get("/records", response_model=PMRecordListOut)
def list_pm_records(
q: str = "",
month: Optional[str] = None,
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
schedule_id: Optional[int] = None,
service_mode: Optional[PMServiceMode] = None,
status_filter: Optional[PMRecordStatusFilter] = Query(None, alias="status"),
page: int = Query(1, ge=1),
page_size: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
today = effective_today(db)
leads = _pm_lead_settings(db)
query = (
db.query(PMRecord)
.join(PMSchedule, PMRecord.schedule_id == PMSchedule.id)
.join(Asset, PMRecord.asset_id == Asset.id)
.outerjoin(Vendor, PMSchedule.provider_id == Vendor.id)
.options(
joinedload(PMRecord.asset).joinedload(Asset.department),
joinedload(PMRecord.asset).joinedload(Asset.location),
joinedload(PMRecord.schedule).joinedload(PMSchedule.provider),
)
)
if current_user.role == Role.department_user.value:
query = query.filter(Asset.department_id == current_user.department_id)
elif department_id is not None:
query = query.filter(Asset.department_id == department_id)
if asset_id is not None:
query = query.filter(PMRecord.asset_id == asset_id)
if schedule_id is not None:
query = query.filter(PMRecord.schedule_id == schedule_id)
if service_mode is not None:
query = query.filter(PMSchedule.service_mode == service_mode)
target_year, target_month = today.year, today.month
if month is not None and month.strip():
m_match = _MONTH_RE.fullmatch(month.strip())
if not m_match:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="month must be in YYYY-MM format.",
)
target_year = int(m_match.group(1))
target_month = int(m_match.group(2))
month_start = date(target_year, target_month, 1)
next_month_start = add_months(month_start, 1)
query = query.filter(
PMRecord.planned_date >= month_start,
PMRecord.planned_date < next_month_start,
)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Asset.asset_code.ilike(like),
Asset.name.ilike(like),
PMSchedule.responsible_team.ilike(like),
Vendor.name.ilike(like),
PMRecord.service_details.ilike(like),
PMRecord.remarks.ilike(like),
)
)
rows = query.order_by(PMRecord.planned_date.asc(), PMRecord.id.asc()).all()
computed_all = [_to_record_out(r, today, leads) for r in rows]
upcoming_cnt = sum(1 for item in computed_all if item.status == "upcoming")
due_cnt = sum(1 for item in computed_all if item.status == "due")
overdue_cnt = sum(1 for item in computed_all if item.status == "overdue")
completed_month_cnt = 0
for item in computed_all:
if item.status == "completed":
ref_date = item.completed_date or item.planned_date
if (ref_date.year == target_year and ref_date.month == target_month) or (
item.planned_date.year == target_year and item.planned_date.month == target_month
):
completed_month_cnt += 1
if status_filter is not None:
filtered = [item for item in computed_all if item.status == status_filter]
else:
filtered = computed_all
total = len(filtered)
start = (page - 1) * page_size
paginated = filtered[start : start + page_size]
return PMRecordListOut(
items=paginated,
total=total,
summary=PMRecordSummaryCounts(
upcoming=upcoming_cnt,
due=due_cnt,
overdue=overdue_cnt,
completed_this_month=completed_month_cnt,
),
)
@router.post("/records/{record_id}/complete", response_model=PMRecordCompleteOut)
def complete_pm_record(
record_id: int,
payload: PMRecordCompleteIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
rec = _load_record_with_joins(db, record_id)
if rec is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM record not found.")
if rec.status in ("completed", "rescheduled"):
raise CodedHTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"PM record is already {rec.status}.",
code="INVALID_PM_STATUS",
)
clean_details = payload.service_details.strip()
if not clean_details:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="service_details cannot be blank.",
)
rec.status = "completed"
rec.completed_date = payload.completed_date
rec.service_details = clean_details
rec.remarks = payload.remarks.strip() if payload.remarks and payload.remarks.strip() else None
rec.updated_by_id = current_user.id
schedule = rec.schedule
next_date = add_months(payload.completed_date, schedule.frequency_months)
schedule.next_planned_date = next_date
schedule.updated_by_id = current_user.id
next_rec = PMRecord(
schedule_id=schedule.id,
asset_id=schedule.asset_id,
planned_date=next_date,
status=None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(next_rec)
db.flush()
log_audit(
db,
entity_type="pm_record",
entity_id=rec.id,
action="complete",
changes={
"completed_date": str(payload.completed_date),
"next_planned_date": str(next_date),
"next_record_id": next_rec.id,
},
user_id=current_user.id,
)
db.commit()
today = effective_today(db)
leads = _pm_lead_settings(db)
loaded_completed = _load_record_with_joins(db, rec.id)
loaded_next = _load_record_with_joins(db, next_rec.id)
return PMRecordCompleteOut(
completed_record=_to_record_out(loaded_completed, today, leads),
next_record=_to_record_out(loaded_next, today, leads),
)
@router.post("/records/{record_id}/reschedule", response_model=PMRecordRescheduleOut)
def reschedule_pm_record(
record_id: int,
payload: PMRecordRescheduleIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
rec = _load_record_with_joins(db, record_id)
if rec is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM record not found.")
if rec.status in ("completed", "rescheduled"):
raise CodedHTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"PM record is already {rec.status}.",
code="INVALID_PM_STATUS",
)
rec.status = "rescheduled"
rec.rescheduled_to = payload.rescheduled_to
rec.remarks = payload.remarks.strip() if payload.remarks and payload.remarks.strip() else None
rec.updated_by_id = current_user.id
schedule = rec.schedule
schedule.next_planned_date = payload.rescheduled_to
schedule.updated_by_id = current_user.id
next_rec = PMRecord(
schedule_id=schedule.id,
asset_id=schedule.asset_id,
planned_date=payload.rescheduled_to,
status=None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(next_rec)
db.flush()
log_audit(
db,
entity_type="pm_record",
entity_id=rec.id,
action="reschedule",
changes={
"rescheduled_to": str(payload.rescheduled_to),
"next_record_id": next_rec.id,
},
user_id=current_user.id,
)
db.commit()
today = effective_today(db)
leads = _pm_lead_settings(db)
loaded_rescheduled = _load_record_with_joins(db, rec.id)
loaded_next = _load_record_with_joins(db, next_rec.id)
return PMRecordRescheduleOut(
rescheduled_record=_to_record_out(loaded_rescheduled, today, leads),
next_record=_to_record_out(loaded_next, today, leads),
)
+25
View File
@@ -9,6 +9,19 @@ from .assets import (
) )
from .attachments import AttachmentListOut, AttachmentOut from .attachments import AttachmentListOut, AttachmentOut
from .auth import LoginRequest, TokenResponse, UserOut from .auth import LoginRequest, TokenResponse, UserOut
from .calibration import (
CalibrationPlanApproveIn,
CalibrationPlanBulkCreateIn,
CalibrationPlanBulkOut,
CalibrationPlanCreateFromAsset,
CalibrationPlanListOut,
CalibrationPlanOut,
CalibrationPlanUpdateIn,
CalibrationRecordCompleteIn,
CalibrationRecordCompleteOut,
CalibrationRecordListOut,
CalibrationRecordOut,
)
from .complaints import ( from .complaints import (
ComplaintAssignIn, ComplaintAssignIn,
ComplaintAttendIn, ComplaintAttendIn,
@@ -42,6 +55,18 @@ from .masters import (
VendorOut, VendorOut,
VendorUpdate, VendorUpdate,
) )
from .pm import (
PMRecordCompleteIn,
PMRecordCompleteOut,
PMRecordListOut,
PMRecordOut,
PMRecordRescheduleIn,
PMRecordRescheduleOut,
PMScheduleCreate,
PMScheduleListOut,
PMScheduleOut,
PMScheduleUpdate,
)
from .settings import DemoDateIn, DemoDateOut, SettingItemOut, SettingsListOut, SettingsUpdateIn from .settings import DemoDateIn, DemoDateOut, SettingItemOut, SettingsListOut, SettingsUpdateIn
__all__ = [ __all__ = [
+114
View File
@@ -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
+113
View File
@@ -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
+40
View File
@@ -187,6 +187,46 @@ SETTINGS_SCHEMA: list[dict[str, Any]] = [
"max": None, "max": None,
"options": ["attended_at", "restored_at", "closed_at"], "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} SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
+424
View File
@@ -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},
)
+2 -2
View File
@@ -11,10 +11,10 @@ import { AssetsPage } from "@/pages/AssetsPage";
import { AssetDetailPage } from "@/pages/AssetDetailPage"; import { AssetDetailPage } from "@/pages/AssetDetailPage";
import { ComplaintsPage } from "@/pages/ComplaintsPage"; import { ComplaintsPage } from "@/pages/ComplaintsPage";
import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage"; import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage";
import { PMPage } from "@/pages/PMPage";
import { CalibrationPage } from "@/pages/CalibrationPage";
import { import {
DashboardPage, DashboardPage,
PMPage,
CalibrationPage,
ContractsPage, ContractsPage,
InsurancePage, InsurancePage,
DemoEquipmentPage, DemoEquipmentPage,
+145
View File
@@ -0,0 +1,145 @@
import { api } from "./client";
export interface CalibrationPlanItem {
id: number;
asset_id: number;
asset_code: string;
asset_name: string;
department_id: number;
department_name: string | null;
frequency_months: number;
calibrations_per_year: number;
agency_id: number | null;
agency_name: string | null;
approved_by_id: number | null;
approved_by_name: string | null;
approved_on: string | null;
next_due_date: string;
is_active: boolean;
}
export interface CalibrationRecordItem {
id: number;
plan_id: number;
asset_id: number;
asset_code: string;
asset_name: string;
department_id: number;
department_name: string | null;
location_name: string | null;
due_date: string;
completed_date: string | null;
agency_id: number | null;
agency_name: string | null;
certificate_no: string | null;
remarks: string | null;
status: "upcoming" | "due" | "overdue" | "completed" | string;
severity: "ok" | "yellow" | "red" | string;
frequency_months: number;
approved_by_name: string | null;
approved_on: string | null;
}
export interface CalibrationSummary {
upcoming: number;
due: number;
overdue: number;
completed: number;
}
export interface CalibrationPlanFromAssetPayload {
frequency_months: number;
calibrations_per_year?: number;
agency_id?: number | null;
next_due_date: string;
approve?: boolean;
}
export const calibrationApi = {
listPlans: (
params: {
q?: string;
department_id?: number;
agency_id?: number;
is_active?: boolean;
page?: number;
page_size?: number;
} = {}
) => {
const qs = new URLSearchParams();
if (params.q) qs.set("q", params.q);
if (params.department_id) qs.set("department_id", String(params.department_id));
if (params.agency_id) qs.set("agency_id", String(params.agency_id));
if (params.is_active !== undefined) qs.set("is_active", String(params.is_active));
qs.set("page", String(params.page ?? 1));
qs.set("page_size", String(params.page_size ?? 200));
return api.get<{ items: CalibrationPlanItem[]; total: number }>(
`/calibration/plans?${qs.toString()}`
);
},
createPlanFromAsset: (assetId: number, data: CalibrationPlanFromAssetPayload) =>
api.post<CalibrationPlanItem>(`/calibration/plans/from-asset/${assetId}`, data),
bulkCreatePlansFromAssets: (
data: CalibrationPlanFromAssetPayload & { asset_ids: number[] }
) =>
api.post<{ created: CalibrationPlanItem[]; skipped_asset_ids: number[] }>(
"/calibration/plans/bulk-from-assets",
data
),
updatePlan: (
id: number,
data: Partial<{
frequency_months: number;
calibrations_per_year: number;
agency_id: number | null;
next_due_date: string;
is_active: boolean;
}>
) => api.put<CalibrationPlanItem>(`/calibration/plans/${id}`, data),
approvePlan: (
id: number,
data: { frequency_months?: number; calibrations_per_year?: number } = {}
) => api.post<CalibrationPlanItem>(`/calibration/plans/${id}/approve`, data),
listRecords: (
params: {
q?: string;
department_id?: number;
asset_id?: number;
agency_id?: number;
status?: string;
due_from?: string;
due_to?: string;
page?: number;
page_size?: number;
} = {}
) => {
const qs = new URLSearchParams();
if (params.q) qs.set("q", params.q);
if (params.department_id) qs.set("department_id", String(params.department_id));
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
if (params.agency_id) qs.set("agency_id", String(params.agency_id));
if (params.status) qs.set("status", params.status);
if (params.due_from) qs.set("due_from", params.due_from);
if (params.due_to) qs.set("due_to", params.due_to);
qs.set("page", String(params.page ?? 1));
qs.set("page_size", String(params.page_size ?? 200));
return api.get<{
items: CalibrationRecordItem[];
total: number;
summary: CalibrationSummary;
}>(`/calibration/records?${qs.toString()}`);
},
completeRecord: (
id: number,
data: {
completed_date: string;
certificate_no: string;
agency_id?: number | null;
remarks?: string | null;
}
) =>
api.post<{
completed_record: CalibrationRecordItem;
next_record: CalibrationRecordItem;
}>(`/calibration/records/${id}/complete`, data),
};
+137
View File
@@ -0,0 +1,137 @@
import { api } from "./client";
export type ServiceMode = "in_house" | "outsourced";
export type ScheduleStatus = "upcoming" | "due" | "overdue" | "completed" | "rescheduled";
export interface PMScheduleItem {
id: number;
asset_id: number;
asset_code: string;
asset_name: string;
department_id: number;
department_name: string | null;
location_name: string | null;
service_mode: ServiceMode;
frequency_months: number;
responsible_team: string | null;
provider_id: number | null;
provider_name: string | null;
contract_id: number | null;
contract_summary: string | null;
next_planned_date: string;
is_active: boolean;
created_at: string;
}
export interface PMRecordItem {
id: number;
schedule_id: number;
asset_id: number;
asset_code: string;
asset_name: string;
department_id: number;
department_name: string | null;
location_name: string | null;
service_mode: ServiceMode;
responsible_team: string | null;
provider_id: number | null;
provider_name: string | null;
contract_id: number | null;
planned_date: string;
completed_date: string | null;
status: ScheduleStatus | string;
severity: "ok" | "yellow" | "red" | string;
service_details: string | null;
remarks: string | null;
rescheduled_to: string | null;
frequency_months: number;
}
export interface PMSummary {
upcoming: number;
due: number;
overdue: number;
completed_this_month: number;
}
export interface PMScheduleCreatePayload {
asset_id: number;
service_mode: ServiceMode;
frequency_months: number;
responsible_team?: string | null;
provider_id?: number | null;
contract_id?: number | null;
next_planned_date: string;
}
export const pmApi = {
listSchedules: (
params: {
q?: string;
department_id?: number;
asset_id?: number;
service_mode?: ServiceMode | "";
is_active?: boolean;
page?: number;
page_size?: number;
} = {}
) => {
const qs = new URLSearchParams();
if (params.q) qs.set("q", params.q);
if (params.department_id) qs.set("department_id", String(params.department_id));
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
if (params.service_mode) qs.set("service_mode", params.service_mode);
if (params.is_active !== undefined) qs.set("is_active", String(params.is_active));
qs.set("page", String(params.page ?? 1));
qs.set("page_size", String(params.page_size ?? 200));
return api.get<{ items: PMScheduleItem[]; total: number }>(`/pm/schedules?${qs.toString()}`);
},
createSchedule: (data: PMScheduleCreatePayload) =>
api.post<PMScheduleItem>("/pm/schedules", data),
updateSchedule: (id: number, data: Partial<PMScheduleCreatePayload & { is_active: boolean }>) =>
api.patch<PMScheduleItem>(`/pm/schedules/${id}`, data),
deleteSchedule: (id: number) => api.delete<void>(`/pm/schedules/${id}`),
listRecords: (
params: {
q?: string;
month?: string;
department_id?: number;
asset_id?: number;
schedule_id?: number;
service_mode?: ServiceMode | "";
status?: ScheduleStatus | "";
page?: number;
page_size?: number;
} = {}
) => {
const qs = new URLSearchParams();
if (params.q) qs.set("q", params.q);
if (params.month) qs.set("month", params.month);
if (params.department_id) qs.set("department_id", String(params.department_id));
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
if (params.schedule_id) qs.set("schedule_id", String(params.schedule_id));
if (params.service_mode) qs.set("service_mode", params.service_mode);
if (params.status) qs.set("status", params.status);
qs.set("page", String(params.page ?? 1));
qs.set("page_size", String(params.page_size ?? 200));
return api.get<{ items: PMRecordItem[]; total: number; summary: PMSummary }>(
`/pm/records?${qs.toString()}`
);
},
completeRecord: (
id: number,
data: { completed_date: string; service_details: string; remarks?: string | null }
) =>
api.post<{ completed_record: PMRecordItem; next_record: PMRecordItem }>(
`/pm/records/${id}/complete`,
data
),
rescheduleRecord: (
id: number,
data: { rescheduled_to: string; remarks?: string | null }
) =>
api.post<{ rescheduled_record: PMRecordItem; next_record: PMRecordItem }>(
`/pm/records/${id}/reschedule`,
data
),
};
@@ -0,0 +1,676 @@
import { useState, useEffect, useMemo } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertCircle, Paperclip, X } from "lucide-react";
import { Modal } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { validateAttachmentFile } from "@/components/Attachments";
import { ApiError } from "@/api/client";
import { assetsApi } from "@/api/assets";
import { vendorsApi } from "@/api/masters";
import { attachmentsApi } from "@/api/attachments";
import { calibrationApi, type CalibrationPlanItem } from "@/api/calibration";
const inputCls =
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
function ErrorAlert({ message }: { message: string | null }) {
if (!message) return null;
return (
<div
role="alert"
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
>
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
<span>{message}</span>
</div>
);
}
export function AddSingleCalibrationPlanModal({
open,
onClose,
assetId,
assetLabel,
canApprove,
}: {
open: boolean;
onClose: () => void;
assetId: number;
assetLabel: string;
canApprove: boolean;
}) {
const qc = useQueryClient();
const [frequencyMonths, setFrequencyMonths] = useState("12");
const [calPerYear, setCalPerYear] = useState("1");
const [agencyId, setAgencyId] = useState("");
const [nextDueDate, setNextDueDate] = useState("");
const [approveNow, setApproveNow] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const vendorsQuery = useQuery({
queryKey: ["vendors", "active-only"],
queryFn: () => vendorsApi.list(false),
enabled: open,
});
useEffect(() => {
if (!open) return;
setFrequencyMonths("12");
setCalPerYear("1");
setAgencyId("");
setNextDueDate(new Date().toISOString().slice(0, 10));
setApproveNow(false);
setError(null);
}, [open, assetId]);
const agencies = (vendorsQuery.data?.items ?? []).filter(
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setSubmitting(true);
setError(null);
try {
await calibrationApi.createPlanFromAsset(assetId, {
frequency_months: Math.max(1, Number(frequencyMonths) || 12),
calibrations_per_year: calPerYear ? Math.max(1, Number(calPerYear)) : undefined,
agency_id: agencyId ? Number(agencyId) : null,
next_due_date: nextDueDate,
approve: canApprove ? approveNow : false,
});
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
onClose();
} catch (err) {
setError(err instanceof ApiError ? err.detail : "Failed to add calibration plan.");
} finally {
setSubmitting(false);
}
}
return (
<Modal
open={open}
onOpenChange={(o) => !o && onClose()}
title={`Add to Calibration List — ${assetLabel}`}
>
<ErrorAlert message={error} />
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-3">
<div>
<label className={labelCls}>Frequency (Months) *</label>
<input
type="number"
min={1}
required
value={frequencyMonths}
onChange={(e) => setFrequencyMonths(e.target.value)}
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Calibrations / Year</label>
<input
type="number"
min={1}
value={calPerYear}
onChange={(e) => setCalPerYear(e.target.value)}
className={inputCls}
/>
</div>
</div>
<div>
<label className={labelCls}>Calibration Agency</label>
<select
value={agencyId}
onChange={(e) => setAgencyId(e.target.value)}
className={inputCls}
>
<option value="">Select agency (optional)...</option>
{agencies.map((a) => (
<option key={a.id} value={String(a.id)}>
{a.name}
</option>
))}
</select>
</div>
<div>
<label className={labelCls}>Next Due Date *</label>
<input
type="date"
required
value={nextDueDate}
onChange={(e) => setNextDueDate(e.target.value)}
className={inputCls}
/>
</div>
{canApprove && (
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
<input
type="checkbox"
checked={approveNow}
onChange={(e) => setApproveNow(e.target.checked)}
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
/>
Approve frequency immediately
</label>
)}
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" loading={submitting}>
Create Calibration Plan
</Button>
</div>
</form>
</Modal>
);
}
export function BulkCalibrationAddModal({
open,
onClose,
existingPlanAssetIds,
canApprove,
}: {
open: boolean;
onClose: () => void;
existingPlanAssetIds: number[];
canApprove: boolean;
}) {
const qc = useQueryClient();
const [search, setSearch] = useState("");
const [onlyRequiresCal, setOnlyRequiresCal] = useState(false);
const [selectedIds, setSelectedIds] = useState<number[]>([]);
const [frequencyMonths, setFrequencyMonths] = useState("12");
const [calPerYear, setCalPerYear] = useState("1");
const [agencyId, setAgencyId] = useState("");
const [nextDueDate, setNextDueDate] = useState("");
const [approveNow, setApproveNow] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const assetsQuery = useQuery({
queryKey: ["assets", "cal-candidates"],
queryFn: () => assetsApi.list({ page_size: 500 }),
enabled: open,
});
const vendorsQuery = useQuery({
queryKey: ["vendors", "active-only"],
queryFn: () => vendorsApi.list(false),
enabled: open,
});
useEffect(() => {
if (!open) return;
setSearch("");
setSelectedIds([]);
setFrequencyMonths("12");
setCalPerYear("1");
setAgencyId("");
setNextDueDate(new Date().toISOString().slice(0, 10));
setApproveNow(false);
setError(null);
}, [open]);
const existingSet = useMemo(() => new Set(existingPlanAssetIds), [existingPlanAssetIds]);
const candidates = useMemo(() => {
const q = search.trim().toLowerCase();
return (assetsQuery.data?.items ?? []).filter((a) => {
if (existingSet.has(a.id)) return false;
if (onlyRequiresCal && !a.requires_calibration) return false;
if (
q &&
!`${a.asset_code} ${a.name} ${a.department_name ?? ""}`
.toLowerCase()
.includes(q)
) {
return false;
}
return true;
});
}, [assetsQuery.data?.items, existingSet, onlyRequiresCal, search]);
const agencies = (vendorsQuery.data?.items ?? []).filter(
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
);
function toggleId(id: number) {
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (selectedIds.length === 0) {
setError("Select at least one asset.");
return;
}
setSubmitting(true);
setError(null);
try {
await calibrationApi.bulkCreatePlansFromAssets({
asset_ids: selectedIds,
frequency_months: Math.max(1, Number(frequencyMonths) || 12),
calibrations_per_year: calPerYear ? Math.max(1, Number(calPerYear)) : undefined,
agency_id: agencyId ? Number(agencyId) : null,
next_due_date: nextDueDate,
approve: canApprove ? approveNow : false,
});
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
onClose();
} catch (err) {
setError(err instanceof ApiError ? err.detail : "Bulk creation failed.");
} finally {
setSubmitting(false);
}
}
return (
<Modal
open={open}
onOpenChange={(o) => !o && onClose()}
title="Add Equipment to Calibration"
className="max-w-2xl"
>
<ErrorAlert message={error} />
<form onSubmit={handleSubmit} className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search unconfigured assets..."
className="flex-1 min-w-48 px-3 py-1.5 text-sm border border-gray-300 rounded-md"
/>
<label className="inline-flex items-center gap-1.5 text-xs text-gray-700 cursor-pointer">
<input
type="checkbox"
checked={onlyRequiresCal}
onChange={(e) => setOnlyRequiresCal(e.target.checked)}
/>
Requires calibration only
</label>
</div>
<div className="max-h-52 overflow-y-auto border border-gray-200 rounded-md divide-y divide-gray-100">
{candidates.length === 0 ? (
<div className="p-4 text-center text-xs text-gray-400">
No matching assets without a calibration plan.
</div>
) : (
candidates.map((a) => (
<label
key={a.id}
className="flex items-center gap-3 px-3 py-2 hover:bg-blue-50/40 cursor-pointer text-sm"
>
<input
type="checkbox"
checked={selectedIds.includes(a.id)}
onChange={() => toggleId(a.id)}
/>
<span className="font-mono text-xs text-[#1e3a8a] font-semibold">
{a.asset_code}
</span>
<span className="flex-1 truncate">{a.name}</span>
<span className="text-xs text-gray-500">{a.department_name}</span>
</label>
))
)}
</div>
<div className="text-xs text-gray-500">{selectedIds.length} asset(s) selected</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className={labelCls}>Frequency (Months) *</label>
<input
type="number"
min={1}
required
value={frequencyMonths}
onChange={(e) => setFrequencyMonths(e.target.value)}
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Calibrations / Year</label>
<input
type="number"
min={1}
value={calPerYear}
onChange={(e) => setCalPerYear(e.target.value)}
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Agency</label>
<select
value={agencyId}
onChange={(e) => setAgencyId(e.target.value)}
className={inputCls}
>
<option value="">Select agency (optional)...</option>
{agencies.map((a) => (
<option key={a.id} value={String(a.id)}>
{a.name}
</option>
))}
</select>
</div>
<div>
<label className={labelCls}>Next Due Date *</label>
<input
type="date"
required
value={nextDueDate}
onChange={(e) => setNextDueDate(e.target.value)}
className={inputCls}
/>
</div>
</div>
{canApprove && (
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
<input
type="checkbox"
checked={approveNow}
onChange={(e) => setApproveNow(e.target.checked)}
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
/>
Approve immediately
</label>
)}
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" loading={submitting}>
Add Selected ({selectedIds.length})
</Button>
</div>
</form>
</Modal>
);
}
export function ApproveCalibrationPlanModal({
open,
onClose,
plan,
}: {
open: boolean;
onClose: () => void;
plan: CalibrationPlanItem | null;
}) {
const qc = useQueryClient();
const [frequencyMonths, setFrequencyMonths] = useState("12");
const [calPerYear, setCalPerYear] = useState("1");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open || !plan) return;
setFrequencyMonths(String(plan.frequency_months));
setCalPerYear(String(plan.calibrations_per_year));
setError(null);
}, [open, plan]);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!plan) return;
setSubmitting(true);
setError(null);
try {
await calibrationApi.approvePlan(plan.id, {
frequency_months: Math.max(1, Number(frequencyMonths) || plan.frequency_months),
calibrations_per_year: Math.max(
1,
Number(calPerYear) || plan.calibrations_per_year
),
});
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
await qc.invalidateQueries({ queryKey: ["asset-overview", plan.asset_id] });
onClose();
} catch (err) {
setError(err instanceof ApiError ? err.detail : "Approval failed.");
} finally {
setSubmitting(false);
}
}
return (
<Modal
open={open}
onOpenChange={(o) => !o && onClose()}
title={`Approve / Edit Frequency — ${plan?.asset_code ?? ""}`}
>
<ErrorAlert message={error} />
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-3">
<div>
<label className={labelCls}>Frequency (Months) *</label>
<input
type="number"
min={1}
required
value={frequencyMonths}
onChange={(e) => setFrequencyMonths(e.target.value)}
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Calibrations / Year *</label>
<input
type="number"
min={1}
required
value={calPerYear}
onChange={(e) => setCalPerYear(e.target.value)}
className={inputCls}
/>
</div>
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" variant="success" loading={submitting}>
Approve Plan
</Button>
</div>
</form>
</Modal>
);
}
export function CompleteCalibrationModal({
open,
onClose,
recordId,
assetLabel,
defaultAgencyId,
assetId,
}: {
open: boolean;
onClose: () => void;
recordId: number | null;
assetLabel: string;
defaultAgencyId?: number | null;
assetId?: number;
}) {
const qc = useQueryClient();
const [completedDate, setCompletedDate] = useState("");
const [certificateNo, setCertificateNo] = useState("");
const [agencyId, setAgencyId] = useState("");
const [remarks, setRemarks] = useState("");
const [certFile, setCertFile] = useState<File | null>(null);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const vendorsQuery = useQuery({
queryKey: ["vendors", "active-only"],
queryFn: () => vendorsApi.list(false),
enabled: open,
});
useEffect(() => {
if (!open) return;
setCompletedDate(new Date().toISOString().slice(0, 10));
setCertificateNo("");
setAgencyId(defaultAgencyId ? String(defaultAgencyId) : "");
setRemarks("");
setCertFile(null);
setError(null);
}, [open, recordId, defaultAgencyId]);
const agencies = (vendorsQuery.data?.items ?? []).filter(
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
);
function handlePickFile(e: React.ChangeEvent<HTMLInputElement>) {
const f = e.target.files?.[0];
e.target.value = "";
if (!f) return;
const err = validateAttachmentFile(f);
if (err) {
setError(err);
return;
}
setError(null);
setCertFile(f);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!recordId) return;
setSubmitting(true);
setError(null);
try {
await calibrationApi.completeRecord(recordId, {
completed_date: completedDate,
certificate_no: certificateNo.trim(),
agency_id: agencyId ? Number(agencyId) : null,
remarks: remarks.trim() || null,
});
if (certFile) {
await attachmentsApi.upload("calibration_record", recordId, certFile);
}
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
await qc.invalidateQueries({ queryKey: ["attachments", "calibration_record", recordId] });
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
onClose();
} catch (err) {
setError(err instanceof ApiError ? err.detail : "Failed to complete calibration.");
} finally {
setSubmitting(false);
}
}
return (
<Modal
open={open}
onOpenChange={(o) => !o && onClose()}
title={`Complete Calibration — ${assetLabel}`}
>
<ErrorAlert message={error} />
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className={labelCls}>Completed Date *</label>
<input
type="date"
required
value={completedDate}
onChange={(e) => setCompletedDate(e.target.value)}
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Certificate No *</label>
<input
type="text"
required
value={certificateNo}
onChange={(e) => setCertificateNo(e.target.value)}
placeholder="e.g. CAL-2026-881"
className={inputCls}
/>
</div>
</div>
<div>
<label className={labelCls}>Agency</label>
<select
value={agencyId}
onChange={(e) => setAgencyId(e.target.value)}
className={inputCls}
>
<option value="">Default / Plan Agency</option>
{agencies.map((a) => (
<option key={a.id} value={String(a.id)}>
{a.name}
</option>
))}
</select>
</div>
<div>
<label className={labelCls}>Remarks</label>
<textarea
rows={2}
value={remarks}
onChange={(e) => setRemarks(e.target.value)}
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Calibration Certificate (Optional JPG/PNG/PDF)</label>
{certFile ? (
<div className="flex items-center justify-between text-xs bg-gray-50 border border-gray-200 rounded px-3 py-2">
<span className="truncate">{certFile.name}</span>
<button
type="button"
onClick={() => setCertFile(null)}
className="text-gray-400 hover:text-red-600 ml-2"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
) : (
<label className="inline-flex items-center gap-2 px-3 py-2 rounded-md border border-gray-300 bg-white hover:bg-gray-50 text-xs font-medium text-gray-700 cursor-pointer">
<Paperclip className="h-3.5 w-3.5" />
Attach Certificate File
<input
type="file"
accept=".jpg,.jpeg,.png,.pdf"
onChange={handlePickFile}
className="hidden"
/>
</label>
)}
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" variant="success" loading={submitting}>
Save &amp; Complete
</Button>
</div>
</form>
</Modal>
);
}
+415
View File
@@ -0,0 +1,415 @@
import { useState, useEffect } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertCircle } from "lucide-react";
import { Modal } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { AssetPicker } from "@/components/AssetPicker";
import { ApiError } from "@/api/client";
import { assetsApi, type AssetLookupItem } from "@/api/assets";
import { vendorsApi } from "@/api/masters";
import { pmApi, type ServiceMode } from "@/api/pm";
const inputCls =
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
function ErrorAlert({ message }: { message: string | null }) {
if (!message) return null;
return (
<div
role="alert"
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
>
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
<span>{message}</span>
</div>
);
}
export function NewPMScheduleModal({
open,
onClose,
fixedAsset = null,
}: {
open: boolean;
onClose: () => void;
fixedAsset?: { id: number; asset_code: string; name: string } | null;
}) {
const qc = useQueryClient();
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
const [serviceMode, setServiceMode] = useState<ServiceMode>("in_house");
const [responsibleTeam, setResponsibleTeam] = useState("Biomedical Engineering");
const [providerId, setProviderId] = useState("");
const [contractId, setContractId] = useState("");
const [frequencyMonths, setFrequencyMonths] = useState("6");
const [nextPlannedDate, setNextPlannedDate] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const assetId = fixedAsset?.id ?? selectedAsset?.id ?? null;
const vendorsQuery = useQuery({
queryKey: ["vendors", "active-only"],
queryFn: () => vendorsApi.list(false),
enabled: open,
});
const assetOverviewQuery = useQuery({
queryKey: ["asset-overview", assetId],
queryFn: () => assetsApi.overview(assetId!),
enabled: open && Boolean(assetId) && serviceMode === "outsourced",
});
useEffect(() => {
if (!open) return;
setSelectedAsset(null);
setServiceMode("in_house");
setResponsibleTeam("Biomedical Engineering");
setProviderId("");
setContractId("");
setFrequencyMonths("6");
setNextPlannedDate(new Date().toISOString().slice(0, 10));
setError(null);
}, [open]);
const serviceVendors = (vendorsQuery.data?.items ?? []).filter(
(v) => v.vendor_type === "service_provider" || v.vendor_type === "oem"
);
const vendorOptions =
serviceVendors.length > 0 ? serviceVendors : vendorsQuery.data?.items ?? [];
const assetContracts = (assetOverviewQuery.data?.contracts ?? []).filter(
(c) => !c.is_superseded
);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!assetId) {
setError("Please select an asset.");
return;
}
if (serviceMode === "in_house" && !responsibleTeam.trim()) {
setError("Responsible team is required for In-House PM.");
return;
}
if (serviceMode === "outsourced" && !providerId) {
setError("Service provider is required for Outsourced PM.");
return;
}
setSubmitting(true);
setError(null);
try {
await pmApi.createSchedule({
asset_id: assetId,
service_mode: serviceMode,
frequency_months: Math.max(1, Number(frequencyMonths) || 6),
responsible_team: serviceMode === "in_house" ? responsibleTeam.trim() : null,
provider_id: serviceMode === "outsourced" ? Number(providerId) : null,
contract_id:
serviceMode === "outsourced" && contractId ? Number(contractId) : null,
next_planned_date: nextPlannedDate,
});
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
await qc.invalidateQueries({ queryKey: ["pm-records"] });
await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
onClose();
} catch (err) {
setError(err instanceof ApiError ? err.detail : "Failed to create PM schedule.");
} finally {
setSubmitting(false);
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title="New PM Schedule" className="max-w-xl">
<ErrorAlert message={error} />
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className={labelCls}>Asset *</label>
{fixedAsset ? (
<div className="px-3 py-2 text-sm bg-gray-50 border border-gray-200 rounded-md font-medium">
<span className="font-mono text-[#1e3a8a]">{fixedAsset.asset_code}</span> —{" "}
{fixedAsset.name}
</div>
) : (
<AssetPicker selectedAsset={selectedAsset} onSelect={setSelectedAsset} />
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className={labelCls}>Service Mode *</label>
<select
value={serviceMode}
onChange={(e) => setServiceMode(e.target.value as ServiceMode)}
className={inputCls}
>
<option value="in_house">In-House</option>
<option value="outsourced">Outsourced</option>
</select>
</div>
<div>
<label className={labelCls}>Frequency (Months) *</label>
<input
type="number"
min={1}
max={60}
required
value={frequencyMonths}
onChange={(e) => setFrequencyMonths(e.target.value)}
className={inputCls}
/>
</div>
</div>
{serviceMode === "in_house" ? (
<div>
<label className={labelCls}>Responsible Team *</label>
<input
type="text"
value={responsibleTeam}
onChange={(e) => setResponsibleTeam(e.target.value)}
placeholder="e.g. Biomedical Engineering"
className={inputCls}
/>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className={labelCls}>Service Provider *</label>
<select
value={providerId}
onChange={(e) => setProviderId(e.target.value)}
className={inputCls}
>
<option value="">Select vendor...</option>
{vendorOptions.map((v) => (
<option key={v.id} value={String(v.id)}>
{v.name}
</option>
))}
</select>
</div>
<div>
<label className={labelCls}>Linked Contract (Optional)</label>
<select
value={contractId}
onChange={(e) => setContractId(e.target.value)}
className={inputCls}
>
<option value="">None</option>
{assetContracts.map((c) => (
<option key={c.id} value={String(c.id)}>
{c.contract_type} — {c.provider_name || `Provider #${c.provider_id}`} (until{" "}
{c.end_date})
</option>
))}
</select>
</div>
</div>
)}
<div>
<label className={labelCls}>Next Planned Date *</label>
<input
type="date"
required
value={nextPlannedDate}
onChange={(e) => setNextPlannedDate(e.target.value)}
className={inputCls}
/>
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" loading={submitting}>
Create Schedule
</Button>
</div>
</form>
</Modal>
);
}
export function CompletePMModal({
open,
onClose,
recordId,
assetLabel,
assetId,
}: {
open: boolean;
onClose: () => void;
recordId: number | null;
assetLabel: string;
assetId?: number;
}) {
const qc = useQueryClient();
const [completedDate, setCompletedDate] = useState("");
const [serviceDetails, setServiceDetails] = useState("");
const [remarks, setRemarks] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
setCompletedDate(new Date().toISOString().slice(0, 10));
setServiceDetails("");
setRemarks("");
setError(null);
}, [open, recordId]);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!recordId) return;
setSubmitting(true);
setError(null);
try {
await pmApi.completeRecord(recordId, {
completed_date: completedDate,
service_details: serviceDetails.trim(),
remarks: remarks.trim() || null,
});
await qc.invalidateQueries({ queryKey: ["pm-records"] });
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
onClose();
} catch (err) {
setError(err instanceof ApiError ? err.detail : "Failed to complete PM.");
} finally {
setSubmitting(false);
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={`Complete PM — ${assetLabel}`}>
<ErrorAlert message={error} />
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className={labelCls}>Completed Date *</label>
<input
type="date"
required
value={completedDate}
onChange={(e) => setCompletedDate(e.target.value)}
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Service Details *</label>
<textarea
rows={3}
required
value={serviceDetails}
onChange={(e) => setServiceDetails(e.target.value)}
placeholder="Checklist items performed, parts cleaned/replaced..."
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Remarks</label>
<textarea
rows={2}
value={remarks}
onChange={(e) => setRemarks(e.target.value)}
className={inputCls}
/>
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" variant="success" loading={submitting}>
Mark Completed
</Button>
</div>
</form>
</Modal>
);
}
export function ReschedulePMModal({
open,
onClose,
recordId,
assetLabel,
assetId,
}: {
open: boolean;
onClose: () => void;
recordId: number | null;
assetLabel: string;
assetId?: number;
}) {
const qc = useQueryClient();
const [rescheduledTo, setRescheduledTo] = useState("");
const [remarks, setRemarks] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
setRescheduledTo(new Date().toISOString().slice(0, 10));
setRemarks("");
setError(null);
}, [open, recordId]);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!recordId) return;
setSubmitting(true);
setError(null);
try {
await pmApi.rescheduleRecord(recordId, {
rescheduled_to: rescheduledTo,
remarks: remarks.trim() || null,
});
await qc.invalidateQueries({ queryKey: ["pm-records"] });
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
onClose();
} catch (err) {
setError(err instanceof ApiError ? err.detail : "Failed to reschedule PM.");
} finally {
setSubmitting(false);
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={`Reschedule PM — ${assetLabel}`}>
<ErrorAlert message={error} />
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className={labelCls}>New Planned Date *</label>
<input
type="date"
required
value={rescheduledTo}
onChange={(e) => setRescheduledTo(e.target.value)}
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Reason / Remarks</label>
<textarea
rows={2}
value={remarks}
onChange={(e) => setRemarks(e.target.value)}
placeholder="e.g. Equipment in active OT use"
className={inputCls}
/>
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" loading={submitting}>
Reschedule
</Button>
</div>
</form>
</Modal>
);
}
+61
View File
@@ -5,6 +5,7 @@ import {
AlertCircle, AlertCircle,
Ban, Ban,
Clock, Clock,
CalendarClock,
ShieldAlert, ShieldAlert,
MinusCircle, MinusCircle,
} from "lucide-react"; } from "lucide-react";
@@ -72,6 +73,66 @@ export function AssetStatusBadge({
); );
} }
export function ScheduleStatusBadge({
status,
severity,
className,
}: {
status: string;
severity?: string;
className?: string;
}) {
const map: Record<string, { label: string; cls: string; icon: React.ReactNode }> = {
upcoming: {
label: "Upcoming",
cls: "bg-blue-100 text-blue-800 border border-blue-200",
icon: <Clock className="h-3 w-3 shrink-0" />,
},
due: {
label: "Due",
cls:
severity === "red"
? "bg-red-100 text-red-800 border border-red-200"
: "bg-amber-100 text-amber-800 border border-amber-200",
icon: <Clock className="h-3 w-3 shrink-0" />,
},
overdue: {
label: "Overdue",
cls: "bg-red-100 text-red-800 border border-red-200",
icon: <AlertTriangle className="h-3 w-3 shrink-0" />,
},
completed: {
label: "Completed",
cls: "bg-green-100 text-green-800 border border-green-200",
icon: <CheckCircle2 className="h-3 w-3 shrink-0" />,
},
rescheduled: {
label: "Rescheduled",
cls: "bg-purple-100 text-purple-800 border border-purple-200",
icon: <CalendarClock className="h-3 w-3 shrink-0" />,
},
};
const cfg = map[status] ?? {
label: status || "None",
cls: "bg-gray-100 text-gray-700 border border-gray-200",
icon: <MinusCircle className="h-3 w-3 shrink-0" />,
};
return (
<span
className={cn(
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",
cfg.cls,
className
)}
>
{cfg.icon}
<span>{cfg.label}</span>
</span>
);
}
export function CoverageBadge({ export function CoverageBadge({
status, status,
severity, severity,
+144 -12
View File
@@ -7,8 +7,10 @@ import {
ShieldCheck, ShieldCheck,
Ban, Ban,
AlertCircle, AlertCircle,
Plus,
} from "lucide-react"; } from "lucide-react";
import { assetsApi } from "@/api/assets"; import { assetsApi } from "@/api/assets";
import type { CalibrationPlanItem } from "@/api/calibration";
import { ApiError } from "@/api/client"; import { ApiError } from "@/api/client";
import { useAuthStore } from "@/hooks/useAuth"; import { useAuthStore } from "@/hooks/useAuth";
import { can } from "@/lib/permissions"; import { can } from "@/lib/permissions";
@@ -20,9 +22,19 @@ import {
CoverageBadge, CoverageBadge,
CalibrationBadge, CalibrationBadge,
CriticalityBadge, CriticalityBadge,
ScheduleStatusBadge,
} from "@/components/StatusBadge"; } from "@/components/StatusBadge";
import { Attachments } from "@/components/Attachments"; import { Attachments } from "@/components/Attachments";
import { AssetFormModal } from "@/components/AssetFormModal"; import { AssetFormModal } from "@/components/AssetFormModal";
import {
NewPMScheduleModal,
CompletePMModal,
ReschedulePMModal,
} from "@/components/PMModals";
import {
AddSingleCalibrationPlanModal,
ApproveCalibrationPlanModal,
} from "@/components/CalibrationModals";
type DetailTab = type DetailTab =
| "overview" | "overview"
@@ -52,10 +64,20 @@ export function AssetDetailPage() {
const [activeTab, setActiveTab] = useState<DetailTab>("overview"); const [activeTab, setActiveTab] = useState<DetailTab>("overview");
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
const [addCalOpen, setAddCalOpen] = useState(false);
const [approveCalOpen, setApproveCalOpen] = useState(false);
const [newPMOpen, setNewPMOpen] = useState(false);
const [completePMRecordId, setCompletePMRecordId] = useState<number | null>(null);
const [reschedulePMRecordId, setReschedulePMRecordId] = useState<number | null>(null);
const canFullEdit = can(role, "create_edit_assets"); const canFullEdit = can(role, "create_edit_assets");
const canContractOnlyEdit = !canFullEdit && can(role, "edit_asset_contracts_only"); const canContractOnlyEdit = !canFullEdit && can(role, "edit_asset_contracts_only");
const canEdit = canFullEdit || canContractOnlyEdit; const canEdit = canFullEdit || canContractOnlyEdit;
const canManagePM = can(role, "manage_pm") || role === "coordinator";
const canAddCalPlan =
can(role, "manage_calibration_contracts") || role === "management";
const canApproveCalPlan =
role === "management" || role === "system_admin" || role === "coordinator";
const { data, isLoading, isError, error } = useQuery({ const { data, isLoading, isError, error } = useQuery({
queryKey: ["asset-overview", assetId], queryKey: ["asset-overview", assetId],
@@ -365,7 +387,24 @@ export function AssetDetailPage() {
{activeTab === "calibration" && ( {activeTab === "calibration" && (
<div className="space-y-4"> <div className="space-y-4">
<div className="bg-white rounded-lg border border-gray-200 p-4"> <div className="bg-white rounded-lg border border-gray-200 p-4">
<h3 className="text-sm font-semibold text-gray-800 mb-2">Calibration Plan</h3> <div className="flex items-center justify-between gap-3 mb-2">
<h3 className="text-sm font-semibold text-gray-800">Calibration Plan</h3>
{!calibration_plan && canAddCalPlan && (
<Button size="sm" onClick={() => setAddCalOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add to Calibration List
</Button>
)}
{calibration_plan && canApproveCalPlan && (
<Button
size="sm"
variant={calibration_plan.approved_on ? "outline" : "default"}
onClick={() => setApproveCalOpen(true)}
>
{calibration_plan.approved_on ? "Edit Frequency" : "Approve Plan"}
</Button>
)}
</div>
{calibration_plan ? ( {calibration_plan ? (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm"> <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm">
<div> <div>
@@ -410,7 +449,15 @@ export function AssetDetailPage() {
{activeTab === "pm" && ( {activeTab === "pm" && (
<div className="space-y-4"> <div className="space-y-4">
<div> <div>
<h3 className="text-sm font-semibold text-gray-800 mb-2">PM Schedules</h3> <div className="flex items-center justify-between gap-3 mb-2">
<h3 className="text-sm font-semibold text-gray-800">PM Schedules</h3>
{canManagePM && (
<Button size="sm" onClick={() => setNewPMOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add PM Schedule
</Button>
)}
</div>
<SimpleTable <SimpleTable
emptyText="No PM schedules configured." emptyText="No PM schedules configured."
headers={["Frequency", "Service Mode", "Responsible / Provider", "Next Planned", "Active"]} headers={["Frequency", "Service Mode", "Responsible / Provider", "Next Planned", "Active"]}
@@ -429,16 +476,48 @@ export function AssetDetailPage() {
<h3 className="text-sm font-semibold text-gray-800 mb-2">Recent PM Records</h3> <h3 className="text-sm font-semibold text-gray-800 mb-2">Recent PM Records</h3>
<SimpleTable <SimpleTable
emptyText="No PM records yet." emptyText="No PM records yet."
headers={["Planned Date", "Completed Date", "Status", "Service Details", "Remarks"]} headers={
rows={pm_records.map((r) => [ canManagePM
formatDate(r.planned_date), ? ["Planned Date", "Completed Date", "Status", "Service Details", "Remarks", "Actions"]
formatDate(r.completed_date), : ["Planned Date", "Completed Date", "Status", "Service Details", "Remarks"]
<Badge key="st" variant={r.status === "completed" ? "success" : "warning"}> }
{r.status} rows={pm_records.map((r) => {
</Badge>, const isDone = r.status === "completed" || r.status === "rescheduled";
r.service_details || "—", const base = [
r.remarks || "—", formatDate(r.planned_date),
])} formatDate(r.completed_date),
<ScheduleStatusBadge key="st" status={r.status} severity={r.severity} />,
r.service_details || "—",
r.remarks || "—",
];
if (canManagePM) {
base.push(
isDone ? (
<span key="act" className="text-xs text-gray-400">
—
</span>
) : (
<div key="act" className="flex items-center gap-1.5">
<Button
size="sm"
variant="outline"
onClick={() => setCompletePMRecordId(r.id)}
>
Complete
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => setReschedulePMRecordId(r.id)}
>
Reschedule
</Button>
</div>
)
);
}
return base;
})}
/> />
</div> </div>
</div> </div>
@@ -493,6 +572,59 @@ export function AssetDetailPage() {
coordinatorOnly={canContractOnlyEdit} coordinatorOnly={canContractOnlyEdit}
/> />
)} )}
{canAddCalPlan && (
<AddSingleCalibrationPlanModal
open={addCalOpen}
onClose={() => setAddCalOpen(false)}
assetId={asset.id}
assetLabel={`${asset.asset_code} — ${asset.name}`}
canApprove={canApproveCalPlan}
/>
)}
{canApproveCalPlan && calibration_plan && (
<ApproveCalibrationPlanModal
open={approveCalOpen}
onClose={() => setApproveCalOpen(false)}
plan={{
...calibration_plan,
asset_code: asset.asset_code,
asset_name: asset.name,
department_id: asset.department_id,
department_name: asset.department_name,
approved_by_name: null,
}}
/>
)}
{canManagePM && (
<>
<NewPMScheduleModal
open={newPMOpen}
onClose={() => setNewPMOpen(false)}
fixedAsset={{
id: asset.id,
asset_code: asset.asset_code,
name: asset.name,
}}
/>
<CompletePMModal
open={completePMRecordId !== null}
onClose={() => setCompletePMRecordId(null)}
recordId={completePMRecordId}
assetLabel={`${asset.asset_code} — ${asset.name}`}
assetId={asset.id}
/>
<ReschedulePMModal
open={reschedulePMRecordId !== null}
onClose={() => setReschedulePMRecordId(null)}
recordId={reschedulePMRecordId}
assetLabel={`${asset.asset_code} — ${asset.name}`}
assetId={asset.id}
/>
</>
)}
</div> </div>
); );
} }
+495
View File
@@ -0,0 +1,495 @@
import { useState } from "react";
import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import type { ColumnDef } from "@tanstack/react-table";
import { Plus, CheckCircle2, Paperclip, ShieldCheck, Search } from "lucide-react";
import {
calibrationApi,
type CalibrationRecordItem,
type CalibrationPlanItem,
} from "@/api/calibration";
import { departmentsApi, vendorsApi } from "@/api/masters";
import { useAuthStore } from "@/hooks/useAuth";
import { formatDate } from "@/lib/format";
import { DataTable } from "@/components/DataTable";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Modal } from "@/components/ui/dialog";
import { ScheduleStatusBadge } from "@/components/StatusBadge";
import { Attachments } from "@/components/Attachments";
import {
BulkCalibrationAddModal,
ApproveCalibrationPlanModal,
CompleteCalibrationModal,
} from "@/components/CalibrationModals";
type CalTab = "records" | "plans";
export function CalibrationPage() {
const user = useAuthStore((s) => s.user);
const role = user?.role;
const isDeptUser = role === "department_user";
const canAddCalPlan =
role === "system_admin" ||
role === "biomedical" ||
role === "coordinator" ||
role === "management";
const canApproveCal =
role === "management" || role === "system_admin" || role === "coordinator";
const canCompleteCal =
role === "system_admin" || role === "biomedical" || role === "coordinator";
const [tab, setTab] = useState<CalTab>("records");
const [q, setQ] = useState("");
const [departmentId, setDepartmentId] = useState("");
const [agencyId, setAgencyId] = useState("");
const [statusFilter, setStatusFilter] = useState("");
const [dueFrom, setDueFrom] = useState("");
const [dueTo, setDueTo] = useState("");
const [bulkAddOpen, setBulkAddOpen] = useState(false);
const [approvingPlan, setApprovingPlan] = useState<CalibrationPlanItem | null>(null);
const [completingRec, setCompletingRec] = useState<CalibrationRecordItem | null>(null);
const [certModalRec, setCertModalRec] = useState<CalibrationRecordItem | null>(null);
const deptsQuery = useQuery({
queryKey: ["departments", "active-only"],
queryFn: () => departmentsApi.list(false),
enabled: !isDeptUser,
});
const vendorsQuery = useQuery({
queryKey: ["vendors", "active-only"],
queryFn: () => vendorsApi.list(false),
});
const recordsQuery = useQuery({
queryKey: [
"calibration-records",
q,
departmentId,
agencyId,
statusFilter,
dueFrom,
dueTo,
],
queryFn: () =>
calibrationApi.listRecords({
q: q.trim() || undefined,
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
agency_id: agencyId ? Number(agencyId) : undefined,
status: statusFilter || undefined,
due_from: dueFrom || undefined,
due_to: dueTo || undefined,
page_size: 200,
}),
});
const plansQuery = useQuery({
queryKey: ["calibration-plans", q, departmentId, agencyId],
queryFn: () =>
calibrationApi.listPlans({
q: q.trim() || undefined,
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
agency_id: agencyId ? Number(agencyId) : undefined,
page_size: 200,
}),
});
const summary = recordsQuery.data?.summary ?? {
upcoming: 0,
due: 0,
overdue: 0,
completed: 0,
};
const recordColumns: ColumnDef<CalibrationRecordItem, unknown>[] = [
{
accessorKey: "due_date",
header: "Due Date",
enableColumnFilter: false,
cell: ({ getValue }) => (
<span className="whitespace-nowrap font-medium">
{formatDate(getValue() as string)}
</span>
),
},
{
id: "asset_display",
accessorFn: (r) => `${r.asset_code} ${r.asset_name}`,
header: "Asset",
enableColumnFilter: true,
cell: ({ row }) => (
<Link to={`/assets/${row.original.asset_id}`} className="hover:underline">
<div className="font-mono text-xs font-semibold text-[#1e3a8a]">
{row.original.asset_code}
</div>
<div className="text-xs text-gray-800">{row.original.asset_name}</div>
</Link>
),
},
{
accessorKey: "department_name",
header: "Department",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "agency_name",
header: "Agency",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "status",
header: "Status",
enableColumnFilter: true,
cell: ({ row }) => (
<ScheduleStatusBadge
status={row.original.status}
severity={row.original.severity}
/>
),
},
{
accessorKey: "completed_date",
header: "Completed Date",
enableColumnFilter: false,
cell: ({ getValue }) => (
<span className="whitespace-nowrap text-xs">
{formatDate(getValue() as string | null)}
</span>
),
},
{
accessorKey: "certificate_no",
header: "Certificate No",
enableColumnFilter: true,
cell: ({ getValue }) => (
<span className="font-mono text-xs">{(getValue() as string | null) || "—"}</span>
),
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => {
const rec = row.original;
return (
<div className="flex items-center gap-1.5">
{canCompleteCal && rec.status !== "completed" && (
<Button
size="sm"
variant="success"
onClick={() => setCompletingRec(rec)}
>
<CheckCircle2 className="h-3.5 w-3.5 mr-1" />
Complete
</Button>
)}
<Button
size="sm"
variant="outline"
onClick={() => setCertModalRec(rec)}
>
<Paperclip className="h-3.5 w-3.5 mr-1" />
Certificates
</Button>
</div>
);
},
},
];
const planColumns: ColumnDef<CalibrationPlanItem, unknown>[] = [
{
id: "asset_display",
accessorFn: (p) => `${p.asset_code} ${p.asset_name}`,
header: "Asset",
enableColumnFilter: true,
cell: ({ row }) => (
<Link to={`/assets/${row.original.asset_id}`} className="hover:underline">
<div className="font-mono text-xs font-semibold text-[#1e3a8a]">
{row.original.asset_code}
</div>
<div className="text-xs text-gray-800">{row.original.asset_name}</div>
</Link>
),
},
{
accessorKey: "department_name",
header: "Department",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "frequency_months",
header: "Frequency",
cell: ({ getValue }) => `${String(getValue())} months`,
},
{
accessorKey: "calibrations_per_year",
header: "Cal / Year",
},
{
accessorKey: "agency_name",
header: "Agency",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
id: "approval",
accessorFn: (p) => p.approved_by_name ?? "Pending",
header: "Approved By / On",
cell: ({ row }) =>
row.original.approved_on ? (
<div className="text-xs">
<div className="font-medium text-green-800">
{row.original.approved_by_name || "Approved"}
</div>
<div className="text-gray-500">{formatDate(row.original.approved_on)}</div>
</div>
) : (
<Badge variant="warning">Pending Approval</Badge>
),
},
{
accessorKey: "next_due_date",
header: "Next Due Date",
cell: ({ getValue }) => formatDate(getValue() as string),
},
...(canApproveCal
? [
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }: { row: { original: CalibrationPlanItem } }) => (
<Button
size="sm"
variant="outline"
onClick={() => setApprovingPlan(row.original)}
>
<ShieldCheck className="h-3.5 w-3.5 mr-1" />
{row.original.approved_on ? "Edit Frequency" : "Approve / Edit Frequency"}
</Button>
),
} satisfies ColumnDef<CalibrationPlanItem, unknown>,
]
: []),
];
const departments = deptsQuery.data?.items ?? [];
const agencies = (vendorsQuery.data?.items ?? []).filter(
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
);
const existingPlanAssetIds = (plansQuery.data?.items ?? []).map((p) => p.asset_id);
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-gray-900">Calibration</h1>
<p className="text-sm text-gray-500 mt-0.5">
Manage calibration plans, management approvals, due dates, and certificates
</p>
</div>
{canAddCalPlan && (
<Button onClick={() => setBulkAddOpen(true)}>
<Plus className="h-4 w-4 mr-1.5" />
Add Equipment to Calibration
</Button>
)}
</div>
{/* KPI Strip */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
<KpiCard label="Upcoming" value={summary.upcoming} color="text-blue-700 bg-blue-50 border-blue-200" />
<KpiCard label="Due" value={summary.due} color="text-amber-700 bg-amber-50 border-amber-200" />
<KpiCard label="Overdue" value={summary.overdue} color="text-red-700 bg-red-50 border-red-200" />
<KpiCard label="Completed" value={summary.completed} color="text-green-700 bg-green-50 border-green-200" />
</div>
{/* Filter Bar */}
<div className="bg-white border border-gray-200 rounded-lg p-3.5 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-2.5">
<div className="relative lg:col-span-2">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400" />
<input
type="text"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Search asset code, name, certificate..."
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
/>
</div>
{!isDeptUser && (
<select
value={departmentId}
onChange={(e) => setDepartmentId(e.target.value)}
aria-label="Filter by Department"
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Departments</option>
{departments.map((d) => (
<option key={d.id} value={String(d.id)}>
{d.name}
</option>
))}
</select>
)}
<select
value={agencyId}
onChange={(e) => setAgencyId(e.target.value)}
aria-label="Filter by Agency"
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Agencies</option>
{agencies.map((a) => (
<option key={a.id} value={String(a.id)}>
{a.name}
</option>
))}
</select>
{tab === "records" && (
<>
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
aria-label="Filter by Status"
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Statuses</option>
<option value="upcoming">Upcoming</option>
<option value="due">Due</option>
<option value="overdue">Overdue</option>
<option value="completed">Completed</option>
</select>
<div className="flex items-center gap-1.5 lg:col-span-2">
<input
type="date"
aria-label="Due from"
value={dueFrom}
onChange={(e) => setDueFrom(e.target.value)}
className="flex-1 px-2 py-1 text-xs border border-gray-200 rounded-md"
/>
<span className="text-xs text-gray-400">to</span>
<input
type="date"
aria-label="Due to"
value={dueTo}
onChange={(e) => setDueTo(e.target.value)}
className="flex-1 px-2 py-1 text-xs border border-gray-200 rounded-md"
/>
</div>
</>
)}
</div>
{/* Tabs */}
<div className="border-b border-gray-200 flex gap-1">
<button
type="button"
onClick={() => setTab("records")}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
tab === "records"
? "border-[#1e3a8a] text-[#1e3a8a]"
: "border-transparent text-gray-500 hover:text-gray-800"
}`}
>
Calibration Records
</button>
<button
type="button"
onClick={() => setTab("plans")}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
tab === "plans"
? "border-[#1e3a8a] text-[#1e3a8a]"
: "border-transparent text-gray-500 hover:text-gray-800"
}`}
>
Calibration Plans
</button>
</div>
{tab === "records" && (
<DataTable
data={recordsQuery.data?.items ?? []}
columns={recordColumns}
loading={recordsQuery.isLoading}
globalFilterPlaceholder="Quick filter calibration records..."
exportFilename="calibration-records"
emptyMessage="No calibration records match the current filters."
/>
)}
{tab === "plans" && (
<DataTable
data={plansQuery.data?.items ?? []}
columns={planColumns}
loading={plansQuery.isLoading}
globalFilterPlaceholder="Quick filter calibration plans..."
exportFilename="calibration-plans"
emptyMessage="No calibration plans found."
/>
)}
<BulkCalibrationAddModal
open={bulkAddOpen}
onClose={() => setBulkAddOpen(false)}
existingPlanAssetIds={existingPlanAssetIds}
canApprove={canApproveCal}
/>
<ApproveCalibrationPlanModal
open={Boolean(approvingPlan)}
onClose={() => setApprovingPlan(null)}
plan={approvingPlan}
/>
<CompleteCalibrationModal
open={Boolean(completingRec)}
onClose={() => setCompletingRec(null)}
recordId={completingRec?.id ?? null}
assetLabel={completingRec ? `${completingRec.asset_code} ${completingRec.asset_name}` : ""}
defaultAgencyId={completingRec?.agency_id}
assetId={completingRec?.asset_id}
/>
<Modal
open={Boolean(certModalRec)}
onOpenChange={(o) => !o && setCertModalRec(null)}
title={
certModalRec
? `Calibration Certificates — ${certModalRec.asset_code}`
: "Certificates"
}
className="max-w-xl"
>
{certModalRec && (
<Attachments
entityType="calibration_record"
entityId={certModalRec.id}
canUpload={canCompleteCal}
canDelete={role === "system_admin" || role === "biomedical"}
/>
)}
</Modal>
</div>
);
}
function KpiCard({ label, value, color }: { label: string; value: number; color: string }) {
return (
<div className={`rounded-xl border p-4 ${color}`}>
<div className="text-xs font-medium opacity-80">{label}</div>
<div className="text-2xl font-bold mt-1">{value}</div>
</div>
);
}
+736
View File
@@ -0,0 +1,736 @@
import { useState, useMemo } from "react";
import { Link } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import type { ColumnDef } from "@tanstack/react-table";
import {
Plus,
Table as TableIcon,
Calendar as CalendarIcon,
CheckCircle2,
CalendarClock,
ChevronLeft,
ChevronRight,
Search,
} from "lucide-react";
import {
pmApi,
type PMRecordItem,
type PMScheduleItem,
type ServiceMode,
type ScheduleStatus,
} from "@/api/pm";
import { departmentsApi } from "@/api/masters";
import { useAuthStore } from "@/hooks/useAuth";
import { can } from "@/lib/permissions";
import { formatDate } from "@/lib/format";
import { DataTable } from "@/components/DataTable";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Modal } from "@/components/ui/dialog";
import { ScheduleStatusBadge } from "@/components/StatusBadge";
import {
NewPMScheduleModal,
CompletePMModal,
ReschedulePMModal,
} from "@/components/PMModals";
type ActiveTab = "records" | "schedules";
type ViewMode = "table" | "calendar";
function currentYearMonth(): string {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}
function shiftYearMonth(ym: string, delta: number): string {
const [y, m] = ym.split("-").map(Number);
const d = new Date(y, m - 1 + delta, 1);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}
function buildMonthGrid(ym: string) {
const [year, month] = ym.split("-").map(Number);
const firstDay = new Date(year, month - 1, 1);
const daysInMonth = new Date(year, month, 0).getDate();
// Convert Sunday=0..Saturday=6 into Monday=0..Sunday=6
const startOffset = (firstDay.getDay() + 6) % 7;
const cells: Array<{ dateStr: string | null; dayNum: number | null }> = [];
for (let i = 0; i < startOffset; i++) {
cells.push({ dateStr: null, dayNum: null });
}
for (let d = 1; d <= daysInMonth; d++) {
const dateStr = `${year}-${String(month).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
cells.push({ dateStr, dayNum: d });
}
while (cells.length % 7 !== 0) {
cells.push({ dateStr: null, dayNum: null });
}
return cells;
}
const CHIP_COLOR: Record<string, string> = {
upcoming: "bg-blue-100 text-blue-800 border-blue-200",
due: "bg-amber-100 text-amber-800 border-amber-200",
overdue: "bg-red-100 text-red-800 border-red-200",
completed: "bg-green-100 text-green-800 border-green-200",
rescheduled: "bg-purple-100 text-purple-800 border-purple-200",
};
export function PMPage() {
const qc = useQueryClient();
const user = useAuthStore((s) => s.user);
const role = user?.role;
const isDeptUser = role === "department_user";
const canManagePm = can(role, "manage_pm") || role === "coordinator";
const [tab, setTab] = useState<ActiveTab>("records");
const [viewMode, setViewMode] = useState<ViewMode>("table");
const [monthFilter, setMonthFilter] = useState("");
const [departmentId, setDepartmentId] = useState("");
const [serviceMode, setServiceMode] = useState<ServiceMode | "">("");
const [statusFilter, setStatusFilter] = useState<ScheduleStatus | "">("");
const [q, setQ] = useState("");
const [newScheduleOpen, setNewScheduleOpen] = useState(false);
const [completingRec, setCompletingRec] = useState<PMRecordItem | null>(null);
const [reschedulingRec, setReschedulingRec] = useState<PMRecordItem | null>(null);
const [calendarDetailRec, setCalendarDetailRec] = useState<PMRecordItem | null>(null);
const effectiveCalendarMonth = monthFilter || currentYearMonth();
const deptsQuery = useQuery({
queryKey: ["departments", "active-only"],
queryFn: () => departmentsApi.list(false),
enabled: !isDeptUser,
});
const recordsQuery = useQuery({
queryKey: [
"pm-records",
viewMode === "calendar" ? effectiveCalendarMonth : monthFilter,
departmentId,
serviceMode,
statusFilter,
q,
],
queryFn: () =>
pmApi.listRecords({
q: q.trim() || undefined,
month:
viewMode === "calendar"
? effectiveCalendarMonth
: monthFilter || undefined,
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
service_mode: serviceMode || undefined,
status: statusFilter || undefined,
page_size: 200,
}),
});
const schedulesQuery = useQuery({
queryKey: ["pm-schedules", departmentId, serviceMode, q],
queryFn: () =>
pmApi.listSchedules({
q: q.trim() || undefined,
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
service_mode: serviceMode || undefined,
is_active: true,
page_size: 200,
}),
enabled: tab === "schedules",
});
const deactivateScheduleMutation = useMutation({
mutationFn: (id: number) => pmApi.deleteSchedule(id),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["pm-schedules"] });
},
});
const summary = recordsQuery.data?.summary ?? {
upcoming: 0,
due: 0,
overdue: 0,
completed_this_month: 0,
};
const recordColumns: ColumnDef<PMRecordItem, unknown>[] = [
{
accessorKey: "planned_date",
header: "Planned Date",
enableColumnFilter: false,
cell: ({ getValue }) => (
<span className="whitespace-nowrap font-medium">
{formatDate(getValue() as string)}
</span>
),
},
{
id: "asset_display",
accessorFn: (r) => `${r.asset_code} ${r.asset_name}`,
header: "Asset",
enableColumnFilter: true,
cell: ({ row }) => (
<Link
to={`/assets/${row.original.asset_id}`}
onClick={(e) => e.stopPropagation()}
className="hover:underline"
>
<div className="font-mono text-xs font-semibold text-[#1e3a8a]">
{row.original.asset_code}
</div>
<div className="text-xs text-gray-800">{row.original.asset_name}</div>
</Link>
),
},
{
accessorKey: "department_name",
header: "Department",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "service_mode",
header: "Mode",
enableColumnFilter: true,
cell: ({ getValue }) => (
<Badge variant="outline">
{getValue() === "in_house" ? "In-House" : "Outsourced"}
</Badge>
),
},
{
id: "team_provider",
accessorFn: (r) => r.provider_name || r.responsible_team || "—",
header: "Team / Provider",
enableColumnFilter: true,
},
{
accessorKey: "status",
header: "Status",
enableColumnFilter: true,
cell: ({ row }) => (
<ScheduleStatusBadge
status={row.original.status}
severity={row.original.severity}
/>
),
},
{
accessorKey: "completed_date",
header: "Completed Date",
enableColumnFilter: false,
cell: ({ getValue }) => (
<span className="whitespace-nowrap text-xs">
{formatDate(getValue() as string | null)}
</span>
),
},
{
accessorKey: "service_details",
header: "Service Details",
cell: ({ getValue }) => (
<span className="text-xs text-gray-600 line-clamp-2">
{(getValue() as string | null) || "—"}
</span>
),
},
...(canManagePm
? [
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }: { row: { original: PMRecordItem } }) => {
const rec = row.original;
const actionable =
rec.status !== "completed" && rec.status !== "rescheduled";
if (!actionable) return <span className="text-xs text-gray-400">—</span>;
return (
<div className="flex items-center gap-1.5">
<Button
size="sm"
variant="success"
onClick={() => setCompletingRec(rec)}
>
<CheckCircle2 className="h-3.5 w-3.5 mr-1" />
Complete
</Button>
<Button
size="sm"
variant="outline"
onClick={() => setReschedulingRec(rec)}
>
<CalendarClock className="h-3.5 w-3.5 mr-1" />
Reschedule
</Button>
</div>
);
},
} satisfies ColumnDef<PMRecordItem, unknown>,
]
: []),
];
const scheduleColumns: ColumnDef<PMScheduleItem, unknown>[] = [
{
id: "asset_display",
accessorFn: (s) => `${s.asset_code} ${s.asset_name}`,
header: "Asset",
enableColumnFilter: true,
cell: ({ row }) => (
<Link to={`/assets/${row.original.asset_id}`} className="hover:underline">
<div className="font-mono text-xs font-semibold text-[#1e3a8a]">
{row.original.asset_code}
</div>
<div className="text-xs text-gray-800">{row.original.asset_name}</div>
</Link>
),
},
{
accessorKey: "department_name",
header: "Department",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "service_mode",
header: "Service Mode",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() === "in_house" ? "In-House" : "Outsourced"),
},
{
accessorKey: "frequency_months",
header: "Frequency",
cell: ({ getValue }) => `Every ${String(getValue())} months`,
},
{
id: "team_provider",
accessorFn: (s) => s.provider_name || s.responsible_team || "—",
header: "Team / Provider",
enableColumnFilter: true,
},
{
accessorKey: "contract_summary",
header: "Contract",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "next_planned_date",
header: "Next Planned",
cell: ({ getValue }) => formatDate(getValue() as string),
},
...(canManagePm
? [
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }: { row: { original: PMScheduleItem } }) => (
<Button
size="sm"
variant="ghost"
className="text-red-600 hover:bg-red-50"
disabled={deactivateScheduleMutation.isPending}
onClick={() => deactivateScheduleMutation.mutate(row.original.id)}
>
Deactivate
</Button>
),
} satisfies ColumnDef<PMScheduleItem, unknown>,
]
: []),
];
const recordsByDate = useMemo(() => {
const map = new Map<string, PMRecordItem[]>();
for (const r of recordsQuery.data?.items ?? []) {
const list = map.get(r.planned_date) ?? [];
list.push(r);
map.set(r.planned_date, list);
}
return map;
}, [recordsQuery.data?.items]);
const calendarCells = useMemo(
() => buildMonthGrid(effectiveCalendarMonth),
[effectiveCalendarMonth]
);
const departments = deptsQuery.data?.items ?? [];
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-gray-900">Preventive Maintenance</h1>
<p className="text-sm text-gray-500 mt-0.5">
Track in-house and outsourced PM schedules, due dates, and completion logs
</p>
</div>
{canManagePm && (
<Button onClick={() => setNewScheduleOpen(true)}>
<Plus className="h-4 w-4 mr-1.5" />
New PM Schedule
</Button>
)}
</div>
{/* KPI Strip */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
<KpiCard label="Upcoming" value={summary.upcoming} color="text-blue-700 bg-blue-50 border-blue-200" />
<KpiCard label="Due" value={summary.due} color="text-amber-700 bg-amber-50 border-amber-200" />
<KpiCard label="Overdue" value={summary.overdue} color="text-red-700 bg-red-50 border-red-200" />
<KpiCard
label="Completed This Month"
value={summary.completed_this_month}
color="text-green-700 bg-green-50 border-green-200"
/>
</div>
{/* Filter Bar */}
<div className="bg-white border border-gray-200 rounded-lg p-3.5 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-2.5">
<div className="relative lg:col-span-2">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400" />
<input
type="text"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Search asset code, name, team..."
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
/>
</div>
<div className="flex items-center gap-1">
<input
type="month"
aria-label="Filter by Month"
value={monthFilter}
onChange={(e) => setMonthFilter(e.target.value)}
className="flex-1 px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
/>
{monthFilter && (
<button
type="button"
onClick={() => setMonthFilter("")}
className="px-2 py-1 text-xs border border-gray-200 rounded hover:bg-gray-50"
>
All
</button>
)}
</div>
{!isDeptUser && (
<select
value={departmentId}
onChange={(e) => setDepartmentId(e.target.value)}
aria-label="Filter by Department"
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Departments</option>
{departments.map((d) => (
<option key={d.id} value={String(d.id)}>
{d.name}
</option>
))}
</select>
)}
<select
value={serviceMode}
onChange={(e) => setServiceMode(e.target.value as ServiceMode | "")}
aria-label="Filter by Service Mode"
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Modes</option>
<option value="in_house">In-House</option>
<option value="outsourced">Outsourced</option>
</select>
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value as ScheduleStatus | "")}
aria-label="Filter by Status"
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Statuses</option>
<option value="upcoming">Upcoming</option>
<option value="due">Due</option>
<option value="overdue">Overdue</option>
<option value="completed">Completed</option>
<option value="rescheduled">Rescheduled</option>
</select>
</div>
{/* Tabs + View Switcher */}
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-gray-200 pb-2">
<div className="flex gap-1">
<button
type="button"
onClick={() => setTab("records")}
className={`px-4 py-2 text-sm font-medium border-b-2 -mb-[9px] transition-colors ${
tab === "records"
? "border-[#1e3a8a] text-[#1e3a8a]"
: "border-transparent text-gray-500 hover:text-gray-800"
}`}
>
PM Records
</button>
<button
type="button"
onClick={() => setTab("schedules")}
className={`px-4 py-2 text-sm font-medium border-b-2 -mb-[9px] transition-colors ${
tab === "schedules"
? "border-[#1e3a8a] text-[#1e3a8a]"
: "border-transparent text-gray-500 hover:text-gray-800"
}`}
>
Active Schedules
</button>
</div>
{tab === "records" && (
<div className="inline-flex rounded-md border border-gray-200 bg-white p-0.5">
<button
type="button"
onClick={() => setViewMode("table")}
className={`inline-flex items-center gap-1.5 px-3 py-1 rounded text-xs font-medium transition-colors ${
viewMode === "table"
? "bg-[#1e3a8a] text-white"
: "text-gray-600 hover:bg-gray-50"
}`}
>
<TableIcon className="h-3.5 w-3.5" />
Table View
</button>
<button
type="button"
onClick={() => setViewMode("calendar")}
className={`inline-flex items-center gap-1.5 px-3 py-1 rounded text-xs font-medium transition-colors ${
viewMode === "calendar"
? "bg-[#1e3a8a] text-white"
: "text-gray-600 hover:bg-gray-50"
}`}
>
<CalendarIcon className="h-3.5 w-3.5" />
Calendar View
</button>
</div>
)}
</div>
{/* Main Content */}
{tab === "records" && viewMode === "table" && (
<DataTable
data={recordsQuery.data?.items ?? []}
columns={recordColumns}
loading={recordsQuery.isLoading}
globalFilterPlaceholder="Quick filter PM records..."
exportFilename="pm-records"
emptyMessage="No PM records match the current filters."
/>
)}
{tab === "records" && viewMode === "calendar" && (
<div className="bg-white border border-gray-200 rounded-xl p-4 space-y-3">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold text-gray-800">
PM Calendar — {effectiveCalendarMonth}
</h2>
<div className="flex items-center gap-1.5">
<Button
size="sm"
variant="outline"
onClick={() => setMonthFilter(shiftYearMonth(effectiveCalendarMonth, -1))}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="outline"
onClick={() => setMonthFilter(currentYearMonth())}
>
Today
</Button>
<Button
size="sm"
variant="outline"
onClick={() => setMonthFilter(shiftYearMonth(effectiveCalendarMonth, 1))}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
<div className="grid grid-cols-7 gap-1 text-center text-xs font-semibold text-gray-500 pb-1">
{["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
<div key={d} className="py-1">
{d}
</div>
))}
</div>
<div className="grid grid-cols-7 gap-1">
{calendarCells.map((cell, idx) => {
const items = cell.dateStr ? recordsByDate.get(cell.dateStr) ?? [] : [];
return (
<div
key={idx}
className={`min-h-24 rounded-md border p-1.5 text-left ${
cell.dayNum ? "bg-white border-gray-200" : "bg-gray-50 border-gray-100"
}`}
>
{cell.dayNum && (
<>
<div className="text-[11px] font-semibold text-gray-500 mb-1">
{cell.dayNum}
</div>
<div className="space-y-1">
{items.map((item) => (
<button
key={item.id}
type="button"
onClick={() => setCalendarDetailRec(item)}
className={`w-full text-left px-1.5 py-0.5 rounded border text-[10px] font-medium truncate ${
CHIP_COLOR[item.status] ?? "bg-gray-100 text-gray-700"
}`}
title={`${item.asset_code} — ${item.asset_name} (${item.status})`}
>
{item.asset_code}
</button>
))}
</div>
</>
)}
</div>
);
})}
</div>
</div>
)}
{tab === "schedules" && (
<DataTable
data={schedulesQuery.data?.items ?? []}
columns={scheduleColumns}
loading={schedulesQuery.isLoading}
globalFilterPlaceholder="Quick filter PM schedules..."
exportFilename="pm-schedules"
emptyMessage="No active PM schedules found."
/>
)}
{/* Calendar Item Quick Detail Modal */}
<Modal
open={Boolean(calendarDetailRec)}
onOpenChange={(o) => !o && setCalendarDetailRec(null)}
title={
calendarDetailRec
? `${calendarDetailRec.asset_code} — ${calendarDetailRec.asset_name}`
: "PM Details"
}
>
{calendarDetailRec && (
<div className="space-y-3 text-sm">
<div className="flex items-center gap-2">
<ScheduleStatusBadge
status={calendarDetailRec.status}
severity={calendarDetailRec.severity}
/>
<Badge variant="outline">
{calendarDetailRec.service_mode === "in_house" ? "In-House" : "Outsourced"}
</Badge>
</div>
<div className="grid grid-cols-2 gap-2 text-xs">
<div>
<span className="text-gray-500">Planned Date:</span>{" "}
<strong>{formatDate(calendarDetailRec.planned_date)}</strong>
</div>
<div>
<span className="text-gray-500">Department:</span>{" "}
<strong>{calendarDetailRec.department_name || "—"}</strong>
</div>
<div>
<span className="text-gray-500">Team / Provider:</span>{" "}
<strong>
{calendarDetailRec.provider_name ||
calendarDetailRec.responsible_team ||
"—"}
</strong>
</div>
<div>
<span className="text-gray-500">Completed:</span>{" "}
<strong>{formatDate(calendarDetailRec.completed_date)}</strong>
</div>
</div>
<div className="flex justify-end gap-2 pt-2">
<Link to={`/assets/${calendarDetailRec.asset_id}`}>
<Button variant="outline" size="sm">
View Asset
</Button>
</Link>
{canManagePm &&
calendarDetailRec.status !== "completed" &&
calendarDetailRec.status !== "rescheduled" && (
<>
<Button
size="sm"
variant="outline"
onClick={() => {
setReschedulingRec(calendarDetailRec);
setCalendarDetailRec(null);
}}
>
Reschedule
</Button>
<Button
size="sm"
variant="success"
onClick={() => {
setCompletingRec(calendarDetailRec);
setCalendarDetailRec(null);
}}
>
Complete
</Button>
</>
)}
</div>
</div>
)}
</Modal>
<NewPMScheduleModal open={newScheduleOpen} onClose={() => setNewScheduleOpen(false)} />
<CompletePMModal
open={Boolean(completingRec)}
onClose={() => setCompletingRec(null)}
recordId={completingRec?.id ?? null}
assetLabel={completingRec ? `${completingRec.asset_code} ${completingRec.asset_name}` : ""}
assetId={completingRec?.asset_id}
/>
<ReschedulePMModal
open={Boolean(reschedulingRec)}
onClose={() => setReschedulingRec(null)}
recordId={reschedulingRec?.id ?? null}
assetLabel={
reschedulingRec ? `${reschedulingRec.asset_code} ${reschedulingRec.asset_name}` : ""
}
assetId={reschedulingRec?.asset_id}
/>
</div>
);
}
function KpiCard({ label, value, color }: { label: string; value: number; color: string }) {
return (
<div className={`rounded-xl border p-4 ${color}`}>
<div className="text-xs font-medium opacity-80">{label}</div>
<div className="text-2xl font-bold mt-1">{value}</div>
</div>
);
}
-6
View File
@@ -36,12 +36,6 @@ export const DashboardPage = () => (
</div> </div>
</StubPage> </StubPage>
); );
export const PMPage = () => (
<StubPage title="Preventive Maintenance" phase={4} description="PM schedules and calendar view." />
);
export const CalibrationPage = () => (
<StubPage title="Calibration" phase={4} description="Calibration plans and records with due-date alerts." />
);
export const ContractsPage = () => ( export const ContractsPage = () => (
<StubPage title="Contracts & Warranty" phase={5} description="AMC/CMC contracts and warranty tracking." /> <StubPage title="Contracts & Warranty" phase={5} description="AMC/CMC contracts and warranty tracking." />
); );
+124
View File
@@ -0,0 +1,124 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { CalibrationPage } from "@/pages/CalibrationPage";
import {
calibrationApi,
type CalibrationPlanItem,
} from "@/api/calibration";
import { departmentsApi, vendorsApi } from "@/api/masters";
import { useAuthStore } from "@/hooks/useAuth";
const MOCK_PLAN: CalibrationPlanItem = {
id: 50,
asset_id: 1,
asset_code: "PHRC-LAB-0009",
asset_name: "Auto Analyzer",
department_id: 2,
department_name: "Pathology",
frequency_months: 12,
calibrations_per_year: 1,
agency_id: 4,
agency_name: "NABL Calibration Labs",
approved_by_id: null,
approved_by_name: null,
approved_on: null,
next_due_date: "2026-12-01",
is_active: true,
};
function renderCalibrationPage() {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={qc}>
<MemoryRouter>
<CalibrationPage />
</MemoryRouter>
</QueryClientProvider>
);
}
describe("CalibrationPage", () => {
beforeEach(() => {
vi.restoreAllMocks();
vi.spyOn(departmentsApi, "list").mockResolvedValue({
items: [{ id: 2, name: "Pathology", code: "LAB", description: null, is_active: true }],
total: 1,
});
vi.spyOn(vendorsApi, "list").mockResolvedValue({
items: [],
total: 0,
});
vi.spyOn(calibrationApi, "listRecords").mockResolvedValue({
items: [],
total: 0,
summary: { upcoming: 1, due: 0, overdue: 0, completed: 2 },
});
vi.spyOn(calibrationApi, "listPlans").mockResolvedValue({
items: [MOCK_PLAN],
total: 1,
});
});
it("shows Approve / Edit Frequency button on Calibration Plans tab for management", async () => {
useAuthStore.setState({
user: {
id: 5,
email: "mgmt@poona.org",
name: "Hospital Director",
role: "management",
department_id: null,
department_name: null,
is_active: true,
},
token: "test-token",
});
renderCalibrationPage();
const plansTab = screen.getByRole("button", { name: /Calibration Plans/i });
fireEvent.click(plansTab);
await waitFor(() => {
expect(screen.getByText("PHRC-LAB-0009")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: /Approve \/ Edit Frequency/i })
).toBeInTheDocument();
});
});
it("hides Approve / Edit Frequency button on Calibration Plans tab for biomedical", async () => {
useAuthStore.setState({
user: {
id: 2,
email: "bio@poona.org",
name: "Biomed Engineer",
role: "biomedical",
department_id: null,
department_name: null,
is_active: true,
},
token: "test-token",
});
renderCalibrationPage();
const plansTab = screen.getByRole("button", { name: /Calibration Plans/i });
fireEvent.click(plansTab);
await waitFor(() => {
expect(screen.getByText("PHRC-LAB-0009")).toBeInTheDocument();
});
expect(
screen.queryByRole("button", { name: /Approve \/ Edit Frequency/i })
).not.toBeInTheDocument();
expect(
screen.queryByRole("button", { name: /Edit Frequency/i })
).not.toBeInTheDocument();
expect(
screen.getByRole("button", { name: /Add Equipment to Calibration/i })
).toBeInTheDocument();
});
});
+118
View File
@@ -0,0 +1,118 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { PMPage } from "@/pages/PMPage";
import { pmApi, type PMRecordItem } from "@/api/pm";
import { departmentsApi } from "@/api/masters";
import { useAuthStore } from "@/hooks/useAuth";
function currentMonthDay(day = 15): string {
const now = new Date();
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, "0");
const d = String(day).padStart(2, "0");
return `${y}-${m}-${d}`;
}
const MOCK_RECORD: PMRecordItem = {
id: 101,
schedule_id: 11,
asset_id: 1,
asset_code: "PHRC-ICU-0001",
asset_name: "ICU Ventilator",
department_id: 1,
department_name: "ICU",
location_name: "ICU Bay 1",
service_mode: "in_house",
responsible_team: "Biomed Team A",
provider_id: null,
provider_name: null,
contract_id: null,
frequency_months: 6,
planned_date: currentMonthDay(15),
completed_date: null,
status: "due",
severity: "yellow",
service_details: null,
remarks: null,
rescheduled_to: null,
};
function renderPMPage() {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={qc}>
<MemoryRouter>
<PMPage />
</MemoryRouter>
</QueryClientProvider>
);
}
describe("PMPage", () => {
beforeEach(() => {
vi.restoreAllMocks();
useAuthStore.setState({
user: {
id: 2,
email: "bio@poona.org",
name: "Biomed Engineer",
role: "biomedical",
department_id: null,
department_name: null,
is_active: true,
},
token: "test-token",
});
vi.spyOn(departmentsApi, "list").mockResolvedValue({
items: [{ id: 1, name: "ICU", code: "ICU", description: null, is_active: true }],
total: 1,
});
vi.spyOn(pmApi, "listRecords").mockResolvedValue({
items: [MOCK_RECORD],
total: 1,
summary: { upcoming: 3, due: 2, overdue: 1, completed_this_month: 5 },
});
vi.spyOn(pmApi, "listSchedules").mockResolvedValue({
items: [],
total: 0,
});
});
it("renders KPI strip counts and switches between Table and Calendar views", async () => {
renderPMPage();
await waitFor(() => {
expect(screen.getAllByText("Upcoming").length).toBeGreaterThanOrEqual(1);
expect(screen.getByText("Completed This Month")).toBeInTheDocument();
expect(screen.getByText("3")).toBeInTheDocument();
expect(screen.getByText("2")).toBeInTheDocument();
expect(screen.getByText("5")).toBeInTheDocument();
});
// Initially in Table view
expect(screen.getByText("PHRC-ICU-0001")).toBeInTheDocument();
expect(screen.getByText("ICU Ventilator")).toBeInTheDocument();
// Switch to Calendar view
const calendarBtn = screen.getByRole("button", { name: /Calendar/i });
fireEvent.click(calendarBtn);
await waitFor(() => {
expect(screen.getByText("Mon")).toBeInTheDocument();
expect(screen.getByText("Sun")).toBeInTheDocument();
expect(screen.getByText(/PHRC-ICU-0001/)).toBeInTheDocument();
});
// Switch back to Table view
const tableBtn = screen.getByRole("button", { name: /Table View/i });
fireEvent.click(tableBtn);
await waitFor(() => {
expect(screen.queryByText("Mon")).not.toBeInTheDocument();
expect(screen.getByText("ICU Ventilator")).toBeInTheDocument();
});
});
});
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"} {"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/pm.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/pmpage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/pm-page.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}