From e2a6fa601e26e8528bbb74aa2146bf9c95b9a448 Mon Sep 17 00:00:00 2001 From: Atharv1705 Date: Thu, 12 Nov 2026 17:34:04 +0530 Subject: [PATCH] fix: reopen clears restored_at, wire settings, docs, startup warning --- README.md | 19 ++++-- backend/app/core/time_utils.py | 6 +- backend/app/main.py | 15 ++++- backend/app/routers/assets.py | 8 ++- backend/app/routers/calibration.py | 8 ++- backend/app/routers/complaints.py | 60 +++++++++++++++-- backend/app/routers/contracts.py | 8 ++- backend/app/routers/dashboard.py | 8 ++- backend/app/routers/pm.py | 8 ++- backend/app/schemas/complaints.py | 2 + backend/app/schemas/pm.py | 2 +- backend/app/services/alerts.py | 32 +++++++-- backend/app/services/asset_import.py | 5 +- backend/app/services/calculations.py | 20 ++++++ backend/app/services/reports_service.py | 8 ++- backend/tests/test_complaints.py | 87 ++++++++++++++++++++++++- docs/IMPLEMENTATION_PLAN.md | 32 +++++++-- 17 files changed, 292 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 3014dd9..d83df17 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,14 @@ A centralized Hospital Asset Management and Maintenance System for Poona Hospita ```bash cd backend python -m venv .venv -# Windows PowerShell: .venv\Scripts\Activate.ps1 -# macOS/Linux: source .venv/bin/activate -.venv/Scripts/pip install -r requirements.txt # or pip install -r requirements.txt once activated -.venv/Scripts/uvicorn app.main:app --reload --port 8000 + +# Windows PowerShell: +.venv\Scripts\activate +# 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 - API docs: http://localhost:8000/docs @@ -37,9 +41,9 @@ make dev ### Run tests ```bash -# Backend +# Backend (activate .venv first: Windows .venv\Scripts\activate | macOS/Linux source .venv/bin/activate) cd backend -.venv/Scripts/python -m pytest tests/ -v +python -m pytest tests/ -v # Or via Make: make test # Frontend (build + Vitest) @@ -50,8 +54,9 @@ npm test ### Seed demo data ```bash +# Activate .venv first: Windows .venv\Scripts\activate | macOS/Linux source .venv/bin/activate cd backend -.venv/Scripts/python -m app.seed.seed +python -m app.seed.seed # Or via Make: make seed ``` diff --git a/backend/app/core/time_utils.py b/backend/app/core/time_utils.py index e739442..b19e1c8 100644 --- a/backend/app/core/time_utils.py +++ b/backend/app/core/time_utils.py @@ -2,8 +2,12 @@ import calendar from datetime import date, datetime, timezone import json 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: diff --git a/backend/app/main.py b/backend/app/main.py index 6835042..e2f99df 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -8,6 +8,7 @@ from apscheduler.triggers.cron import CronTrigger from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse +from .core.config import settings as app_settings from .core.db import SessionLocal, engine, get_scheduler_db from .core.exceptions import CodedHTTPException, coded_http_exception_handler from .models import Base @@ -60,19 +61,27 @@ async def lifespan(app: FastAPI): db.commit() 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 is_testing = bool(os.environ.get("PYTEST_CURRENT_TEST") or "pytest" in sys.modules) if not is_testing: _scheduled_alert_job() - scheduler = BackgroundScheduler(timezone="Asia/Kolkata") + scheduler = BackgroundScheduler(timezone=app_settings.TIMEZONE) scheduler.add_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", replace_existing=True, ) 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.") try: diff --git a/backend/app/routers/assets.py b/backend/app/routers/assets.py index 65b078e..a67d453 100644 --- a/backend/app/routers/assets.py +++ b/backend/app/routers/assets.py @@ -61,7 +61,13 @@ def _lead_settings(db: Session) -> dict[str, int]: "warranty": int(get_setting_value(db, "warranty_expiry_alert_days")), "contract": int(get_setting_value(db, "contract_expiry_alert_days")), "insurance": int(get_setting_value(db, "insurance_expiry_alert_days")), - "calibration": int(get_setting_value(db, "calibration_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_in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)), "pm_outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)), diff --git a/backend/app/routers/calibration.py b/backend/app/routers/calibration.py index cbf77f4..a4645aa 100644 --- a/backend/app/routers/calibration.py +++ b/backend/app/routers/calibration.py @@ -36,7 +36,13 @@ APPROVER_ROLES = {Role.management.value, Role.system_admin.value, Role.coordinat def _cal_lead_settings(db: Session) -> dict[str, int]: 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)), } diff --git a/backend/app/routers/complaints.py b/backend/app/routers/complaints.py index 7b13e6c..54727bc 100644 --- a/backend/app/routers/complaints.py +++ b/backend/app/routers/complaints.py @@ -28,6 +28,7 @@ from ..services.calculations import ( compute_ce_response_time_minutes, compute_downtime_minutes, compute_response_time_minutes, + compute_sla_status, ) from ..services.numbering import generate_complaint_no from ..services.permissions import RESTRICTED_COMPLAINT_FIELDS, Role @@ -59,10 +60,12 @@ def _effective_now_utc(db: Session) -> datetime: 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")) 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]: @@ -91,6 +94,8 @@ def _to_complaint_out( milestone: str, response_start: str, now_utc: datetime, + critical_sla_hours: int = 4, + non_critical_sla_hours: int = 24, ) -> ComplaintOut: reg_at = _norm_utc(c.registered_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 ) 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 return ComplaintOut( @@ -156,6 +170,8 @@ def _to_complaint_out( downtime_end_milestone=milestone, response_start_setting=response_start, ce_response_time_minutes=ce_min, + sla_target_hours=sla_target_hours, + sla_breached=sla_breached, 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: 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) - 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: @@ -297,9 +321,20 @@ def list_complaints( rows = query.all() 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) - 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} @@ -650,6 +685,18 @@ def close_complaint( current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)), ): 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() prev_status = comp.call_status comp.closed_by_id = current_user.id @@ -696,6 +743,7 @@ def reopen_complaint( prev_status = comp.call_status comp.closed_at = None comp.closed_by_id = None + comp.restored_at = None comp.call_status = "in_progress" comp.updated_by_id = current_user.id diff --git a/backend/app/routers/contracts.py b/backend/app/routers/contracts.py index 601a7cf..4674321 100644 --- a/backend/app/routers/contracts.py +++ b/backend/app/routers/contracts.py @@ -36,7 +36,13 @@ def _contract_lead_settings(db: Session) -> tuple[int, int]: 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 diff --git a/backend/app/routers/dashboard.py b/backend/app/routers/dashboard.py index acf0339..e2c258d 100644 --- a/backend/app/routers/dashboard.py +++ b/backend/app/routers/dashboard.py @@ -54,7 +54,13 @@ def get_dashboard_summary( dept_scope_name = dept_obj.name if dept_obj else None # 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( get_setting_value( db, diff --git a/backend/app/routers/pm.py b/backend/app/routers/pm.py index 053ab5c..4dcbf7e 100644 --- a/backend/app/routers/pm.py +++ b/backend/app/routers/pm.py @@ -240,10 +240,12 @@ def create_pm_schedule( if asset is None: 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( db, asset_id=asset.id, - service_mode=payload.service_mode, + service_mode=mode, responsible_team=payload.responsible_team, provider_id=payload.provider_id, contract_id=payload.contract_id, @@ -251,7 +253,7 @@ def create_pm_schedule( schedule = PMSchedule( asset_id=asset.id, - service_mode=payload.service_mode, + service_mode=mode, frequency_months=payload.frequency_months, responsible_team=clean_team, provider_id=provider_id, @@ -282,7 +284,7 @@ def create_pm_schedule( action="create", changes={ "asset_id": asset.id, - "service_mode": payload.service_mode, + "service_mode": mode, "frequency_months": payload.frequency_months, "next_planned_date": str(payload.next_planned_date), "initial_record_id": initial_record.id, diff --git a/backend/app/schemas/complaints.py b/backend/app/schemas/complaints.py index 0addc1f..ae4b372 100644 --- a/backend/app/schemas/complaints.py +++ b/backend/app/schemas/complaints.py @@ -120,6 +120,8 @@ class ComplaintOut(BaseModel): downtime_end_milestone: str response_start_setting: str ce_response_time_minutes: Optional[int] = None + sla_target_hours: Optional[int] = None + sla_breached: bool = False updated_at: datetime diff --git a/backend/app/schemas/pm.py b/backend/app/schemas/pm.py index 8c59da8..cb88e69 100644 --- a/backend/app/schemas/pm.py +++ b/backend/app/schemas/pm.py @@ -8,7 +8,7 @@ PMRecordStatusFilter = Literal["upcoming", "due", "overdue", "completed", "resch class PMScheduleCreate(BaseModel): asset_id: int - service_mode: PMServiceMode + service_mode: Optional[PMServiceMode] = None frequency_months: int = Field(..., ge=1, le=120) responsible_team: Optional[str] = None provider_id: Optional[int] = None diff --git a/backend/app/services/alerts.py b/backend/app/services/alerts.py index b775e7e..4e39cbc 100644 --- a/backend/app/services/alerts.py +++ b/backend/app/services/alerts.py @@ -17,7 +17,7 @@ from ..models import ( User, Warranty, ) -from .calculations import alert_state +from .calculations import alert_state, compute_sla_status from .permissions import Role 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), ) ), - "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_outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)), "insurance": int( @@ -67,6 +73,13 @@ def _alert_settings(db: Session) -> dict[str, int]: 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)), "critical_hours": int( get_setting_value( @@ -75,6 +88,8 @@ def _alert_settings(db: Session) -> dict[str, int]: 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() ) 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"): created += _add_if_new( db, @@ -273,7 +288,16 @@ def run_alert_check(db: Session) -> dict[str, object]: threshold_secs = cfg["critical_hours"] * 3600 for c in crit_complaints: 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( db, existing_keys, diff --git a/backend/app/services/asset_import.py b/backend/app/services/asset_import.py index 63b1fbb..e88bd12 100644 --- a/backend/app/services/asset_import.py +++ b/backend/app/services/asset_import.py @@ -12,6 +12,7 @@ from sqlalchemy.orm import Session from ..core.exceptions import CodedHTTPException from ..models import Asset, Category, Department, Location, Vendor from .audit import log_audit +from .settings_service import get_setting_value IMPORT_COLUMNS = [ "asset_code", @@ -93,8 +94,10 @@ def build_import_template_xlsx(db: Session) -> BytesIO: sample_cat = categories[0] if categories 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 = [ - "PHRC-ICU-0901", + f"{sample_prefix}-{sample_dept_code}-0901", "SN-DEMO-901", "Infusion Pump", sample_cat.name if sample_cat else "Infusion Pump", diff --git a/backend/app/services/calculations.py b/backend/app/services/calculations.py index fd3a94d..bb8dbbf 100644 --- a/backend/app/services/calculations.py +++ b/backend/app/services/calculations.py @@ -124,6 +124,26 @@ def compute_ce_response_time_minutes( 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( start_utc: datetime, end_utc: datetime, diff --git a/backend/app/services/reports_service.py b/backend/app/services/reports_service.py index 2a53d38..f12a7a7 100644 --- a/backend/app/services/reports_service.py +++ b/backend/app/services/reports_service.py @@ -643,7 +643,13 @@ def _build_calibration_due( agency_id = params.get("agency_id") 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)) query = ( diff --git a/backend/tests/test_complaints.py b/backend/tests/test_complaints.py index cef2578..58a2556 100644 --- a/backend/tests/test_complaints.py +++ b/backend/tests/test_complaints.py @@ -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()["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( f"/api/complaints/{cid}/reopen", 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.json()["call_status"] == "in_progress" 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" # 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]["to_value"] == bio2.name 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 + diff --git a/docs/IMPLEMENTATION_PLAN.md b/docs/IMPLEMENTATION_PLAN.md index 424a643..4eeb4d7 100644 --- a/docs/IMPLEMENTATION_PLAN.md +++ b/docs/IMPLEMENTATION_PLAN.md @@ -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. -This file will be updated progressively as phases are completed. +**Status:** Phases 0–8 complete, plus Excel exports / bulk import / responsive layout as of commit `22fad38`. -**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.