fix: reopen clears restored_at, wire settings, docs, startup warning

This commit is contained in:
Atharv1705
2026-11-12 17:34:04 +05:30
parent 5027c0766e
commit e2a6fa601e
17 changed files with 292 additions and 36 deletions
+12 -7
View File
@@ -14,10 +14,14 @@ A centralized Hospital Asset Management and Maintenance System for Poona Hospita
```bash ```bash
cd backend cd backend
python -m venv .venv python -m venv .venv
# Windows PowerShell: .venv\Scripts\Activate.ps1
# macOS/Linux: source .venv/bin/activate # Windows PowerShell:
.venv/Scripts/pip install -r requirements.txt # or pip install -r requirements.txt once activated .venv\Scripts\activate
.venv/Scripts/uvicorn app.main:app --reload --port 8000 # macOS/Linux:
# source .venv/bin/activate
pip install -r requirements.txt
python -m uvicorn app.main:app --reload --port 8000
``` ```
- Health check: http://localhost:8000/api/health - Health check: http://localhost:8000/api/health
- API docs: http://localhost:8000/docs - API docs: http://localhost:8000/docs
@@ -37,9 +41,9 @@ make dev
### Run tests ### Run tests
```bash ```bash
# Backend # Backend (activate .venv first: Windows .venv\Scripts\activate | macOS/Linux source .venv/bin/activate)
cd backend cd backend
.venv/Scripts/python -m pytest tests/ -v python -m pytest tests/ -v
# Or via Make: make test # Or via Make: make test
# Frontend (build + Vitest) # Frontend (build + Vitest)
@@ -50,8 +54,9 @@ npm test
### Seed demo data ### Seed demo data
```bash ```bash
# Activate .venv first: Windows .venv\Scripts\activate | macOS/Linux source .venv/bin/activate
cd backend cd backend
.venv/Scripts/python -m app.seed.seed python -m app.seed.seed
# Or via Make: make seed # Or via Make: make seed
``` ```
+5 -1
View File
@@ -2,8 +2,12 @@ import calendar
from datetime import date, datetime, timezone from datetime import date, datetime, timezone
import json import json
import pytz import pytz
from .config import settings
KOLKATA = pytz.timezone("Asia/Kolkata") try:
KOLKATA = pytz.timezone(settings.TIMEZONE)
except Exception:
KOLKATA = pytz.timezone("Asia/Kolkata")
def utc_now() -> datetime: def utc_now() -> datetime:
+12 -3
View File
@@ -8,6 +8,7 @@ from apscheduler.triggers.cron import CronTrigger
from fastapi import FastAPI, Request from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from .core.config import settings as app_settings
from .core.db import SessionLocal, engine, get_scheduler_db from .core.db import SessionLocal, engine, get_scheduler_db
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
@@ -60,19 +61,27 @@ async def lifespan(app: FastAPI):
db.commit() db.commit()
logger.info("Database tables created/verified.") logger.info("Database tables created/verified.")
if app_settings.SECRET_KEY in {
"change-me-in-production-32-chars-min",
"change-me-in-production-use-a-32-char-random-string",
}:
logging.warning(
"SECURITY: SECRET_KEY is set to the insecure default. Set a strong SECRET_KEY env var before any non-local use."
)
scheduler: BackgroundScheduler | None = None scheduler: BackgroundScheduler | None = None
is_testing = bool(os.environ.get("PYTEST_CURRENT_TEST") or "pytest" in sys.modules) is_testing = bool(os.environ.get("PYTEST_CURRENT_TEST") or "pytest" in sys.modules)
if not is_testing: if not is_testing:
_scheduled_alert_job() _scheduled_alert_job()
scheduler = BackgroundScheduler(timezone="Asia/Kolkata") scheduler = BackgroundScheduler(timezone=app_settings.TIMEZONE)
scheduler.add_job( scheduler.add_job(
_scheduled_alert_job, _scheduled_alert_job,
trigger=CronTrigger(hour=6, minute=0, timezone="Asia/Kolkata"), trigger=CronTrigger(hour=6, minute=0, timezone=app_settings.TIMEZONE),
id="daily_alert_check", id="daily_alert_check",
replace_existing=True, replace_existing=True,
) )
scheduler.start() scheduler.start()
logger.info("APScheduler daily alert check started (06:00 Asia/Kolkata).") logger.info("APScheduler daily alert check started (06:00 %s).", app_settings.TIMEZONE)
logger.info("Poona Hospital AMS started.") logger.info("Poona Hospital AMS started.")
try: try:
+7 -1
View File
@@ -61,7 +61,13 @@ 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_lead_days", 15)), "calibration": int(
get_setting_value(
db,
"calibration_due_window_days",
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")),
"pm_in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)), "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)), "pm_outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
+7 -1
View File
@@ -36,7 +36,13 @@ APPROVER_ROLES = {Role.management.value, Role.system_admin.value, Role.coordinat
def _cal_lead_settings(db: Session) -> dict[str, int]: def _cal_lead_settings(db: Session) -> dict[str, int]:
return { return {
"lead": int(get_setting_value(db, "calibration_lead_days", 15)), "lead": int(
get_setting_value(
db,
"calibration_due_window_days",
get_setting_value(db, "calibration_lead_days", 15),
)
),
"red": int(get_setting_value(db, "red_threshold_days", 7)), "red": int(get_setting_value(db, "red_threshold_days", 7)),
} }
+54 -6
View File
@@ -28,6 +28,7 @@ from ..services.calculations import (
compute_ce_response_time_minutes, compute_ce_response_time_minutes,
compute_downtime_minutes, compute_downtime_minutes,
compute_response_time_minutes, compute_response_time_minutes,
compute_sla_status,
) )
from ..services.numbering import generate_complaint_no from ..services.numbering import generate_complaint_no
from ..services.permissions import RESTRICTED_COMPLAINT_FIELDS, Role from ..services.permissions import RESTRICTED_COMPLAINT_FIELDS, Role
@@ -59,10 +60,12 @@ def _effective_now_utc(db: Session) -> datetime:
return utc_now() return utc_now()
def _complaint_settings(db: Session) -> tuple[str, str]: def _complaint_settings(db: Session) -> tuple[str, str, int, int]:
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at")) milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
response_start = str(get_setting_value(db, "response_start", "registered_at")) response_start = str(get_setting_value(db, "response_start", "registered_at"))
return milestone, response_start critical_sla = int(get_setting_value(db, "critical_complaint_sla_hours", 4))
non_critical_sla = int(get_setting_value(db, "non_critical_complaint_sla_hours", 24))
return milestone, response_start, critical_sla, non_critical_sla
def _load_user_names(db: Session, complaints: list[Complaint]) -> dict[int, str]: def _load_user_names(db: Session, complaints: list[Complaint]) -> dict[int, str]:
@@ -91,6 +94,8 @@ def _to_complaint_out(
milestone: str, milestone: str,
response_start: str, response_start: str,
now_utc: datetime, now_utc: datetime,
critical_sla_hours: int = 4,
non_critical_sla_hours: int = 24,
) -> ComplaintOut: ) -> ComplaintOut:
reg_at = _norm_utc(c.registered_at) reg_at = _norm_utc(c.registered_at)
recv_at = _norm_utc(c.received_at) recv_at = _norm_utc(c.received_at)
@@ -106,6 +111,15 @@ def _to_complaint_out(
reg_at, att_at, rst_at, cls_at, milestone=milestone, now_utc=now_utc reg_at, att_at, rst_at, cls_at, milestone=milestone, now_utc=now_utc
) )
ce_min = compute_ce_response_time_minutes(reg_at, ce_at) ce_min = compute_ce_response_time_minutes(reg_at, ce_at)
sla_breached, sla_target_hours = compute_sla_status(
c.priority,
reg_at,
att_at,
rst_at,
critical_sla_hours=critical_sla_hours,
non_critical_sla_hours=non_critical_sla_hours,
now_utc=now_utc,
)
asset = c.asset asset = c.asset
return ComplaintOut( return ComplaintOut(
@@ -156,6 +170,8 @@ def _to_complaint_out(
downtime_end_milestone=milestone, downtime_end_milestone=milestone,
response_start_setting=response_start, response_start_setting=response_start,
ce_response_time_minutes=ce_min, ce_response_time_minutes=ce_min,
sla_target_hours=sla_target_hours,
sla_breached=sla_breached,
updated_at=upd_at, updated_at=upd_at,
) )
@@ -185,9 +201,17 @@ def _check_complaint_visibility(comp: Complaint, user: User) -> None:
def _serialize_one(db: Session, comp: Complaint) -> ComplaintOut: def _serialize_one(db: Session, comp: Complaint) -> ComplaintOut:
user_names = _load_user_names(db, [comp]) user_names = _load_user_names(db, [comp])
milestone, response_start = _complaint_settings(db) milestone, response_start, critical_sla, non_critical_sla = _complaint_settings(db)
now_utc = _effective_now_utc(db) now_utc = _effective_now_utc(db)
return _to_complaint_out(comp, user_names, milestone, response_start, now_utc) return _to_complaint_out(
comp,
user_names,
milestone,
response_start,
now_utc,
critical_sla_hours=critical_sla,
non_critical_sla_hours=non_critical_sla,
)
def _sync_asset_status(db: Session, asset: Asset, exclude_complaint_id: int, require_unrestored: bool) -> None: def _sync_asset_status(db: Session, asset: Asset, exclude_complaint_id: int, require_unrestored: bool) -> None:
@@ -297,9 +321,20 @@ def list_complaints(
rows = query.all() rows = query.all()
user_names = _load_user_names(db, rows) user_names = _load_user_names(db, rows)
milestone, response_start = _complaint_settings(db) milestone, response_start, critical_sla, non_critical_sla = _complaint_settings(db)
now_utc = _effective_now_utc(db) now_utc = _effective_now_utc(db)
items = [_to_complaint_out(c, user_names, milestone, response_start, now_utc) for c in rows] items = [
_to_complaint_out(
c,
user_names,
milestone,
response_start,
now_utc,
critical_sla_hours=critical_sla,
non_critical_sla_hours=non_critical_sla,
)
for c in rows
]
return {"items": items, "total": total} return {"items": items, "total": total}
@@ -650,6 +685,18 @@ def close_complaint(
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)), current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
): ):
comp = _load_complaint_or_404(db, complaint_id) comp = _load_complaint_or_404(db, complaint_id)
require_remarks = bool(get_setting_value(db, "require_closure_remarks", True))
effective_remarks = (
payload.closure_remarks if payload.closure_remarks is not None else comp.closure_remarks
)
if require_remarks and (effective_remarks is None or not str(effective_remarks).strip()):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail={
"code": "CLOSURE_REMARKS_REQUIRED",
"message": "Closure remarks are required.",
},
)
now = utc_now() now = utc_now()
prev_status = comp.call_status prev_status = comp.call_status
comp.closed_by_id = current_user.id comp.closed_by_id = current_user.id
@@ -696,6 +743,7 @@ def reopen_complaint(
prev_status = comp.call_status prev_status = comp.call_status
comp.closed_at = None comp.closed_at = None
comp.closed_by_id = None comp.closed_by_id = None
comp.restored_at = None
comp.call_status = "in_progress" comp.call_status = "in_progress"
comp.updated_by_id = current_user.id comp.updated_by_id = current_user.id
+7 -1
View File
@@ -36,7 +36,13 @@ def _contract_lead_settings(db: Session) -> tuple[int, int]:
get_setting_value(db, "contract_expiry_alert_days", 30), get_setting_value(db, "contract_expiry_alert_days", 30),
) )
) )
red = int(get_setting_value(db, "red_threshold_days", 7)) red = int(
get_setting_value(
db,
"contract_critical_alert_days",
get_setting_value(db, "red_threshold_days", 7),
)
)
return lead, red return lead, red
+7 -1
View File
@@ -54,7 +54,13 @@ def get_dashboard_summary(
dept_scope_name = dept_obj.name if dept_obj else None dept_scope_name = dept_obj.name if dept_obj else None
# Settings for dynamic calculations # Settings for dynamic calculations
cal_lead = int(get_setting_value(db, "calibration_lead_days", 15)) cal_lead = int(
get_setting_value(
db,
"calibration_due_window_days",
get_setting_value(db, "calibration_lead_days", 15),
)
)
amc_lead = int( amc_lead = int(
get_setting_value( get_setting_value(
db, db,
+5 -3
View File
@@ -240,10 +240,12 @@ def create_pm_schedule(
if asset is None: if asset is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.") raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
mode = payload.service_mode or str(get_setting_value(db, "default_pm_mode", "in_house"))
clean_team, provider_id, contract_id = _validate_schedule_fields( clean_team, provider_id, contract_id = _validate_schedule_fields(
db, db,
asset_id=asset.id, asset_id=asset.id,
service_mode=payload.service_mode, service_mode=mode,
responsible_team=payload.responsible_team, responsible_team=payload.responsible_team,
provider_id=payload.provider_id, provider_id=payload.provider_id,
contract_id=payload.contract_id, contract_id=payload.contract_id,
@@ -251,7 +253,7 @@ def create_pm_schedule(
schedule = PMSchedule( schedule = PMSchedule(
asset_id=asset.id, asset_id=asset.id,
service_mode=payload.service_mode, service_mode=mode,
frequency_months=payload.frequency_months, frequency_months=payload.frequency_months,
responsible_team=clean_team, responsible_team=clean_team,
provider_id=provider_id, provider_id=provider_id,
@@ -282,7 +284,7 @@ def create_pm_schedule(
action="create", action="create",
changes={ changes={
"asset_id": asset.id, "asset_id": asset.id,
"service_mode": payload.service_mode, "service_mode": mode,
"frequency_months": payload.frequency_months, "frequency_months": payload.frequency_months,
"next_planned_date": str(payload.next_planned_date), "next_planned_date": str(payload.next_planned_date),
"initial_record_id": initial_record.id, "initial_record_id": initial_record.id,
+2
View File
@@ -120,6 +120,8 @@ class ComplaintOut(BaseModel):
downtime_end_milestone: str downtime_end_milestone: str
response_start_setting: str response_start_setting: str
ce_response_time_minutes: Optional[int] = None ce_response_time_minutes: Optional[int] = None
sla_target_hours: Optional[int] = None
sla_breached: bool = False
updated_at: datetime updated_at: datetime
+1 -1
View File
@@ -8,7 +8,7 @@ PMRecordStatusFilter = Literal["upcoming", "due", "overdue", "completed", "resch
class PMScheduleCreate(BaseModel): class PMScheduleCreate(BaseModel):
asset_id: int asset_id: int
service_mode: PMServiceMode service_mode: Optional[PMServiceMode] = None
frequency_months: int = Field(..., ge=1, le=120) frequency_months: int = Field(..., ge=1, le=120)
responsible_team: Optional[str] = None responsible_team: Optional[str] = None
provider_id: Optional[int] = None provider_id: Optional[int] = None
+28 -4
View File
@@ -17,7 +17,7 @@ from ..models import (
User, User,
Warranty, Warranty,
) )
from .calculations import alert_state from .calculations import alert_state, compute_sla_status
from .permissions import Role from .permissions import Role
from .settings_service import get_setting_value from .settings_service import get_setting_value
@@ -50,7 +50,13 @@ def _alert_settings(db: Session) -> dict[str, int]:
get_setting_value(db, "contract_expiry_alert_days", 30), get_setting_value(db, "contract_expiry_alert_days", 30),
) )
), ),
"calibration": int(get_setting_value(db, "calibration_lead_days", 15)), "calibration": int(
get_setting_value(
db,
"calibration_due_window_days",
get_setting_value(db, "calibration_lead_days", 15),
)
),
"pm_in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)), "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)), "pm_outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
"insurance": int( "insurance": int(
@@ -67,6 +73,13 @@ def _alert_settings(db: Session) -> dict[str, int]:
get_setting_value(db, "warranty_expiry_alert_days", 30), get_setting_value(db, "warranty_expiry_alert_days", 30),
) )
), ),
"contract_red": int(
get_setting_value(
db,
"contract_critical_alert_days",
get_setting_value(db, "red_threshold_days", 7),
)
),
"red": int(get_setting_value(db, "red_threshold_days", 7)), "red": int(get_setting_value(db, "red_threshold_days", 7)),
"critical_hours": int( "critical_hours": int(
get_setting_value( get_setting_value(
@@ -75,6 +88,8 @@ def _alert_settings(db: Session) -> dict[str, int]:
get_setting_value(db, "escalation_open_complaint_hours", 24), get_setting_value(db, "escalation_open_complaint_hours", 24),
) )
), ),
"critical_sla_hours": int(get_setting_value(db, "critical_complaint_sla_hours", 4)),
"non_critical_sla_hours": int(get_setting_value(db, "non_critical_complaint_sla_hours", 24)),
} }
@@ -130,7 +145,7 @@ def run_alert_check(db: Session) -> dict[str, object]:
.all() .all()
) )
for c in contracts: for c in contracts:
state = alert_state(c.end_date, today, cfg["amc"], cfg["red"]) state = alert_state(c.end_date, today, cfg["amc"], cfg["contract_red"])
if state in ("yellow", "red"): if state in ("yellow", "red"):
created += _add_if_new( created += _add_if_new(
db, db,
@@ -273,7 +288,16 @@ def run_alert_check(db: Session) -> dict[str, object]:
threshold_secs = cfg["critical_hours"] * 3600 threshold_secs = cfg["critical_hours"] * 3600
for c in crit_complaints: for c in crit_complaints:
elapsed = (_ensure_utc(eff_now) - _ensure_utc(c.registered_at)).total_seconds() elapsed = (_ensure_utc(eff_now) - _ensure_utc(c.registered_at)).total_seconds()
if elapsed >= threshold_secs: sla_breached, _target_h = compute_sla_status(
c.priority,
c.registered_at,
c.attended_at,
c.restored_at,
critical_sla_hours=cfg["critical_sla_hours"],
non_critical_sla_hours=cfg["non_critical_sla_hours"],
now_utc=eff_now,
)
if elapsed >= threshold_secs or sla_breached:
created += _add_if_new( created += _add_if_new(
db, db,
existing_keys, existing_keys,
+4 -1
View File
@@ -12,6 +12,7 @@ from sqlalchemy.orm import Session
from ..core.exceptions import CodedHTTPException from ..core.exceptions import CodedHTTPException
from ..models import Asset, Category, Department, Location, Vendor from ..models import Asset, Category, Department, Location, Vendor
from .audit import log_audit from .audit import log_audit
from .settings_service import get_setting_value
IMPORT_COLUMNS = [ IMPORT_COLUMNS = [
"asset_code", "asset_code",
@@ -93,8 +94,10 @@ def build_import_template_xlsx(db: Session) -> BytesIO:
sample_cat = categories[0] if categories else None sample_cat = categories[0] if categories else None
sample_sup = vendors[0] if vendors else None sample_sup = vendors[0] if vendors else None
sample_prefix = str(get_setting_value(db, "asset_code_prefix", "PHRC")).strip() or "PHRC"
sample_dept_code = sample_dept.code if sample_dept else "ICU"
sample_row = [ sample_row = [
"PHRC-ICU-0901", f"{sample_prefix}-{sample_dept_code}-0901",
"SN-DEMO-901", "SN-DEMO-901",
"Infusion Pump", "Infusion Pump",
sample_cat.name if sample_cat else "Infusion Pump", sample_cat.name if sample_cat else "Infusion Pump",
+20
View File
@@ -124,6 +124,26 @@ def compute_ce_response_time_minutes(
return max(0, int((ce_utc - reg_utc).total_seconds() // 60)) return max(0, int((ce_utc - reg_utc).total_seconds() // 60))
def compute_sla_status(
priority: str,
registered_at: datetime,
attended_at: datetime | None,
restored_at: datetime | None,
critical_sla_hours: int = 4,
non_critical_sla_hours: int = 24,
now_utc: datetime | None = None,
) -> tuple[bool, int]:
"""Return (is_sla_breached, target_sla_hours) using configured SLA thresholds."""
target_hours = critical_sla_hours if priority == "critical" else non_critical_sla_hours
reg_utc = _ensure_utc(registered_at)
end_ref = restored_at or attended_at
end_utc = _ensure_utc(end_ref) if end_ref is not None else (
_ensure_utc(now_utc) if now_utc is not None else utc_now()
)
elapsed_seconds = max(0.0, (end_utc - reg_utc).total_seconds())
return elapsed_seconds > (target_hours * 3600), target_hours
def clip_downtime_to_month( def clip_downtime_to_month(
start_utc: datetime, start_utc: datetime,
end_utc: datetime, end_utc: datetime,
+7 -1
View File
@@ -643,7 +643,13 @@ def _build_calibration_due(
agency_id = params.get("agency_id") agency_id = params.get("agency_id")
status_filter = params.get("status") status_filter = params.get("status")
cal_lead = int(get_setting_value(db, "calibration_lead_days", 15)) cal_lead = int(
get_setting_value(
db,
"calibration_due_window_days",
get_setting_value(db, "calibration_lead_days", 15),
)
)
red_days = int(get_setting_value(db, "red_threshold_days", 7)) red_days = int(get_setting_value(db, "red_threshold_days", 7))
query = ( query = (
+86 -1
View File
@@ -283,7 +283,7 @@ def test_full_complaint_workflow_and_asset_status_sync(client, db):
assert cls_res.json()["closed_at"] is not None assert cls_res.json()["closed_at"] is not None
assert cls_res.json()["asset_status"] == "in_service" assert cls_res.json()["asset_status"] == "in_service"
# 7. Reopen -> critical asset back to under_repair # 7. Reopen -> critical asset back to under_repair and restored_at cleared
reopen_res = client.post( reopen_res = client.post(
f"/api/complaints/{cid}/reopen", f"/api/complaints/{cid}/reopen",
headers=bio_headers, headers=bio_headers,
@@ -292,6 +292,8 @@ def test_full_complaint_workflow_and_asset_status_sync(client, db):
assert reopen_res.status_code == 200 assert reopen_res.status_code == 200
assert reopen_res.json()["call_status"] == "in_progress" assert reopen_res.json()["call_status"] == "in_progress"
assert reopen_res.json()["closed_at"] is None assert reopen_res.json()["closed_at"] is None
assert reopen_res.json()["restored_at"] is None
assert reopen_res.json()["downtime_is_ongoing"] is True
assert reopen_res.json()["asset_status"] == "under_repair" assert reopen_res.json()["asset_status"] == "under_repair"
# 8. Correct timestamp: biomedical -> 403, system_admin -> 200 # 8. Correct timestamp: biomedical -> 403, system_admin -> 200
@@ -330,3 +332,86 @@ def test_full_complaint_workflow_and_asset_status_sync(client, db):
assert events[2]["from_value"] == bio1.name assert events[2]["from_value"] == bio1.name
assert events[2]["to_value"] == bio2.name assert events[2]["to_value"] == bio2.name
assert events[8]["note"] == "registered_at: Logged after phone call" assert events[8]["note"] == "registered_at: Logged after phone call"
def test_require_closure_remarks_and_wired_settings(client, db):
from datetime import date
from app.services.calculations import compute_sla_status
admin_headers = _auth_headers(client, "admin@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
asset = db.query(Asset).first()
assert asset is not None
# Create a complaint to test close with require_closure_remarks True vs False
c_res = client.post(
"/api/complaints",
headers=bio_headers,
json={
"asset_id": asset.id,
"description": "Display backlight flicker",
"priority": "non_critical",
},
)
assert c_res.status_code == 201
cid = c_res.json()["id"]
assert c_res.json()["sla_target_hours"] == 24
assert c_res.json()["sla_breached"] is False
# Default require_closure_remarks=True -> blank remarks returns 422 CLOSURE_REMARKS_REQUIRED
fail_close = client.post(
f"/api/complaints/{cid}/close",
headers=bio_headers,
json={"closure_remarks": " "},
)
assert fail_close.status_code == 422
assert fail_close.json()["detail"]["code"] == "CLOSURE_REMARKS_REQUIRED"
try:
# Disable require_closure_remarks -> blank remarks closes cleanly (200)
upd = client.put(
"/api/settings",
headers=admin_headers,
json={"values": {"require_closure_remarks": False}},
)
assert upd.status_code == 200
ok_close = client.post(
f"/api/complaints/{cid}/close",
headers=bio_headers,
json={"closure_remarks": ""},
)
assert ok_close.status_code == 200
assert ok_close.json()["call_status"] == "closed"
# Verify default_pm_mode setting when service_mode is omitted on POST /api/pm/schedules
pm_res = client.post(
"/api/pm/schedules",
headers=bio_headers,
json={
"asset_id": asset.id,
"frequency_months": 6,
"responsible_team": "Biomedical Team",
"next_planned_date": str(date.today()),
},
)
assert pm_res.status_code == 201, pm_res.text
assert pm_res.json()["service_mode"] == "in_house"
finally:
client.put(
"/api/settings",
headers=admin_headers,
json={"values": {"require_closure_remarks": True}},
)
# Pure unit test for compute_sla_status using injected SLA settings
t0 = datetime(2026, 6, 1, 8, 0, tzinfo=timezone.utc)
breached, target = compute_sla_status(
"critical", t0, None, None, critical_sla_hours=4, non_critical_sla_hours=24, now_utc=t0 + timedelta(hours=5)
)
assert target == 4 and breached is True
not_breached, target2 = compute_sla_status(
"non_critical", t0, None, None, critical_sla_hours=4, non_critical_sla_hours=24, now_utc=t0 + timedelta(hours=5)
)
assert target2 == 24 and not_breached is False
+28 -4
View File
@@ -1,6 +1,30 @@
# Implementation Plan # Poona Hospital AMS — Implementation Plan Summary
Full plan is in docs/. See the user's implementation plan document for the complete specification. **Status:** Phases 0–8 complete, plus Excel exports / bulk import / responsive layout as of commit `22fad38`.
This file will be updated progressively as phases are completed.
**Current phase:** 0 — Scaffold For local development, Docker Compose, seeding, and test commands, see [README.md](../README.md).
## Tech Stack
| Layer | Technology |
|---|---|
| Backend API | FastAPI + Pydantic v2 (`Python 3.13`, `uvicorn`) |
| Database & ORM | SQLAlchemy 2.0 (`SQLite` with indexed 19-table schema) |
| Authentication & Security | JWT (`python-jose`), `bcrypt`, 5-role RBAC, sliding-window login rate limiter |
| Background Scheduler | `APScheduler` (`06:00` daily alert evaluation job) |
| Exports & Bulk Import | `openpyxl` (styled `.xlsx` reports & 2-sheet import template), `csv`, SheetJS (`xlsx`) |
| Frontend UI | React 18, TypeScript, Vite, Tailwind CSS, shadcn/ui, TanStack Query & Table, Recharts |
| Packaging & Docs | Docker, Nginx reverse proxy, `docker-compose.yml`, Demo Script & Acceptance Checklist |
| Testing | `pytest` + `httpx` (`ASGITransport`), `Vitest` + React Testing Library |
## Phases Overview (0–8)
- **Phase 0 — Scaffold:** Project layout, FastAPI health endpoint, React + Vite + Tailwind + shadcn/ui shell, Makefile.
- **Phase 1 — Auth, Masters & Settings:** JWT login/me, 5-role RBAC matrix, Admin Master Lists CRUD, typed System Settings, and `seed.py`.
- **Phase 2 — Asset Register & Attachments:** Full Asset CRUD (`409` duplicate check), `AssetPicker`, department scoping, magic-byte validated attachments.
- **Phase 3 — Breakdown & Complaint Lifecycle:** Sequential `complaint_no`, IST response/downtime calculations (`clip_downtime_to_month`), workflow transitions & technical-field locks.
- **Phase 4 — Preventive Maintenance & Calibration:** In-house/outsourced PM table & 7-column calendar views, clamped `add_months`, gated calibration approval & certificates.
- **Phase 5 — Contracts, Warranties, Insurance, Demo & Visits:** Contract renewal chain (`is_superseded`), warranties, insurance drawer, overdue demo equipment, department visit rounds.
- **Phase 6 — Notifications, Alerts & Dashboard:** Daily `APScheduler` 7-type deduplicated alerts, TopBar Demo Clock, calibration login modal, and role-scoped Recharts dashboard.
- **Phase 7 — Operational Reports & Exports:** 8 operational reports with formula transparency, `daily-visit` RBAC, server-side `.xlsx`/`.csv` exports, and A4 `@media print`.
- **Phase 8 — Polish & Packaging:** Global quick search (`/api/search`), Admin audit log viewer (`/api/audit-logs`), DB indexes, login rate limiting, Docker Compose, and demo/acceptance docs.