Compare commits

...
10 Commits
129 changed files with 24306 additions and 317 deletions
+16
View File
@@ -1,4 +1,20 @@
# Database connection URL (SQLite default persists under backend/data/)
DATABASE_URL=sqlite:///./data/ams.db
# JWT signing secret (replace with a 32+ character random string in production)
SECRET_KEY=change-me-in-production-use-a-32-char-random-string
# Directory for uploaded attachments (PDF, JPG, PNG)
UPLOAD_DIR=./data/uploads
# Application display & scheduler timezone
TIMEZONE=Asia/Kolkata
# JWT access token expiration duration in minutes (default: 480 = 8 hours)
ACCESS_TOKEN_EXPIRE_MINUTES=480
# JWT signing algorithm
ALGORITHM=HS256
# Maximum allowed attachment file size in megabytes
MAX_UPLOAD_SIZE_MB=10
+53 -18
View File
@@ -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,18 +41,38 @@ make dev
### Run tests
```bash
make test
# Or directly:
# 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)
cd frontend
npm run build
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
```
### Docker Compose (Production-style local container run)
```bash
cp .env.example .env
docker compose up --build
```
- Frontend (Nginx + `/api` reverse proxy): http://localhost:5173
- Backend API & Swagger docs: http://localhost:8000/docs
- SQLite DB and uploads persist under `./backend/data` (mounted to `/app/data`).
## Documentation & Walkthroughs
- [10-Minute Demo Script](docs/DEMO_SCRIPT.md)
- [Acceptance Checklist (Proposal §10)](docs/ACCEPTANCE_CHECKLIST.md)
## Demo Accounts
| Email | Password | Role |
|---|---|---|
@@ -58,19 +82,30 @@ cd backend
| mgmt@poona.demo | Demo@123 | Management |
| coord@poona.demo | Demo@123 | Coordinator |
## What exists now (Phase 2)
- 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
- 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`)
- 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
## Implemented Application (Phases 0–8 Complete)
- Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules with performance indexes on foreign keys, status, and date columns
- JWT authentication (`/api/auth/login`, `/api/auth/me`), sliding-window login rate limiter (`429 RATE_LIMITED`), RBAC permission matrix for 5 roles, and Quick Demo Login
- Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users) and Audit Log Viewer (`/audit-logs`, `system_admin` only with entity/user/action/date filters and JSON diff modal)
- Typed System Settings (`/settings`) and TopBar "As of Date" Demo Clock (`POST /api/settings/demo-date`) + Admin `"Run alert check now"` (`POST /api/alerts/run`)
- Live Global Quick Search in TopBar (`GET /api/search?q=`) returning grouped Assets & Complaints with `department_user` scoping
- 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, audit logging, and Bulk Asset Import (`GET /api/assets/import-template` Excel template with `Master Reference` sheet + `POST /api/assets/bulk-import` dry-run validation preview & skip-invalid option)
- 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
- Contracts & Warranties (`/contracts`): AMC/CMC/OTHER contract CRUD, expiry chips (`amc_cmc_lead_days`, `red_threshold_days`), renewal workflow (`POST /api/contracts/:id/renew` marking prior contract `is_superseded=True` and linking `renewed_from_id`), renewal history chain (`/api/contracts/history/:assetId`), warranty tracking with auto-computed editable end date, and inline document attachments (`contract`/`warranty`)
- Asset Insurance (`/insurance`) & Slide-Over `InsuranceDrawer`: insurance policy register with INR coverage display, expiry alerts, policy attachments (`insurance`), and `"View Insurance"` drawer accessible from `AssetDetailPage`, `AssetPicker`, and `ComplaintDetailPage`
- Demo Equipment (`/demo-equipment`): trial equipment register with dynamic `on_demo`/`overdue_return`/`returned` status relative to `effective_today()`, return logging (`POST /api/demo-equipment/:id/return`), and `demo_equipment` attachments
- Department Visits (`/visits`): biomedical/admin round logs with management read access (403 for `department_user` and `coordinator`), department-filtered multi-asset checklist, observations, and complaint creation/linking (`POST /api/visits/:id/link-complaint`)
- Alert Engine, Scheduler & Notifications (`/notifications` + TopBar Bell & Calibration Login Pop-up): APScheduler `06:00 Asia/Kolkata` daily job using short-lived `get_scheduler_db()`, deduplicated 7-type alerts (`amc_expiry`, `calibration_due`, `pm_due`, `insurance_expiry`, `warranty_expiry`, `demo_overdue`, `critical_complaint`) evaluated against `effective_today()`/`effective_now_utc()`, per-user `NotificationRead` state with `department_user` entity-department filtering, 60s bell polling with live toast alerts, and once-per-login `CalibrationReminderModal`
- Hospital Operations Dashboard (`/`): role-aware `department_scope` banner, 7 clickable KPI cards, 4 Recharts visualizations (Complaints by Status, Complaints by Department, 6-month `clip_downtime_to_month` Downtime Trend, PM Planned vs Completed), `"Needs Attention"` red alerts panel, and `"Recent Complaints"` table
- 8 Operational Reports & Excel Exports (`/reports` & `/reports/:reportKey`): Monthly Maintenance (with `clip_downtime_to_month` uptime/downtime hours, `"How this is calculated"` `formula_info` panel, and Recharts BarChart + PieChart), Monthly Department, Daily Department Visit (403 for `department_user` & `coordinator`), Breakdown & Complaints, PM Compliance, Calibration Due, AMC/CMC & Warranty, and Demo Equipment reports; tailored filters, styled openpyxl Excel (`.xlsx`) report exports (`/api/reports/{report_key}/export`), Excel (`.xlsx`) table exports across all `DataTable` views, and A4 `@media print` styles (`no-print` / `print-header`)
- 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)
- Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data
- React + TypeScript frontend app shell with role-filtered sidebar, route guards, DataTable, and Tailwind CSS + shadcn/ui
- Makefile for common tasks
- Responsive React + TypeScript frontend app shell across `360px+` mobile, `768px+` tablet, and `1280px+` desktop (wrapping TopBar, `lg:` drawer Sidebar, responsive modals & tabs, accessible `<ConfirmDialog />`, DataTable with Excel `.xlsx` export, Tailwind CSS + shadcn/ui)
- Docker packaging (`docker-compose.yml`, `backend/Dockerfile`, `frontend/Dockerfile`, `frontend/nginx.conf`, `.env.example`) & `Makefile`
## Modules (all phases)
## Modules (Phases 0–8 Complete)
Phase 0: Scaffold | Phase 1: Auth & Masters | Phase 2: Assets | Phase 3: Complaints
Phase 4: PM & Calibration | Phase 5: Contracts, Warranty, Insurance, Demo, Visits
Phase 6: Notifications & Dashboard | Phase 7: Reports | Phase 8: Polish
Phase 6: Notifications & Dashboard | Phase 7: Reports | Phase 8: Polish, Search, Audit Log, Packaging & Docs
+16
View File
@@ -0,0 +1,16 @@
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN mkdir -p /app/data/uploads
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+26 -1
View File
@@ -1,8 +1,13 @@
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:
@@ -39,6 +44,17 @@ def effective_today(db=None) -> date:
return datetime.now(KOLKATA).date()
def effective_now_utc(db=None) -> datetime:
"""Returns current UTC datetime anchored to effective_today(db) in Asia/Kolkata when demo date is set."""
now_kol = datetime.now(KOLKATA)
today = effective_today(db)
if today == now_kol.date():
return now_kol.astimezone(timezone.utc)
return KOLKATA.localize(datetime.combine(today, now_kol.timetz().replace(tzinfo=None))).astimezone(
timezone.utc
)
def to_kolkata(dt: datetime) -> datetime:
return dt.astimezone(KOLKATA)
@@ -56,6 +72,15 @@ def format_date(d: date | None) -> str | None:
return d.strftime("%d-%b-%Y")
def add_months(d: date, months: int) -> date:
"""Add calendar months to a date, clamping day-of-month to the target month's length."""
total_months = (d.year * 12 + (d.month - 1)) + months
year, zero_month = divmod(total_months, 12)
month = zero_month + 1
max_day = calendar.monthrange(year, month)[1]
return date(year, month, min(d.day, max_day))
def format_duration(minutes: int | None) -> str:
if minutes is None:
return "\u2014"
+80 -3
View File
@@ -1,13 +1,40 @@
import logging
import os
import sys
import traceback
from contextlib import asynccontextmanager
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from .core.db import SessionLocal, engine
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
from .routers import assets, attachments, auth, health, masters, settings, users
from .routers import (
assets,
attachments,
audit,
auth,
calibration,
complaints,
contracts,
dashboard,
demo_equipment,
health,
insurance,
masters,
notifications,
pm,
reports,
search,
settings,
users,
visits,
warranties,
)
from .services.alerts import run_alert_check
from .services.settings_service import ensure_default_settings
logging.basicConfig(
@@ -17,6 +44,15 @@ logging.basicConfig(
logger = logging.getLogger("poona_ams")
def _scheduled_alert_job() -> None:
try:
with get_scheduler_db() as db:
res = run_alert_check(db)
logger.info("Scheduled alert check finished: %s", res)
except Exception:
logger.exception("Scheduled alert check failed.")
@asynccontextmanager
async def lifespan(app: FastAPI):
Base.metadata.create_all(bind=engine)
@@ -24,8 +60,36 @@ async def lifespan(app: FastAPI):
ensure_default_settings(db)
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=app_settings.TIMEZONE)
scheduler.add_job(
_scheduled_alert_job,
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 %s).", app_settings.TIMEZONE)
logger.info("Poona Hospital AMS started.")
yield
try:
yield
finally:
if scheduler is not None:
scheduler.shutdown(wait=False)
logger.info("APScheduler stopped.")
app = FastAPI(
@@ -62,3 +126,16 @@ app.include_router(masters.router, prefix="/api")
app.include_router(users.router, prefix="/api")
app.include_router(assets.router, prefix="/api")
app.include_router(attachments.router, prefix="/api")
app.include_router(complaints.router, prefix="/api")
app.include_router(pm.router, prefix="/api")
app.include_router(calibration.router, prefix="/api")
app.include_router(contracts.router, prefix="/api")
app.include_router(warranties.router, prefix="/api")
app.include_router(insurance.router, prefix="/api")
app.include_router(demo_equipment.router, prefix="/api")
app.include_router(visits.router, prefix="/api")
app.include_router(notifications.router, prefix="/api")
app.include_router(dashboard.router, prefix="/api")
app.include_router(reports.router, prefix="/api")
app.include_router(search.router, prefix="/api")
app.include_router(audit.router, prefix="/api")
+13 -13
View File
@@ -13,14 +13,14 @@ class Asset(Base):
asset_code: Mapped[str] = mapped_column(String(60), unique=True, index=True, nullable=False)
serial_no: Mapped[str] = mapped_column(String(100), index=True, nullable=False)
name: Mapped[str] = mapped_column(String(200), nullable=False)
category_id: Mapped[int] = mapped_column(ForeignKey("categories.id"), nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
location_id: Mapped[int] = mapped_column(ForeignKey("locations.id"), nullable=False)
category_id: Mapped[int] = mapped_column(ForeignKey("categories.id"), index=True, nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
location_id: Mapped[int] = mapped_column(ForeignKey("locations.id"), index=True, nullable=False)
supplier_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
purchase_value: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
purchase_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
installation_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
status: Mapped[str] = mapped_column(String(40), default="in_service", nullable=False)
status: Mapped[str] = mapped_column(String(40), default="in_service", index=True, nullable=False)
criticality: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False)
requires_calibration: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
insurance_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
@@ -40,11 +40,11 @@ class Contract(Base):
__tablename__ = "contracts"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
contract_type: Mapped[str] = mapped_column(String(20), nullable=False)
provider_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
end_date: Mapped[date] = mapped_column(Date, nullable=False)
start_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
coverage_period_text: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
renewed_from_id: Mapped[Optional[int]] = mapped_column(ForeignKey("contracts.id"), nullable=True)
is_superseded: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
@@ -62,10 +62,10 @@ class Warranty(Base):
__tablename__ = "warranties"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
duration_months: Mapped[int] = mapped_column(Integer, nullable=False)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
end_date: Mapped[date] = mapped_column(Date, nullable=False)
start_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
provider_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
@@ -81,11 +81,11 @@ class InsurancePolicy(Base):
__tablename__ = "insurance_policies"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
insurer_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
policy_no: Mapped[str] = mapped_column(String(100), nullable=False)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
end_date: Mapped[date] = mapped_column(Date, nullable=False)
start_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
coverage_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
+5 -4
View File
@@ -11,22 +11,23 @@ class Complaint(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
complaint_no: Mapped[str] = mapped_column(String(60), unique=True, index=True, nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
description: Mapped[str] = mapped_column(Text, nullable=False)
breakdown_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
priority: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False)
notes: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
registered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
registered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False)
registered_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
received_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True)
assigned_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
attended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
restored_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
closed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
call_status: Mapped[str] = mapped_column(String(30), default="open", nullable=False)
call_status: Mapped[str] = mapped_column(String(30), default="open", index=True, nullable=False)
closure_remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
action_taken: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
root_cause: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+7 -6
View File
@@ -25,15 +25,16 @@ class CalibrationPlan(Base):
asset = relationship("Asset")
agency = relationship("Vendor")
approved_by = relationship("User", foreign_keys=[approved_by_id])
class CalibrationRecord(Base):
__tablename__ = "calibration_records"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
plan_id: Mapped[int] = mapped_column(ForeignKey("calibration_plans.id"), nullable=False)
due_date: Mapped[date] = mapped_column(Date, nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
plan_id: Mapped[int] = mapped_column(ForeignKey("calibration_plans.id"), index=True, nullable=False)
due_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
agency_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
certificate_no: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
@@ -76,9 +77,9 @@ class PMRecord(Base):
__tablename__ = "pm_records"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
schedule_id: Mapped[int] = mapped_column(ForeignKey("pm_schedules.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
planned_date: Mapped[date] = mapped_column(Date, nullable=False)
schedule_id: Mapped[int] = mapped_column(ForeignKey("pm_schedules.id"), index=True, nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
planned_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
# Only "completed" or "rescheduled" is persisted; upcoming/due/overdue are computed at read time.
status: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
+5 -4
View File
@@ -28,10 +28,10 @@ class DemoEquipment(Base):
name: Mapped[str] = mapped_column(String(200), nullable=False)
equipment_type: Mapped[str] = mapped_column(String(100), nullable=False)
supplier_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
location_id: Mapped[Optional[int]] = mapped_column(ForeignKey("locations.id"), nullable=True)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
expected_return_date: Mapped[date] = mapped_column(Date, nullable=False)
expected_return_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
actual_return_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
@@ -48,9 +48,9 @@ class DepartmentVisit(Base):
__tablename__ = "department_visits"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
visited_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
visit_date: Mapped[date] = mapped_column(Date, nullable=False)
visit_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
observations: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
@@ -58,5 +58,6 @@ class DepartmentVisit(Base):
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
department = relationship("Department")
visited_by = relationship("User", foreign_keys=[visited_by_id])
assets = relationship("Asset", secondary=department_visit_assets)
complaints = relationship("Complaint", secondary=department_visit_complaints)
+8 -8
View File
@@ -10,8 +10,8 @@ class Attachment(Base):
__tablename__ = "attachments"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
entity_type: Mapped[str] = mapped_column(String(60), nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, nullable=False)
entity_type: Mapped[str] = mapped_column(String(60), index=True, nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False)
original_name: Mapped[str] = mapped_column(String(255), nullable=False)
stored_name: Mapped[str] = mapped_column(String(255), nullable=False)
mime_type: Mapped[str] = mapped_column(String(120), nullable=False)
@@ -24,7 +24,7 @@ class Notification(Base):
__tablename__ = "notifications"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
type: Mapped[str] = mapped_column(String(60), nullable=False)
type: Mapped[str] = mapped_column(String(60), index=True, nullable=False)
severity: Mapped[str] = mapped_column(String(20), nullable=False)
title: Mapped[str] = mapped_column(String(200), nullable=False)
message: Mapped[str] = mapped_column(Text, nullable=False)
@@ -34,7 +34,7 @@ class Notification(Base):
target_role: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
target_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
dedupe_key: Mapped[str] = mapped_column(String(200), unique=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False)
class NotificationRead(Base):
@@ -53,9 +53,9 @@ class AuditLog(Base):
__tablename__ = "audit_logs"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
entity_type: Mapped[str] = mapped_column(String(60), nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, nullable=False)
entity_type: Mapped[str] = mapped_column(String(60), index=True, nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False)
action: Mapped[str] = mapped_column(String(50), nullable=False)
changes_json: Mapped[str] = mapped_column(Text, nullable=False)
by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True)
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False)
+44 -2
View File
@@ -1,3 +1,45 @@
from . import assets, attachments, auth, health, masters, settings, users
from . import (
assets,
attachments,
audit,
auth,
calibration,
complaints,
contracts,
dashboard,
demo_equipment,
health,
insurance,
masters,
notifications,
pm,
reports,
search,
settings,
users,
visits,
warranties,
)
__all__ = ["assets", "attachments", "auth", "health", "masters", "settings", "users"]
__all__ = [
"assets",
"attachments",
"audit",
"auth",
"calibration",
"complaints",
"contracts",
"dashboard",
"demo_equipment",
"health",
"insurance",
"masters",
"notifications",
"pm",
"reports",
"search",
"settings",
"users",
"visits",
"warranties",
]
+54 -4
View File
@@ -1,6 +1,7 @@
from datetime import date
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile, status
from fastapi.responses import StreamingResponse
from sqlalchemy import or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, joinedload
@@ -44,6 +45,7 @@ from ..schemas.assets import (
PMScheduleSummaryOut,
WarrantySummaryOut,
)
from ..services.asset_import import build_import_template_xlsx, process_asset_import
from ..services.audit import log_audit
from ..services.calculations import compute_schedule_status, coverage_status
from ..services.permissions import Role
@@ -59,9 +61,17 @@ def _lead_settings(db: Session) -> dict[str, int]:
"warranty": int(get_setting_value(db, "warranty_expiry_alert_days")),
"contract": int(get_setting_value(db, "contract_expiry_alert_days")),
"insurance": int(get_setting_value(db, "insurance_expiry_alert_days")),
"calibration": int(get_setting_value(db, "calibration_due_window_days")),
"calibration": int(
get_setting_value(
db,
"calibration_due_window_days",
get_setting_value(db, "calibration_lead_days", 15),
)
),
"pm": int(get_setting_value(db, "pm_due_window_days")),
"red": int(get_setting_value(db, "contract_critical_alert_days")),
"pm_in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)),
"pm_outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
"red": int(get_setting_value(db, "red_threshold_days", 7)),
}
@@ -504,6 +514,40 @@ def create_asset(
return _to_asset_out(loaded, rels, effective_today(db), _lead_settings(db))
@router.get("/import-template")
def download_asset_import_template(
db: Session = Depends(get_db),
_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
buf = build_import_template_xlsx(db)
return StreamingResponse(
buf,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={
"Content-Disposition": 'attachment; filename="asset_import_template.xlsx"',
},
)
@router.post("/bulk-import")
def bulk_import_assets(
file: UploadFile = File(...),
dry_run: bool = Query(False),
skip_invalid: bool = Query(False),
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
content = file.file.read()
return process_asset_import(
db=db,
filename=file.filename or "upload.xlsx",
content=content,
user_id=current_user.id,
dry_run=dry_run,
skip_invalid=skip_invalid,
)
@router.get("/{asset_id}", response_model=AssetOut)
def get_asset(
asset_id: int,
@@ -771,13 +815,19 @@ def get_asset_overview(
pm_rec_rows = (
db.query(PMRecord)
.options(joinedload(PMRecord.schedule))
.filter(PMRecord.asset_id == asset.id)
.order_by(PMRecord.planned_date.desc(), PMRecord.id.desc())
.all()
)
pm_rec_out = []
for r in pm_rec_rows:
st, sev = compute_schedule_status(r.planned_date, r.status, today, leads["pm"], leads["red"])
pm_lead = (
leads["pm_in_house"]
if r.schedule and r.schedule.service_mode == "in_house"
else leads["pm_outsourced"]
)
st, sev = compute_schedule_status(r.planned_date, r.status, today, pm_lead, leads["red"])
pm_rec_out.append(
PMRecordSummaryOut(
id=r.id,
+82
View File
@@ -0,0 +1,82 @@
from datetime import date, datetime, time, timedelta, timezone
from fastapi import APIRouter, Depends, Query
from sqlalchemy import String, cast, or_
from sqlalchemy.orm import Session
from ..core.db import get_db
from ..core.deps import require_roles
from ..core.time_utils import KOLKATA
from ..models import AuditLog, User
from ..services.permissions import Role
router = APIRouter(prefix="/audit-logs", tags=["audit"])
@router.get("")
def list_audit_logs(
entity_type: str | None = Query(None),
by_user_id: int | None = Query(None),
action: str | None = Query(None),
date_from: date | None = Query(None),
date_to: date | None = Query(None),
q: str | None = Query(None),
page: int = Query(1, ge=1),
page_size: int = Query(100, ge=1, le=500),
db: Session = Depends(get_db),
_admin: User = Depends(require_roles(Role.system_admin)),
):
query = db.query(AuditLog, User.name).outerjoin(User, AuditLog.by_user_id == User.id)
if entity_type:
query = query.filter(AuditLog.entity_type == entity_type.strip())
if by_user_id is not None:
query = query.filter(AuditLog.by_user_id == by_user_id)
if action:
query = query.filter(AuditLog.action == action.strip())
if date_from is not None:
dt_from_utc = KOLKATA.localize(
datetime.combine(date_from, time(0, 0, 0))
).astimezone(timezone.utc)
query = query.filter(AuditLog.at >= dt_from_utc)
if date_to is not None:
dt_to_utc = KOLKATA.localize(
datetime.combine(date_to + timedelta(days=1), time(0, 0, 0))
).astimezone(timezone.utc)
query = query.filter(AuditLog.at < dt_to_utc)
if q and q.strip():
pat = f"%{q.strip()}%"
query = query.filter(
or_(
AuditLog.entity_type.ilike(pat),
AuditLog.action.ilike(pat),
AuditLog.changes_json.ilike(pat),
cast(AuditLog.entity_id, String).ilike(pat),
User.name.ilike(pat),
)
)
total = query.count()
rows = (
query.order_by(AuditLog.at.desc(), AuditLog.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return {
"items": [
{
"id": log.id,
"entity_type": log.entity_type,
"entity_id": log.entity_id,
"action": log.action,
"changes_json": log.changes_json,
"by_user_id": log.by_user_id,
"by_user_name": user_name or "System",
"at": log.at,
}
for log, user_name in rows
],
"total": total,
}
+36 -2
View File
@@ -1,7 +1,11 @@
from fastapi import APIRouter, Depends, HTTPException, status
from collections import defaultdict, deque
import threading
import time
from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user
from ..core.exceptions import CodedHTTPException
from ..core.security import create_access_token, verify_password
from ..models.masters import User
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
@@ -9,6 +13,34 @@ from ..services.settings_service import get_demo_as_of_date
router = APIRouter(prefix="/auth", tags=["auth"])
MAX_LOGIN_ATTEMPTS = 15
LOGIN_WINDOW_SECONDS = 60.0
_login_attempts: dict[str, deque[float]] = defaultdict(deque)
_rate_limit_lock = threading.Lock()
def reset_login_rate_limiter() -> None:
"""Clear sliding-window login attempt counters (used in tests)."""
with _rate_limit_lock:
_login_attempts.clear()
def _enforce_login_rate_limit(client_ip: str, email_norm: str) -> None:
now = time.monotonic()
cutoff = now - LOGIN_WINDOW_SECONDS
key = f"{client_ip}:{email_norm}"
with _rate_limit_lock:
attempts = _login_attempts[key]
while attempts and attempts[0] <= cutoff:
attempts.popleft()
if len(attempts) >= MAX_LOGIN_ATTEMPTS:
raise CodedHTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Too many login attempts. Please wait a minute.",
code="RATE_LIMITED",
)
attempts.append(now)
def _build_user_out(user: User, db: Session) -> UserOut:
return UserOut(
@@ -24,8 +56,10 @@ def _build_user_out(user: User, db: Session) -> UserOut:
@router.post("/login", response_model=TokenResponse)
def login(payload: LoginRequest, db: Session = Depends(get_db)):
def login(payload: LoginRequest, request: Request, db: Session = Depends(get_db)):
email_norm = payload.email.strip().lower()
client_ip = request.client.host if request.client else "unknown"
_enforce_login_rate_limit(client_ip, email_norm)
user = (
db.query(User)
.options(joinedload(User.department))
+646
View File
@@ -0,0 +1,646 @@
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_due_window_days",
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),
)
+818
View File
@@ -0,0 +1,818 @@
from datetime import date, datetime, time, timedelta, timezone
from typing import Any, 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 KOLKATA, utc_now
from ..models import Asset, Complaint, ComplaintEvent, User
from ..schemas.complaints import (
ComplaintAssignIn,
ComplaintAttendIn,
ComplaintCloseIn,
ComplaintCorrectTimestampIn,
ComplaintCreate,
ComplaintEventListOut,
ComplaintEventOut,
ComplaintListOut,
ComplaintOut,
ComplaintReopenIn,
ComplaintRestoreIn,
ComplaintUpdate,
)
from ..services.audit import log_audit
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
from ..services.settings_service import get_demo_as_of_date, get_setting_value
router = APIRouter(prefix="/complaints", tags=["complaints"])
DEPT_USER_EDITABLE_FIELDS = {"description", "breakdown_details", "notes"}
def _norm_utc(dt: datetime | None) -> datetime | None:
if dt is None:
return None
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def _effective_now_utc(db: Session) -> datetime:
demo_str = get_demo_as_of_date(db)
if demo_str:
demo_d = date.fromisoformat(demo_str)
real_now_ist = datetime.now(KOLKATA)
if demo_d > real_now_ist.date():
local_dt = KOLKATA.localize(datetime.combine(demo_d, time(23, 59, 59)))
else:
local_dt = KOLKATA.localize(datetime.combine(demo_d, real_now_ist.time()))
return local_dt.astimezone(timezone.utc)
return utc_now()
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"))
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]:
ids: set[int] = set()
for c in complaints:
for uid in (
c.registered_by_id,
c.received_by_id,
c.assigned_to_id,
c.attended_by_id,
c.closed_by_id,
):
if uid is not None:
ids.add(uid)
if not ids:
return {}
return {
u.id: u.name
for u in db.query(User.id, User.name).filter(User.id.in_(ids)).all()
}
def _to_complaint_out(
c: Complaint,
user_names: dict[int, str],
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)
asg_at = _norm_utc(c.assigned_at)
att_at = _norm_utc(c.attended_at)
rst_at = _norm_utc(c.restored_at)
cls_at = _norm_utc(c.closed_at)
ce_at = _norm_utc(c.ce_attended_at)
upd_at = _norm_utc(c.updated_at)
resp_min = compute_response_time_minutes(reg_at, recv_at, att_at, response_start=response_start)
dt_min, is_ongoing = compute_downtime_minutes(
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(
id=c.id,
complaint_no=c.complaint_no,
asset_id=c.asset_id,
asset_code=asset.asset_code,
asset_name=asset.name,
asset_status=asset.status,
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,
description=c.description,
breakdown_details=c.breakdown_details,
priority=c.priority,
notes=c.notes,
registered_at=reg_at,
registered_by_id=c.registered_by_id,
registered_by_name=user_names.get(c.registered_by_id),
received_by_id=c.received_by_id,
received_by_name=user_names.get(c.received_by_id),
received_at=recv_at,
assigned_to_id=c.assigned_to_id,
assigned_to_name=user_names.get(c.assigned_to_id) if c.assigned_to_id else None,
assigned_at=asg_at,
attended_by_id=c.attended_by_id,
attended_by_name=user_names.get(c.attended_by_id) if c.attended_by_id else None,
attended_at=att_at,
restored_at=rst_at,
closed_by_id=c.closed_by_id,
closed_by_name=user_names.get(c.closed_by_id) if c.closed_by_id else None,
closed_at=cls_at,
call_status=c.call_status,
closure_remarks=c.closure_remarks,
action_taken=c.action_taken,
root_cause=c.root_cause,
corrective_action=c.corrective_action,
lessons_learned=c.lessons_learned,
ce_name=c.ce_name,
ce_attended_at=ce_at,
ce_action_taken=c.ce_action_taken,
spare_required=c.spare_required,
spare_details=c.spare_details,
spare_cost_estimate=c.spare_cost_estimate,
response_time_minutes=resp_min,
downtime_minutes=dt_min,
downtime_is_ongoing=is_ongoing,
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,
)
def _load_complaint_or_404(db: Session, complaint_id: int) -> Complaint:
comp = (
db.query(Complaint)
.options(
joinedload(Complaint.asset).joinedload(Asset.department),
joinedload(Complaint.asset).joinedload(Asset.location),
)
.filter(Complaint.id == complaint_id)
.first()
)
if comp is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Complaint not found.")
return comp
def _check_complaint_visibility(comp: Complaint, user: User) -> None:
if user.role == Role.department_user.value and comp.asset.department_id != user.department_id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access denied for another department's complaint.",
)
def _serialize_one(db: Session, comp: Complaint) -> ComplaintOut:
user_names = _load_user_names(db, [comp])
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,
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:
if asset.status != "under_repair":
return
q = db.query(Complaint.id).filter(
Complaint.asset_id == asset.id,
Complaint.id != exclude_complaint_id,
Complaint.priority == "critical",
Complaint.call_status != "closed",
)
if require_unrestored:
q = q.filter(Complaint.restored_at.is_(None))
if q.first() is None:
asset.status = "in_service"
@router.get("", response_model=ComplaintListOut)
def list_complaints(
q: Optional[str] = None,
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
call_status: Optional[str] = None,
priority: Optional[str] = None,
assigned_to_id: Optional[int] = None,
closure_state: Optional[str] = None,
date_from: Optional[str] = None,
date_to: Optional[str] = None,
page: int = Query(1, ge=1),
page_size: int = Query(100, ge=0, le=500),
sort: str = "-registered_at",
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
query = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.options(
joinedload(Complaint.asset).joinedload(Asset.department),
joinedload(Complaint.asset).joinedload(Asset.location),
)
)
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(Complaint.asset_id == asset_id)
if call_status:
query = query.filter(Complaint.call_status == call_status)
if priority:
query = query.filter(Complaint.priority == priority)
if assigned_to_id is not None:
query = query.filter(Complaint.assigned_to_id == assigned_to_id)
if closure_state == "open_only":
query = query.filter(Complaint.call_status != "closed")
elif closure_state == "closed_only":
query = query.filter(Complaint.call_status == "closed")
if date_from:
try:
d_from = date.fromisoformat(date_from)
except ValueError:
raise HTTPException(status_code=422, detail="date_from must be YYYY-MM-DD.")
start_utc = KOLKATA.localize(datetime.combine(d_from, time(0, 0, 0))).astimezone(timezone.utc)
query = query.filter(Complaint.registered_at >= start_utc)
if date_to:
try:
d_to = date.fromisoformat(date_to)
except ValueError:
raise HTTPException(status_code=422, detail="date_to must be YYYY-MM-DD.")
end_utc = KOLKATA.localize(
datetime.combine(d_to + timedelta(days=1), time(0, 0, 0))
).astimezone(timezone.utc)
query = query.filter(Complaint.registered_at < end_utc)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Complaint.complaint_no.ilike(like),
Complaint.description.ilike(like),
Asset.asset_code.ilike(like),
Asset.name.ilike(like),
)
)
sort_desc = sort.startswith("-")
sort_key = sort.lstrip("-")
sort_col_map = {
"id": Complaint.id,
"complaint_no": Complaint.complaint_no,
"registered_at": Complaint.registered_at,
"priority": Complaint.priority,
"call_status": Complaint.call_status,
"closed_at": Complaint.closed_at,
}
col = sort_col_map.get(sort_key, Complaint.registered_at)
query = query.order_by(col.desc() if sort_desc else col.asc(), Complaint.id.desc())
total = query.count()
if page_size > 0:
query = query.offset((page - 1) * page_size).limit(page_size)
rows = query.all()
user_names = _load_user_names(db, rows)
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,
critical_sla_hours=critical_sla,
non_critical_sla_hours=non_critical_sla,
)
for c in rows
]
return {"items": items, "total": total}
@router.post("", response_model=ComplaintOut, status_code=status.HTTP_201_CREATED)
def create_complaint(
payload: ComplaintCreate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.department_user)),
):
asset = (
db.query(Asset)
.options(joinedload(Asset.department), joinedload(Asset.location))
.filter(Asset.id == payload.asset_id)
.first()
)
if asset is None:
raise HTTPException(status_code=404, detail="Asset not found.")
if current_user.role == Role.department_user.value and asset.department_id != current_user.department_id:
raise HTTPException(status_code=403, detail="Cannot raise complaint for another department's asset.")
recv_by_id = payload.received_by_id or current_user.id
if payload.received_by_id is not None:
if not db.query(User.id).filter(User.id == payload.received_by_id).first():
raise HTTPException(status_code=404, detail="Received-by user not found.")
reg_at = utc_now()
recv_at = _norm_utc(payload.received_at) if payload.received_at is not None else reg_at
prefix = str(get_setting_value(db, "complaint_no_prefix", "CMP"))
cno = generate_complaint_no(db, prefix, reg_at)
comp = Complaint(
complaint_no=cno,
asset_id=asset.id,
description=payload.description.strip(),
breakdown_details=payload.breakdown_details,
priority=payload.priority,
notes=payload.notes,
registered_at=reg_at,
registered_by_id=current_user.id,
received_by_id=recv_by_id,
received_at=recv_at,
call_status="open",
updated_by_id=current_user.id,
)
db.add(comp)
db.flush()
if payload.priority == "critical" and bool(
get_setting_value(db, "critical_complaint_sets_under_repair", True)
):
asset.status = "under_repair"
asset.updated_by_id = current_user.id
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="registered",
from_value=None,
to_value="open",
by_user_id=current_user.id,
at=reg_at,
note=payload.notes,
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="create",
changes={"complaint_no": cno, "asset_id": asset.id, "priority": payload.priority},
user_id=current_user.id,
)
db.commit()
loaded = _load_complaint_or_404(db, comp.id)
return _serialize_one(db, loaded)
@router.get("/{complaint_id}", response_model=ComplaintOut)
def get_complaint(
complaint_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
comp = _load_complaint_or_404(db, complaint_id)
_check_complaint_visibility(comp, current_user)
return _serialize_one(db, comp)
@router.get("/{complaint_id}/events", response_model=ComplaintEventListOut)
def get_complaint_events(
complaint_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
comp = _load_complaint_or_404(db, complaint_id)
_check_complaint_visibility(comp, current_user)
rows = (
db.query(ComplaintEvent)
.filter(ComplaintEvent.complaint_id == comp.id)
.order_by(ComplaintEvent.at.asc(), ComplaintEvent.id.asc())
.all()
)
uid_set = {r.by_user_id for r in rows}
user_names = (
{u.id: u.name for u in db.query(User.id, User.name).filter(User.id.in_(uid_set)).all()}
if uid_set
else {}
)
items = [
ComplaintEventOut(
id=r.id,
complaint_id=r.complaint_id,
event_type=r.event_type,
from_value=r.from_value,
to_value=r.to_value,
by_user_id=r.by_user_id,
by_user_name=user_names.get(r.by_user_id),
at=_norm_utc(r.at),
note=r.note,
)
for r in rows
]
return {"items": items, "total": len(items)}
@router.patch("/{complaint_id}", response_model=ComplaintOut)
def update_complaint(
complaint_id: int,
payload: ComplaintUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
comp = _load_complaint_or_404(db, complaint_id)
fields_sent = payload.model_fields_set
if RESTRICTED_COMPLAINT_FIELDS & fields_sent and current_user.role not in (
Role.system_admin.value,
Role.biomedical.value,
):
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only Biomedical or System Admin can edit technical resolution fields.",
code="FORBIDDEN_TECHNICAL_FIELDS",
)
if current_user.role in (Role.management.value, Role.coordinator.value):
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You do not have permission to edit complaints.",
code="FORBIDDEN",
)
if current_user.role == Role.department_user.value:
_check_complaint_visibility(comp, current_user)
if comp.call_status == "closed":
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Closed complaints cannot be edited by department users.",
code="FORBIDDEN",
)
if not fields_sent.issubset(DEPT_USER_EDITABLE_FIELDS):
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Department users can only edit description, breakdown_details, and notes.",
code="FORBIDDEN",
)
data = payload.model_dump(exclude_unset=True)
if "description" in data and data["description"] is not None:
data["description"] = data["description"].strip()
if "ce_attended_at" in data and data["ce_attended_at"] is not None:
data["ce_attended_at"] = _norm_utc(data["ce_attended_at"])
changes: dict[str, dict[str, Any]] = {}
for k, v in data.items():
old_val = getattr(comp, k)
if isinstance(old_val, datetime):
old_val = _norm_utc(old_val)
if old_val != v:
changes[k] = {"from": old_val, "to": v}
setattr(comp, k, v)
comp.updated_by_id = current_user.id
if changes:
now = utc_now()
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="field_edited",
from_value=None,
to_value=", ".join(sorted(changes.keys())),
by_user_id=current_user.id,
at=now,
note=f"Updated fields: {', '.join(sorted(changes.keys()))}",
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="update",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_complaint_or_404(db, comp.id)
return _serialize_one(db, loaded)
@router.post("/{complaint_id}/assign", response_model=ComplaintOut)
def assign_complaint(
complaint_id: int,
payload: ComplaintAssignIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
comp = _load_complaint_or_404(db, complaint_id)
assignee = db.query(User).filter(User.id == payload.assigned_to_id, User.is_active.is_(True)).first()
if assignee is None:
raise HTTPException(status_code=404, detail="Assigned user not found or inactive.")
old_name: Optional[str] = None
event_type = "assigned"
if comp.assigned_to_id is not None:
event_type = "reassigned"
old_user = db.query(User.name).filter(User.id == comp.assigned_to_id).first()
old_name = old_user[0] if old_user else str(comp.assigned_to_id)
now = utc_now()
comp.assigned_to_id = assignee.id
comp.assigned_at = now
if comp.call_status == "open":
comp.call_status = "in_progress"
comp.updated_by_id = current_user.id
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type=event_type,
from_value=old_name,
to_value=assignee.name,
by_user_id=current_user.id,
at=now,
note=payload.note,
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action=event_type,
changes={"assigned_to_id": assignee.id, "note": payload.note},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
@router.post("/{complaint_id}/attend", response_model=ComplaintOut)
def attend_complaint(
complaint_id: int,
payload: ComplaintAttendIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
comp = _load_complaint_or_404(db, complaint_id)
att_uid = payload.attended_by_id or current_user.id
att_user = db.query(User).filter(User.id == att_uid).first()
if att_user is None:
raise HTTPException(status_code=404, detail="Attending user not found.")
now = utc_now()
prev_status = comp.call_status
comp.attended_by_id = att_user.id
comp.attended_at = now
if comp.call_status == "open":
comp.call_status = "in_progress"
comp.updated_by_id = current_user.id
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="attended",
from_value=prev_status,
to_value=comp.call_status,
by_user_id=current_user.id,
at=now,
note=payload.note or f"Attended by {att_user.name}",
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="attend",
changes={"attended_by_id": att_user.id},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
@router.post("/{complaint_id}/restore", response_model=ComplaintOut)
def restore_complaint(
complaint_id: int,
payload: ComplaintRestoreIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
comp = _load_complaint_or_404(db, complaint_id)
now = utc_now()
comp.restored_at = now
comp.updated_by_id = current_user.id
_sync_asset_status(db, comp.asset, exclude_complaint_id=comp.id, require_unrestored=True)
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="restored",
from_value=None,
to_value=now.isoformat(),
by_user_id=current_user.id,
at=now,
note=payload.note,
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="restore",
changes={"restored_at": now.isoformat()},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
@router.post("/{complaint_id}/close", response_model=ComplaintOut)
def close_complaint(
complaint_id: int,
payload: ComplaintCloseIn,
db: Session = Depends(get_db),
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()):
# Use CodedHTTPException so 422 responses match {"detail": str, "code": str} across the API
raise CodedHTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Closure remarks are required.",
code="CLOSURE_REMARKS_REQUIRED",
)
now = utc_now()
prev_status = comp.call_status
comp.closed_by_id = current_user.id
comp.closed_at = now
if comp.restored_at is None:
comp.restored_at = comp.closed_at
if payload.closure_remarks is not None:
comp.closure_remarks = payload.closure_remarks
comp.call_status = "closed"
comp.updated_by_id = current_user.id
_sync_asset_status(db, comp.asset, exclude_complaint_id=comp.id, require_unrestored=False)
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="closed",
from_value=prev_status,
to_value="closed",
by_user_id=current_user.id,
at=now,
note=payload.closure_remarks,
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="close",
changes={"call_status": "closed", "closure_remarks": payload.closure_remarks},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
@router.post("/{complaint_id}/reopen", response_model=ComplaintOut)
def reopen_complaint(
complaint_id: int,
payload: ComplaintReopenIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
comp = _load_complaint_or_404(db, complaint_id)
now = utc_now()
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
if comp.priority == "critical" and bool(
get_setting_value(db, "critical_complaint_sets_under_repair", True)
):
comp.asset.status = "under_repair"
comp.asset.updated_by_id = current_user.id
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="reopened",
from_value=prev_status,
to_value="in_progress",
by_user_id=current_user.id,
at=now,
note=payload.reason,
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="reopen",
changes={"reason": payload.reason},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
@router.post("/{complaint_id}/correct-timestamp", response_model=ComplaintOut)
def correct_complaint_timestamp(
complaint_id: int,
payload: ComplaintCorrectTimestampIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin)),
):
comp = _load_complaint_or_404(db, complaint_id)
now = utc_now()
old_val = _norm_utc(getattr(comp, payload.field))
new_val = _norm_utc(payload.new_value)
setattr(comp, payload.field, new_val)
comp.updated_by_id = current_user.id
from_str = old_val.isoformat() if old_val else None
to_str = new_val.isoformat() if new_val else None
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="timestamp_corrected",
from_value=from_str,
to_value=to_str,
by_user_id=current_user.id,
at=now,
note=f"{payload.field}: {payload.reason}",
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="correct_timestamp",
changes={"field": payload.field, "from": from_str, "to": to_str, "reason": payload.reason},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
+390
View File
@@ -0,0 +1,390 @@
from datetime import date
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Response, 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.time_utils import effective_today
from ..models import Asset, Contract, PMSchedule, User, Vendor
from ..schemas.contracts import (
ContractCreate,
ContractHistoryOut,
ContractListOut,
ContractOut,
ContractRenewIn,
ContractRenewOut,
ContractStatusFilter,
ContractType,
ContractUpdate,
)
from ..services.attachment_service import get_attachment_counts
from ..services.audit import log_audit
from ..services.calculations import coverage_status
from ..services.permissions import Role
from ..services.settings_service import get_setting_value
router = APIRouter(prefix="/contracts", tags=["contracts"])
def _contract_lead_settings(db: Session) -> tuple[int, int]:
lead = int(
get_setting_value(
db,
"amc_cmc_lead_days",
get_setting_value(db, "contract_expiry_alert_days", 30),
)
)
red = int(
get_setting_value(
db,
"contract_critical_alert_days",
get_setting_value(db, "red_threshold_days", 7),
)
)
return lead, red
def _to_contract_out(
c: Contract,
today: date,
lead_days: int,
red_days: int,
att_counts: dict[int, int],
) -> ContractOut:
asset = c.asset
if c.is_superseded:
st, sev = "superseded", "ok"
else:
st, sev = coverage_status(c.start_date, c.end_date, today, lead_days, red_days)
return ContractOut(
id=c.id,
asset_id=c.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,
contract_type=c.contract_type,
provider_id=c.provider_id,
provider_name=c.provider.name if c.provider else None,
start_date=c.start_date,
end_date=c.end_date,
coverage_period_text=c.coverage_period_text,
renewed_from_id=c.renewed_from_id,
is_superseded=c.is_superseded,
status=st,
severity=sev,
days_to_expiry=(c.end_date - today).days,
attachment_count=att_counts.get(c.id, 0),
remarks=c.remarks,
created_at=c.created_at,
)
def _load_contract(db: Session, contract_id: int) -> Contract | None:
return (
db.query(Contract)
.options(
joinedload(Contract.asset).joinedload(Asset.department),
joinedload(Contract.provider),
)
.filter(Contract.id == contract_id)
.first()
)
@router.get("", response_model=ContractListOut)
def list_contracts(
q: str = "",
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
provider_id: Optional[int] = None,
contract_type: Optional[ContractType] = None,
status_filter: Optional[ContractStatusFilter] = Query(None, alias="status"),
include_superseded: bool = True,
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)
lead_days, red_days = _contract_lead_settings(db)
query = (
db.query(Contract)
.join(Asset, Contract.asset_id == Asset.id)
.outerjoin(Vendor, Contract.provider_id == Vendor.id)
.options(
joinedload(Contract.asset).joinedload(Asset.department),
joinedload(Contract.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(Contract.asset_id == asset_id)
if provider_id is not None:
query = query.filter(Contract.provider_id == provider_id)
if contract_type is not None:
query = query.filter(Contract.contract_type == contract_type)
if not include_superseded:
query = query.filter(Contract.is_superseded.is_(False))
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),
Contract.coverage_period_text.ilike(like),
Contract.remarks.ilike(like),
)
)
rows = query.order_by(Contract.is_superseded.asc(), Contract.end_date.asc(), Contract.id.desc()).all()
att_counts = get_attachment_counts(db, "contract", [r.id for r in rows])
items_all = [_to_contract_out(r, today, lead_days, red_days, att_counts) for r in rows]
if status_filter is not None:
items_all = [item for item in items_all if item.status == status_filter]
total = len(items_all)
start = (page - 1) * page_size
return ContractListOut(items=items_all[start : start + page_size], total=total)
@router.get("/history/{asset_id}", response_model=ContractHistoryOut)
def get_contract_history(
asset_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
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.")
if current_user.role == Role.department_user.value and asset.department_id != current_user.department_id:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied for another department's asset.")
today = effective_today(db)
lead_days, red_days = _contract_lead_settings(db)
rows = (
db.query(Contract)
.options(
joinedload(Contract.asset).joinedload(Asset.department),
joinedload(Contract.provider),
)
.filter(Contract.asset_id == asset_id)
.order_by(Contract.start_date.desc(), Contract.id.desc())
.all()
)
att_counts = get_attachment_counts(db, "contract", [r.id for r in rows])
return ContractHistoryOut(
items=[_to_contract_out(r, today, lead_days, red_days, att_counts) for r in rows]
)
@router.post("", response_model=ContractOut, status_code=status.HTTP_201_CREATED)
def create_contract(
payload: ContractCreate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
if payload.end_date < payload.start_date:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="end_date cannot be earlier than start_date.",
)
if not db.query(Asset.id).filter(Asset.id == payload.asset_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
if not db.query(Vendor.id).filter(Vendor.id == payload.provider_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
contract = Contract(
asset_id=payload.asset_id,
contract_type=payload.contract_type,
provider_id=payload.provider_id,
start_date=payload.start_date,
end_date=payload.end_date,
coverage_period_text=payload.coverage_period_text.strip() if payload.coverage_period_text else None,
renewed_from_id=None,
is_superseded=False,
remarks=payload.remarks.strip() if payload.remarks else None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(contract)
db.flush()
log_audit(
db,
entity_type="contract",
entity_id=contract.id,
action="create",
changes={
"asset_id": payload.asset_id,
"contract_type": payload.contract_type,
"provider_id": payload.provider_id,
"start_date": str(payload.start_date),
"end_date": str(payload.end_date),
},
user_id=current_user.id,
)
db.commit()
loaded = _load_contract(db, contract.id)
today = effective_today(db)
lead_days, red_days = _contract_lead_settings(db)
att_counts = get_attachment_counts(db, "contract", [contract.id])
return _to_contract_out(loaded, today, lead_days, red_days, att_counts)
@router.patch("/{contract_id}", response_model=ContractOut)
def update_contract(
contract_id: int,
payload: ContractUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
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.")
data = payload.model_dump(exclude_unset=True)
if "provider_id" in data and data["provider_id"] is not None:
if not db.query(Vendor.id).filter(Vendor.id == data["provider_id"]).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
new_start = data.get("start_date", contract.start_date)
new_end = data.get("end_date", contract.end_date)
if new_end < new_start:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="end_date cannot be earlier than start_date.",
)
changes: dict[str, dict[str, object]] = {}
for k, v in data.items():
if isinstance(v, str):
v = v.strip() or None
old_val = getattr(contract, k)
if old_val != v:
changes[k] = {"from": old_val, "to": v}
setattr(contract, k, v)
contract.updated_by_id = current_user.id
if changes:
log_audit(
db,
entity_type="contract",
entity_id=contract.id,
action="update",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_contract(db, contract.id)
today = effective_today(db)
lead_days, red_days = _contract_lead_settings(db)
att_counts = get_attachment_counts(db, "contract", [contract.id])
return _to_contract_out(loaded, today, lead_days, red_days, att_counts)
@router.delete("/{contract_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_contract(
contract_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
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.")
db.query(Contract).filter(Contract.renewed_from_id == contract.id).update({"renewed_from_id": None})
db.query(PMSchedule).filter(PMSchedule.contract_id == contract.id).update({"contract_id": None})
log_audit(
db,
entity_type="contract",
entity_id=contract.id,
action="delete",
changes={"asset_id": contract.asset_id, "contract_type": contract.contract_type},
user_id=current_user.id,
)
db.delete(contract)
db.commit()
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.post("/{contract_id}/renew", response_model=ContractRenewOut)
def renew_contract(
contract_id: int,
payload: ContractRenewIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
old_contract = db.query(Contract).filter(Contract.id == contract_id).first()
if old_contract is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
if payload.end_date < payload.start_date:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="end_date cannot be earlier than start_date.",
)
target_provider_id = payload.provider_id if payload.provider_id is not None else old_contract.provider_id
if not db.query(Vendor.id).filter(Vendor.id == target_provider_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
old_contract.is_superseded = True
old_contract.updated_by_id = current_user.id
new_contract = Contract(
asset_id=old_contract.asset_id,
contract_type=payload.contract_type or old_contract.contract_type,
provider_id=target_provider_id,
start_date=payload.start_date,
end_date=payload.end_date,
coverage_period_text=(
payload.coverage_period_text.strip()
if payload.coverage_period_text is not None
else old_contract.coverage_period_text
),
renewed_from_id=old_contract.id,
is_superseded=False,
remarks=payload.remarks.strip() if payload.remarks else None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(new_contract)
db.flush()
log_audit(
db,
entity_type="contract",
entity_id=old_contract.id,
action="renew",
changes={
"superseded_contract_id": old_contract.id,
"new_contract_id": new_contract.id,
"start_date": str(payload.start_date),
"end_date": str(payload.end_date),
},
user_id=current_user.id,
)
db.commit()
today = effective_today(db)
lead_days, red_days = _contract_lead_settings(db)
att_counts = get_attachment_counts(db, "contract", [old_contract.id, new_contract.id])
loaded_old = _load_contract(db, old_contract.id)
loaded_new = _load_contract(db, new_contract.id)
return ContractRenewOut(
old_contract=_to_contract_out(loaded_old, today, lead_days, red_days, att_counts),
new_contract=_to_contract_out(loaded_new, today, lead_days, red_days, att_counts),
)
+292
View File
@@ -0,0 +1,292 @@
from datetime import date
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user
from ..core.time_utils import add_months, effective_now_utc, effective_today
from ..models import (
Asset,
CalibrationRecord,
Complaint,
Contract,
DemoEquipment,
Department,
PMRecord,
User,
)
from ..schemas.dashboard import (
ComplaintsByDepartmentItem,
ComplaintsByStatusItem,
DashboardKPIs,
DashboardSummaryOut,
MonthlyDowntimeItem,
MonthlyPMComparisonItem,
NeedsAttentionItem,
RecentComplaintItem,
)
from ..services.alerts import get_visible_notifications_for_user, notification_link_url
from ..services.calculations import (
clip_downtime_to_month,
compute_downtime_minutes,
compute_schedule_status,
coverage_status,
)
from ..services.permissions import Role
from ..services.settings_service import get_setting_value
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
@router.get("/summary", response_model=DashboardSummaryOut)
def get_dashboard_summary(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
today = effective_today(db)
eff_now = effective_now_utc(db)
scoped_dept_id: int | None = None
dept_scope_name: str | None = None
if current_user.role == Role.department_user.value:
scoped_dept_id = current_user.department_id
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
dept_scope_name = dept_obj.name if dept_obj else None
# Settings for dynamic calculations
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,
"amc_cmc_lead_days",
get_setting_value(db, "contract_expiry_alert_days", 30),
)
)
red_days = int(get_setting_value(db, "red_threshold_days", 7))
downtime_milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
# 1. Assets KPIs
asset_q = db.query(Asset)
if scoped_dept_id is not None:
asset_q = asset_q.filter(Asset.department_id == scoped_dept_id)
total_assets = asset_q.count()
assets_under_repair = asset_q.filter(Asset.status == "under_repair").count()
# 2. Complaints queries (used for KPIs, status chart, dept chart, downtime trend, recent list)
cmp_q = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.options(joinedload(Complaint.asset).joinedload(Asset.department))
)
if scoped_dept_id is not None:
cmp_q = cmp_q.filter(Asset.department_id == scoped_dept_id)
complaints = cmp_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc()).all()
open_cnt = sum(1 for c in complaints if c.call_status == "open")
in_prog_cnt = sum(1 for c in complaints if c.call_status == "in_progress")
closed_cnt = sum(1 for c in complaints if c.call_status == "closed")
open_complaints_kpi = open_cnt + in_prog_cnt
complaints_by_status = [
ComplaintsByStatusItem(status="open", count=open_cnt),
ComplaintsByStatusItem(status="in_progress", count=in_prog_cnt),
ComplaintsByStatusItem(status="closed", count=closed_cnt),
]
dept_q = db.query(Department).filter(Department.is_active.is_(True))
if scoped_dept_id is not None:
dept_q = dept_q.filter(Department.id == scoped_dept_id)
departments = dept_q.order_by(Department.name.asc()).all()
dept_crit_counts: dict[str, dict[str, int]] = {
d.name: {"critical": 0, "non_critical": 0} for d in departments
}
for c in complaints:
dname = c.asset.department.name if (c.asset and c.asset.department) else "Unknown"
if dname not in dept_crit_counts:
dept_crit_counts[dname] = {"critical": 0, "non_critical": 0}
if c.priority == "critical":
dept_crit_counts[dname]["critical"] += 1
else:
dept_crit_counts[dname]["non_critical"] += 1
complaints_by_department = [
ComplaintsByDepartmentItem(
department=dname,
critical=vals["critical"],
non_critical=vals["non_critical"],
)
for dname, vals in dept_crit_counts.items()
]
# 3. PM records (KPI + 6-month chart)
pm_q = db.query(PMRecord).join(Asset, PMRecord.asset_id == Asset.id)
if scoped_dept_id is not None:
pm_q = pm_q.filter(Asset.department_id == scoped_dept_id)
pm_records = pm_q.all()
pm_due_this_month = 0
for r in pm_records:
if r.status in ("completed", "rescheduled"):
continue
if r.planned_date < today or (
r.planned_date.year == today.year and r.planned_date.month == today.month
):
pm_due_this_month += 1
# 4. Calibrations due KPI
cal_q = db.query(CalibrationRecord).join(Asset, CalibrationRecord.asset_id == Asset.id)
if scoped_dept_id is not None:
cal_q = cal_q.filter(Asset.department_id == scoped_dept_id)
cal_records = cal_q.all()
calibrations_due = 0
for r in cal_records:
st, _ = compute_schedule_status(r.due_date, r.status, today, cal_lead, red_days)
if st in ("due", "overdue"):
calibrations_due += 1
# 5. Contracts expiring KPI
con_q = (
db.query(Contract)
.join(Asset, Contract.asset_id == Asset.id)
.filter(Contract.is_superseded.is_(False))
)
if scoped_dept_id is not None:
con_q = con_q.filter(Asset.department_id == scoped_dept_id)
contracts = con_q.all()
contracts_expiring = 0
for c in contracts:
st, _ = coverage_status(c.start_date, c.end_date, today, amc_lead, red_days)
if st in ("expiring", "expired"):
contracts_expiring += 1
# 6. Equipment on demo KPI
demo_q = db.query(DemoEquipment).filter(DemoEquipment.actual_return_date.is_(None))
if scoped_dept_id is not None:
demo_q = demo_q.filter(DemoEquipment.department_id == scoped_dept_id)
equipment_on_demo = demo_q.count()
# 7. Last 6 calendar months (oldest -> current month)
cur_month_start = date(today.year, today.month, 1)
months_seq = [add_months(cur_month_start, offset) for offset in range(-5, 1)]
monthly_downtime_trend: list[MonthlyDowntimeItem] = []
pm_planned_vs_completed: list[MonthlyPMComparisonItem] = []
for m_start in months_seq:
y, m = m_start.year, m_start.month
m_key = f"{y:04d}-{m:02d}"
m_label = m_start.strftime("%b %Y")
total_mins = 0
for c in complaints:
end_map = {
"attended_at": c.attended_at,
"restored_at": c.restored_at,
"closed_at": c.closed_at,
}
end_dt = end_map.get(downtime_milestone) or eff_now
mins, _ = clip_downtime_to_month(c.registered_at, end_dt, y, m)
total_mins += mins
monthly_downtime_trend.append(
MonthlyDowntimeItem(
month=m_key,
label=m_label,
downtime_minutes=total_mins,
downtime_hours=round(total_mins / 60.0, 2),
)
)
planned_cnt = sum(
1 for r in pm_records if r.planned_date.year == y and r.planned_date.month == m
)
completed_cnt = sum(
1
for r in pm_records
if r.status == "completed"
and (r.completed_date or r.planned_date).year == y
and (r.completed_date or r.planned_date).month == m
)
pm_planned_vs_completed.append(
MonthlyPMComparisonItem(
month=m_key,
label=m_label,
planned=planned_cnt,
completed=completed_cnt,
)
)
# 8. Needs attention (top 15 unread red notifications visible to user)
visible_notifs, read_map = get_visible_notifications_for_user(db, current_user)
red_unread = [
n for n in visible_notifs if n.severity == "red" and n.id not in read_map
]
red_unread.sort(key=lambda n: (n.due_date or today, -n.id))
needs_attention = [
NeedsAttentionItem(
id=n.id,
type=n.type,
severity=n.severity,
title=n.title,
message=n.message,
entity_type=n.entity_type,
entity_id=n.entity_id,
due_date=n.due_date,
link_url=notification_link_url(n.entity_type, n.entity_id),
)
for n in red_unread[:15]
]
# 9. Recent complaints (latest 8)
recent_complaints: list[RecentComplaintItem] = []
for c in complaints[:8]:
dt_mins, is_ongoing = compute_downtime_minutes(
c.registered_at,
c.attended_at,
c.restored_at,
c.closed_at,
milestone=downtime_milestone,
now_utc=eff_now,
)
recent_complaints.append(
RecentComplaintItem(
id=c.id,
complaint_no=c.complaint_no,
asset_code=c.asset.asset_code,
asset_name=c.asset.name,
department_name=c.asset.department.name if c.asset.department else None,
priority=c.priority,
call_status=c.call_status,
registered_at=c.registered_at,
downtime_minutes=dt_mins,
downtime_is_ongoing=is_ongoing,
)
)
return DashboardSummaryOut(
department_scope=dept_scope_name,
effective_today=today,
kpis=DashboardKPIs(
total_assets=total_assets,
assets_under_repair=assets_under_repair,
open_complaints=open_complaints_kpi,
pm_due_this_month=pm_due_this_month,
calibrations_due=calibrations_due,
contracts_expiring=contracts_expiring,
equipment_on_demo=equipment_on_demo,
),
complaints_by_status=complaints_by_status,
complaints_by_department=complaints_by_department,
monthly_downtime_trend=monthly_downtime_trend,
pm_planned_vs_completed=pm_planned_vs_completed,
needs_attention=needs_attention,
recent_complaints=recent_complaints,
)
+323
View File
@@ -0,0 +1,323 @@
from datetime import date
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Response, 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 effective_today
from ..models import DemoEquipment, Department, Location, User, Vendor
from ..schemas.demo_equipment import (
DemoEquipmentCreate,
DemoEquipmentListOut,
DemoEquipmentOut,
DemoEquipmentReturnIn,
DemoEquipmentUpdate,
DemoStatusFilter,
)
from ..services.attachment_service import get_attachment_counts
from ..services.audit import log_audit
from ..services.permissions import Role
from ..services.settings_service import get_setting_value
router = APIRouter(prefix="/demo-equipment", tags=["demo_equipment"])
def _to_demo_out(
item: DemoEquipment,
today: date,
alert_days: int,
att_counts: dict[int, int],
) -> DemoEquipmentOut:
if item.actual_return_date is not None:
st = "returned"
sev = "ok"
days_rem = (item.expected_return_date - item.actual_return_date).days
elif item.expected_return_date < today:
st = "overdue_return"
sev = "red"
days_rem = (item.expected_return_date - today).days
else:
st = "on_demo"
days_rem = (item.expected_return_date - today).days
sev = "yellow" if days_rem <= alert_days else "info"
return DemoEquipmentOut(
id=item.id,
name=item.name,
equipment_type=item.equipment_type,
supplier_id=item.supplier_id,
supplier_name=item.supplier.name if item.supplier else None,
department_id=item.department_id,
department_name=item.department.name if item.department else None,
location_id=item.location_id,
location_name=item.location.name if item.location else None,
start_date=item.start_date,
expected_return_date=item.expected_return_date,
actual_return_date=item.actual_return_date,
status=st,
severity=sev,
days_remaining=days_rem,
attachment_count=att_counts.get(item.id, 0),
remarks=item.remarks,
created_at=item.created_at,
)
def _load_demo(db: Session, demo_id: int) -> DemoEquipment | None:
return (
db.query(DemoEquipment)
.options(
joinedload(DemoEquipment.supplier),
joinedload(DemoEquipment.department),
joinedload(DemoEquipment.location),
)
.filter(DemoEquipment.id == demo_id)
.first()
)
@router.get("", response_model=DemoEquipmentListOut)
def list_demo_equipment(
q: str = "",
supplier_id: Optional[int] = None,
department_id: Optional[int] = None,
status_filter: Optional[DemoStatusFilter] = Query(None, alias="status"),
date_from: Optional[date] = None,
date_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)
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
query = (
db.query(DemoEquipment)
.outerjoin(Vendor, DemoEquipment.supplier_id == Vendor.id)
.options(
joinedload(DemoEquipment.supplier),
joinedload(DemoEquipment.department),
joinedload(DemoEquipment.location),
)
)
if current_user.role == Role.department_user.value:
query = query.filter(DemoEquipment.department_id == current_user.department_id)
elif department_id is not None:
query = query.filter(DemoEquipment.department_id == department_id)
if supplier_id is not None:
query = query.filter(DemoEquipment.supplier_id == supplier_id)
if date_from is not None:
query = query.filter(DemoEquipment.expected_return_date >= date_from)
if date_to is not None:
query = query.filter(DemoEquipment.expected_return_date <= date_to)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
DemoEquipment.name.ilike(like),
DemoEquipment.equipment_type.ilike(like),
Vendor.name.ilike(like),
DemoEquipment.remarks.ilike(like),
)
)
rows = query.order_by(DemoEquipment.expected_return_date.asc(), DemoEquipment.id.desc()).all()
att_counts = get_attachment_counts(db, "demo_equipment", [r.id for r in rows])
items_all = [_to_demo_out(r, today, alert_days, att_counts) for r in rows]
if status_filter is not None:
items_all = [item for item in items_all if item.status == status_filter]
total = len(items_all)
start = (page - 1) * page_size
return DemoEquipmentListOut(items=items_all[start : start + page_size], total=total)
@router.post("", response_model=DemoEquipmentOut, status_code=status.HTTP_201_CREATED)
def create_demo_equipment(
payload: DemoEquipmentCreate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
if payload.expected_return_date < payload.start_date:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="expected_return_date cannot be earlier than start_date.",
)
if not db.query(Vendor.id).filter(Vendor.id == payload.supplier_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Supplier vendor not found.")
if not db.query(Department.id).filter(Department.id == payload.department_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
if payload.location_id is not None:
if not db.query(Location.id).filter(Location.id == payload.location_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
item = DemoEquipment(
name=payload.name.strip(),
equipment_type=payload.equipment_type.strip(),
supplier_id=payload.supplier_id,
department_id=payload.department_id,
location_id=payload.location_id,
start_date=payload.start_date,
expected_return_date=payload.expected_return_date,
actual_return_date=None,
remarks=payload.remarks.strip() if payload.remarks else None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(item)
db.flush()
log_audit(
db,
entity_type="demo_equipment",
entity_id=item.id,
action="create",
changes={
"name": item.name,
"supplier_id": payload.supplier_id,
"department_id": payload.department_id,
"expected_return_date": str(payload.expected_return_date),
},
user_id=current_user.id,
)
db.commit()
loaded = _load_demo(db, item.id)
today = effective_today(db)
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
att_counts = get_attachment_counts(db, "demo_equipment", [item.id])
return _to_demo_out(loaded, today, alert_days, att_counts)
@router.patch("/{demo_id}", response_model=DemoEquipmentOut)
def update_demo_equipment(
demo_id: int,
payload: DemoEquipmentUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
item = db.query(DemoEquipment).filter(DemoEquipment.id == demo_id).first()
if item is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Demo equipment not found.")
data = payload.model_dump(exclude_unset=True)
if "supplier_id" in data and data["supplier_id"] is not None:
if not db.query(Vendor.id).filter(Vendor.id == data["supplier_id"]).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Supplier vendor not found.")
if "department_id" in data and data["department_id"] is not None:
if not db.query(Department.id).filter(Department.id == data["department_id"]).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
if "location_id" in data and data["location_id"] is not None:
if not db.query(Location.id).filter(Location.id == data["location_id"]).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
new_start = data.get("start_date", item.start_date)
new_exp = data.get("expected_return_date", item.expected_return_date)
if new_exp < new_start:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="expected_return_date cannot be earlier than start_date.",
)
changes: dict[str, dict[str, object]] = {}
for k, v in data.items():
if k in ("name", "equipment_type") and isinstance(v, str):
v = v.strip()
if not v:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"{k} cannot be blank.",
)
elif k == "remarks" and isinstance(v, str):
v = v.strip() or None
old_val = getattr(item, k)
if old_val != v:
changes[k] = {"from": old_val, "to": v}
setattr(item, k, v)
item.updated_by_id = current_user.id
if changes:
log_audit(
db,
entity_type="demo_equipment",
entity_id=item.id,
action="update",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_demo(db, item.id)
today = effective_today(db)
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
att_counts = get_attachment_counts(db, "demo_equipment", [item.id])
return _to_demo_out(loaded, today, alert_days, att_counts)
@router.delete("/{demo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_demo_equipment(
demo_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
item = db.query(DemoEquipment).filter(DemoEquipment.id == demo_id).first()
if item is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Demo equipment not found.")
log_audit(
db,
entity_type="demo_equipment",
entity_id=item.id,
action="delete",
changes={"name": item.name},
user_id=current_user.id,
)
db.delete(item)
db.commit()
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.post("/{demo_id}/return", response_model=DemoEquipmentOut)
def return_demo_equipment(
demo_id: int,
payload: DemoEquipmentReturnIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
item = db.query(DemoEquipment).filter(DemoEquipment.id == demo_id).first()
if item is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Demo equipment not found.")
if item.actual_return_date is not None:
raise CodedHTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Demo equipment has already been marked as returned.",
code="ALREADY_RETURNED",
)
item.actual_return_date = payload.actual_return_date
if payload.remarks and payload.remarks.strip():
item.remarks = payload.remarks.strip()
item.updated_by_id = current_user.id
log_audit(
db,
entity_type="demo_equipment",
entity_id=item.id,
action="return",
changes={"actual_return_date": str(payload.actual_return_date)},
user_id=current_user.id,
)
db.commit()
loaded = _load_demo(db, item.id)
today = effective_today(db)
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
att_counts = get_attachment_counts(db, "demo_equipment", [item.id])
return _to_demo_out(loaded, today, alert_days, att_counts)
+281
View File
@@ -0,0 +1,281 @@
from datetime import date
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Response, 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.time_utils import effective_today
from ..models import Asset, InsurancePolicy, User, Vendor
from ..schemas.insurance import (
InsuranceCreate,
InsuranceListOut,
InsuranceOut,
InsuranceStatusFilter,
InsuranceUpdate,
)
from ..services.attachment_service import get_attachment_counts
from ..services.audit import log_audit
from ..services.calculations import coverage_status
from ..services.permissions import Role
from ..services.settings_service import get_setting_value
router = APIRouter(prefix="/insurance", tags=["insurance"])
def _insurance_lead_settings(db: Session) -> tuple[int, int]:
lead = int(
get_setting_value(
db,
"insurance_lead_days",
get_setting_value(db, "insurance_expiry_alert_days", 30),
)
)
red = int(get_setting_value(db, "red_threshold_days", 7))
return lead, red
def _to_insurance_out(
pol: InsurancePolicy,
today: date,
lead_days: int,
red_days: int,
att_counts: dict[int, int],
) -> InsuranceOut:
asset = pol.asset
st, sev = coverage_status(pol.start_date, pol.end_date, today, lead_days, red_days)
return InsuranceOut(
id=pol.id,
asset_id=pol.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,
insurer_id=pol.insurer_id,
insurer_name=pol.insurer.name if pol.insurer else None,
policy_no=pol.policy_no,
start_date=pol.start_date,
end_date=pol.end_date,
coverage_amount=pol.coverage_amount,
status=st,
severity=sev,
days_to_expiry=(pol.end_date - today).days,
attachment_count=att_counts.get(pol.id, 0),
remarks=pol.remarks,
created_at=pol.created_at,
)
def _load_insurance(db: Session, policy_id: int) -> InsurancePolicy | None:
return (
db.query(InsurancePolicy)
.options(
joinedload(InsurancePolicy.asset).joinedload(Asset.department),
joinedload(InsurancePolicy.insurer),
)
.filter(InsurancePolicy.id == policy_id)
.first()
)
@router.get("", response_model=InsuranceListOut)
def list_insurance_policies(
q: str = "",
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
insurer_id: Optional[int] = None,
status_filter: Optional[InsuranceStatusFilter] = 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)
lead_days, red_days = _insurance_lead_settings(db)
query = (
db.query(InsurancePolicy)
.join(Asset, InsurancePolicy.asset_id == Asset.id)
.outerjoin(Vendor, InsurancePolicy.insurer_id == Vendor.id)
.options(
joinedload(InsurancePolicy.asset).joinedload(Asset.department),
joinedload(InsurancePolicy.insurer),
)
)
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(InsurancePolicy.asset_id == asset_id)
if insurer_id is not None:
query = query.filter(InsurancePolicy.insurer_id == insurer_id)
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),
InsurancePolicy.policy_no.ilike(like),
InsurancePolicy.remarks.ilike(like),
)
)
rows = query.order_by(InsurancePolicy.end_date.asc(), InsurancePolicy.id.desc()).all()
att_counts = get_attachment_counts(db, "insurance", [r.id for r in rows])
items_all = [_to_insurance_out(r, today, lead_days, red_days, att_counts) for r in rows]
if status_filter is not None:
items_all = [item for item in items_all if item.status == status_filter]
total = len(items_all)
start = (page - 1) * page_size
return InsuranceListOut(items=items_all[start : start + page_size], total=total)
@router.post("", response_model=InsuranceOut, status_code=status.HTTP_201_CREATED)
def create_insurance_policy(
payload: InsuranceCreate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
if payload.end_date < payload.start_date:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="end_date cannot be earlier than start_date.",
)
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.")
if not db.query(Vendor.id).filter(Vendor.id == payload.insurer_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurer vendor not found.")
clean_policy_no = payload.policy_no.strip()
if not clean_policy_no:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="policy_no cannot be blank.",
)
asset.insurance_applicable = True
pol = InsurancePolicy(
asset_id=payload.asset_id,
insurer_id=payload.insurer_id,
policy_no=clean_policy_no,
start_date=payload.start_date,
end_date=payload.end_date,
coverage_amount=payload.coverage_amount,
remarks=payload.remarks.strip() if payload.remarks else None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(pol)
db.flush()
log_audit(
db,
entity_type="insurance",
entity_id=pol.id,
action="create",
changes={
"asset_id": payload.asset_id,
"insurer_id": payload.insurer_id,
"policy_no": clean_policy_no,
"start_date": str(payload.start_date),
"end_date": str(payload.end_date),
},
user_id=current_user.id,
)
db.commit()
loaded = _load_insurance(db, pol.id)
today = effective_today(db)
lead_days, red_days = _insurance_lead_settings(db)
att_counts = get_attachment_counts(db, "insurance", [pol.id])
return _to_insurance_out(loaded, today, lead_days, red_days, att_counts)
@router.patch("/{policy_id}", response_model=InsuranceOut)
def update_insurance_policy(
policy_id: int,
payload: InsuranceUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
pol = db.query(InsurancePolicy).filter(InsurancePolicy.id == policy_id).first()
if pol is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurance policy not found.")
data = payload.model_dump(exclude_unset=True)
if "insurer_id" in data and data["insurer_id"] is not None:
if not db.query(Vendor.id).filter(Vendor.id == data["insurer_id"]).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurer vendor not found.")
if "policy_no" in data and data["policy_no"] is not None:
clean_no = data["policy_no"].strip()
if not clean_no:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="policy_no cannot be blank.",
)
data["policy_no"] = clean_no
new_start = data.get("start_date", pol.start_date)
new_end = data.get("end_date", pol.end_date)
if new_end < new_start:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="end_date cannot be earlier than start_date.",
)
changes: dict[str, dict[str, object]] = {}
for k, v in data.items():
if k == "remarks" and isinstance(v, str):
v = v.strip() or None
old_val = getattr(pol, k)
if old_val != v:
changes[k] = {"from": old_val, "to": v}
setattr(pol, k, v)
pol.updated_by_id = current_user.id
if changes:
log_audit(
db,
entity_type="insurance",
entity_id=pol.id,
action="update",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_insurance(db, pol.id)
today = effective_today(db)
lead_days, red_days = _insurance_lead_settings(db)
att_counts = get_attachment_counts(db, "insurance", [pol.id])
return _to_insurance_out(loaded, today, lead_days, red_days, att_counts)
@router.delete("/{policy_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_insurance_policy(
policy_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
pol = db.query(InsurancePolicy).filter(InsurancePolicy.id == policy_id).first()
if pol is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurance policy not found.")
log_audit(
db,
entity_type="insurance",
entity_id=pol.id,
action="delete",
changes={"asset_id": pol.asset_id, "policy_no": pol.policy_no},
user_id=current_user.id,
)
db.delete(pol)
db.commit()
return Response(status_code=status.HTTP_204_NO_CONTENT)
+150
View File
@@ -0,0 +1,150 @@
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from ..core.db import get_db
from ..core.deps import get_current_user, require_roles
from ..core.time_utils import utc_now
from ..models import Notification, NotificationRead, User
from ..schemas.notifications import (
AlertRunOut,
NotificationListOut,
NotificationOut,
NotificationReadAllOut,
NotificationReadOut,
)
from ..services.alerts import (
get_visible_notifications_for_user,
notification_link_url,
run_alert_check,
)
from ..services.permissions import Role
router = APIRouter(tags=["notifications"])
@router.post("/alerts/run", response_model=AlertRunOut)
def trigger_alert_run(
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
result = run_alert_check(db)
db.commit()
return AlertRunOut(**result)
@router.get("/notifications", response_model=NotificationListOut)
def list_notifications(
notif_type: Optional[str] = Query(None, alias="type"),
severity: Optional[str] = None,
unread_only: bool = False,
limit: Optional[int] = Query(None, ge=1, le=200),
page: int = Query(1, ge=1),
page_size: int = Query(50, ge=1, le=200),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
visible, read_map = get_visible_notifications_for_user(db, current_user)
unread_count = sum(1 for n in visible if n.id not in read_map)
unread_calibration_count = sum(
1 for n in visible if n.id not in read_map and n.type == "calibration_due"
)
filtered: list[Notification] = []
for n in visible:
is_read = n.id in read_map
if notif_type and n.type != notif_type:
continue
if severity and n.severity != severity:
continue
if unread_only and is_read:
continue
filtered.append(n)
total = len(filtered)
eff_size = limit if limit is not None else page_size
start = (page - 1) * eff_size
page_items = filtered[start : start + eff_size]
items_out = [
NotificationOut(
id=n.id,
type=n.type,
severity=n.severity,
title=n.title,
message=n.message,
entity_type=n.entity_type,
entity_id=n.entity_id,
due_date=n.due_date,
link_url=notification_link_url(n.entity_type, n.entity_id),
is_read=n.id in read_map,
read_at=read_map.get(n.id),
created_at=n.created_at,
)
for n in page_items
]
return NotificationListOut(
items=items_out,
total=total,
unread_count=unread_count,
unread_calibration_count=unread_calibration_count,
)
@router.post("/notifications/read-all", response_model=NotificationReadAllOut)
def mark_all_notifications_read(
notif_type: Optional[str] = Query(None, alias="type"),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
visible, read_map = get_visible_notifications_for_user(db, current_user)
now = utc_now()
marked = 0
for n in visible:
if n.id in read_map:
continue
if notif_type and n.type != notif_type:
continue
db.add(
NotificationRead(
notification_id=n.id,
user_id=current_user.id,
read_at=now,
)
)
marked += 1
if marked:
db.commit()
return NotificationReadAllOut(marked_read=marked)
@router.post("/notifications/{notification_id}/read", response_model=NotificationReadOut)
def mark_notification_read(
notification_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
notif = db.query(Notification).filter(Notification.id == notification_id).first()
if notif is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Notification not found.")
visible, read_map = get_visible_notifications_for_user(db, current_user)
if all(n.id != notification_id for n in visible):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access denied for this notification.",
)
if notification_id not in read_map:
db.add(
NotificationRead(
notification_id=notification_id,
user_id=current_user.id,
read_at=utc_now(),
)
)
db.commit()
return NotificationReadOut(notification_id=notification_id, is_read=True)
+627
View File
@@ -0,0 +1,627 @@
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.")
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=mode,
responsible_team=payload.responsible_team,
provider_id=payload.provider_id,
contract_id=payload.contract_id,
)
schedule = PMSchedule(
asset_id=asset.id,
service_mode=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": 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),
)
+87
View File
@@ -0,0 +1,87 @@
from datetime import date
from typing import Any, Literal
from fastapi import APIRouter, Depends, Query
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
from ..core.db import get_db
from ..core.deps import get_current_user
from ..models import User
from ..services.exports import build_csv, build_xlsx
from ..services.reports_service import generate_report
router = APIRouter(prefix="/reports", tags=["reports"])
def _report_params(
month: str | None = Query(None),
date_from: date | None = Query(None),
date_to: date | None = Query(None),
due_from: date | None = Query(None),
due_to: date | None = Query(None),
department_id: int | None = Query(None),
asset_id: int | None = Query(None),
priority: str | None = Query(None),
call_status: str | None = Query(None),
assigned_to_id: int | None = Query(None),
service_mode: str | None = Query(None),
agency_id: int | None = Query(None),
status: str | None = Query(None),
record_kind: str | None = Query(None),
contract_type: str | None = Query(None),
supplier_id: int | None = Query(None),
) -> dict[str, Any]:
return {
"month": month,
"date_from": date_from,
"date_to": date_to,
"due_from": due_from,
"due_to": due_to,
"department_id": department_id,
"asset_id": asset_id,
"priority": priority,
"call_status": call_status,
"assigned_to_id": assigned_to_id,
"service_mode": service_mode,
"agency_id": agency_id,
"status": status,
"record_kind": record_kind,
"contract_type": contract_type,
"supplier_id": supplier_id,
}
@router.get("/{report_key}")
def get_report(
report_key: str,
params: dict[str, Any] = Depends(_report_params),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
return generate_report(db, current_user, report_key, params)
@router.get("/{report_key}/export")
def export_report(
report_key: str,
format: Literal["xlsx", "csv"] = Query("xlsx"),
params: dict[str, Any] = Depends(_report_params),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
payload = generate_report(db, current_user, report_key, params)
if format == "csv":
buf = build_csv(payload)
media_type = "text/csv; charset=utf-8"
else:
buf = build_xlsx(payload)
media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
return StreamingResponse(
buf,
media_type=media_type,
headers={
"Content-Disposition": f'attachment; filename="{report_key}.{format}"',
},
)
+84
View File
@@ -0,0 +1,84 @@
from fastapi import APIRouter, Depends, Query
from sqlalchemy import or_
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user
from ..models import Asset, Complaint, User
from ..services.permissions import Role
router = APIRouter(prefix="/search", tags=["search"])
@router.get("")
def global_search(
q: str = Query(..., min_length=1),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
term = q.strip()
if not term:
return {"assets": [], "complaints": []}
pattern = f"%{term}%"
is_dept_scoped = current_user.role == Role.department_user.value
asset_q = db.query(Asset).options(joinedload(Asset.department)).filter(
or_(
Asset.asset_code.ilike(pattern),
Asset.name.ilike(pattern),
Asset.serial_no.ilike(pattern),
)
)
if is_dept_scoped:
asset_q = asset_q.filter(Asset.department_id == current_user.department_id)
assets = asset_q.order_by(Asset.asset_code.asc()).limit(8).all()
complaint_q = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.options(joinedload(Complaint.asset).joinedload(Asset.department))
.filter(
or_(
Complaint.complaint_no.ilike(pattern),
Complaint.description.ilike(pattern),
Asset.asset_code.ilike(pattern),
Asset.name.ilike(pattern),
)
)
)
if is_dept_scoped:
complaint_q = complaint_q.filter(Asset.department_id == current_user.department_id)
complaints = (
complaint_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc())
.limit(8)
.all()
)
return {
"assets": [
{
"id": a.id,
"asset_code": a.asset_code,
"name": a.name,
"serial_no": a.serial_no,
"department_name": a.department.name if a.department else "—",
"status": a.status,
}
for a in assets
],
"complaints": [
{
"id": c.id,
"complaint_no": c.complaint_no,
"asset_code": c.asset.asset_code if c.asset else "—",
"asset_name": c.asset.name if c.asset else "—",
"department_name": (
c.asset.department.name if c.asset and c.asset.department else "—"
),
"call_status": c.call_status,
"priority": c.priority,
}
for c in complaints
],
}
+2 -2
View File
@@ -57,7 +57,7 @@ def list_users(
return {"items": [_user_list_out(u) for u in items], "total": total}
@router.get("/lookup", response_model=list[UserLookupOut])
@router.get("/lookup", response_model=PaginatedOut[UserLookupOut])
def lookup_users(
db: Session = Depends(get_db),
_: User = Depends(get_current_user),
@@ -68,7 +68,7 @@ def lookup_users(
.order_by(User.name.asc())
.all()
)
return users
return {"items": users, "total": len(users)}
@router.post("", response_model=UserListOut, status_code=status.HTTP_201_CREATED)
+339
View File
@@ -0,0 +1,339 @@
from datetime import date
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy import or_
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import require_roles
from ..models import Asset, Complaint, Department, DepartmentVisit, User
from ..schemas.visits import (
VisitAssetSummary,
VisitComplaintSummary,
VisitCreate,
VisitLinkComplaintIn,
VisitListOut,
VisitOut,
VisitUpdate,
)
from ..services.audit import log_audit
from ..services.permissions import Role
router = APIRouter(prefix="/visits", tags=["visits"])
def _to_visit_out(v: DepartmentVisit) -> VisitOut:
return VisitOut(
id=v.id,
department_id=v.department_id,
department_name=v.department.name if v.department else None,
visited_by_id=v.visited_by_id,
visited_by_name=v.visited_by.name if v.visited_by else None,
visit_date=v.visit_date,
observations=v.observations,
assets=[
VisitAssetSummary(id=a.id, asset_code=a.asset_code, name=a.name)
for a in v.assets
],
complaints=[
VisitComplaintSummary(
id=c.id,
complaint_no=c.complaint_no,
call_status=c.call_status,
priority=c.priority,
description=c.description,
)
for c in v.complaints
],
created_at=v.created_at,
)
def _load_visit(db: Session, visit_id: int) -> DepartmentVisit | None:
return (
db.query(DepartmentVisit)
.options(
joinedload(DepartmentVisit.department),
joinedload(DepartmentVisit.visited_by),
joinedload(DepartmentVisit.assets),
joinedload(DepartmentVisit.complaints),
)
.filter(DepartmentVisit.id == visit_id)
.first()
)
def _resolve_assets_and_complaints(
db: Session,
asset_ids: list[int] | None,
complaint_ids: list[int] | None,
) -> tuple[list[Asset] | None, list[Complaint] | None]:
assets_list: list[Asset] | None = None
complaints_list: list[Complaint] | None = None
if asset_ids is not None:
unique_aids = list(dict.fromkeys(asset_ids))
if unique_aids:
found_assets = db.query(Asset).filter(Asset.id.in_(unique_aids)).all()
by_id = {a.id: a for a in found_assets}
missing = [aid for aid in unique_aids if aid not in by_id]
if missing:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Assets not found: {missing}",
)
assets_list = [by_id[aid] for aid in unique_aids]
else:
assets_list = []
if complaint_ids is not None:
unique_cids = list(dict.fromkeys(complaint_ids))
if unique_cids:
found_cmps = db.query(Complaint).filter(Complaint.id.in_(unique_cids)).all()
by_id = {c.id: c for c in found_cmps}
missing = [cid for cid in unique_cids if cid not in by_id]
if missing:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Complaints not found: {missing}",
)
complaints_list = [by_id[cid] for cid in unique_cids]
else:
complaints_list = []
return assets_list, complaints_list
@router.get("", response_model=VisitListOut)
def list_visits(
q: str = "",
department_id: Optional[int] = None,
visited_by_id: Optional[int] = None,
date_from: Optional[date] = None,
date_to: Optional[date] = None,
page: int = Query(1, ge=1),
page_size: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.management)),
):
query = (
db.query(DepartmentVisit)
.join(Department, DepartmentVisit.department_id == Department.id)
.join(User, DepartmentVisit.visited_by_id == User.id)
.options(
joinedload(DepartmentVisit.department),
joinedload(DepartmentVisit.visited_by),
joinedload(DepartmentVisit.assets),
joinedload(DepartmentVisit.complaints),
)
)
if department_id is not None:
query = query.filter(DepartmentVisit.department_id == department_id)
if visited_by_id is not None:
query = query.filter(DepartmentVisit.visited_by_id == visited_by_id)
if date_from is not None:
query = query.filter(DepartmentVisit.visit_date >= date_from)
if date_to is not None:
query = query.filter(DepartmentVisit.visit_date <= date_to)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
DepartmentVisit.observations.ilike(like),
Department.name.ilike(like),
User.name.ilike(like),
)
)
total = query.count()
rows = (
query.order_by(DepartmentVisit.visit_date.desc(), DepartmentVisit.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return VisitListOut(items=[_to_visit_out(r) for r in rows], total=total)
@router.get("/{visit_id}", response_model=VisitOut)
def get_visit(
visit_id: int,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.management)),
):
visit = _load_visit(db, visit_id)
if visit is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
return _to_visit_out(visit)
@router.post("", response_model=VisitOut, status_code=status.HTTP_201_CREATED)
def create_visit(
payload: VisitCreate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
if not db.query(Department.id).filter(Department.id == payload.department_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
clean_obs = payload.observations.strip()
if not clean_obs:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="observations cannot be blank.",
)
visited_by_id = current_user.id
if current_user.role == Role.system_admin.value and payload.visited_by_id is not None:
if not db.query(User.id).filter(User.id == payload.visited_by_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visited-by user not found.")
visited_by_id = payload.visited_by_id
assets_list, complaints_list = _resolve_assets_and_complaints(
db, payload.asset_ids, payload.complaint_ids
)
visit = DepartmentVisit(
department_id=payload.department_id,
visited_by_id=visited_by_id,
visit_date=payload.visit_date,
observations=clean_obs,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
if assets_list is not None:
visit.assets = assets_list
if complaints_list is not None:
visit.complaints = complaints_list
db.add(visit)
db.flush()
log_audit(
db,
entity_type="department_visit",
entity_id=visit.id,
action="create",
changes={
"department_id": payload.department_id,
"visit_date": str(payload.visit_date),
"asset_ids": [a.id for a in visit.assets],
"complaint_ids": [c.id for c in visit.complaints],
},
user_id=current_user.id,
)
db.commit()
loaded = _load_visit(db, visit.id)
return _to_visit_out(loaded)
@router.patch("/{visit_id}", response_model=VisitOut)
def update_visit(
visit_id: int,
payload: VisitUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
visit = _load_visit(db, visit_id)
if visit is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
data = payload.model_dump(exclude_unset=True)
if "department_id" in data and data["department_id"] is not None:
if not db.query(Department.id).filter(Department.id == data["department_id"]).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
visit.department_id = data["department_id"]
if "visit_date" in data and data["visit_date"] is not None:
visit.visit_date = data["visit_date"]
if "observations" in data and data["observations"] is not None:
clean_obs = data["observations"].strip()
if not clean_obs:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="observations cannot be blank.",
)
visit.observations = clean_obs
assets_list, complaints_list = _resolve_assets_and_complaints(
db,
data["asset_ids"] if "asset_ids" in data else None,
data["complaint_ids"] if "complaint_ids" in data else None,
)
if assets_list is not None:
visit.assets = assets_list
if complaints_list is not None:
visit.complaints = complaints_list
visit.updated_by_id = current_user.id
log_audit(
db,
entity_type="department_visit",
entity_id=visit.id,
action="update",
changes={"updated_fields": list(data.keys())},
user_id=current_user.id,
)
db.commit()
loaded = _load_visit(db, visit.id)
return _to_visit_out(loaded)
@router.delete("/{visit_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_visit(
visit_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
visit = _load_visit(db, visit_id)
if visit is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
visit.assets = []
visit.complaints = []
db.flush()
log_audit(
db,
entity_type="department_visit",
entity_id=visit.id,
action="delete",
changes={"department_id": visit.department_id, "visit_date": str(visit.visit_date)},
user_id=current_user.id,
)
db.delete(visit)
db.commit()
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.post("/{visit_id}/link-complaint", response_model=VisitOut)
def link_complaint_to_visit(
visit_id: int,
payload: VisitLinkComplaintIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
visit = _load_visit(db, visit_id)
if visit is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
complaint = db.query(Complaint).filter(Complaint.id == payload.complaint_id).first()
if complaint is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Complaint not found.")
if all(c.id != complaint.id for c in visit.complaints):
visit.complaints.append(complaint)
visit.updated_by_id = current_user.id
log_audit(
db,
entity_type="department_visit",
entity_id=visit.id,
action="link_complaint",
changes={"complaint_id": complaint.id, "complaint_no": complaint.complaint_no},
user_id=current_user.id,
)
db.commit()
loaded = _load_visit(db, visit.id)
return _to_visit_out(loaded)
+268
View File
@@ -0,0 +1,268 @@
from datetime import date
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Response, 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.time_utils import add_months, effective_today
from ..models import Asset, User, Vendor, Warranty
from ..schemas.warranties import (
CoverageStatusFilter,
WarrantyCreate,
WarrantyListOut,
WarrantyOut,
WarrantyUpdate,
)
from ..services.attachment_service import get_attachment_counts
from ..services.audit import log_audit
from ..services.calculations import coverage_status
from ..services.permissions import Role
from ..services.settings_service import get_setting_value
router = APIRouter(prefix="/warranties", tags=["warranties"])
def _warranty_lead_settings(db: Session) -> tuple[int, int]:
lead = int(
get_setting_value(
db,
"warranty_lead_days",
get_setting_value(db, "warranty_expiry_alert_days", 30),
)
)
red = int(get_setting_value(db, "red_threshold_days", 7))
return lead, red
def _to_warranty_out(
w: Warranty,
today: date,
lead_days: int,
red_days: int,
att_counts: dict[int, int],
) -> WarrantyOut:
asset = w.asset
st, sev = coverage_status(w.start_date, w.end_date, today, lead_days, red_days)
return WarrantyOut(
id=w.id,
asset_id=w.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,
duration_months=w.duration_months,
start_date=w.start_date,
end_date=w.end_date,
provider_id=w.provider_id,
provider_name=w.provider.name if w.provider else None,
status=st,
severity=sev,
days_to_expiry=(w.end_date - today).days,
attachment_count=att_counts.get(w.id, 0),
remarks=w.remarks,
created_at=w.created_at,
)
def _load_warranty(db: Session, warranty_id: int) -> Warranty | None:
return (
db.query(Warranty)
.options(
joinedload(Warranty.asset).joinedload(Asset.department),
joinedload(Warranty.provider),
)
.filter(Warranty.id == warranty_id)
.first()
)
@router.get("", response_model=WarrantyListOut)
def list_warranties(
q: str = "",
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
status_filter: Optional[CoverageStatusFilter] = 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)
lead_days, red_days = _warranty_lead_settings(db)
query = (
db.query(Warranty)
.join(Asset, Warranty.asset_id == Asset.id)
.outerjoin(Vendor, Warranty.provider_id == Vendor.id)
.options(
joinedload(Warranty.asset).joinedload(Asset.department),
joinedload(Warranty.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(Warranty.asset_id == asset_id)
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),
Warranty.remarks.ilike(like),
)
)
rows = query.order_by(Warranty.end_date.asc(), Warranty.id.desc()).all()
att_counts = get_attachment_counts(db, "warranty", [r.id for r in rows])
items_all = [_to_warranty_out(r, today, lead_days, red_days, att_counts) for r in rows]
if status_filter is not None:
items_all = [item for item in items_all if item.status == status_filter]
total = len(items_all)
start = (page - 1) * page_size
return WarrantyListOut(items=items_all[start : start + page_size], total=total)
@router.post("", response_model=WarrantyOut, status_code=status.HTTP_201_CREATED)
def create_warranty(
payload: WarrantyCreate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
if not db.query(Asset.id).filter(Asset.id == payload.asset_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
if payload.provider_id is not None:
if not db.query(Vendor.id).filter(Vendor.id == payload.provider_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
computed_end = payload.end_date or add_months(payload.start_date, payload.duration_months)
if computed_end < payload.start_date:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="end_date cannot be earlier than start_date.",
)
warranty = Warranty(
asset_id=payload.asset_id,
duration_months=payload.duration_months,
start_date=payload.start_date,
end_date=computed_end,
provider_id=payload.provider_id,
remarks=payload.remarks.strip() if payload.remarks else None,
created_by_id=current_user.id,
updated_by_id=current_user.id,
)
db.add(warranty)
db.flush()
log_audit(
db,
entity_type="warranty",
entity_id=warranty.id,
action="create",
changes={
"asset_id": payload.asset_id,
"duration_months": payload.duration_months,
"start_date": str(payload.start_date),
"end_date": str(computed_end),
},
user_id=current_user.id,
)
db.commit()
loaded = _load_warranty(db, warranty.id)
today = effective_today(db)
lead_days, red_days = _warranty_lead_settings(db)
att_counts = get_attachment_counts(db, "warranty", [warranty.id])
return _to_warranty_out(loaded, today, lead_days, red_days, att_counts)
@router.patch("/{warranty_id}", response_model=WarrantyOut)
def update_warranty(
warranty_id: int,
payload: WarrantyUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
warranty = db.query(Warranty).filter(Warranty.id == warranty_id).first()
if warranty is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Warranty not found.")
data = payload.model_dump(exclude_unset=True)
if "provider_id" in data and data["provider_id"] is not None:
if not db.query(Vendor.id).filter(Vendor.id == data["provider_id"]).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
new_start = data.get("start_date", warranty.start_date)
new_duration = data.get("duration_months", warranty.duration_months)
if "end_date" in data and data["end_date"] is not None:
new_end = data["end_date"]
elif "start_date" in data or "duration_months" in data:
new_end = add_months(new_start, new_duration)
data["end_date"] = new_end
else:
new_end = warranty.end_date
if new_end < new_start:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="end_date cannot be earlier than start_date.",
)
changes: dict[str, dict[str, object]] = {}
for k, v in data.items():
if isinstance(v, str):
v = v.strip() or None
old_val = getattr(warranty, k)
if old_val != v:
changes[k] = {"from": old_val, "to": v}
setattr(warranty, k, v)
warranty.updated_by_id = current_user.id
if changes:
log_audit(
db,
entity_type="warranty",
entity_id=warranty.id,
action="update",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_warranty(db, warranty.id)
today = effective_today(db)
lead_days, red_days = _warranty_lead_settings(db)
att_counts = get_attachment_counts(db, "warranty", [warranty.id])
return _to_warranty_out(loaded, today, lead_days, red_days, att_counts)
@router.delete("/{warranty_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_warranty(
warranty_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
):
warranty = db.query(Warranty).filter(Warranty.id == warranty_id).first()
if warranty is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Warranty not found.")
log_audit(
db,
entity_type="warranty",
entity_id=warranty.id,
action="delete",
changes={"asset_id": warranty.asset_id},
user_id=current_user.id,
)
db.delete(warranty)
db.commit()
return Response(status_code=status.HTTP_204_NO_CONTENT)
+83
View File
@@ -9,6 +9,60 @@ from .assets import (
)
from .attachments import AttachmentListOut, AttachmentOut
from .auth import LoginRequest, TokenResponse, UserOut
from .calibration import (
CalibrationPlanApproveIn,
CalibrationPlanBulkCreateIn,
CalibrationPlanBulkOut,
CalibrationPlanCreateFromAsset,
CalibrationPlanListOut,
CalibrationPlanOut,
CalibrationPlanUpdateIn,
CalibrationRecordCompleteIn,
CalibrationRecordCompleteOut,
CalibrationRecordListOut,
CalibrationRecordOut,
)
from .complaints import (
ComplaintAssignIn,
ComplaintAttendIn,
ComplaintCloseIn,
ComplaintCorrectTimestampIn,
ComplaintCreate,
ComplaintEventListOut,
ComplaintEventOut,
ComplaintListOut,
ComplaintOut,
ComplaintReopenIn,
ComplaintRestoreIn,
ComplaintUpdate,
)
from .contracts import (
ContractCreate,
ContractHistoryOut,
ContractListOut,
ContractOut,
ContractRenewIn,
ContractRenewOut,
ContractUpdate,
)
from .dashboard import (
ComplaintsByDepartmentItem,
ComplaintsByStatusItem,
DashboardKPIs,
DashboardSummaryOut,
MonthlyDowntimeItem,
MonthlyPMComparisonItem,
NeedsAttentionItem,
RecentComplaintItem,
)
from .demo_equipment import (
DemoEquipmentCreate,
DemoEquipmentListOut,
DemoEquipmentOut,
DemoEquipmentReturnIn,
DemoEquipmentUpdate,
)
from .insurance import InsuranceCreate, InsuranceListOut, InsuranceOut, InsuranceUpdate
from .masters import (
CategoryCreate,
CategoryOut,
@@ -28,7 +82,36 @@ from .masters import (
VendorOut,
VendorUpdate,
)
from .notifications import (
AlertRunOut,
NotificationListOut,
NotificationOut,
NotificationReadAllOut,
NotificationReadOut,
)
from .pm import (
PMRecordCompleteIn,
PMRecordCompleteOut,
PMRecordListOut,
PMRecordOut,
PMRecordRescheduleIn,
PMRecordRescheduleOut,
PMScheduleCreate,
PMScheduleListOut,
PMScheduleOut,
PMScheduleUpdate,
)
from .settings import DemoDateIn, DemoDateOut, SettingItemOut, SettingsListOut, SettingsUpdateIn
from .visits import (
VisitAssetSummary,
VisitComplaintSummary,
VisitCreate,
VisitLinkComplaintIn,
VisitListOut,
VisitOut,
VisitUpdate,
)
from .warranties import WarrantyCreate, WarrantyListOut, WarrantyOut, WarrantyUpdate
__all__ = [
"AssetCreate",
+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
+149
View File
@@ -0,0 +1,149 @@
from datetime import datetime
from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
ComplaintPriority = Literal["critical", "non_critical"]
TimestampField = Literal[
"registered_at",
"received_at",
"attended_at",
"restored_at",
"closed_at",
"ce_attended_at",
]
class ComplaintCreate(BaseModel):
asset_id: int
description: str = Field(..., min_length=1)
breakdown_details: Optional[str] = None
priority: ComplaintPriority = "non_critical"
notes: Optional[str] = None
received_by_id: Optional[int] = None
received_at: Optional[datetime] = None
class ComplaintUpdate(BaseModel):
description: Optional[str] = Field(None, min_length=1)
breakdown_details: Optional[str] = None
priority: Optional[ComplaintPriority] = None
notes: Optional[str] = None
closure_remarks: Optional[str] = None
# Restricted technical fields (system_admin / biomedical only)
action_taken: Optional[str] = None
root_cause: Optional[str] = None
corrective_action: Optional[str] = None
lessons_learned: Optional[str] = None
ce_name: Optional[str] = None
ce_attended_at: Optional[datetime] = None
ce_action_taken: Optional[str] = None
spare_required: Optional[bool] = None
spare_details: Optional[str] = None
spare_cost_estimate: Optional[float] = Field(None, ge=0)
class ComplaintAssignIn(BaseModel):
assigned_to_id: int
note: Optional[str] = None
class ComplaintAttendIn(BaseModel):
attended_by_id: Optional[int] = None
note: Optional[str] = None
class ComplaintRestoreIn(BaseModel):
note: Optional[str] = None
class ComplaintCloseIn(BaseModel):
closure_remarks: Optional[str] = None
class ComplaintReopenIn(BaseModel):
reason: str = Field(..., min_length=3)
class ComplaintCorrectTimestampIn(BaseModel):
field: TimestampField
new_value: datetime
reason: str = Field(..., min_length=3)
class ComplaintOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
complaint_no: str
asset_id: int
asset_code: str
asset_name: str
asset_status: str
department_id: int
department_name: Optional[str] = None
location_name: Optional[str] = None
description: str
breakdown_details: Optional[str] = None
priority: str
notes: Optional[str] = None
registered_at: datetime
registered_by_id: int
registered_by_name: Optional[str] = None
received_by_id: int
received_by_name: Optional[str] = None
received_at: Optional[datetime] = None
assigned_to_id: Optional[int] = None
assigned_to_name: Optional[str] = None
assigned_at: Optional[datetime] = None
attended_by_id: Optional[int] = None
attended_by_name: Optional[str] = None
attended_at: Optional[datetime] = None
restored_at: Optional[datetime] = None
closed_by_id: Optional[int] = None
closed_by_name: Optional[str] = None
closed_at: Optional[datetime] = None
call_status: str
closure_remarks: Optional[str] = None
action_taken: Optional[str] = None
root_cause: Optional[str] = None
corrective_action: Optional[str] = None
lessons_learned: Optional[str] = None
ce_name: Optional[str] = None
ce_attended_at: Optional[datetime] = None
ce_action_taken: Optional[str] = None
spare_required: bool
spare_details: Optional[str] = None
spare_cost_estimate: Optional[float] = None
response_time_minutes: Optional[int] = None
downtime_minutes: int
downtime_is_ongoing: bool
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
class ComplaintListOut(BaseModel):
items: list[ComplaintOut]
total: int
class ComplaintEventOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
complaint_id: int
event_type: str
from_value: Optional[str] = None
to_value: Optional[str] = None
by_user_id: int
by_user_name: Optional[str] = None
at: datetime
note: Optional[str] = None
class ComplaintEventListOut(BaseModel):
items: list[ComplaintEventOut]
total: int
+74
View File
@@ -0,0 +1,74 @@
from datetime import date, datetime
from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
ContractType = Literal["AMC", "CMC", "OTHER"]
ContractStatusFilter = Literal["active", "expiring", "expired", "superseded"]
class ContractCreate(BaseModel):
asset_id: int
contract_type: ContractType
provider_id: int
start_date: date
end_date: date
coverage_period_text: Optional[str] = None
remarks: Optional[str] = None
class ContractUpdate(BaseModel):
contract_type: Optional[ContractType] = None
provider_id: Optional[int] = None
start_date: Optional[date] = None
end_date: Optional[date] = None
coverage_period_text: Optional[str] = None
is_superseded: Optional[bool] = None
remarks: Optional[str] = None
class ContractRenewIn(BaseModel):
contract_type: Optional[ContractType] = None
provider_id: Optional[int] = None
start_date: date
end_date: date
coverage_period_text: Optional[str] = None
remarks: Optional[str] = None
class ContractOut(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
contract_type: str
provider_id: int
provider_name: Optional[str] = None
start_date: date
end_date: date
coverage_period_text: Optional[str] = None
renewed_from_id: Optional[int] = None
is_superseded: bool
status: str
severity: str
days_to_expiry: int
attachment_count: int = 0
remarks: Optional[str] = None
created_at: datetime
class ContractListOut(BaseModel):
items: list[ContractOut]
total: int
class ContractRenewOut(BaseModel):
old_contract: ContractOut
new_contract: ContractOut
class ContractHistoryOut(BaseModel):
items: list[ContractOut]
+75
View File
@@ -0,0 +1,75 @@
from datetime import date, datetime
from typing import Optional
from pydantic import BaseModel
class DashboardKPIs(BaseModel):
total_assets: int
assets_under_repair: int
open_complaints: int
pm_due_this_month: int
calibrations_due: int
contracts_expiring: int
equipment_on_demo: int
class ComplaintsByStatusItem(BaseModel):
status: str
count: int
class ComplaintsByDepartmentItem(BaseModel):
department: str
critical: int
non_critical: int
class MonthlyDowntimeItem(BaseModel):
month: str
label: str
downtime_minutes: int
downtime_hours: float
class MonthlyPMComparisonItem(BaseModel):
month: str
label: str
planned: int
completed: int
class NeedsAttentionItem(BaseModel):
id: int
type: str
severity: str
title: str
message: str
entity_type: str
entity_id: int
due_date: Optional[date] = None
link_url: str
class RecentComplaintItem(BaseModel):
id: int
complaint_no: str
asset_code: str
asset_name: str
department_name: Optional[str] = None
priority: str
call_status: str
registered_at: datetime
downtime_minutes: int
downtime_is_ongoing: bool
class DashboardSummaryOut(BaseModel):
department_scope: Optional[str] = None
effective_today: date
kpis: DashboardKPIs
complaints_by_status: list[ComplaintsByStatusItem]
complaints_by_department: list[ComplaintsByDepartmentItem]
monthly_downtime_trend: list[MonthlyDowntimeItem]
pm_planned_vs_completed: list[MonthlyPMComparisonItem]
needs_attention: list[NeedsAttentionItem]
recent_complaints: list[RecentComplaintItem]
+61
View File
@@ -0,0 +1,61 @@
from datetime import date, datetime
from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
DemoStatusFilter = Literal["on_demo", "overdue_return", "returned"]
class DemoEquipmentCreate(BaseModel):
name: str = Field(..., min_length=1)
equipment_type: str = Field(..., min_length=1)
supplier_id: int
department_id: int
location_id: Optional[int] = None
start_date: date
expected_return_date: date
remarks: Optional[str] = None
class DemoEquipmentUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1)
equipment_type: Optional[str] = Field(None, min_length=1)
supplier_id: Optional[int] = None
department_id: Optional[int] = None
location_id: Optional[int] = None
start_date: Optional[date] = None
expected_return_date: Optional[date] = None
actual_return_date: Optional[date] = None
remarks: Optional[str] = None
class DemoEquipmentReturnIn(BaseModel):
actual_return_date: date
remarks: Optional[str] = None
class DemoEquipmentOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
equipment_type: str
supplier_id: int
supplier_name: Optional[str] = None
department_id: int
department_name: Optional[str] = None
location_id: Optional[int] = None
location_name: Optional[str] = None
start_date: date
expected_return_date: date
actual_return_date: Optional[date] = None
status: str
severity: str
days_remaining: int
attachment_count: int = 0
remarks: Optional[str] = None
created_at: datetime
class DemoEquipmentListOut(BaseModel):
items: list[DemoEquipmentOut]
total: int
+52
View File
@@ -0,0 +1,52 @@
from datetime import date, datetime
from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
InsuranceStatusFilter = Literal["active", "expiring", "expired"]
class InsuranceCreate(BaseModel):
asset_id: int
insurer_id: int
policy_no: str = Field(..., min_length=1)
start_date: date
end_date: date
coverage_amount: Optional[float] = Field(None, ge=0)
remarks: Optional[str] = None
class InsuranceUpdate(BaseModel):
insurer_id: Optional[int] = None
policy_no: Optional[str] = Field(None, min_length=1)
start_date: Optional[date] = None
end_date: Optional[date] = None
coverage_amount: Optional[float] = Field(None, ge=0)
remarks: Optional[str] = None
class InsuranceOut(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
insurer_id: int
insurer_name: Optional[str] = None
policy_no: str
start_date: date
end_date: date
coverage_amount: Optional[float] = None
status: str
severity: str
days_to_expiry: int
attachment_count: int = 0
remarks: Optional[str] = None
created_at: datetime
class InsuranceListOut(BaseModel):
items: list[InsuranceOut]
total: int
+42
View File
@@ -0,0 +1,42 @@
from datetime import date, datetime
from typing import Optional
from pydantic import BaseModel, ConfigDict
class AlertRunOut(BaseModel):
created: int
evaluated_today: str
class NotificationOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
type: str
severity: str
title: str
message: str
entity_type: str
entity_id: int
due_date: Optional[date] = None
link_url: str
is_read: bool
read_at: Optional[datetime] = None
created_at: datetime
class NotificationListOut(BaseModel):
items: list[NotificationOut]
total: int
unread_count: int
unread_calibration_count: int
class NotificationReadOut(BaseModel):
status: str = "ok"
notification_id: int
is_read: bool = True
class NotificationReadAllOut(BaseModel):
marked_read: int
+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: Optional[PMServiceMode] = None
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
+58
View File
@@ -0,0 +1,58 @@
from datetime import date, datetime
from typing import Optional
from pydantic import BaseModel, ConfigDict, Field
class VisitAssetSummary(BaseModel):
id: int
asset_code: str
name: str
class VisitComplaintSummary(BaseModel):
id: int
complaint_no: str
call_status: str
priority: str
description: str
class VisitCreate(BaseModel):
department_id: int
visit_date: date
observations: str = Field(..., min_length=1)
asset_ids: list[int] = Field(default_factory=list)
complaint_ids: list[int] = Field(default_factory=list)
visited_by_id: Optional[int] = None
class VisitUpdate(BaseModel):
department_id: Optional[int] = None
visit_date: Optional[date] = None
observations: Optional[str] = Field(None, min_length=1)
asset_ids: Optional[list[int]] = None
complaint_ids: Optional[list[int]] = None
class VisitLinkComplaintIn(BaseModel):
complaint_id: int
class VisitOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
department_id: int
department_name: Optional[str] = None
visited_by_id: int
visited_by_name: Optional[str] = None
visit_date: date
observations: Optional[str] = None
assets: list[VisitAssetSummary] = Field(default_factory=list)
complaints: list[VisitComplaintSummary] = Field(default_factory=list)
created_at: datetime
class VisitListOut(BaseModel):
items: list[VisitOut]
total: int
+49
View File
@@ -0,0 +1,49 @@
from datetime import date, datetime
from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
CoverageStatusFilter = Literal["active", "expiring", "expired"]
class WarrantyCreate(BaseModel):
asset_id: int
duration_months: int = Field(..., ge=1, le=240)
start_date: date
end_date: Optional[date] = None
provider_id: Optional[int] = None
remarks: Optional[str] = None
class WarrantyUpdate(BaseModel):
duration_months: Optional[int] = Field(None, ge=1, le=240)
start_date: Optional[date] = None
end_date: Optional[date] = None
provider_id: Optional[int] = None
remarks: Optional[str] = None
class WarrantyOut(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
duration_months: int
start_date: date
end_date: date
provider_id: Optional[int] = None
provider_name: Optional[str] = None
status: str
severity: str
days_to_expiry: int
attachment_count: int = 0
remarks: Optional[str] = None
created_at: datetime
class WarrantyListOut(BaseModel):
items: list[WarrantyOut]
total: int
+7
View File
@@ -31,6 +31,7 @@ from ..models import (
Vendor,
Warranty,
)
from ..services.alerts import run_alert_check
from ..services.settings_service import ensure_default_settings
@@ -88,6 +89,7 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
except Exception:
pass
db.flush()
db.expunge_all()
# 2. Settings (14 keys)
ensure_default_settings(db)
@@ -618,6 +620,7 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
registered_at=reg_at,
registered_by_id=reg_user.id,
received_by_id=recv_user.id,
received_at=reg_at,
assigned_to_id=assigned_user.id if call_status in ("in_progress", "closed") else None,
assigned_at=c_assigned_at,
attended_by_id=assigned_user.id if call_status in ("in_progress", "closed") else None,
@@ -774,6 +777,8 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
visit.complaints.append(complaints[3])
db.add(visit)
db.flush()
alert_res = run_alert_check(db)
db.commit()
return {
"departments": len(departments),
@@ -790,11 +795,13 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
"complaints": len(complaints),
"demo_equipment": len(demo_items),
"department_visits": 12,
"notifications": int(alert_res["created"]),
}
def main():
t0 = pytime.perf_counter()
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)
with SessionLocal() as db:
summary = seed_database(db)
+423
View File
@@ -0,0 +1,423 @@
from datetime import date, datetime, timezone
from sqlalchemy import or_
from sqlalchemy.orm import Session, joinedload
from ..core.time_utils import effective_now_utc, effective_today, format_date
from ..models import (
Asset,
CalibrationRecord,
Complaint,
Contract,
DemoEquipment,
InsurancePolicy,
Notification,
NotificationRead,
PMRecord,
PMSchedule,
User,
Warranty,
)
from .calculations import alert_state, compute_sla_status
from .permissions import Role
from .settings_service import get_setting_value
def _ensure_utc(dt: datetime) -> datetime:
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def notification_link_url(entity_type: str, entity_id: int) -> str:
mapping = {
"contract": "/contracts",
"warranty": "/contracts?tab=warranties",
"calibration_record": "/calibration",
"pm_record": "/pm",
"insurance": "/insurance",
"demo_equipment": "/demo-equipment",
"complaint": f"/complaints/{entity_id}",
}
return mapping.get(entity_type, "/")
def _alert_settings(db: Session) -> dict[str, int]:
return {
"amc": int(
get_setting_value(
db,
"amc_cmc_lead_days",
get_setting_value(db, "contract_expiry_alert_days", 30),
)
),
"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(
get_setting_value(
db,
"insurance_lead_days",
get_setting_value(db, "insurance_expiry_alert_days", 30),
)
),
"warranty": int(
get_setting_value(
db,
"warranty_lead_days",
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(
db,
"critical_complaint_alert_hours",
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)),
}
def _add_if_new(
db: Session,
existing_keys: set[str],
*,
dedupe_key: str,
alert_type: str,
severity: str,
title: str,
message: str,
entity_type: str,
entity_id: int,
due_date: date | None,
target_role: str,
created_at: datetime,
) -> int:
if dedupe_key in existing_keys:
return 0
existing_keys.add(dedupe_key)
db.add(
Notification(
type=alert_type,
severity=severity,
title=title,
message=message,
entity_type=entity_type,
entity_id=entity_id,
due_date=due_date,
target_role=target_role,
target_user_id=None,
dedupe_key=dedupe_key,
created_at=created_at,
)
)
return 1
def run_alert_check(db: Session) -> dict[str, object]:
today = effective_today(db)
eff_now = effective_now_utc(db)
cfg = _alert_settings(db)
existing_keys = {row[0] for row in db.query(Notification.dedupe_key).all()}
created = 0
# 1. AMC / CMC / OTHER contracts expiring
contracts = (
db.query(Contract)
.options(joinedload(Contract.asset))
.filter(Contract.is_superseded.is_(False))
.all()
)
for c in contracts:
state = alert_state(c.end_date, today, cfg["amc"], cfg["contract_red"])
if state in ("yellow", "red"):
created += _add_if_new(
db,
existing_keys,
dedupe_key=f"amc:{c.id}:{state}",
alert_type="amc_expiry",
severity=state,
title=f"{c.contract_type} Contract {'Critical' if state == 'red' else 'Expiring'}: {c.asset.asset_code}",
message=f"{c.contract_type} contract for {c.asset.name} ({c.asset.asset_code}) ends on {format_date(c.end_date)}.",
entity_type="contract",
entity_id=c.id,
due_date=c.end_date,
target_role="coordinator,management,biomedical,system_admin",
created_at=eff_now,
)
# 2. Calibration due / overdue
cal_records = (
db.query(CalibrationRecord)
.options(joinedload(CalibrationRecord.asset))
.filter(or_(CalibrationRecord.status.is_(None), CalibrationRecord.status != "completed"))
.all()
)
for r in cal_records:
state = alert_state(r.due_date, today, cfg["calibration"], cfg["red"])
if state in ("yellow", "red"):
status_word = "Overdue" if r.due_date < today else "Due Soon"
created += _add_if_new(
db,
existing_keys,
dedupe_key=f"cal:{r.id}:{state}",
alert_type="calibration_due",
severity=state,
title=f"Calibration {status_word}: {r.asset.asset_code}",
message=f"Calibration for {r.asset.name} ({r.asset.asset_code}) is due on {format_date(r.due_date)}.",
entity_type="calibration_record",
entity_id=r.id,
due_date=r.due_date,
target_role="biomedical,coordinator,management,system_admin",
created_at=eff_now,
)
# 3. PM due / overdue
pm_records = (
db.query(PMRecord)
.options(joinedload(PMRecord.asset), joinedload(PMRecord.schedule))
.filter(or_(PMRecord.status.is_(None), ~PMRecord.status.in_(["completed", "rescheduled"])))
.all()
)
for r in pm_records:
mode = r.schedule.service_mode if r.schedule else "in_house"
lead = cfg["pm_in_house"] if mode == "in_house" else cfg["pm_outsourced"]
state = alert_state(r.planned_date, today, lead, cfg["red"])
if state in ("yellow", "red"):
status_word = "Overdue" if r.planned_date < today else "Due Soon"
created += _add_if_new(
db,
existing_keys,
dedupe_key=f"pm:{r.id}:{state}",
alert_type="pm_due",
severity=state,
title=f"PM {status_word}: {r.asset.asset_code}",
message=f"Preventive maintenance ({mode.replace('_', '-')}) for {r.asset.name} ({r.asset.asset_code}) is planned for {format_date(r.planned_date)}.",
entity_type="pm_record",
entity_id=r.id,
due_date=r.planned_date,
target_role="biomedical,coordinator,management,system_admin",
created_at=eff_now,
)
# 4. Insurance expiry
policies = db.query(InsurancePolicy).options(joinedload(InsurancePolicy.asset)).all()
for p in policies:
state = alert_state(p.end_date, today, cfg["insurance"], cfg["red"])
if state in ("yellow", "red"):
created += _add_if_new(
db,
existing_keys,
dedupe_key=f"ins:{p.id}:{state}",
alert_type="insurance_expiry",
severity=state,
title=f"Insurance {'Critical' if state == 'red' else 'Expiring'}: {p.asset.asset_code}",
message=f"Policy {p.policy_no} for {p.asset.name} ({p.asset.asset_code}) ends on {format_date(p.end_date)}.",
entity_type="insurance",
entity_id=p.id,
due_date=p.end_date,
target_role="coordinator,management,system_admin",
created_at=eff_now,
)
# 5. Warranty expiry
warranties = db.query(Warranty).options(joinedload(Warranty.asset)).all()
for w in warranties:
state = alert_state(w.end_date, today, cfg["warranty"], cfg["red"])
if state in ("yellow", "red"):
created += _add_if_new(
db,
existing_keys,
dedupe_key=f"war:{w.id}:{state}",
alert_type="warranty_expiry",
severity=state,
title=f"Warranty {'Critical' if state == 'red' else 'Expiring'}: {w.asset.asset_code}",
message=f"Warranty for {w.asset.name} ({w.asset.asset_code}) ends on {format_date(w.end_date)}.",
entity_type="warranty",
entity_id=w.id,
due_date=w.end_date,
target_role="coordinator,biomedical,management,system_admin",
created_at=eff_now,
)
# 6. Demo equipment overdue return
demos = (
db.query(DemoEquipment)
.filter(DemoEquipment.actual_return_date.is_(None), DemoEquipment.expected_return_date < today)
.all()
)
for d in demos:
created += _add_if_new(
db,
existing_keys,
dedupe_key=f"demo:{d.id}:overdue",
alert_type="demo_overdue",
severity="red",
title=f"Demo Return Overdue: {d.name}",
message=f"Demo equipment '{d.name}' expected back on {format_date(d.expected_return_date)} has not been returned.",
entity_type="demo_equipment",
entity_id=d.id,
due_date=d.expected_return_date,
target_role="biomedical,coordinator,management,system_admin",
created_at=eff_now,
)
# 7. Critical complaints open >= escalation_open_complaint_hours
crit_complaints = (
db.query(Complaint)
.options(joinedload(Complaint.asset))
.filter(Complaint.call_status != "closed", Complaint.priority == "critical")
.all()
)
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:
created += _add_if_new(
db,
existing_keys,
dedupe_key=f"cmp:{c.id}:critical_overdue",
alert_type="critical_complaint",
severity="red",
title=f"Critical Complaint Open > {cfg['critical_hours']}h: {c.complaint_no}",
message=f"Critical complaint {c.complaint_no} for {c.asset.name} ({c.asset.asset_code}) remains {c.call_status}.",
entity_type="complaint",
entity_id=c.id,
due_date=today,
target_role="biomedical,management,system_admin,department_user",
created_at=eff_now,
)
# 8. Open unrestored complaints breaching configured SLA hours
open_unrestored = (
db.query(Complaint)
.options(joinedload(Complaint.asset))
.filter(Complaint.call_status != "closed", Complaint.restored_at.is_(None))
.all()
)
for c in open_unrestored:
sla_breached, sla_hours = 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 sla_breached:
created += _add_if_new(
db,
existing_keys,
dedupe_key=f"cmp:{c.id}:sla_breach",
alert_type="sla_breach",
severity="red",
title=f"SLA Breach: Open > {sla_hours}h: {c.complaint_no}",
message=f"Complaint {c.complaint_no} for {c.asset.name} ({c.asset.asset_code}) exceeded {sla_hours}h SLA without restoration.",
entity_type="complaint",
entity_id=c.id,
due_date=today,
target_role="biomedical,management,system_admin,department_user",
created_at=eff_now,
)
db.flush()
return {"created": created, "evaluated_today": today.isoformat()}
def _resolve_entity_departments(db: Session, notifications: list[Notification]) -> dict[tuple[str, int], int]:
by_type: dict[str, list[int]] = {}
for n in notifications:
by_type.setdefault(n.entity_type, []).append(n.entity_id)
dept_map: dict[tuple[str, int], int] = {}
asset_model_map = {
"contract": Contract,
"warranty": Warranty,
"insurance": InsurancePolicy,
"calibration_record": CalibrationRecord,
"pm_record": PMRecord,
"complaint": Complaint,
}
for etype, model in asset_model_map.items():
ids = list(set(by_type.get(etype, [])))
if ids:
rows = (
db.query(model.id, Asset.department_id)
.join(Asset, model.asset_id == Asset.id)
.filter(model.id.in_(ids))
.all()
)
for eid, dept_id in rows:
dept_map[(etype, eid)] = dept_id
demo_ids = list(set(by_type.get("demo_equipment", [])))
if demo_ids:
rows = (
db.query(DemoEquipment.id, DemoEquipment.department_id)
.filter(DemoEquipment.id.in_(demo_ids))
.all()
)
for eid, dept_id in rows:
dept_map[("demo_equipment", eid)] = dept_id
return dept_map
def get_visible_notifications_for_user(
db: Session,
user: User,
) -> tuple[list[Notification], dict[int, datetime]]:
"""Return (visible_notifications_ordered, read_at_by_notification_id) for the given user."""
all_rows = (
db.query(Notification)
.order_by(Notification.created_at.desc(), Notification.id.desc())
.all()
)
role_filtered: list[Notification] = []
for n in all_rows:
roles = {r.strip() for r in (n.target_role or "").split(",") if r.strip()}
if user.role in roles or n.target_user_id == user.id:
role_filtered.append(n)
if user.role == Role.department_user.value:
dept_map = _resolve_entity_departments(db, role_filtered)
visible = [
n
for n in role_filtered
if dept_map.get((n.entity_type, n.entity_id)) == user.department_id
]
else:
visible = role_filtered
visible_ids = [n.id for n in visible]
read_map: dict[int, datetime] = {}
if visible_ids:
reads = (
db.query(NotificationRead)
.filter(
NotificationRead.user_id == user.id,
NotificationRead.notification_id.in_(visible_ids),
)
.all()
)
read_map = {r.notification_id: r.read_at for r in reads}
return visible, read_map
+478
View File
@@ -0,0 +1,478 @@
import csv
from datetime import date, datetime
from io import BytesIO, StringIO
from pathlib import Path
from typing import Any
import openpyxl
from openpyxl.styles import Font, PatternFill
from openpyxl.utils import get_column_letter
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",
"serial_no",
"name",
"category",
"department",
"location",
"supplier",
"purchase_value",
"purchase_date",
"installation_date",
"status",
"criticality",
"requires_calibration",
"insurance_applicable",
"remarks",
]
VALID_STATUSES = ("in_service", "under_repair", "out_of_service", "condemned")
VALID_CRITICALITIES = ("critical", "non_critical")
_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
_HEADER_FONT = Font(color="FFFFFF", bold=True)
def _auto_fit_columns(ws, max_width: int = 42) -> None:
for col_idx in range(1, ws.max_column + 1):
max_len = 0
for row_idx in range(1, ws.max_row + 1):
val = ws.cell(row=row_idx, column=col_idx).value
if val is not None:
max_len = max(max_len, len(str(val)))
ws.column_dimensions[get_column_letter(col_idx)].width = min(max(max_len + 4, 14), max_width)
def build_import_template_xlsx(db: Session) -> BytesIO:
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Assets"
for col_idx, col_name in enumerate(IMPORT_COLUMNS, start=1):
cell = ws.cell(row=1, column=col_idx, value=col_name)
cell.fill = _HEADER_FILL
cell.font = _HEADER_FONT
ws.freeze_panes = "A2"
departments = (
db.query(Department)
.filter(Department.is_active.is_(True))
.order_by(Department.code.asc())
.all()
)
locations = (
db.query(Location)
.join(Department, Location.department_id == Department.id)
.filter(Location.is_active.is_(True), Department.is_active.is_(True))
.order_by(Department.code.asc(), Location.name.asc())
.all()
)
categories = (
db.query(Category)
.filter(Category.is_active.is_(True))
.order_by(Category.name.asc())
.all()
)
vendors = (
db.query(Vendor)
.filter(Vendor.is_active.is_(True))
.order_by(Vendor.name.asc())
.all()
)
sample_dept = departments[0] if departments else None
sample_loc = (
next((loc for loc in locations if sample_dept and loc.department_id == sample_dept.id), None)
or (locations[0] if locations else None)
)
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 = [
f"{sample_prefix}-{sample_dept_code}-0901",
"SN-DEMO-901",
"Infusion Pump",
sample_cat.name if sample_cat else "Infusion Pump",
sample_dept.code if sample_dept else "ICU",
sample_loc.name if sample_loc else "ICU Bay 1",
sample_sup.name if sample_sup else "",
125000,
"2025-01-15",
"2025-01-20",
"in_service",
"critical",
"true",
"false",
"Sample row - replace or remove before import",
]
for col_idx, val in enumerate(sample_row, start=1):
ws.cell(row=2, column=col_idx, value=val)
_auto_fit_columns(ws)
# Sheet 2: Master Reference
ref = wb.create_sheet(title="Master Reference")
headers_map = [
(1, "Department Code"),
(2, "Department Name"),
(4, "Department Code"),
(5, "Location Name"),
(7, "Category Name"),
(9, "Supplier Name"),
(11, "Valid Statuses"),
(13, "Valid Criticality"),
]
for col_idx, label in headers_map:
c = ref.cell(row=1, column=col_idx, value=label)
c.fill = _HEADER_FILL
c.font = _HEADER_FONT
ref.freeze_panes = "A2"
dept_by_id = {d.id: d for d in departments}
for idx, d in enumerate(departments, start=2):
ref.cell(row=idx, column=1, value=d.code)
ref.cell(row=idx, column=2, value=d.name)
for idx, loc in enumerate(locations, start=2):
d = dept_by_id.get(loc.department_id)
ref.cell(row=idx, column=4, value=d.code if d else "")
ref.cell(row=idx, column=5, value=loc.name)
for idx, cat in enumerate(categories, start=2):
ref.cell(row=idx, column=7, value=cat.name)
for idx, v in enumerate(vendors, start=2):
ref.cell(row=idx, column=9, value=v.name)
for idx, st in enumerate(VALID_STATUSES, start=2):
ref.cell(row=idx, column=11, value=st)
for idx, crit in enumerate(VALID_CRITICALITIES, start=2):
ref.cell(row=idx, column=13, value=crit)
_auto_fit_columns(ref)
buf = BytesIO()
wb.save(buf)
buf.seek(0)
return buf
def _clean_str(val: Any) -> str:
if val is None:
return ""
return str(val).strip()
def _parse_optional_date(val: Any, field_name: str) -> tuple[date | None, str | None]:
if val is None or (isinstance(val, str) and not val.strip()):
return None, None
if isinstance(val, datetime):
return val.date(), None
if isinstance(val, date):
return val, None
text = str(val).strip()
for fmt in ("%Y-%m-%d", "%d-%b-%Y"):
try:
return datetime.strptime(text, fmt).date(), None
except ValueError:
continue
return None, f"Invalid {field_name} '{text}' (expected YYYY-MM-DD or DD-MMM-YYYY)"
def _parse_bool(val: Any, field_name: str) -> tuple[bool, str | None]:
if val is None or (isinstance(val, str) and not val.strip()):
return False, None
if isinstance(val, bool):
return val, None
if isinstance(val, (int, float)) and val in (0, 1):
return bool(val), None
text = str(val).strip().lower()
if text in ("true", "yes", "1", "y"):
return True, None
if text in ("false", "no", "0", "n"):
return False, None
return False, f"Invalid {field_name} '{val}' (use true/false or yes/no)"
def _parse_optional_float(val: Any, field_name: str) -> tuple[float | None, str | None]:
if val is None or (isinstance(val, str) and not val.strip()):
return None, None
try:
parsed = float(val)
except (TypeError, ValueError):
return None, f"Invalid {field_name} '{val}' (must be a number)"
if parsed < 0:
return None, f"{field_name} cannot be negative"
return parsed, None
def _extract_rows(filename: str, content: bytes) -> list[tuple[int, dict[str, Any]]]:
ext = Path(filename or "").suffix.lower()
if ext not in (".xlsx", ".csv"):
raise CodedHTTPException(
status_code=400,
detail="Unsupported file type. Please upload an .xlsx or .csv file.",
code="INVALID_FILE_TYPE",
)
rows_out: list[tuple[int, dict[str, Any]]] = []
if ext == ".xlsx":
try:
wb = openpyxl.load_workbook(BytesIO(content), data_only=True)
except Exception as exc:
raise CodedHTTPException(
status_code=400,
detail="Invalid Excel file. Please download and use the import template.",
code="INVALID_FILE_TYPE",
) from exc
ws = wb["Assets"] if "Assets" in wb.sheetnames else wb.active
header_cells = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None)
if not header_cells:
return []
headers = [_clean_str(h).lower().replace(" ", "_") for h in header_cells]
for row_idx, row_vals in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2):
if all(v is None or _clean_str(v) == "" for v in row_vals):
continue
row_dict = {
headers[i]: (row_vals[i] if i < len(row_vals) else None)
for i in range(len(headers))
if headers[i]
}
rows_out.append((row_idx, row_dict))
else:
try:
decoded = content.decode("utf-8-sig")
except UnicodeDecodeError:
decoded = content.decode("latin-1")
reader = csv.reader(StringIO(decoded))
header_row = next(reader, None)
if not header_row:
return []
headers = [_clean_str(h).lower().replace(" ", "_") for h in header_row]
for row_idx, row_vals in enumerate(reader, start=2):
if all(_clean_str(v) == "" for v in row_vals):
continue
row_dict = {
headers[i]: (row_vals[i] if i < len(row_vals) else None)
for i in range(len(headers))
if headers[i]
}
rows_out.append((row_idx, row_dict))
return rows_out
def process_asset_import(
db: Session,
filename: str,
content: bytes,
user_id: int,
dry_run: bool = False,
skip_invalid: bool = False,
) -> dict[str, Any]:
raw_rows = _extract_rows(filename, content)
departments = db.query(Department).filter(Department.is_active.is_(True)).all()
dept_lookup: dict[str, Department] = {}
for d in departments:
dept_lookup[d.code.strip().lower()] = d
dept_lookup[d.name.strip().lower()] = d
locations = db.query(Location).filter(Location.is_active.is_(True)).all()
loc_lookup: dict[tuple[int, str], Location] = {
(loc.department_id, loc.name.strip().lower()): loc for loc in locations
}
categories = db.query(Category).filter(Category.is_active.is_(True)).all()
cat_lookup: dict[str, Category] = {c.name.strip().lower(): c for c in categories}
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
vendor_lookup: dict[str, Vendor] = {v.name.strip().lower(): v for v in vendors}
existing_codes = {
code.strip().lower() for (code,) in db.query(Asset.asset_code).all() if code
}
seen_codes: set[str] = set()
errors: list[dict[str, Any]] = []
preview_rows: list[dict[str, Any]] = []
valid_assets: list[Asset] = []
for row_idx, row_dict in raw_rows:
row_errors: list[str] = []
asset_code = _clean_str(row_dict.get("asset_code"))
serial_no = _clean_str(row_dict.get("serial_no"))
name = _clean_str(row_dict.get("name"))
cat_raw = _clean_str(row_dict.get("category"))
dept_raw = _clean_str(row_dict.get("department"))
loc_raw = _clean_str(row_dict.get("location"))
sup_raw = _clean_str(row_dict.get("supplier"))
remarks = _clean_str(row_dict.get("remarks")) or None
for req_label, req_val in (
("asset_code", asset_code),
("serial_no", serial_no),
("name", name),
("category", cat_raw),
("department", dept_raw),
("location", loc_raw),
):
if not req_val:
row_errors.append(f"Missing required field '{req_label}'")
if asset_code:
code_norm = asset_code.lower()
if code_norm in existing_codes:
row_errors.append(f"Duplicate asset_code '{asset_code}' already exists in database")
elif code_norm in seen_codes:
row_errors.append(f"Duplicate asset_code '{asset_code}' within import file")
seen_codes.add(code_norm)
dept_obj = dept_lookup.get(dept_raw.lower()) if dept_raw else None
if dept_raw and dept_obj is None:
row_errors.append(f"Unknown active department '{dept_raw}'")
loc_obj = None
if loc_raw and dept_obj is not None:
loc_obj = loc_lookup.get((dept_obj.id, loc_raw.lower()))
if loc_obj is None:
row_errors.append(
f"Unknown active location '{loc_raw}' in department '{dept_obj.name}'"
)
cat_obj = cat_lookup.get(cat_raw.lower()) if cat_raw else None
if cat_raw and cat_obj is None:
row_errors.append(f"Unknown active category '{cat_raw}'")
sup_obj = None
if sup_raw:
sup_obj = vendor_lookup.get(sup_raw.lower())
if sup_obj is None:
row_errors.append(f"Unknown active supplier '{sup_raw}'")
purchase_value, val_err = _parse_optional_float(row_dict.get("purchase_value"), "purchase_value")
if val_err:
row_errors.append(val_err)
purchase_date, pdate_err = _parse_optional_date(row_dict.get("purchase_date"), "purchase_date")
if pdate_err:
row_errors.append(pdate_err)
installation_date, idate_err = _parse_optional_date(
row_dict.get("installation_date"), "installation_date"
)
if idate_err:
row_errors.append(idate_err)
status_raw = _clean_str(row_dict.get("status"))
status_val = status_raw.lower().replace(" ", "_") if status_raw else "in_service"
if status_val not in VALID_STATUSES:
row_errors.append(f"Invalid status '{status_raw}' (valid: {', '.join(VALID_STATUSES)})")
crit_raw = _clean_str(row_dict.get("criticality"))
crit_val = crit_raw.lower().replace(" ", "_") if crit_raw else "non_critical"
if crit_val not in VALID_CRITICALITIES:
row_errors.append(
f"Invalid criticality '{crit_raw}' (valid: {', '.join(VALID_CRITICALITIES)})"
)
req_cal, cal_err = _parse_bool(row_dict.get("requires_calibration"), "requires_calibration")
if cal_err:
row_errors.append(cal_err)
ins_app, ins_err = _parse_bool(row_dict.get("insurance_applicable"), "insurance_applicable")
if ins_err:
row_errors.append(ins_err)
is_valid = len(row_errors) == 0
err_text = "; ".join(row_errors) if row_errors else None
if not is_valid:
errors.append(
{
"row": row_idx,
"asset_code": asset_code or None,
"error": err_text,
}
)
else:
valid_assets.append(
Asset(
asset_code=asset_code,
serial_no=serial_no,
name=name,
category_id=cat_obj.id,
department_id=dept_obj.id,
location_id=loc_obj.id,
supplier_id=sup_obj.id if sup_obj else None,
purchase_value=purchase_value,
purchase_date=purchase_date,
installation_date=installation_date,
status=status_val,
criticality=crit_val,
requires_calibration=req_cal,
insurance_applicable=ins_app,
remarks=remarks,
created_by_id=user_id,
updated_by_id=user_id,
)
)
preview_rows.append(
{
"row": row_idx,
"asset_code": asset_code or None,
"serial_no": serial_no or None,
"name": name or None,
"category_name": cat_obj.name if cat_obj else (cat_raw or None),
"department_name": dept_obj.name if dept_obj else (dept_raw or None),
"location_name": loc_obj.name if loc_obj else (loc_raw or None),
"status": status_val,
"valid": is_valid,
"error": err_text,
}
)
created_count = 0
if not dry_run:
if errors and not skip_invalid:
raise CodedHTTPException(
status_code=400,
detail=f"{len(errors)} row(s) failed validation.",
code="IMPORT_VALIDATION_ERRORS",
)
if valid_assets:
db.add_all(valid_assets)
db.flush()
for a in valid_assets:
log_audit(
db,
entity_type="asset",
entity_id=a.id,
action="bulk_import",
changes={
"asset_code": a.asset_code,
"name": a.name,
"department_id": a.department_id,
},
user_id=user_id,
)
db.commit()
created_count = len(valid_assets)
return {
"dry_run": dry_run,
"total_rows": len(raw_rows),
"valid_count": len(valid_assets),
"error_count": len(errors),
"created_count": created_count,
"errors": errors,
"preview_rows": preview_rows,
}
@@ -1,6 +1,7 @@
from pathlib import Path
from uuid import uuid4
from fastapi import UploadFile
from sqlalchemy import func
from sqlalchemy.orm import Session, joinedload
from ..core.config import settings
@@ -302,3 +303,15 @@ def delete_attachment(db: Session, user: User, attachment_id: int) -> None:
)
db.delete(att)
db.commit()
def get_attachment_counts(db: Session, entity_type: str, entity_ids: list[int]) -> dict[int, int]:
if not entity_ids:
return {}
rows = (
db.query(Attachment.entity_id, func.count(Attachment.id))
.filter(Attachment.entity_type == entity_type, Attachment.entity_id.in_(entity_ids))
.group_by(Attachment.entity_id)
.all()
)
return {eid: cnt for eid, cnt in rows}
+119 -1
View File
@@ -1,5 +1,12 @@
from datetime import date
from datetime import date, datetime, time, timedelta, timezone
from typing import Literal
from ..core.time_utils import KOLKATA, utc_now
def _ensure_utc(dt: datetime) -> datetime:
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def alert_state(
@@ -60,3 +67,114 @@ def compute_schedule_status(
sev = "red" if days_left <= red_days else "yellow"
return ("due", sev)
return ("upcoming", "ok")
def compute_response_time_minutes(
registered_at: datetime,
received_at: datetime | None,
attended_at: datetime | None,
response_start: str = "registered_at",
) -> int | None:
"""Compute response time in whole minutes from registered_at or received_at to attended_at."""
if attended_at is None:
return None
reg_utc = _ensure_utc(registered_at)
att_utc = _ensure_utc(attended_at)
if response_start == "received_at" and received_at is not None:
start = _ensure_utc(received_at)
else:
start = reg_utc
return max(0, int((att_utc - start).total_seconds() // 60))
def compute_downtime_minutes(
registered_at: datetime,
attended_at: datetime | None,
restored_at: datetime | None,
closed_at: datetime | None,
milestone: str = "restored_at",
now_utc: datetime | None = None,
) -> tuple[int, bool]:
"""Compute (downtime_minutes, is_ongoing) using the configured end milestone."""
reg_utc = _ensure_utc(registered_at)
end_map = {
"attended_at": attended_at,
"restored_at": restored_at,
"closed_at": closed_at,
}
raw_end = end_map.get(milestone)
if raw_end is None:
is_ongoing = True
end_dt = _ensure_utc(now_utc) if now_utc is not None else utc_now()
else:
is_ongoing = False
end_dt = _ensure_utc(raw_end)
return max(0, int((end_dt - reg_utc).total_seconds() // 60)), is_ongoing
def compute_ce_response_time_minutes(
registered_at: datetime,
ce_attended_at: datetime | None,
) -> int | None:
"""Compute Company Engineer response time in whole minutes from registered_at."""
if ce_attended_at is None:
return None
reg_utc = _ensure_utc(registered_at)
ce_utc = _ensure_utc(ce_attended_at)
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,
year: int,
month: int,
) -> tuple[int, set[date]]:
"""Clip a UTC downtime interval to a calendar month in Asia/Kolkata.
Returns (minutes_in_month, distinct_kolkata_calendar_dates).
"""
win_start = KOLKATA.localize(datetime(year, month, 1, 0, 0, 0))
next_year, next_month = (year + 1, 1) if month == 12 else (year, month + 1)
win_end = KOLKATA.localize(datetime(next_year, next_month, 1, 0, 0, 0))
start_local = _ensure_utc(start_utc).astimezone(KOLKATA)
end_local = _ensure_utc(end_utc).astimezone(KOLKATA)
clipped_start = max(start_local, win_start)
clipped_end = min(end_local, win_end)
if clipped_end <= clipped_start:
return (0, set())
minutes = int((clipped_end - clipped_start).total_seconds() // 60)
distinct_dates: set[date] = set()
cur_day = clipped_start.date()
last_day = clipped_end.date()
while cur_day <= last_day:
day_start = KOLKATA.localize(datetime.combine(cur_day, time(0, 0, 0)))
day_end = day_start + timedelta(days=1)
if max(clipped_start, day_start) < min(clipped_end, day_end):
distinct_dates.add(cur_day)
cur_day += timedelta(days=1)
return (minutes, distinct_dates)
+108
View File
@@ -0,0 +1,108 @@
import csv
from io import BytesIO, StringIO
from typing import Any
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font, PatternFill
from openpyxl.utils import get_column_letter
from ..core.time_utils import format_datetime, utc_now
def _format_filters_echo(filters_applied: dict[str, Any]) -> str:
if not filters_applied:
return "None"
return ", ".join(f"{k}={v}" for k, v in filters_applied.items())
def _format_summary_echo(summary: dict[str, Any]) -> str:
if not summary:
return ""
return " | ".join(f"{k.replace('_', ' ').title()}: {v}" for k, v in summary.items())
def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
wb = Workbook()
ws = wb.active
ws.title = report_payload["title"][:31]
title_text = f"Poona Hospital & Research Centre \u2014 {report_payload['title']}"
meta_text = (
f"Generated: {format_datetime(utc_now())} IST | "
f"Filters: {_format_filters_echo(report_payload.get('filters_applied', {}))}"
)
summary_text = _format_summary_echo(report_payload.get("summary", {}))
ws.cell(row=1, column=1, value=title_text).font = Font(name="Calibri", size=14, bold=True, color="0F172A")
ws.cell(row=2, column=1, value=meta_text).font = Font(name="Calibri", size=10, color="475569")
ws.cell(row=3, column=1, value=summary_text).font = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
columns: list[dict[str, str]] = report_payload.get("columns", [])
rows: list[dict[str, Any]] = report_payload.get("rows", [])
header_fill = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
header_font = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
header_row = 5
col_widths: list[int] = []
for c_idx, col in enumerate(columns, start=1):
cell = ws.cell(row=header_row, column=c_idx, value=col["label"])
cell.fill = header_fill
cell.font = header_font
cell.alignment = Alignment(horizontal="left", vertical="center")
col_widths.append(len(str(col["label"])))
ws.freeze_panes = "A6"
for r_offset, row_data in enumerate(rows):
excel_row = header_row + 1 + r_offset
for c_idx, col in enumerate(columns, start=1):
val = row_data.get(col["key"])
if isinstance(val, bool):
val = "Yes" if val else "No"
ws.cell(row=excel_row, column=c_idx, value=val)
val_len = len(str(val)) if val is not None else 0
if val_len > col_widths[c_idx - 1]:
col_widths[c_idx - 1] = val_len
for c_idx, width in enumerate(col_widths, start=1):
ws.column_dimensions[get_column_letter(c_idx)].width = min(45, max(12, width + 3))
buf = BytesIO()
wb.save(buf)
buf.seek(0)
return buf
def build_csv(report_payload: dict[str, Any]) -> BytesIO:
sio = StringIO()
writer = csv.writer(sio)
writer.writerow([f"Poona Hospital & Research Centre - {report_payload['title']}"])
writer.writerow(
[
f"Generated: {format_datetime(utc_now())} IST",
f"Filters: {_format_filters_echo(report_payload.get('filters_applied', {}))}",
]
)
summary_text = _format_summary_echo(report_payload.get("summary", {}))
if summary_text:
writer.writerow([f"Summary: {summary_text}"])
writer.writerow([])
columns: list[dict[str, str]] = report_payload.get("columns", [])
rows: list[dict[str, Any]] = report_payload.get("rows", [])
writer.writerow([col["label"] for col in columns])
for row_data in rows:
out_row = []
for col in columns:
val = row_data.get(col["key"])
if isinstance(val, bool):
val = "Yes" if val else "No"
out_row.append("" if val is None else val)
writer.writerow(out_row)
data = sio.getvalue().encode("utf-8-sig")
buf = BytesIO(data)
buf.seek(0)
return buf
+24
View File
@@ -0,0 +1,24 @@
from datetime import datetime, timezone
from sqlalchemy.orm import Session
from ..core.time_utils import to_kolkata
from ..models.complaints import Complaint
def generate_complaint_no(db: Session, prefix: str, dt_utc: datetime) -> str:
dt_aware = dt_utc if dt_utc.tzinfo else dt_utc.replace(tzinfo=timezone.utc)
year = to_kolkata(dt_aware).year
base = f"{prefix}-{year}-"
existing = (
db.query(Complaint.complaint_no)
.filter(Complaint.complaint_no.like(f"{base}%"))
.all()
)
max_seq = 0
for (cno,) in existing:
if cno and cno.startswith(base):
suffix = cno[len(base) :]
if suffix.isdigit():
val = int(suffix)
if val > max_seq:
max_seq = val
return f"{base}{max_seq + 1:04d}"
-1
View File
@@ -81,7 +81,6 @@ CAPABILITIES: dict[Role, set[str]] = {
Role.coordinator: {
"edit_asset_contracts_only",
"view_assets",
"raise_complaint",
"handle_complaint",
"view_pm",
"manage_calibration_contracts",
+996
View File
@@ -0,0 +1,996 @@
import calendar
from datetime import date, datetime, time, timedelta, timezone
import re
from typing import Any, Callable, Optional
from fastapi import HTTPException, status
from sqlalchemy.orm import Session, joinedload
from ..core.time_utils import (
KOLKATA,
add_months,
effective_now_utc,
effective_today,
format_date,
format_datetime,
format_duration,
)
from ..models import (
Asset,
CalibrationPlan,
CalibrationRecord,
Complaint,
Contract,
DemoEquipment,
Department,
DepartmentVisit,
PMRecord,
PMSchedule,
User,
Warranty,
)
from .attachment_service import get_attachment_counts
from .calculations import (
clip_downtime_to_month,
compute_downtime_minutes,
compute_response_time_minutes,
compute_schedule_status,
coverage_status,
)
from .permissions import Role
from .settings_service import get_setting_value
_MONTH_RE = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
def _parse_month(month_str: Optional[str], fallback_today: date) -> tuple[str, int, int]:
clean = month_str.strip() if month_str and month_str.strip() else fallback_today.strftime("%Y-%m")
match = _MONTH_RE.fullmatch(clean)
if not match:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="month must be in YYYY-MM format.",
)
return clean, int(match.group(1)), int(match.group(2))
def _scoped_dept_id(user: User, requested_dept_id: Optional[int]) -> Optional[int]:
if user.role == Role.department_user.value:
return user.department_id
return requested_dept_id
def _clean_filters(**kwargs: Any) -> dict[str, Any]:
out: dict[str, Any] = {}
for k, v in kwargs.items():
if v is None or v == "":
continue
out[k] = str(v) if isinstance(v, date) else v
return out
def _build_monthly_maintenance(
db: Session,
user: User,
params: dict[str, Any],
) -> dict[str, Any]:
today = effective_today(db)
eff_now = effective_now_utc(db)
month_str, year, month = _parse_month(params.get("month"), today)
dept_id = _scoped_dept_id(user, params.get("department_id"))
asset_id = params.get("asset_id")
days_in_month = calendar.monthrange(year, month)[1]
sched_hours = int(get_setting_value(db, "scheduled_hours_per_day", 24))
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
sched_mins_per_asset = days_in_month * sched_hours * 60
dept_q = db.query(Department).filter(Department.is_active.is_(True))
if dept_id is not None:
dept_q = dept_q.filter(Department.id == dept_id)
departments = dept_q.order_by(Department.name.asc()).all()
dept_by_id = {d.id: d for d in departments}
asset_q = db.query(Asset).filter(Asset.status != "condemned")
if dept_id is not None:
asset_q = asset_q.filter(Asset.department_id == dept_id)
if asset_id is not None:
asset_q = asset_q.filter(Asset.id == asset_id)
assets = asset_q.all()
asset_count_by_dept: dict[int, int] = {}
for a in assets:
asset_count_by_dept[a.department_id] = asset_count_by_dept.get(a.department_id, 0) + 1
if a.department_id not in dept_by_id:
dept_obj = db.query(Department).filter(Department.id == a.department_id).first()
if dept_obj:
dept_by_id[dept_obj.id] = dept_obj
cmp_q = db.query(Complaint).join(Asset, Complaint.asset_id == Asset.id).options(joinedload(Complaint.asset))
if dept_id is not None:
cmp_q = cmp_q.filter(Asset.department_id == dept_id)
if asset_id is not None:
cmp_q = cmp_q.filter(Complaint.asset_id == asset_id)
complaints = cmp_q.all()
dt_mins_by_dept: dict[int, int] = {}
cmp_count_by_dept: dict[int, int] = {}
dates_by_dept: dict[int, set[date]] = {}
overall_dates: set[date] = set()
overall_complaints = 0
for c in complaints:
end_map = {
"attended_at": c.attended_at,
"restored_at": c.restored_at,
"closed_at": c.closed_at,
}
end_dt = end_map.get(milestone) or eff_now
mins, dates = clip_downtime_to_month(c.registered_at, end_dt, year, month)
if mins > 0 or len(dates) > 0:
did = c.asset.department_id
dt_mins_by_dept[did] = dt_mins_by_dept.get(did, 0) + mins
cmp_count_by_dept[did] = cmp_count_by_dept.get(did, 0) + 1
dates_by_dept.setdefault(did, set()).update(dates)
overall_dates.update(dates)
overall_complaints += 1
rows: list[dict[str, Any]] = []
chart_data: list[dict[str, Any]] = []
ordered_dept_ids = sorted(dept_by_id.keys(), key=lambda did: dept_by_id[did].name)
for did in ordered_dept_ids:
dept = dept_by_id[did]
a_cnt = asset_count_by_dept.get(did, 0)
if asset_id is not None and a_cnt == 0 and cmp_count_by_dept.get(did, 0) == 0:
continue
c_cnt = cmp_count_by_dept.get(did, 0)
dt_mins = dt_mins_by_dept.get(did, 0)
dt_days = len(dates_by_dept.get(did, set()))
sched_mins = a_cnt * sched_mins_per_asset
up_mins = max(0, sched_mins - dt_mins)
dt_pct = round(dt_mins / sched_mins * 100, 2) if sched_mins > 0 else 0.0
rows.append(
{
"department_id": did,
"department_name": dept.name,
"asset_count": a_cnt,
"complaint_count": c_cnt,
"total_downtime_minutes": dt_mins,
"downtime_formatted": format_duration(dt_mins),
"downtime_days_count": dt_days,
"scheduled_minutes": sched_mins,
"total_uptime_minutes": up_mins,
"uptime_formatted": format_duration(up_mins),
"downtime_pct": dt_pct,
}
)
chart_data.append(
{
"department": dept.name,
"downtime_hours": round(dt_mins / 60.0, 2),
"uptime_hours": round(up_mins / 60.0, 2),
}
)
total_assets = sum(r["asset_count"] for r in rows)
total_dt_mins = sum(r["total_downtime_minutes"] for r in rows)
total_sched_mins = sum(r["scheduled_minutes"] for r in rows)
total_up_mins = max(0, total_sched_mins - total_dt_mins)
total_dt_pct = round(total_dt_mins / total_sched_mins * 100, 2) if total_sched_mins > 0 else 0.0
dt_vs_up_pct = round(total_dt_mins / total_up_mins * 100, 2) if total_up_mins > 0 else 0.0
return {
"report_key": "monthly-maintenance",
"title": "Monthly Maintenance Summary",
"filters_applied": _clean_filters(month=month_str, department_id=dept_id, asset_id=asset_id),
"formula_info": {
"scheduled_hours_per_day": sched_hours,
"downtime_end_milestone": milestone,
"days_in_month": days_in_month,
"uptime_formula": (
f"max(0, (non_condemned_assets * {days_in_month} * {sched_hours} * 60) - total_downtime_minutes)"
),
"downtime_formula": (
f"Sum of breakdown intervals [registered_at -> {milestone} or effective_now] clipped to "
f"{month_str} (Asia/Kolkata); downtime_days_count is distinct calendar days with any breakdown."
),
},
"summary": {
"total_assets": total_assets,
"total_complaints": overall_complaints,
"total_downtime_minutes": total_dt_mins,
"downtime_formatted": format_duration(total_dt_mins),
"downtime_days_count": len(overall_dates),
"total_scheduled_minutes": total_sched_mins,
"total_uptime_minutes": total_up_mins,
"uptime_formatted": format_duration(total_up_mins),
"downtime_pct": total_dt_pct,
"downtime_vs_uptime_pct": dt_vs_up_pct,
"scheduled_hours_per_day": sched_hours,
"downtime_end_milestone": milestone,
},
"columns": [
{"key": "department_name", "label": "Department"},
{"key": "asset_count", "label": "Assets"},
{"key": "complaint_count", "label": "Breakdowns"},
{"key": "downtime_formatted", "label": "Downtime"},
{"key": "downtime_days_count", "label": "Downtime Days"},
{"key": "uptime_formatted", "label": "Uptime"},
{"key": "downtime_pct", "label": "Downtime %"},
],
"rows": rows,
"chart_data": chart_data,
}
def _build_monthly_department(
db: Session,
user: User,
params: dict[str, Any],
) -> dict[str, Any]:
today = effective_today(db)
month_str, year, month = _parse_month(params.get("month"), today)
dept_id = _scoped_dept_id(user, params.get("department_id"))
month_start = date(year, month, 1)
next_month_start = add_months(month_start, 1)
dept_q = db.query(Department).filter(Department.is_active.is_(True))
if dept_id is not None:
dept_q = dept_q.filter(Department.id == dept_id)
departments = dept_q.order_by(Department.name.asc()).all()
assets = db.query(Asset).all()
open_complaints = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.options(joinedload(Complaint.asset))
.filter(Complaint.call_status != "closed")
.all()
)
visits = (
db.query(DepartmentVisit)
.filter(
DepartmentVisit.visit_date >= month_start,
DepartmentVisit.visit_date < next_month_start,
)
.order_by(DepartmentVisit.visit_date.desc(), DepartmentVisit.id.desc())
.all()
)
rows: list[dict[str, Any]] = []
for d in departments:
d_assets = [a for a in assets if a.department_id == d.id]
d_cmps = [c for c in open_complaints if c.asset.department_id == d.id]
d_visits = [v for v in visits if v.department_id == d.id]
notes = "; ".join(
f"[{format_date(v.visit_date)}] {v.observations.strip()}"
for v in d_visits
if v.observations and v.observations.strip()
)
rows.append(
{
"department_id": d.id,
"department_name": d.name,
"total_assets": len(d_assets),
"under_repair_count": sum(1 for a in d_assets if a.status == "under_repair"),
"out_of_service_count": sum(1 for a in d_assets if a.status == "out_of_service"),
"outstanding_complaints_count": len(d_cmps),
"critical_open_count": sum(1 for c in d_cmps if c.priority == "critical"),
"visits_this_month": len(d_visits),
"latest_requirements_notes": notes or "\u2014",
}
)
return {
"report_key": "monthly-department",
"title": "Monthly Department Report",
"filters_applied": _clean_filters(month=month_str, department_id=dept_id),
"summary": {
"departments_count": len(rows),
"total_under_repair": sum(r["under_repair_count"] for r in rows),
"total_outstanding_complaints": sum(r["outstanding_complaints_count"] for r in rows),
"total_visits": sum(r["visits_this_month"] for r in rows),
},
"columns": [
{"key": "department_name", "label": "Department"},
{"key": "total_assets", "label": "Total Assets"},
{"key": "under_repair_count", "label": "Under Repair"},
{"key": "out_of_service_count", "label": "Out of Service"},
{"key": "outstanding_complaints_count", "label": "Open Complaints"},
{"key": "critical_open_count", "label": "Critical Open"},
{"key": "visits_this_month", "label": "Visits"},
{"key": "latest_requirements_notes", "label": "Visit Observations / Requirements"},
],
"rows": rows,
}
def _build_daily_visit(
db: Session,
user: User,
params: dict[str, Any],
) -> dict[str, Any]:
if user.role in (Role.department_user.value, Role.coordinator.value):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Insufficient permissions to access Daily Department Visit Report.",
)
date_from = params.get("date_from")
date_to = params.get("date_to")
dept_id = params.get("department_id")
query = db.query(DepartmentVisit).options(
joinedload(DepartmentVisit.department),
joinedload(DepartmentVisit.visited_by),
joinedload(DepartmentVisit.assets),
joinedload(DepartmentVisit.complaints),
)
if dept_id is not None:
query = query.filter(DepartmentVisit.department_id == dept_id)
if date_from is not None:
query = query.filter(DepartmentVisit.visit_date >= date_from)
if date_to is not None:
query = query.filter(DepartmentVisit.visit_date <= date_to)
visits = query.order_by(DepartmentVisit.visit_date.desc(), DepartmentVisit.id.desc()).all()
rows: list[dict[str, Any]] = []
depts_visited: set[int] = set()
total_eq_checked = 0
total_linked = 0
for v in visits:
depts_visited.add(v.department_id)
eq_list = ", ".join(f"{a.asset_code} ({a.name})" for a in v.assets)
cmp_list = ", ".join(c.complaint_no for c in v.complaints)
total_eq_checked += len(v.assets)
total_linked += len(v.complaints)
rows.append(
{
"id": v.id,
"visit_date": format_date(v.visit_date),
"department_name": v.department.name if v.department else "\u2014",
"visited_by_name": v.visited_by.name if v.visited_by else "\u2014",
"equipment_checked_count": len(v.assets),
"equipment_checked": eq_list or "\u2014",
"observations": v.observations or "\u2014",
"linked_complaints_count": len(v.complaints),
"linked_complaints": cmp_list or "\u2014",
}
)
return {
"report_key": "daily-visit",
"title": "Daily Department Visit Report",
"filters_applied": _clean_filters(date_from=date_from, date_to=date_to, department_id=dept_id),
"summary": {
"total_visits": len(rows),
"departments_visited": len(depts_visited),
"total_equipment_checked": total_eq_checked,
"linked_complaints_count": total_linked,
},
"columns": [
{"key": "visit_date", "label": "Visit Date"},
{"key": "department_name", "label": "Department"},
{"key": "visited_by_name", "label": "Visited By"},
{"key": "equipment_checked_count", "label": "Assets Checked"},
{"key": "equipment_checked", "label": "Equipment Checked"},
{"key": "observations", "label": "Observations"},
{"key": "linked_complaints_count", "label": "Linked Count"},
{"key": "linked_complaints", "label": "Linked Complaints"},
],
"rows": rows,
}
def _build_breakdown_complaints(
db: Session,
user: User,
params: dict[str, Any],
) -> dict[str, Any]:
dept_id = _scoped_dept_id(user, params.get("department_id"))
date_from = params.get("date_from")
date_to = params.get("date_to")
asset_id = params.get("asset_id")
priority = params.get("priority")
call_status = params.get("call_status")
assigned_to_id = params.get("assigned_to_id")
response_start = str(get_setting_value(db, "response_start", "registered_at"))
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
eff_now = effective_now_utc(db)
query = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.options(
joinedload(Complaint.asset).joinedload(Asset.department),
)
)
if dept_id is not None:
query = query.filter(Asset.department_id == dept_id)
if asset_id is not None:
query = query.filter(Complaint.asset_id == asset_id)
if priority:
query = query.filter(Complaint.priority == priority)
if call_status:
query = query.filter(Complaint.call_status == call_status)
if assigned_to_id is not None:
query = query.filter(Complaint.assigned_to_id == assigned_to_id)
if date_from is not None:
dt_from_utc = KOLKATA.localize(datetime.combine(date_from, time(0, 0, 0))).astimezone(timezone.utc)
query = query.filter(Complaint.registered_at >= dt_from_utc)
if date_to is not None:
dt_to_utc = KOLKATA.localize(
datetime.combine(date_to + timedelta(days=1), time(0, 0, 0))
).astimezone(timezone.utc)
query = query.filter(Complaint.registered_at < dt_to_utc)
complaints = query.order_by(Complaint.registered_at.desc(), Complaint.id.desc()).all()
assigned_ids = {c.assigned_to_id for c in complaints if c.assigned_to_id is not None}
user_name_by_id: dict[int, str] = {}
if assigned_ids:
user_name_by_id = {
u.id: u.name for u in db.query(User).filter(User.id.in_(assigned_ids)).all()
}
rows: list[dict[str, Any]] = []
rt_values: list[int] = []
total_dt = 0
for c in complaints:
rt = compute_response_time_minutes(c.registered_at, c.received_at, c.attended_at, response_start)
if rt is not None:
rt_values.append(rt)
dt_mins, ongoing = compute_downtime_minutes(
c.registered_at,
c.attended_at,
c.restored_at,
c.closed_at,
milestone=milestone,
now_utc=eff_now,
)
total_dt += dt_mins
rows.append(
{
"complaint_no": c.complaint_no,
"asset_code": c.asset.asset_code,
"asset_name": c.asset.name,
"department_name": c.asset.department.name if c.asset.department else "\u2014",
"priority": c.priority,
"call_status": c.call_status,
"registered_at": format_datetime(c.registered_at),
"assigned_to_name": user_name_by_id.get(c.assigned_to_id, "\u2014") if c.assigned_to_id else "\u2014",
"response_time_minutes": rt,
"response_time_formatted": format_duration(rt),
"downtime_minutes": dt_mins,
"downtime_formatted": format_duration(dt_mins),
"downtime_is_ongoing": ongoing,
"action_taken": c.action_taken or "\u2014",
"closed_at": format_datetime(c.closed_at) or "\u2014",
"closure_remarks": c.closure_remarks or "\u2014",
}
)
avg_rt = round(sum(rt_values) / len(rt_values), 1) if rt_values else 0.0
return {
"report_key": "breakdown-complaints",
"title": "Breakdown / Complaint Report",
"filters_applied": _clean_filters(
date_from=date_from,
date_to=date_to,
department_id=dept_id,
asset_id=asset_id,
priority=priority,
call_status=call_status,
assigned_to_id=assigned_to_id,
),
"summary": {
"total_complaints": len(rows),
"open_count": sum(1 for c in complaints if c.call_status == "open"),
"in_progress_count": sum(1 for c in complaints if c.call_status == "in_progress"),
"closed_count": sum(1 for c in complaints if c.call_status == "closed"),
"critical_count": sum(1 for c in complaints if c.priority == "critical"),
"avg_response_minutes": avg_rt,
"total_downtime_minutes": total_dt,
},
"columns": [
{"key": "complaint_no", "label": "Complaint No"},
{"key": "asset_code", "label": "Asset Code"},
{"key": "asset_name", "label": "Equipment"},
{"key": "department_name", "label": "Department"},
{"key": "priority", "label": "Priority"},
{"key": "call_status", "label": "Status"},
{"key": "registered_at", "label": "Registered At"},
{"key": "assigned_to_name", "label": "Assigned To"},
{"key": "response_time_formatted", "label": "Response Time"},
{"key": "downtime_formatted", "label": "Downtime"},
{"key": "action_taken", "label": "Action Taken"},
{"key": "closed_at", "label": "Closed At"},
{"key": "closure_remarks", "label": "Closure Remarks"},
],
"rows": rows,
}
def _build_pm_compliance(
db: Session,
user: User,
params: dict[str, Any],
) -> dict[str, Any]:
today = effective_today(db)
dept_id = _scoped_dept_id(user, params.get("department_id"))
month_param = params.get("month")
date_from = params.get("date_from")
date_to = params.get("date_to")
asset_id = params.get("asset_id")
service_mode = params.get("service_mode")
inhouse_lead = int(get_setting_value(db, "pm_inhouse_lead_days", 15))
outsourced_lead = int(get_setting_value(db, "pm_outsourced_lead_days", 15))
red_days = int(get_setting_value(db, "red_threshold_days", 7))
query = (
db.query(PMRecord)
.join(PMSchedule, PMRecord.schedule_id == PMSchedule.id)
.join(Asset, PMRecord.asset_id == Asset.id)
.options(
joinedload(PMRecord.asset).joinedload(Asset.department),
joinedload(PMRecord.schedule).joinedload(PMSchedule.provider),
)
)
if dept_id is not None:
query = query.filter(Asset.department_id == dept_id)
if asset_id is not None:
query = query.filter(PMRecord.asset_id == asset_id)
if service_mode:
query = query.filter(PMSchedule.service_mode == service_mode)
clean_month: str | None = None
if month_param and str(month_param).strip():
clean_month, y, m = _parse_month(month_param, today)
m_start = date(y, m, 1)
m_end = add_months(m_start, 1)
query = query.filter(PMRecord.planned_date >= m_start, PMRecord.planned_date < m_end)
else:
if date_from is not None:
query = query.filter(PMRecord.planned_date >= date_from)
if date_to is not None:
query = query.filter(PMRecord.planned_date <= date_to)
records = query.order_by(PMRecord.planned_date.asc(), PMRecord.id.asc()).all()
rows: list[dict[str, Any]] = []
counts = {"completed": 0, "upcoming": 0, "due": 0, "overdue": 0, "rescheduled": 0}
for rec in records:
sched = rec.schedule
mode = sched.service_mode
lead = inhouse_lead if mode == "in_house" else outsourced_lead
if rec.status in ("completed", "rescheduled"):
st = rec.status
else:
st, _ = compute_schedule_status(rec.planned_date, None, today, lead, red_days)
counts[st] = counts.get(st, 0) + 1
team_or_provider = (
sched.responsible_team
if mode == "in_house"
else (sched.provider.name if sched.provider else "\u2014")
)
rows.append(
{
"planned_date": format_date(rec.planned_date),
"asset_code": rec.asset.asset_code,
"asset_name": rec.asset.name,
"department_name": rec.asset.department.name if rec.asset.department else "\u2014",
"service_mode": mode,
"team_or_provider": team_or_provider or "\u2014",
"status": st,
"completed_date": format_date(rec.completed_date) or "\u2014",
"service_details": rec.service_details or "\u2014",
"remarks": rec.remarks or "\u2014",
}
)
planned_count = len(rows)
compliance_pct = round(counts["completed"] / planned_count * 100, 2) if planned_count > 0 else 0.0
return {
"report_key": "pm-compliance",
"title": "PM Compliance Report",
"filters_applied": _clean_filters(
month=clean_month,
date_from=date_from,
date_to=date_to,
department_id=dept_id,
asset_id=asset_id,
service_mode=service_mode,
),
"summary": {
"planned_count": planned_count,
"completed_count": counts["completed"],
"upcoming_count": counts["upcoming"],
"due_count": counts["due"],
"overdue_count": counts["overdue"],
"rescheduled_count": counts["rescheduled"],
"compliance_pct": compliance_pct,
},
"columns": [
{"key": "planned_date", "label": "Planned Date"},
{"key": "asset_code", "label": "Asset Code"},
{"key": "asset_name", "label": "Equipment"},
{"key": "department_name", "label": "Department"},
{"key": "service_mode", "label": "Service Mode"},
{"key": "team_or_provider", "label": "Team / Provider"},
{"key": "status", "label": "Status"},
{"key": "completed_date", "label": "Completed Date"},
{"key": "service_details", "label": "Service Details"},
{"key": "remarks", "label": "Remarks"},
],
"rows": rows,
}
def _build_calibration_due(
db: Session,
user: User,
params: dict[str, Any],
) -> dict[str, Any]:
today = effective_today(db)
dept_id = _scoped_dept_id(user, params.get("department_id"))
due_from = params.get("due_from")
due_to = params.get("due_to")
asset_id = params.get("asset_id")
agency_id = params.get("agency_id")
status_filter = params.get("status")
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 = (
db.query(CalibrationRecord)
.join(CalibrationPlan, CalibrationRecord.plan_id == CalibrationPlan.id)
.join(Asset, CalibrationRecord.asset_id == Asset.id)
.options(
joinedload(CalibrationRecord.asset).joinedload(Asset.department),
joinedload(CalibrationRecord.agency),
joinedload(CalibrationRecord.plan),
)
)
if dept_id is not None:
query = query.filter(Asset.department_id == dept_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)
records = query.order_by(CalibrationRecord.due_date.asc(), CalibrationRecord.id.asc()).all()
rows: list[dict[str, Any]] = []
counts = {"upcoming": 0, "due": 0, "overdue": 0, "completed": 0}
for rec in records:
if rec.status == "completed":
st = "completed"
else:
st, _ = compute_schedule_status(rec.due_date, None, today, cal_lead, red_days)
if status_filter and st != status_filter:
continue
counts[st] = counts.get(st, 0) + 1
rows.append(
{
"due_date": format_date(rec.due_date),
"asset_code": rec.asset.asset_code,
"asset_name": rec.asset.name,
"department_name": rec.asset.department.name if rec.asset.department else "\u2014",
"agency_name": rec.agency.name if rec.agency else "\u2014",
"frequency_months": rec.plan.frequency_months if rec.plan else 0,
"status": st,
"completed_date": format_date(rec.completed_date) or "\u2014",
"certificate_no": rec.certificate_no or "\u2014",
"remarks": rec.remarks or "\u2014",
}
)
return {
"report_key": "calibration-due",
"title": "Calibration Due Report",
"filters_applied": _clean_filters(
due_from=due_from,
due_to=due_to,
department_id=dept_id,
asset_id=asset_id,
agency_id=agency_id,
status=status_filter,
),
"summary": {
"total_records": len(rows),
"upcoming_count": counts["upcoming"],
"due_count": counts["due"],
"overdue_count": counts["overdue"],
"completed_count": counts["completed"],
},
"columns": [
{"key": "due_date", "label": "Due Date"},
{"key": "asset_code", "label": "Asset Code"},
{"key": "asset_name", "label": "Equipment"},
{"key": "department_name", "label": "Department"},
{"key": "agency_name", "label": "Agency"},
{"key": "frequency_months", "label": "Freq (Mo)"},
{"key": "status", "label": "Status"},
{"key": "completed_date", "label": "Completed Date"},
{"key": "certificate_no", "label": "Certificate No"},
{"key": "remarks", "label": "Remarks"},
],
"rows": rows,
}
def _build_contracts_warranty(
db: Session,
user: User,
params: dict[str, Any],
) -> dict[str, Any]:
today = effective_today(db)
dept_id = _scoped_dept_id(user, params.get("department_id"))
asset_id = params.get("asset_id")
record_kind = params.get("record_kind") or "all"
status_filter = params.get("status")
contract_type = params.get("contract_type")
con_lead = int(
get_setting_value(
db,
"amc_cmc_lead_days",
get_setting_value(db, "contract_expiry_alert_days", 30),
)
)
war_lead = int(
get_setting_value(
db,
"warranty_lead_days",
get_setting_value(db, "warranty_expiry_alert_days", 30),
)
)
red_days = int(get_setting_value(db, "red_threshold_days", 7))
rows: list[dict[str, Any]] = []
con_counts = {"active": 0, "expiring": 0, "expired": 0}
war_counts = {"active": 0, "expiring": 0, "expired": 0}
if record_kind in ("all", "contracts"):
cq = (
db.query(Contract)
.join(Asset, Contract.asset_id == Asset.id)
.options(joinedload(Contract.asset).joinedload(Asset.department), joinedload(Contract.provider))
)
if status_filter != "superseded":
cq = cq.filter(Contract.is_superseded.is_(False))
if dept_id is not None:
cq = cq.filter(Asset.department_id == dept_id)
if asset_id is not None:
cq = cq.filter(Contract.asset_id == asset_id)
if contract_type:
cq = cq.filter(Contract.contract_type == contract_type)
contracts = cq.order_by(Contract.end_date.asc(), Contract.id.desc()).all()
con_att = get_attachment_counts(db, "contract", [c.id for c in contracts])
for c in contracts:
if c.is_superseded:
st = "superseded"
else:
st, _ = coverage_status(c.start_date, c.end_date, today, con_lead, red_days)
if status_filter and st != status_filter:
continue
if st in con_counts:
con_counts[st] += 1
rows.append(
{
"record_kind": "Contract",
"asset_code": c.asset.asset_code,
"asset_name": c.asset.name,
"department_name": c.asset.department.name if c.asset.department else "\u2014",
"type_or_duration": c.contract_type,
"provider_name": c.provider.name if c.provider else "\u2014",
"start_date": format_date(c.start_date),
"end_date": format_date(c.end_date),
"days_to_expiry": (c.end_date - today).days,
"status": st,
"attachment_count": con_att.get(c.id, 0),
}
)
if record_kind in ("all", "warranties") and not contract_type:
wq = (
db.query(Warranty)
.join(Asset, Warranty.asset_id == Asset.id)
.options(joinedload(Warranty.asset).joinedload(Asset.department), joinedload(Warranty.provider))
)
if dept_id is not None:
wq = wq.filter(Asset.department_id == dept_id)
if asset_id is not None:
wq = wq.filter(Warranty.asset_id == asset_id)
warranties = wq.order_by(Warranty.end_date.asc(), Warranty.id.desc()).all()
war_att = get_attachment_counts(db, "warranty", [w.id for w in warranties])
for w in warranties:
st, _ = coverage_status(w.start_date, w.end_date, today, war_lead, red_days)
if status_filter and st != status_filter:
continue
if st in war_counts:
war_counts[st] += 1
rows.append(
{
"record_kind": "Warranty",
"asset_code": w.asset.asset_code,
"asset_name": w.asset.name,
"department_name": w.asset.department.name if w.asset.department else "\u2014",
"type_or_duration": f"{w.duration_months} mo",
"provider_name": w.provider.name if w.provider else "\u2014",
"start_date": format_date(w.start_date),
"end_date": format_date(w.end_date),
"days_to_expiry": (w.end_date - today).days,
"status": st,
"attachment_count": war_att.get(w.id, 0),
}
)
return {
"report_key": "contracts-warranty",
"title": "AMC / CMC & Warranty Report",
"filters_applied": _clean_filters(
department_id=dept_id,
asset_id=asset_id,
record_kind=record_kind,
status=status_filter,
contract_type=contract_type,
),
"summary": {
"total_records": len(rows),
"active_contracts": con_counts["active"],
"expiring_contracts": con_counts["expiring"],
"expired_contracts": con_counts["expired"],
"active_warranties": war_counts["active"],
"expiring_warranties": war_counts["expiring"],
},
"columns": [
{"key": "record_kind", "label": "Kind"},
{"key": "asset_code", "label": "Asset Code"},
{"key": "asset_name", "label": "Equipment"},
{"key": "department_name", "label": "Department"},
{"key": "type_or_duration", "label": "Type / Duration"},
{"key": "provider_name", "label": "Provider"},
{"key": "start_date", "label": "Start Date"},
{"key": "end_date", "label": "End Date"},
{"key": "days_to_expiry", "label": "Days Left"},
{"key": "status", "label": "Status"},
{"key": "attachment_count", "label": "Files"},
],
"rows": rows,
}
def _build_demo_equipment(
db: Session,
user: User,
params: dict[str, Any],
) -> dict[str, Any]:
today = effective_today(db)
dept_id = _scoped_dept_id(user, params.get("department_id"))
supplier_id = params.get("supplier_id")
status_filter = params.get("status")
date_from = params.get("date_from")
date_to = params.get("date_to")
query = db.query(DemoEquipment).options(
joinedload(DemoEquipment.supplier),
joinedload(DemoEquipment.department),
joinedload(DemoEquipment.location),
)
if dept_id is not None:
query = query.filter(DemoEquipment.department_id == dept_id)
if supplier_id is not None:
query = query.filter(DemoEquipment.supplier_id == supplier_id)
if date_from is not None:
query = query.filter(DemoEquipment.expected_return_date >= date_from)
if date_to is not None:
query = query.filter(DemoEquipment.expected_return_date <= date_to)
items = query.order_by(DemoEquipment.expected_return_date.asc(), DemoEquipment.id.desc()).all()
rows: list[dict[str, Any]] = []
counts = {"on_demo": 0, "overdue_return": 0, "returned": 0}
for d in items:
if d.actual_return_date is not None:
st = "returned"
days_rem = (d.expected_return_date - d.actual_return_date).days
elif d.expected_return_date < today:
st = "overdue_return"
days_rem = (d.expected_return_date - today).days
else:
st = "on_demo"
days_rem = (d.expected_return_date - today).days
if status_filter and st != status_filter:
continue
counts[st] = counts.get(st, 0) + 1
rows.append(
{
"name": d.name,
"equipment_type": d.equipment_type,
"supplier_name": d.supplier.name if d.supplier else "\u2014",
"department_name": d.department.name if d.department else "\u2014",
"location_name": d.location.name if d.location else "\u2014",
"start_date": format_date(d.start_date),
"expected_return_date": format_date(d.expected_return_date),
"actual_return_date": format_date(d.actual_return_date) or "\u2014",
"status": st,
"days_remaining": days_rem,
"remarks": d.remarks or "\u2014",
}
)
return {
"report_key": "demo-equipment",
"title": "Demo Equipment Report",
"filters_applied": _clean_filters(
department_id=dept_id,
supplier_id=supplier_id,
status=status_filter,
date_from=date_from,
date_to=date_to,
),
"summary": {
"total_items": len(rows),
"on_demo_count": counts["on_demo"],
"overdue_count": counts["overdue_return"],
"returned_count": counts["returned"],
},
"columns": [
{"key": "name", "label": "Equipment Name"},
{"key": "equipment_type", "label": "Type / Model"},
{"key": "supplier_name", "label": "Supplier"},
{"key": "department_name", "label": "Department"},
{"key": "location_name", "label": "Location"},
{"key": "start_date", "label": "Start Date"},
{"key": "expected_return_date", "label": "Expected Return"},
{"key": "actual_return_date", "label": "Actual Return"},
{"key": "status", "label": "Status"},
{"key": "days_remaining", "label": "Days Remaining"},
{"key": "remarks", "label": "Remarks"},
],
"rows": rows,
}
REPORT_BUILDERS: dict[str, Callable[[Session, User, dict[str, Any]], dict[str, Any]]] = {
"monthly-maintenance": _build_monthly_maintenance,
"monthly-department": _build_monthly_department,
"daily-visit": _build_daily_visit,
"breakdown-complaints": _build_breakdown_complaints,
"pm-compliance": _build_pm_compliance,
"calibration-due": _build_calibration_due,
"contracts-warranty": _build_contracts_warranty,
"demo-equipment": _build_demo_equipment,
}
def generate_report(
db: Session,
user: User,
report_key: str,
params: dict[str, Any],
) -> dict[str, Any]:
builder = REPORT_BUILDERS.get(report_key)
if builder is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Unknown report key '{report_key}'.",
)
return builder(db, user, params)
+95 -5
View File
@@ -131,8 +131,8 @@ SETTINGS_SCHEMA: list[dict[str, Any]] = [
"key": "asset_code_prefix",
"type": "str",
"default": "PHRC",
"label": "Asset Code Prefix",
"description": "Default prefix used when formatting hospital asset codes (e.g. PHRC-ICU-0001).",
"label": "Asset Code Prefix (used in bulk-import template sample row only)",
"description": "Sample code prefix shown in the bulk-import template sample row (e.g. PHRC-ICU-0001). Hand-typed asset codes are not restricted.",
"min": None,
"max": None,
"options": None,
@@ -147,6 +147,96 @@ SETTINGS_SCHEMA: list[dict[str, Any]] = [
"max": None,
"options": ["in_house", "outsourced"],
},
{
"key": "complaint_no_prefix",
"type": "str",
"default": "CMP",
"label": "Complaint Number Prefix",
"description": "Prefix used when generating sequential breakdown complaint numbers (e.g. CMP-2026-0001).",
"min": None,
"max": None,
"options": None,
},
{
"key": "critical_complaint_sets_under_repair",
"type": "bool",
"default": True,
"label": "Critical Complaint Marks Asset Under Repair",
"description": "Automatically set asset status to under_repair when a critical breakdown complaint is registered or reopened.",
"min": None,
"max": None,
"options": None,
},
{
"key": "response_start",
"type": "enum",
"default": "registered_at",
"label": "Response Time Start Milestone",
"description": "Timestamp used as the starting point for biomedical response time calculation.",
"min": None,
"max": None,
"options": ["registered_at", "received_at"],
},
{
"key": "downtime_end_milestone",
"type": "enum",
"default": "restored_at",
"label": "Downtime End Milestone",
"description": "Milestone timestamp that stops the equipment downtime clock.",
"min": None,
"max": None,
"options": ["attended_at", "restored_at", "closed_at"],
},
{
"key": "pm_inhouse_lead_days",
"type": "int",
"default": 15,
"label": "In-House PM Lead Days",
"description": "Days before planned in-house PM date when status transitions from upcoming to due.",
"min": 1,
"max": 90,
"options": None,
},
{
"key": "pm_outsourced_lead_days",
"type": "int",
"default": 15,
"label": "Outsourced PM Lead Days",
"description": "Days before planned outsourced PM date when status transitions from upcoming to due.",
"min": 1,
"max": 90,
"options": None,
},
{
"key": "calibration_lead_days",
"type": "int",
"default": 15,
"label": "Calibration Lead Days",
"description": "Days before calibration due date when status transitions from upcoming to due.",
"min": 1,
"max": 90,
"options": None,
},
{
"key": "red_threshold_days",
"type": "int",
"default": 7,
"label": "Critical Alert Threshold Days",
"description": "Days remaining at or below which a due schedule alert escalates to critical (red).",
"min": 1,
"max": 60,
"options": None,
},
{
"key": "scheduled_hours_per_day",
"type": "int",
"default": 24,
"label": "Scheduled Equipment Hours Per Day",
"description": "Scheduled daily operating hours per asset used for Monthly Maintenance uptime/downtime calculations.",
"min": 1,
"max": 24,
"options": None,
},
]
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
@@ -243,15 +333,15 @@ def ensure_default_settings(db: Session) -> None:
db.flush()
def get_setting_value(db: Session, key: str) -> Any:
def get_setting_value(db: Session, key: str, default: Any = None) -> Any:
spec = SETTINGS_BY_KEY.get(key)
row = db.query(Setting).filter(Setting.key == key).first()
if row is None:
return spec["default"] if spec else None
return spec["default"] if spec else default
try:
return json.loads(row.value_json)
except (ValueError, TypeError):
return spec["default"] if spec else None
return spec["default"] if spec else default
def get_demo_as_of_date(db: Session) -> str | None:
+91 -4
View File
@@ -1,18 +1,95 @@
import asyncio
import threading
import httpx
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.main import app
from app.core.db import get_db
from app.main import app
from app.models import Base
from app.routers.auth import reset_login_rate_limiter
SQLALCHEMY_TEST_URL = "sqlite:///./data/test.db"
engine_test = create_engine(SQLALCHEMY_TEST_URL, connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine_test)
class _WaitSelector:
def __init__(self, event: threading.Event):
self._event = event
def select(self, timeout=None):
self._event.wait(timeout)
self._event.clear()
return []
def close(self):
pass
class _SocketFreeEventLoop(asyncio.BaseEventLoop):
"""Pure-Python asyncio loop using threading.Event instead of socketpair (works in Windows sandbox)."""
def __init__(self):
self._wake_event = threading.Event()
super().__init__()
self._selector = _WaitSelector(self._wake_event)
def _write_to_self(self):
self._wake_event.set()
def _process_events(self, event_list):
pass
def _close_self_pipe(self):
pass
def close(self):
super().close()
self._selector.close()
class SyncASGITestClient:
"""Synchronous HTTP test client backed by httpx.AsyncClient + ASGITransport."""
def __init__(self, asgi_app):
self._app = asgi_app
self._loop = _SocketFreeEventLoop()
self._lifespan_cm = asgi_app.router.lifespan_context(asgi_app)
self._loop.run_until_complete(self._lifespan_cm.__aenter__())
self._client = httpx.AsyncClient(
transport=httpx.ASGITransport(app=asgi_app),
base_url="http://testserver",
)
def request(self, method: str, url: str, **kwargs) -> httpx.Response:
return self._loop.run_until_complete(self._client.request(method, url, **kwargs))
def get(self, url: str, **kwargs) -> httpx.Response:
return self.request("GET", url, **kwargs)
def post(self, url: str, **kwargs) -> httpx.Response:
return self.request("POST", url, **kwargs)
def put(self, url: str, **kwargs) -> httpx.Response:
return self.request("PUT", url, **kwargs)
def patch(self, url: str, **kwargs) -> httpx.Response:
return self.request("PATCH", url, **kwargs)
def delete(self, url: str, **kwargs) -> httpx.Response:
return self.request("DELETE", url, **kwargs)
def close(self):
self._loop.run_until_complete(self._client.aclose())
self._loop.run_until_complete(self._lifespan_cm.__aexit__(None, None, None))
self._loop.close()
@pytest.fixture(scope="session")
def db():
Base.metadata.drop_all(bind=engine_test)
Base.metadata.create_all(bind=engine_test)
session = TestingSessionLocal()
yield session
@@ -29,6 +106,16 @@ def client(db):
pass
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as c:
c = SyncASGITestClient(app)
try:
yield c
app.dependency_overrides.clear()
finally:
c.close()
app.dependency_overrides.clear()
@pytest.fixture(autouse=True)
def _clear_login_rate_limiter():
reset_login_rate_limiter()
yield
reset_login_rate_limiter()
+227
View File
@@ -0,0 +1,227 @@
from io import BytesIO
import openpyxl
import pytest
from app.models import Asset, AuditLog
from app.seed.seed import seed_database
@pytest.fixture(scope="module", autouse=True)
def seeded_bulk_import_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("bulk_import_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 _make_xlsx_bytes(headers: list[str], rows: list[list[object]]) -> bytes:
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Assets"
ws.append(headers)
for r in rows:
ws.append(r)
buf = BytesIO()
wb.save(buf)
return buf.getvalue()
def test_import_template_download_and_rbac(client):
bio_headers = _auth_headers(client, "bio@poona.demo")
admin_headers = _auth_headers(client, "admin@poona.demo")
for email in ("dept@poona.demo", "coord@poona.demo", "mgmt@poona.demo"):
h = _auth_headers(client, email)
assert client.get("/api/assets/import-template", headers=h).status_code == 403
assert (
client.post(
"/api/assets/bulk-import",
headers=h,
files={"file": ("assets.csv", b"asset_code\n", "text/csv")},
).status_code
== 403
)
res = client.get("/api/assets/import-template", headers=bio_headers)
assert res.status_code == 200
assert "spreadsheetml.sheet" in res.headers["content-type"]
assert 'filename="asset_import_template.xlsx"' in res.headers["content-disposition"]
wb = openpyxl.load_workbook(BytesIO(res.content))
assert "Assets" in wb.sheetnames
assert "Master Reference" in wb.sheetnames
ws = wb["Assets"]
headers = [ws.cell(row=1, column=i).value for i in range(1, 16)]
assert headers[:6] == ["asset_code", "serial_no", "name", "category", "department", "location"]
assert ws.freeze_panes == "A2"
# Admin also allowed
assert client.get("/api/assets/import-template", headers=admin_headers).status_code == 200
def test_bulk_import_dry_run_validation_and_commit(client, db):
bio_headers = _auth_headers(client, "bio@poona.demo")
# Read a valid sample from template so we match real seeded department/location/category
tmpl_res = client.get("/api/assets/import-template", headers=bio_headers)
wb_tmpl = openpyxl.load_workbook(BytesIO(tmpl_res.content))
ws_tmpl = wb_tmpl["Assets"]
headers = [ws_tmpl.cell(row=1, column=i).value for i in range(1, 16)]
cat_name = ws_tmpl.cell(row=2, column=4).value
dept_code = ws_tmpl.cell(row=2, column=5).value
loc_name = ws_tmpl.cell(row=2, column=6).value
sup_name = ws_tmpl.cell(row=2, column=7).value
initial_count = db.query(Asset).count()
# Mix: 2 valid rows + 1 invalid row (unknown department)
rows = [
[
"BLK-IMP-001",
"BLK-SN-001",
"Bulk Infusion Pump",
cat_name,
dept_code,
loc_name,
sup_name,
95000,
"2025-02-01",
"2025-02-05",
"in_service",
"critical",
"yes",
"no",
"Dry run test row 1",
],
[
"BLK-IMP-002",
"BLK-SN-002",
"Bulk Syringe Pump",
cat_name,
dept_code,
loc_name,
"",
45000,
"15-Feb-2025",
"",
"in_service",
"non_critical",
"false",
"true",
"Dry run test row 2",
],
[
"BLK-IMP-BAD",
"BLK-SN-BAD",
"Invalid Dept Equipment",
cat_name,
"NO_SUCH_DEPT",
loc_name,
"",
10000,
"",
"",
"in_service",
"non_critical",
"false",
"false",
"",
],
]
xlsx_bytes = _make_xlsx_bytes(headers, rows)
# 1. dry_run=true validates all 3 without inserting into DB
dry_res = client.post(
"/api/assets/bulk-import?dry_run=true",
headers=bio_headers,
files={
"file": (
"bulk_assets.xlsx",
xlsx_bytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
},
)
assert dry_res.status_code == 200, dry_res.text
dry_data = dry_res.json()
assert dry_data["dry_run"] is True
assert dry_data["total_rows"] == 3
assert dry_data["valid_count"] == 2
assert dry_data["error_count"] == 1
assert dry_data["created_count"] == 0
assert dry_data["errors"][0]["row"] == 4
assert db.query(Asset).count() == initial_count
# 2. dry_run=false & skip_invalid=false rejects with 400 IMPORT_VALIDATION_ERRORS
strict_res = client.post(
"/api/assets/bulk-import?dry_run=false&skip_invalid=false",
headers=bio_headers,
files={
"file": (
"bulk_assets.xlsx",
xlsx_bytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
},
)
assert strict_res.status_code == 400
assert strict_res.json()["code"] == "IMPORT_VALIDATION_ERRORS"
assert db.query(Asset).count() == initial_count
# 3. dry_run=false & skip_invalid=true imports the 2 valid rows and logs audit entries
skip_res = client.post(
"/api/assets/bulk-import?dry_run=false&skip_invalid=true",
headers=bio_headers,
files={
"file": (
"bulk_assets.xlsx",
xlsx_bytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
},
)
assert skip_res.status_code == 200, skip_res.text
skip_data = skip_res.json()
assert skip_data["created_count"] == 2
assert skip_data["error_count"] == 1
assert db.query(Asset).count() == initial_count + 2
created_asset = db.query(Asset).filter(Asset.asset_code == "BLK-IMP-001").first()
assert created_asset is not None
audit = (
db.query(AuditLog)
.filter(
AuditLog.entity_type == "asset",
AuditLog.entity_id == created_asset.id,
AuditLog.action == "bulk_import",
)
.first()
)
assert audit is not None
# 4. CSV import (all valid) + unsupported extension rejected
csv_bytes = (
"asset_code,serial_no,name,category,department,location\n"
f"BLK-CSV-003,SN-CSV-003,CSV Patient Monitor,{cat_name},{dept_code},{loc_name}\n"
).encode("utf-8")
csv_res = client.post(
"/api/assets/bulk-import?dry_run=false",
headers=bio_headers,
files={"file": ("assets.csv", csv_bytes, "text/csv")},
)
assert csv_res.status_code == 200, csv_res.text
assert csv_res.json()["created_count"] == 1
bad_ext = client.post(
"/api/assets/bulk-import",
headers=bio_headers,
files={"file": ("assets.txt", b"hello", "text/plain")},
)
assert bad_ext.status_code == 400
assert bad_ext.json()["code"] == "INVALID_FILE_TYPE"
+2 -1
View File
@@ -266,6 +266,7 @@ def test_permissions_matrix_all_roles():
# coordinator
assert has_capability(Role.coordinator, "manage_admin") is False
assert has_capability(Role.coordinator, "raise_complaint") is False
assert has_capability(Role.coordinator, "edit_asset_contracts_only") is True
assert has_capability(Role.coordinator, "handle_complaint") is True
assert has_capability(Role.coordinator, "edit_technical_fields") is False
@@ -284,7 +285,7 @@ def test_settings_validation_and_demo_date(client, db):
res = client.get("/api/settings", headers=headers)
assert res.status_code == 200
items = res.json()["items"]
assert len(items) == 14
assert len(items) >= 14
# Out of range int
bad_range = client.put(
+569
View File
@@ -0,0 +1,569 @@
from datetime import date, datetime, timedelta, timezone
import pytest
from app.core.time_utils import KOLKATA
from app.models import Asset, Complaint, Department, User
from app.seed.seed import seed_database
from app.services.calculations import (
clip_downtime_to_month,
compute_ce_response_time_minutes,
compute_downtime_minutes,
compute_response_time_minutes,
)
from app.services.numbering import generate_complaint_no
@pytest.fixture(scope="module", autouse=True)
def seeded_complaints_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("complaint_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 test_generate_complaint_no_and_custom_prefix(db):
dt = datetime(2026, 4, 15, 10, 0, tzinfo=timezone.utc)
# Seed created CMP-2026-0001..0030 (when run in 2026) or current year; test custom prefix cleanly
c1 = generate_complaint_no(db, "PHRC", dt)
assert c1 == "PHRC-2026-0001"
# Existing CMP prefix in current KOLKATA year increments sequentially
now_utc = datetime.now(timezone.utc)
cur_year = now_utc.astimezone(KOLKATA).year
next_cmp = generate_complaint_no(db, "CMP", now_utc)
assert next_cmp == f"CMP-{cur_year}-0031"
def test_response_time_and_downtime_calculations():
reg = datetime(2026, 5, 10, 8, 0, tzinfo=timezone.utc)
recv = datetime(2026, 5, 10, 8, 15, tzinfo=timezone.utc)
att = datetime(2026, 5, 10, 9, 0, tzinfo=timezone.utc)
rst = datetime(2026, 5, 10, 11, 30, tzinfo=timezone.utc)
cls = datetime(2026, 5, 10, 12, 0, tzinfo=timezone.utc)
ce_att = datetime(2026, 5, 10, 10, 0, tzinfo=timezone.utc)
now = datetime(2026, 5, 10, 13, 0, tzinfo=timezone.utc)
# Response time
assert compute_response_time_minutes(reg, recv, None, "registered_at") is None
assert compute_response_time_minutes(reg, recv, att, "registered_at") == 60
assert compute_response_time_minutes(reg, recv, att, "received_at") == 45
# CE response time
assert compute_ce_response_time_minutes(reg, None) is None
assert compute_ce_response_time_minutes(reg, ce_att) == 120
# Downtime milestones
assert compute_downtime_minutes(reg, att, rst, cls, "attended_at", now) == (60, False)
assert compute_downtime_minutes(reg, att, rst, cls, "restored_at", now) == (210, False)
assert compute_downtime_minutes(reg, att, rst, cls, "closed_at", now) == (240, False)
# Ongoing downtime when chosen milestone is None
assert compute_downtime_minutes(reg, att, None, None, "restored_at", now) == (300, True)
def test_clip_downtime_to_month_across_boundary():
# Jan 30 22:00 IST to Feb 02 04:00 IST
start_utc = KOLKATA.localize(datetime(2026, 1, 30, 22, 0, 0)).astimezone(timezone.utc)
end_utc = KOLKATA.localize(datetime(2026, 2, 2, 4, 0, 0)).astimezone(timezone.utc)
jan_mins, jan_days = clip_downtime_to_month(start_utc, end_utc, 2026, 1)
assert jan_mins == 26 * 60 # 2h on Jan 30 + 24h on Jan 31 = 1560 mins
assert jan_days == {date(2026, 1, 30), date(2026, 1, 31)}
feb_mins, feb_days = clip_downtime_to_month(start_utc, end_utc, 2026, 2)
assert feb_mins == 28 * 60 # 24h on Feb 1 + 4h on Feb 2 = 1680 mins
assert feb_days == {date(2026, 2, 1), date(2026, 2, 2)}
mar_mins, mar_days = clip_downtime_to_month(start_utc, end_utc, 2026, 3)
assert mar_mins == 0
assert mar_days == set()
def test_complaint_field_level_permissions(client, db):
dept_headers = _auth_headers(client, "dept@poona.demo")
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
coord_headers = _auth_headers(client, "coord@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
admin_headers = _auth_headers(client, "admin@poona.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
ot = db.query(Department).filter(Department.code == "OT").first()
icu_cmp = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.filter(Asset.department_id == icu.id, Complaint.call_status != "closed")
.first()
)
ot_cmp = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.filter(Asset.department_id == ot.id)
.first()
)
if icu_cmp is None:
icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first()
r = client.post(
"/api/complaints",
headers=dept_headers,
json={"asset_id": icu_asset.id, "description": "Permission test issue", "priority": "non_critical"},
)
assert r.status_code == 201
icu_cmp_id = r.json()["id"]
else:
icu_cmp_id = icu_cmp.id
# Department scoping on list and detail
if ot_cmp is not None:
assert client.get(f"/api/complaints/{ot_cmp.id}", headers=dept_headers).status_code == 403
assert client.get(f"/api/complaints/{ot_cmp.id}/events", headers=dept_headers).status_code == 403
list_res = client.get("/api/complaints?page_size=200", headers=dept_headers)
assert list_res.status_code == 200
assert all(item["department_id"] == icu.id for item in list_res.json()["items"])
# Restricted technical fields rejected with 403 for dept_user, management, coordinator
for headers in (dept_headers, mgmt_headers, coord_headers):
for payload in (
{"action_taken": "Replaced PCB"},
{"root_cause": "Short circuit"},
{"spare_required": True, "spare_cost_estimate": 5000},
):
r = client.patch(f"/api/complaints/{icu_cmp_id}", headers=headers, json=payload)
assert r.status_code == 403
assert r.json()["code"] == "FORBIDDEN_TECHNICAL_FIELDS"
# Non-restricted edit by dept_user works on own non-closed complaint, fails for mgmt/coord
assert (
client.patch(
f"/api/complaints/{icu_cmp_id}",
headers=dept_headers,
json={"notes": "Updated ward note"},
).status_code
== 200
)
assert (
client.patch(
f"/api/complaints/{icu_cmp_id}",
headers=mgmt_headers,
json={"notes": "Mgmt edit"},
).status_code
== 403
)
assert (
client.patch(
f"/api/complaints/{icu_cmp_id}",
headers=coord_headers,
json={"notes": "Coord edit"},
).status_code
== 403
)
# biomedical and system_admin succeed on technical fields
bio_patch = client.patch(
f"/api/complaints/{icu_cmp_id}",
headers=bio_headers,
json={"action_taken": "Cleaned connector", "root_cause": "Loose cable"},
)
assert bio_patch.status_code == 200
assert bio_patch.json()["action_taken"] == "Cleaned connector"
admin_patch = client.patch(
f"/api/complaints/{icu_cmp_id}",
headers=admin_headers,
json={"corrective_action": "Secured latch"},
)
assert admin_patch.status_code == 200
assert admin_patch.json()["corrective_action"] == "Secured latch"
def test_full_complaint_workflow_and_asset_status_sync(client, db):
dept_headers = _auth_headers(client, "dept@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
admin_headers = _auth_headers(client, "admin@poona.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
asset = db.query(Asset).filter(Asset.department_id == icu.id, Asset.status == "in_service").first()
assert asset is not None
bio1 = db.query(User).filter(User.email == "bio@poona.demo").first()
bio2 = db.query(User).filter(User.email == "vikram.shinde@poona.demo").first()
# 1. Dept user raises critical complaint -> asset becomes under_repair
create_res = client.post(
"/api/complaints",
headers=dept_headers,
json={
"asset_id": asset.id,
"description": "Ventilator pressure drop alarm",
"breakdown_details": "Alarm triggered during patient weaning",
"priority": "critical",
"notes": "Urgent ICU support needed",
},
)
assert create_res.status_code == 201, create_res.text
cmp_data = create_res.json()
cid = cmp_data["id"]
assert cmp_data["call_status"] == "open"
assert cmp_data["asset_status"] == "under_repair"
assert cmp_data["downtime_is_ongoing"] is True
# 2. Assign -> reassign (events logged)
asg1 = client.post(
f"/api/complaints/{cid}/assign",
headers=bio_headers,
json={"assigned_to_id": bio1.id, "note": "Initial assignment"},
)
assert asg1.status_code == 200
assert asg1.json()["call_status"] == "in_progress"
assert asg1.json()["assigned_to_id"] == bio1.id
asg2 = client.post(
f"/api/complaints/{cid}/assign",
headers=bio_headers,
json={"assigned_to_id": bio2.id, "note": "Escalated to senior bio"},
)
assert asg2.status_code == 200
assert asg2.json()["assigned_to_id"] == bio2.id
# 3. Attend -> response_time_minutes computed
att_res = client.post(
f"/api/complaints/{cid}/attend",
headers=bio_headers,
json={"attended_by_id": bio2.id, "note": "Reached ICU Bay"},
)
assert att_res.status_code == 200
assert att_res.json()["attended_at"] is not None
assert att_res.json()["response_time_minutes"] is not None
# 4. Edit technical / spare / CE fields
ce_time = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
tech_res = client.patch(
f"/api/complaints/{cid}",
headers=bio_headers,
json={
"action_taken": "Replaced inspiratory valve diaphragm",
"root_cause": "Diaphragm tear",
"corrective_action": "Replaced valve kit and ran leak test",
"lessons_learned": "Inspect diaphragm at every 6m PM",
"ce_name": "Mahesh Kulkarni (OEM)",
"ce_attended_at": ce_time,
"ce_action_taken": "Calibrated flow sensor post replacement",
"spare_required": True,
"spare_details": "Inspiratory valve diaphragm kit",
"spare_cost_estimate": 12500.0,
},
)
assert tech_res.status_code == 200
assert tech_res.json()["spare_required"] is True
assert tech_res.json()["ce_response_time_minutes"] is not None
# 5. Restore -> asset returns to in_service
rst_res = client.post(
f"/api/complaints/{cid}/restore",
headers=bio_headers,
json={"note": "Passed 30-min leak test"},
)
assert rst_res.status_code == 200
assert rst_res.json()["restored_at"] is not None
assert rst_res.json()["asset_status"] == "in_service"
assert rst_res.json()["downtime_is_ongoing"] is False
# 6. Close -> call_status closed
cls_res = client.post(
f"/api/complaints/{cid}/close",
headers=bio_headers,
json={"closure_remarks": "Handed over to ICU charge nurse"},
)
assert cls_res.status_code == 200
assert cls_res.json()["call_status"] == "closed"
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 and restored_at cleared
reopen_res = client.post(
f"/api/complaints/{cid}/reopen",
headers=bio_headers,
json={"reason": "Alarm reappeared during shift change"},
)
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
new_reg = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
bio_ts = client.post(
f"/api/complaints/{cid}/correct-timestamp",
headers=bio_headers,
json={"field": "registered_at", "new_value": new_reg, "reason": "Late entry"},
)
assert bio_ts.status_code == 403
admin_ts = client.post(
f"/api/complaints/{cid}/correct-timestamp",
headers=admin_headers,
json={"field": "registered_at", "new_value": new_reg, "reason": "Logged after phone call"},
)
assert admin_ts.status_code == 200
assert admin_ts.json()["response_time_minutes"] >= 119
# 9. Verify events timeline
ev_res = client.get(f"/api/complaints/{cid}/events", headers=bio_headers)
assert ev_res.status_code == 200
events = ev_res.json()["items"]
event_types = [e["event_type"] for e in events]
assert event_types == [
"registered",
"assigned",
"reassigned",
"attended",
"field_edited",
"restored",
"closed",
"reopened",
"timestamp_corrected",
]
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()["code"] == "CLOSURE_REMARKS_REQUIRED"
assert fail_close.json()["detail"] == "Closure remarks are 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
def test_close_without_restore_sets_restored_at_and_reopen_recloses(client, db):
bio_headers = _auth_headers(client, "bio@poona.demo")
asset = db.query(Asset).first()
assert asset is not None
create_res = client.post(
"/api/complaints",
headers=bio_headers,
json={
"asset_id": asset.id,
"priority": "non_critical",
"description": "Close without explicit restore check",
},
)
assert create_res.status_code == 201, create_res.text
cid = create_res.json()["id"]
# Close directly without /restore -> restored_at is backfilled to closed_at
close1 = client.post(
f"/api/complaints/{cid}/close",
headers=bio_headers,
json={"closure_remarks": "Resolved during inspection"},
)
assert close1.status_code == 200, close1.text
c1 = close1.json()
assert c1["call_status"] == "closed"
assert c1["closed_at"] is not None
assert c1["restored_at"] == c1["closed_at"]
assert c1["downtime_is_ongoing"] is False
# Reopen -> restored_at is cleared and downtime is ongoing again
reopen1 = client.post(
f"/api/complaints/{cid}/reopen",
headers=bio_headers,
json={"reason": "Issue recurred"},
)
assert reopen1.status_code == 200, reopen1.text
r1 = reopen1.json()
assert r1["call_status"] != "closed"
assert r1["restored_at"] is None
assert r1["closed_at"] is None
assert r1["downtime_is_ongoing"] is True
# Close again without /restore -> restored_at == closed_at again
close2 = client.post(
f"/api/complaints/{cid}/close",
headers=bio_headers,
json={"closure_remarks": "Replaced cable and verified"},
)
assert close2.status_code == 200, close2.text
c2 = close2.json()
assert c2["closed_at"] is not None
assert c2["restored_at"] == c2["closed_at"]
assert c2["downtime_is_ongoing"] is False
def test_sla_breach_alert_emitted_and_suppressed_when_restored(client, db):
from app.core.time_utils import effective_now_utc
from app.models import Notification
from app.services.alerts import run_alert_check
bio_headers = _auth_headers(client, "bio@poona.demo")
asset = db.query(Asset).first()
assert asset is not None
r_unrestored = client.post(
"/api/complaints",
headers=bio_headers,
json={
"asset_id": asset.id,
"priority": "critical",
"description": "SLA breach unrestored test",
},
)
r_restored = client.post(
"/api/complaints",
headers=bio_headers,
json={
"asset_id": asset.id,
"priority": "critical",
"description": "SLA breach already restored test",
},
)
assert r_unrestored.status_code == 201 and r_restored.status_code == 201
cid_unrestored = r_unrestored.json()["id"]
cid_restored = r_restored.json()["id"]
now = effective_now_utc(db)
past_5h = now - timedelta(hours=5)
try:
c_unrestored = db.query(Complaint).filter(Complaint.id == cid_unrestored).first()
c_restored = db.query(Complaint).filter(Complaint.id == cid_restored).first()
c_unrestored.registered_at = past_5h
c_unrestored.restored_at = None
c_restored.registered_at = past_5h
c_restored.restored_at = now - timedelta(hours=1)
db.commit()
run_alert_check(db)
db.commit()
sla_unrestored = (
db.query(Notification)
.filter(
Notification.type == "sla_breach",
Notification.entity_type == "complaint",
Notification.entity_id == cid_unrestored,
)
.all()
)
assert len(sla_unrestored) == 1
assert "SLA Breach: Open > 4h" in sla_unrestored[0].title
# Restored complaint past SLA should NOT emit sla_breach
sla_restored = (
db.query(Notification)
.filter(
Notification.type == "sla_breach",
Notification.entity_type == "complaint",
Notification.entity_id == cid_restored,
)
.all()
)
assert sla_restored == []
# 5h open is < default escalation_open_complaint_hours (24h), so critical_complaint stays silent
crit_unrestored = (
db.query(Notification)
.filter(
Notification.type == "critical_complaint",
Notification.entity_type == "complaint",
Notification.entity_id == cid_unrestored,
)
.all()
)
assert crit_unrestored == []
finally:
db.query(Notification).filter(
Notification.entity_type == "complaint",
Notification.entity_id.in_([cid_unrestored, cid_restored]),
).delete(synchronize_session=False)
db.commit()
for cid_cleanup in (cid_unrestored, cid_restored):
client.post(
f"/api/complaints/{cid_cleanup}/close",
headers=bio_headers,
json={"closure_remarks": "Cleanup after SLA alert test"},
)
@@ -0,0 +1,148 @@
from datetime import timedelta
import pytest
from app.core.time_utils import effective_today
from app.models import Asset, Complaint, Department, Notification
from app.seed.seed import seed_database
from app.services.alerts import run_alert_check
@pytest.fixture(scope="module", autouse=True)
def seeded_phase6_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("phase6_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 test_alert_check_dedupe_and_seed_notifications(db):
# seed_database already ran run_alert_check -> notifications exist in DB
initial_count = db.query(Notification).count()
assert initial_count > 0
# Running run_alert_check again immediately creates 0 duplicates
res2 = run_alert_check(db)
db.commit()
assert res2["created"] == 0
assert db.query(Notification).count() == initial_count
def test_demo_clock_alert_run_and_admin_only_permission(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
coord_headers = _auth_headers(client, "coord@poona.demo")
# Non-admins get 403 on POST /api/alerts/run
for h in (bio_headers, dept_headers, mgmt_headers, coord_headers):
assert client.post("/api/alerts/run", headers=h).status_code == 403
base_today = effective_today(db)
future_date = base_today + timedelta(days=20)
try:
set_res = client.post(
"/api/settings/demo-date",
headers=admin_headers,
json={"demo_as_of_date": str(future_date)},
)
assert set_res.status_code == 200
# First run at +20 days creates new notifications for newly-entered windows
run1 = client.post("/api/alerts/run", headers=admin_headers)
assert run1.status_code == 200, run1.text
data1 = run1.json()
assert data1["evaluated_today"] == str(future_date)
assert data1["created"] > 0
# Second run at same +20 days creates 0 (dedupe)
run2 = client.post("/api/alerts/run", headers=admin_headers)
assert run2.status_code == 200
assert run2.json()["created"] == 0
finally:
client.post(
"/api/settings/demo-date",
headers=admin_headers,
json={"demo_as_of_date": None},
)
def test_per_user_read_state_and_department_scoping(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
admin_list_before = client.get("/api/notifications?limit=100", headers=admin_headers).json()
bio_list_before = client.get("/api/notifications?limit=100", headers=bio_headers).json()
assert admin_list_before["unread_count"] > 0
assert bio_list_before["unread_count"] > 0
# Pick a calibration_due notification visible to both admin and bio
cal_items = [n for n in admin_list_before["items"] if n["type"] == "calibration_due"]
assert len(cal_items) > 0
target_id = cal_items[0]["id"]
assert cal_items[0]["link_url"] == "/calibration"
# Admin marks single notification as read -> bio still sees it unread
mark_res = client.post(f"/api/notifications/{target_id}/read", headers=admin_headers)
assert mark_res.status_code == 200
assert mark_res.json()["is_read"] is True
admin_after_one = client.get("/api/notifications?limit=100", headers=admin_headers).json()
bio_after_one = client.get("/api/notifications?limit=100", headers=bio_headers).json()
assert admin_after_one["unread_count"] == admin_list_before["unread_count"] - 1
assert bio_after_one["unread_count"] == bio_list_before["unread_count"]
# Admin marks all calibration_due notifications read -> unread_calibration_count becomes 0 for admin, unchanged for bio
mark_cal = client.post("/api/notifications/read-all?type=calibration_due", headers=admin_headers)
assert mark_cal.status_code == 200
admin_after_cal = client.get("/api/notifications?limit=100", headers=admin_headers).json()
bio_after_cal = client.get("/api/notifications?limit=100", headers=bio_headers).json()
assert admin_after_cal["unread_calibration_count"] == 0
assert bio_after_cal["unread_calibration_count"] > 0
# department_user only sees critical_complaint alerts for their own department (ICU)
icu = db.query(Department).filter(Department.code == "ICU").first()
dept_notifs = client.get("/api/notifications?limit=100", headers=dept_headers).json()
for n in dept_notifs["items"]:
assert n["entity_type"] == "complaint"
assert n["link_url"] == f"/complaints/{n['entity_id']}"
comp = db.query(Complaint).filter(Complaint.id == n["entity_id"]).first()
assert comp.asset.department_id == icu.id
def test_dashboard_summary_role_scoping_and_charts(client, db):
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
icu_asset_count = db.query(Asset).filter(Asset.department_id == icu.id).count()
total_asset_count = db.query(Asset).count()
mgmt_res = client.get("/api/dashboard/summary", headers=mgmt_headers)
assert mgmt_res.status_code == 200, mgmt_res.text
mgmt = mgmt_res.json()
assert mgmt["department_scope"] is None
assert mgmt["kpis"]["total_assets"] == total_asset_count
assert len(mgmt["monthly_downtime_trend"]) == 6
assert len(mgmt["pm_planned_vs_completed"]) == 6
assert len(mgmt["complaints_by_status"]) == 3
assert len(mgmt["complaints_by_department"]) >= 2
assert len(mgmt["recent_complaints"]) <= 8
dept_res = client.get("/api/dashboard/summary", headers=dept_headers)
assert dept_res.status_code == 200, dept_res.text
dept = dept_res.json()
assert dept["department_scope"] == icu.name
assert dept["kpis"]["total_assets"] == icu_asset_count
assert dept["kpis"]["total_assets"] < mgmt["kpis"]["total_assets"]
assert len(dept["monthly_downtime_trend"]) == 6
assert len(dept["pm_planned_vs_completed"]) == 6
assert [d["department"] for d in dept["complaints_by_department"]] == [icu.name]
assert all(rc["department_name"] == icu.name for rc in dept["recent_complaints"])
+397
View File
@@ -0,0 +1,397 @@
from datetime import date, timedelta
import io
import pytest
from PIL import Image
from app.core.time_utils import effective_today
from app.models import Asset, Category, Complaint, Contract, Department, Location, Vendor
from app.seed.seed import seed_database
@pytest.fixture(scope="module", autouse=True)
def seeded_phase5_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("phase5_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 _make_png_bytes() -> bytes:
buf = io.BytesIO()
Image.new("RGB", (16, 16), color=(20, 90, 160)).save(buf, format="PNG")
return buf.getvalue()
def test_contract_create_renew_supersede_history_and_scoping(client, db):
coord_headers = _auth_headers(client, "coord@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
ot = db.query(Department).filter(Department.code == "OT").first()
icu_loc = db.query(Location).filter(Location.department_id == icu.id).first()
cat = db.query(Category).first()
provider = db.query(Vendor).filter(Vendor.vendor_type == "service_provider").first()
# Dedicated asset in ICU for deterministic renewal chain check
asset_res = client.post(
"/api/assets",
headers=bio_headers,
json={
"asset_code": "PHRC-CON-001",
"serial_no": "SN-CON-001",
"name": "Contract Renewal Test Ventilator",
"category_id": cat.id,
"department_id": icu.id,
"location_id": icu_loc.id,
"status": "in_service",
"criticality": "critical",
},
)
assert asset_res.status_code == 201
asset_id = asset_res.json()["id"]
# department_user cannot create contracts
assert (
client.post(
"/api/contracts",
headers=dept_headers,
json={
"asset_id": asset_id,
"contract_type": "AMC",
"provider_id": provider.id,
"start_date": "2025-01-01",
"end_date": "2025-12-31",
},
).status_code
== 403
)
# Coordinator creates initial contract
c1_res = client.post(
"/api/contracts",
headers=coord_headers,
json={
"asset_id": asset_id,
"contract_type": "AMC",
"provider_id": provider.id,
"start_date": "2025-01-01",
"end_date": "2025-12-31",
"coverage_period_text": "1 Year",
"remarks": "Initial AMC",
},
)
assert c1_res.status_code == 201, c1_res.text
c1 = c1_res.json()
assert c1["is_superseded"] is False
# Renew contract -> Note N1: old_contract.is_superseded=True, new_contract.renewed_from_id=c1.id
renew_res = client.post(
f"/api/contracts/{c1['id']}/renew",
headers=coord_headers,
json={
"contract_type": "CMC",
"start_date": "2026-01-01",
"end_date": "2026-12-31",
"coverage_period_text": "1 Year Comprehensive",
"remarks": "Upgraded to CMC",
},
)
assert renew_res.status_code == 200, renew_res.text
rj = renew_res.json()
assert rj["old_contract"]["id"] == c1["id"]
assert rj["old_contract"]["is_superseded"] is True
assert rj["old_contract"]["status"] == "superseded"
assert rj["new_contract"]["renewed_from_id"] == c1["id"]
assert rj["new_contract"]["is_superseded"] is False
assert rj["new_contract"]["contract_type"] == "CMC"
# History returns both contracts newest first
hist_res = client.get(f"/api/contracts/history/{asset_id}", headers=dept_headers)
assert hist_res.status_code == 200
hist_items = hist_res.json()["items"]
assert len(hist_items) == 2
assert hist_items[0]["id"] == rj["new_contract"]["id"]
assert hist_items[1]["id"] == c1["id"]
assert hist_items[1]["is_superseded"] is True
# include_superseded=false hides superseded contract
active_only = client.get(
f"/api/contracts?asset_id={asset_id}&include_superseded=false",
headers=coord_headers,
).json()
assert active_only["total"] == 1
assert active_only["items"][0]["id"] == rj["new_contract"]["id"]
# department_user gets 403 on another department's asset history and list only returns ICU
ot_asset = db.query(Asset).filter(Asset.department_id == ot.id).first()
assert client.get(f"/api/contracts/history/{ot_asset.id}", headers=dept_headers).status_code == 403
dept_list = client.get("/api/contracts", headers=dept_headers).json()["items"]
assert all(item["department_id"] == icu.id for item in dept_list)
def test_warranty_and_insurance_expiry_and_permissions(client, db):
coord_headers = _auth_headers(client, "coord@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first()
insurer = db.query(Vendor).filter(Vendor.vendor_type == "insurer").first()
today = effective_today(db)
# department_user cannot write warranty or insurance
assert (
client.post(
"/api/warranties",
headers=dept_headers,
json={
"asset_id": icu_asset.id,
"duration_months": 12,
"start_date": str(today - timedelta(days=30)),
},
).status_code
== 403
)
assert (
client.post(
"/api/insurance",
headers=dept_headers,
json={
"asset_id": icu_asset.id,
"insurer_id": insurer.id,
"policy_no": "POL-DENIED",
"start_date": str(today),
"end_date": str(today + timedelta(days=365)),
},
).status_code
== 403
)
# Coordinator creates expiring warranty (ends in 5 days -> expiring, red)
w_start = today - timedelta(days=360)
w_end = today + timedelta(days=5)
w_res = client.post(
"/api/warranties",
headers=coord_headers,
json={
"asset_id": icu_asset.id,
"duration_months": 12,
"start_date": str(w_start),
"end_date": str(w_end),
"provider_id": icu_asset.supplier_id,
"remarks": "Expiring warranty check",
},
)
assert w_res.status_code == 201, w_res.text
wj = w_res.json()
assert wj["status"] == "expiring"
assert wj["severity"] == "red"
assert wj["days_to_expiry"] == 5
# Coordinator creates expired insurance policy (ended yesterday -> expired, red)
ins_res = client.post(
"/api/insurance",
headers=coord_headers,
json={
"asset_id": icu_asset.id,
"insurer_id": insurer.id,
"policy_no": "PHRC-POL-TEST-99",
"start_date": str(today - timedelta(days=366)),
"end_date": str(today - timedelta(days=1)),
"coverage_amount": 450000.0,
"remarks": "Expired policy check",
},
)
assert ins_res.status_code == 201, ins_res.text
ij = ins_res.json()
assert ij["status"] == "expired"
assert ij["severity"] == "red"
assert ij["days_to_expiry"] == -1
# Upload attachment to insurance -> attachment_count increments to 1
up = client.post(
"/api/attachments",
headers=bio_headers,
data={"entity_type": "insurance", "entity_id": str(ij["id"])},
files={"file": ("policy.png", _make_png_bytes(), "image/png")},
)
assert up.status_code == 201
fetched = client.get(f"/api/insurance?asset_id={icu_asset.id}", headers=coord_headers).json()["items"]
matched = [x for x in fetched if x["id"] == ij["id"]][0]
assert matched["attachment_count"] == 1
def test_demo_equipment_overdue_detection_and_return(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
coord_headers = _auth_headers(client, "coord@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
icu_loc = db.query(Location).filter(Location.department_id == icu.id).first()
supplier = db.query(Vendor).filter(Vendor.vendor_type == "supplier").first()
# department_user gets 403 on write
assert (
client.post(
"/api/demo-equipment",
headers=dept_headers,
json={
"name": "Unauthorized Demo",
"equipment_type": "Monitor",
"supplier_id": supplier.id,
"department_id": icu.id,
"start_date": "2028-01-01",
"expected_return_date": "2028-01-10",
},
).status_code
== 403
)
create_res = client.post(
"/api/demo-equipment",
headers=coord_headers,
json={
"name": "Demo Transport Ventilator X2",
"equipment_type": "Ventilator",
"supplier_id": supplier.id,
"department_id": icu.id,
"location_id": icu_loc.id,
"start_date": "2028-04-01",
"expected_return_date": "2028-04-15",
"remarks": "Clinical trial in ICU",
},
)
assert create_res.status_code == 201, create_res.text
demo_id = create_res.json()["id"]
try:
# 1) Set demo_as_of_date = 2028-04-13 (2 days left -> on_demo, yellow)
client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": "2028-04-13"})
r1 = [x for x in client.get("/api/demo-equipment", headers=coord_headers).json()["items"] if x["id"] == demo_id][0]
assert r1["status"] == "on_demo"
assert r1["severity"] == "yellow"
assert r1["days_remaining"] == 2
# 2) Set demo_as_of_date = 2028-04-20 (past expected_return_date -> overdue_return, red, days_remaining=-5)
client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": "2028-04-20"})
r2 = [x for x in client.get("/api/demo-equipment?status=overdue_return", headers=coord_headers).json()["items"] if x["id"] == demo_id][0]
assert r2["status"] == "overdue_return"
assert r2["severity"] == "red"
assert r2["days_remaining"] == -5
# 3) Mark returned on 2028-04-18 -> status='returned', severity='ok'
ret_res = client.post(
f"/api/demo-equipment/{demo_id}/return",
headers=coord_headers,
json={"actual_return_date": "2028-04-18", "remarks": "Picked up by vendor."},
)
assert ret_res.status_code == 200, ret_res.text
rj = ret_res.json()
assert rj["status"] == "returned"
assert rj["severity"] == "ok"
assert rj["actual_return_date"] == "2028-04-18"
finally:
client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": None})
def test_department_visits_permissions_and_multi_linking(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")
coord_headers = _auth_headers(client, "coord@poona.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
icu_assets = db.query(Asset).filter(Asset.department_id == icu.id).limit(2).all()
complaints = db.query(Complaint).limit(3).all()
assert len(icu_assets) >= 2 and len(complaints) >= 3
# department_user and coordinator get 403 on GET and POST
assert client.get("/api/visits", headers=dept_headers).status_code == 403
assert client.get("/api/visits", headers=coord_headers).status_code == 403
assert (
client.post(
"/api/visits",
headers=coord_headers,
json={
"department_id": icu.id,
"visit_date": "2026-05-10",
"observations": "Coordinator denied",
},
).status_code
== 403
)
# management can GET (200) but gets 403 on POST
assert client.get("/api/visits", headers=mgmt_headers).status_code == 200
assert (
client.post(
"/api/visits",
headers=mgmt_headers,
json={
"department_id": icu.id,
"visit_date": "2026-05-10",
"observations": "Mgmt write denied",
},
).status_code
== 403
)
# biomedical creates visit with multiple assets and initial complaint
create_res = client.post(
"/api/visits",
headers=bio_headers,
json={
"department_id": icu.id,
"visit_date": "2026-05-10",
"observations": "Checked ICU beds 1-4; alarm issue noted on ventilator.",
"asset_ids": [a.id for a in icu_assets],
"complaint_ids": [complaints[0].id],
},
)
assert create_res.status_code == 201, create_res.text
visit = create_res.json()
visit_id = visit["id"]
assert len(visit["assets"]) == 2
assert [c["id"] for c in visit["complaints"]] == [complaints[0].id]
# management can GET /api/visits/{id} (200) but gets 403 on link-complaint and PATCH
assert client.get(f"/api/visits/{visit_id}", headers=mgmt_headers).status_code == 200
assert (
client.post(
f"/api/visits/{visit_id}/link-complaint",
headers=mgmt_headers,
json={"complaint_id": complaints[1].id},
).status_code
== 403
)
assert (
client.patch(
f"/api/visits/{visit_id}",
headers=mgmt_headers,
json={"observations": "Should fail"},
).status_code
== 403
)
# biomedical links a second complaint (and linking duplicate is idempotent)
link1 = client.post(
f"/api/visits/{visit_id}/link-complaint",
headers=bio_headers,
json={"complaint_id": complaints[1].id},
)
assert link1.status_code == 200, link1.text
assert {c["id"] for c in link1.json()["complaints"]} == {complaints[0].id, complaints[1].id}
link_dup = client.post(
f"/api/visits/{visit_id}/link-complaint",
headers=bio_headers,
json={"complaint_id": complaints[1].id},
)
assert link_dup.status_code == 200
assert len(link_dup.json()["complaints"]) == 2
+153
View File
@@ -0,0 +1,153 @@
import pytest
from app.models import Asset, AuditLog, Base, Department, User
from app.routers.auth import MAX_LOGIN_ATTEMPTS, reset_login_rate_limiter
from app.seed.seed import seed_database
@pytest.fixture(scope="module", autouse=True)
def seeded_phase8_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("phase8_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 test_global_search_grouped_and_department_scoped(client, db):
bio_headers = _auth_headers(client, "bio@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
dept_user = db.query(User).filter(User.email == "dept@poona.demo").first()
icu_dept = db.query(Department).filter(Department.id == dept_user.department_id).first()
assert dept_user is not None and icu_dept is not None
icu_asset = db.query(Asset).filter(Asset.department_id == icu_dept.id).first()
non_icu_asset = db.query(Asset).filter(Asset.department_id != icu_dept.id).first()
assert icu_asset is not None and non_icu_asset is not None
# Broad search returns grouped assets & complaints capped at 8 each
broad = client.get("/api/search?q=PHRC", headers=bio_headers)
assert broad.status_code == 200, broad.text
data = broad.json()
assert isinstance(data["assets"], list) and 0 < len(data["assets"]) <= 8
assert isinstance(data["complaints"], list) and len(data["complaints"]) <= 8
assert {"id", "asset_code", "name", "serial_no", "department_name", "status"}.issubset(
data["assets"][0].keys()
)
# Complaint search by prefix
cmp_search = client.get("/api/search?q=CMP", headers=bio_headers)
assert cmp_search.status_code == 200
assert len(cmp_search.json()["complaints"]) > 0
assert {
"id",
"complaint_no",
"asset_code",
"asset_name",
"department_name",
"call_status",
"priority",
}.issubset(cmp_search.json()["complaints"][0].keys())
# Department user sees ICU asset, cannot see non-ICU asset
icu_res = client.get(f"/api/search?q={icu_asset.asset_code}", headers=dept_headers)
assert icu_res.status_code == 200
assert any(a["asset_code"] == icu_asset.asset_code for a in icu_res.json()["assets"])
other_res = client.get(f"/api/search?q={non_icu_asset.asset_code}", headers=dept_headers)
assert other_res.status_code == 200
assert other_res.json()["assets"] == []
assert other_res.json()["complaints"] == []
# Empty query rejected
assert client.get("/api/search?q=", headers=bio_headers).status_code == 422
def test_audit_logs_rbac_and_filters(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
for email in ("bio@poona.demo", "mgmt@poona.demo", "dept@poona.demo", "coord@poona.demo"):
headers = _auth_headers(client, email)
assert client.get("/api/audit-logs", headers=headers).status_code == 403
# Ensure there is at least one distinct AuditLog entry via API/DB
admin_user = db.query(User).filter(User.email == "admin@poona.demo").first()
assert admin_user is not None
log_entry = AuditLog(
entity_type="asset",
entity_id=9999,
action="phase8_audit_probe",
changes_json='{"status": {"old": "in_service", "new": "under_repair"}}',
by_user_id=admin_user.id,
)
db.add(log_entry)
db.commit()
res = client.get("/api/audit-logs?entity_type=asset&action=phase8_audit_probe", headers=admin_headers)
assert res.status_code == 200, res.text
body = res.json()
assert body["total"] >= 1
assert len(body["items"]) >= 1
first = body["items"][0]
assert first["entity_type"] == "asset"
assert first["action"] == "phase8_audit_probe"
assert first["by_user_id"] == admin_user.id
assert first["by_user_name"] == admin_user.name
assert "under_repair" in first["changes_json"]
# Search filter `q`
q_res = client.get("/api/audit-logs?q=phase8_audit_probe", headers=admin_headers)
assert q_res.status_code == 200
assert q_res.json()["total"] == 1
def test_login_rate_limiter_429_and_reset(client):
reset_login_rate_limiter()
for i in range(MAX_LOGIN_ATTEMPTS):
res = client.post(
"/api/auth/login",
json={"email": "ratelimit@poona.demo", "password": "WrongPassword"},
)
assert res.status_code == 401, f"Attempt {i + 1} unexpected status {res.status_code}"
# Attempt 16 triggers 429 RATE_LIMITED
blocked = client.post(
"/api/auth/login",
json={"email": "ratelimit@poona.demo", "password": "WrongPassword"},
)
assert blocked.status_code == 429
assert blocked.json()["code"] == "RATE_LIMITED"
# Reset restores login capability
reset_login_rate_limiter()
ok = client.post(
"/api/auth/login",
json={"email": "admin@poona.demo", "password": "Demo@123"},
)
assert ok.status_code == 200
def test_database_indexes_defined():
expected_indexed_columns = {
"assets": {"asset_code", "serial_no", "department_id", "category_id", "location_id", "status"},
"complaints": {"complaint_no", "asset_id", "registered_at", "call_status", "assigned_to_id"},
"contracts": {"asset_id", "start_date", "end_date"},
"warranties": {"asset_id", "start_date", "end_date"},
"insurance_policies": {"asset_id", "start_date", "end_date"},
"calibration_records": {"asset_id", "plan_id", "due_date"},
"pm_records": {"asset_id", "schedule_id", "planned_date"},
"demo_equipment": {"department_id", "expected_return_date"},
"department_visits": {"department_id", "visit_date"},
"attachments": {"entity_type", "entity_id"},
"notifications": {"created_at", "type"},
"audit_logs": {"entity_type", "entity_id", "by_user_id", "at"},
}
for table_name, cols in expected_indexed_columns.items():
table = Base.metadata.tables[table_name]
indexed = {col.name for idx in table.indexes for col in idx.columns}
missing = cols - indexed
assert not missing, f"Missing indexes on {table_name}: {missing}"
+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},
)
+244
View File
@@ -0,0 +1,244 @@
import csv
from datetime import datetime, timezone
from io import BytesIO, StringIO
import openpyxl
import pytest
from app.core.time_utils import KOLKATA
from app.models import Asset, Category, Complaint, Department, Location, User
from app.seed.seed import seed_database
ALL_REPORT_KEYS = [
"monthly-maintenance",
"monthly-department",
"daily-visit",
"breakdown-complaints",
"pm-compliance",
"calibration-due",
"contracts-warranty",
"demo-equipment",
]
@pytest.fixture(scope="module", autouse=True)
def seeded_phase7_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("phase7_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 test_all_eight_reports_accessible_for_management_and_admin(client):
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
admin_headers = _auth_headers(client, "admin@poona.demo")
for headers in (mgmt_headers, admin_headers):
for key in ALL_REPORT_KEYS:
res = client.get(f"/api/reports/{key}", headers=headers)
assert res.status_code == 200, f"{key} failed: {res.text}"
body = res.json()
assert body["report_key"] == key
assert body["title"]
assert isinstance(body["filters_applied"], dict)
assert isinstance(body["summary"], dict)
assert isinstance(body["columns"], list) and len(body["columns"]) > 0
assert isinstance(body["rows"], list)
missing = client.get("/api/reports/non-existent-report", headers=admin_headers)
assert missing.status_code == 404
def test_daily_visit_rbac_and_department_user_scoping(client, db):
dept_headers = _auth_headers(client, "dept@poona.demo")
coord_headers = _auth_headers(client, "coord@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
# daily-visit is forbidden for department_user and coordinator (JSON + export)
for headers in (dept_headers, coord_headers):
assert client.get("/api/reports/daily-visit", headers=headers).status_code == 403
assert client.get("/api/reports/daily-visit/export?format=xlsx", headers=headers).status_code == 403
# Allowed for biomedical engineer
assert client.get("/api/reports/daily-visit", headers=bio_headers).status_code == 200
# Department user attempting to pass another department_id is still scoped to own department
dept_user = db.query(User).filter(User.email == "dept@poona.demo").first()
other_dept = db.query(Department).filter(Department.id != dept_user.department_id).first()
assert dept_user is not None and dept_user.department_id is not None
assert other_dept is not None
for key in [k for k in ALL_REPORT_KEYS if k != "daily-visit"]:
res = client.get(
f"/api/reports/{key}?department_id={other_dept.id}",
headers=dept_headers,
)
assert res.status_code == 200, f"{key} failed for dept user: {res.text}"
body = res.json()
if "department_id" in body["filters_applied"]:
assert body["filters_applied"]["department_id"] == dept_user.department_id
maint = client.get(
f"/api/reports/monthly-maintenance?department_id={other_dept.id}",
headers=dept_headers,
).json()
assert len(maint["rows"]) == 1
assert maint["rows"][0]["department_id"] == dept_user.department_id
def test_monthly_maintenance_three_complaint_reconciliation(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
admin_user = db.query(User).filter(User.email == "admin@poona.demo").first()
category = db.query(Category).first()
location = db.query(Location).first()
assert admin_user is not None and category is not None and location is not None
# Create isolated department with 2 non-condemned assets so calculation is deterministic
dept = Department(name="Reconciliation Test Unit", code="REC-TEST-01", is_active=True)
db.add(dept)
db.flush()
asset1 = Asset(
asset_code="REC-AST-001",
serial_no="REC-SN-001",
name="Reconciliation Monitor 1",
category_id=category.id,
department_id=dept.id,
location_id=location.id,
status="in_service",
criticality="critical",
)
asset2 = Asset(
asset_code="REC-AST-002",
serial_no="REC-SN-002",
name="Reconciliation Monitor 2",
category_id=category.id,
department_id=dept.id,
location_id=location.id,
status="in_service",
criticality="non_critical",
)
db.add_all([asset1, asset2])
db.flush()
# 3 fixed complaints for March 2027 (31 days * 24h * 60m = 44640 mins/asset -> 89280 total):
# 1) Crosses month boundary: Feb 28 22:00 IST -> Mar 01 04:00 IST => 240 mins in March, day Mar 01
# 2) Mid-month: Mar 10 10:00 IST -> Mar 10 13:30 IST => 210 mins, day Mar 10
# 3) Distinct day: Mar 20 09:00 IST -> Mar 20 10:15 IST => 75 mins, day Mar 20
# Expected total downtime = 525 mins, downtime days = 3, uptime = 88755 mins
complaints = [
Complaint(
complaint_no="REC-CMP-001",
asset_id=asset1.id,
description="Month boundary downtime test",
priority="critical",
registered_at=KOLKATA.localize(datetime(2027, 2, 28, 22, 0)).astimezone(timezone.utc),
restored_at=KOLKATA.localize(datetime(2027, 3, 1, 4, 0)).astimezone(timezone.utc),
registered_by_id=admin_user.id,
received_by_id=admin_user.id,
call_status="closed",
),
Complaint(
complaint_no="REC-CMP-002",
asset_id=asset1.id,
description="Mid-month downtime test",
priority="non_critical",
registered_at=KOLKATA.localize(datetime(2027, 3, 10, 10, 0)).astimezone(timezone.utc),
restored_at=KOLKATA.localize(datetime(2027, 3, 10, 13, 30)).astimezone(timezone.utc),
registered_by_id=admin_user.id,
received_by_id=admin_user.id,
call_status="closed",
),
Complaint(
complaint_no="REC-CMP-003",
asset_id=asset2.id,
description="Third distinct day downtime test",
priority="non_critical",
registered_at=KOLKATA.localize(datetime(2027, 3, 20, 9, 0)).astimezone(timezone.utc),
restored_at=KOLKATA.localize(datetime(2027, 3, 20, 10, 15)).astimezone(timezone.utc),
registered_by_id=admin_user.id,
received_by_id=admin_user.id,
call_status="closed",
),
]
db.add_all(complaints)
db.commit()
res = client.get(
f"/api/reports/monthly-maintenance?month=2027-03&department_id={dept.id}",
headers=admin_headers,
)
assert res.status_code == 200, res.text
payload = res.json()
summary = payload["summary"]
assert summary["total_assets"] == 2
assert summary["total_complaints"] == 3
assert summary["total_downtime_minutes"] == 525
assert summary["downtime_days_count"] == 3
assert summary["total_scheduled_minutes"] == 89280
assert summary["total_uptime_minutes"] == 88755
assert summary["downtime_pct"] == round(525 / 89280 * 100, 2)
assert len(payload["rows"]) == 1
row = payload["rows"][0]
assert row["department_name"] == "Reconciliation Test Unit"
assert row["asset_count"] == 2
assert row["complaint_count"] == 3
assert row["total_downtime_minutes"] == 525
assert row["downtime_days_count"] == 3
assert row["scheduled_minutes"] == 89280
assert row["total_uptime_minutes"] == 88755
def test_report_exports_xlsx_and_csv(client):
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
# Excel export
xlsx_res = client.get(
"/api/reports/monthly-maintenance/export?format=xlsx&month=2027-03",
headers=mgmt_headers,
)
assert xlsx_res.status_code == 200
assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"]
assert 'filename="monthly-maintenance.xlsx"' in xlsx_res.headers["content-disposition"]
wb = openpyxl.load_workbook(BytesIO(xlsx_res.content))
ws = wb.active
assert "Poona Hospital" in str(ws["A1"].value)
assert "Generated:" in str(ws["A2"].value)
assert "Filters:" in str(ws["A2"].value)
assert "Total Downtime Minutes: 525" in str(ws["A3"].value)
assert ws.freeze_panes == "A6"
assert ws.cell(row=5, column=1).value == "Department"
assert "1E3A8A" in str(ws.cell(row=5, column=1).fill.start_color.rgb)
assert ws.max_row >= 6
# CSV export
csv_res = client.get(
"/api/reports/breakdown-complaints/export?format=csv",
headers=mgmt_headers,
)
assert csv_res.status_code == 200
assert "text/csv" in csv_res.headers["content-type"]
assert 'filename="breakdown-complaints.csv"' in csv_res.headers["content-disposition"]
assert csv_res.content.startswith(b"\xef\xbb\xbf")
decoded = csv_res.content.decode("utf-8-sig")
parsed = list(csv.reader(StringIO(decoded)))
assert len(parsed) >= 5
assert "Poona Hospital" in parsed[0][0]
assert parsed[4][0] == "Complaint No"
# Unsupported export format rejected
bad_fmt = client.get(
"/api/reports/monthly-maintenance/export?format=pdf",
headers=mgmt_headers,
)
assert bad_fmt.status_code == 422
+26
View File
@@ -0,0 +1,26 @@
services:
backend:
build: ./backend
container_name: poona-ams-backend
ports:
- "8000:8000"
environment:
DATABASE_URL: ${DATABASE_URL:-sqlite:////app/data/ams.db}
SECRET_KEY: ${SECRET_KEY:-change-me-in-production-use-a-32-char-random-string}
UPLOAD_DIR: ${UPLOAD_DIR:-/app/data/uploads}
TIMEZONE: ${TIMEZONE:-Asia/Kolkata}
ACCESS_TOKEN_EXPIRE_MINUTES: ${ACCESS_TOKEN_EXPIRE_MINUTES:-480}
ALGORITHM: ${ALGORITHM:-HS256}
MAX_UPLOAD_SIZE_MB: ${MAX_UPLOAD_SIZE_MB:-10}
volumes:
- ./backend/data:/app/data
restart: unless-stopped
frontend:
build: ./frontend
container_name: poona-ams-frontend
ports:
- "5173:80"
depends_on:
- backend
restart: unless-stopped
+12
View File
@@ -0,0 +1,12 @@
# Poona Hospital AMS — Acceptance Checklist (Proposal §10 Mapping)
| # | Acceptance Criterion | Automated Test Coverage | Manual Verification Steps |
|---|---|---|---|
| **1** | **Auth, 5-Role RBAC, Masters & Settings** (`system_admin`, `biomedical`, `department_user`, `management`, `coordinator`, JWT auth, login rate limiting, configurable settings, audit logs) | `backend/tests/test_auth_and_permissions.py`<br>`backend/tests/test_phase8_polish.py` (`test_audit_logs_rbac_and_filters`, `test_login_rate_limiter_429_and_reset`)<br>`frontend/src/test/login.test.tsx`<br>`frontend/src/test/permissions.test.ts`<br>`frontend/src/test/smoke.test.tsx`<br>`frontend/src/test/phase8-polish.test.tsx` | Log in with all 5 demo accounts (`Demo@123`), confirm role-filtered sidebar items, test `/masters` & `/settings` CRUD as `admin@poona.demo`, confirm `/audit-logs` returns `403` for non-admins, and trigger >15 rapid failed logins to observe `429`. |
| **2** | **Asset Register, Global Quick Search & Secure Attachments** (unique `asset_code`, department scoping, coordinator edit restrictions, `AssetPicker`, `/api/search`, JPG/PNG/PDF magic-byte + 10 MB checks) | `backend/tests/test_assets_and_attachments.py`<br>`backend/tests/test_phase8_polish.py` (`test_global_search_grouped_and_department_scoped`)<br>`frontend/src/test/asset-picker.test.tsx`<br>`frontend/src/test/attachments.test.tsx`<br>`frontend/src/test/phase8-polish.test.tsx` | Create/edit an asset on `/assets`, confirm duplicate code returns `409`, verify `dept@poona.demo` sees ICU assets only, search in TopBar to jump to asset/complaint detail, and upload/preview/delete attachments on `/assets/:id`. |
| **3** | **Breakdown & Complaint Workflow + Ist Downtime Calculation** (sequential `complaint_no`, response time, `clip_downtime_to_month`, assign/attend/restore/close/reopen syncing `Asset.status`, role-gated technical fields) | `backend/tests/test_complaints.py`<br>`backend/tests/test_time_utils.py`<br>`frontend/src/test/complaint-detail.test.tsx` | Raise a complaint via `AssetPicker`, verify `dept@poona.demo` sees the Technical/CE/Spares read-only lock, complete the repair workflow as `bio@poona.demo`, and verify `Asset.status` returns to `in_service`. |
| **4** | **Preventive Maintenance & Calibration Schedules** (in-house & outsourced PM, dynamic `upcoming`/`due`/`overdue` vs `effective_today()`, clamped `add_months`, calibration approval gate, certificate upload) | `backend/tests/test_pm_and_calibration.py`<br>`frontend/src/test/pm-page.test.tsx`<br>`frontend/src/test/calibration-page.test.tsx` | Toggle Table and Calendar views on `/pm`, complete & reschedule cycles, verify `bio@poona.demo` receives `403` on calibration approval while `mgmt@poona.demo`/`coord@poona.demo` can approve, and upload calibration certificates. |
| **5** | **Contracts, Warranties, Insurance, Demo Equipment & Department Visits** (contract renewal superseding & history, warranty/insurance expiry chips, `InsuranceDrawer`, demo return tracking, visit `403` for `department_user`/`coordinator`) | `backend/tests/test_phase5_modules.py`<br>`frontend/src/test/phase5-modules.test.tsx` | Renew a contract on `/contracts` and check history chain, open `InsuranceDrawer` from `AssetDetailPage`, mark a demo equipment returned on `/demo-equipment`, and log a multi-asset visit on `/visits` as `bio@poona.demo`. |
| **6** | **Automated Alert Engine, `06:00 Asia/Kolkata` Scheduler & Notifications** (7 alert types, dedupe keys, per-user read state, TopBar bell polling, `CalibrationReminderModal`, Demo Clock `demo_as_of_date`) | `backend/tests/test_notifications_and_dashboard.py`<br>`frontend/src/test/phase6-modules.test.tsx` | Advance TopBar Demo Clock (+20 days) as `admin@poona.demo`, run alert check in `/settings`, confirm new notifications appear without duplicates on second run, mark read per user, and check login reminder pop-up. |
| **7** | **Hospital Operations Dashboard** (role-aware department scope banner, 7 clickable KPI cards, 4 Recharts charts, Needs Attention & Recent Complaints) | `backend/tests/test_notifications_and_dashboard.py` (`test_dashboard_summary_role_scoping_and_charts`)<br>`frontend/src/test/phase6-modules.test.tsx` | Compare `/` as `mgmt@poona.demo` (hospital-wide) vs `dept@poona.demo` (ICU-scoped) and verify KPI navigation and chart tooltips. |
| **8** | **8 Operational Reports, Excel/CSV Exports & A4 Print** (8 report keys, 3-complaint downtime reconciliation, `daily-visit` RBAC `403`, openpyxl `.xlsx` & UTF-8 BOM `.csv` exports, `@media print`) | `backend/tests/test_reports.py`<br>`frontend/src/test/reports.test.tsx` | Open `/reports`, verify `daily-visit` is hidden/`403` for `dept@poona.demo` & `coord@poona.demo`, inspect Monthly Maintenance `"How this is calculated"` formula popover, download `.xlsx`/`.csv`, and open Print Preview (A4 landscape). |
+11
View File
@@ -13,3 +13,14 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her
9. **Demo Clock (`demo_as_of_date`)**: System-wide `effective_today()` reads `demo_as_of_date` (`YYYY-MM-DD`) from Settings if non-empty; otherwise uses the real current date in `Asia/Kolkata`.
10. **Soft Deletion for Masters & Users**: Deleting departments, locations, categories, vendors, or users sets `is_active = False` rather than hard-deleting rows so historical asset/complaint/maintenance foreign keys remain intact.
11. **Password Hashing on Python 3.13**: `passlib==1.7.4` is incompatible with `bcrypt>=4.1` on Python 3.13 (`__about__` attribute removed / 72-byte wrap-check error), so `app/core/security.py` uses `bcrypt` (`bcrypt==5.0.0`) directly.
## Assumptions added post-Phase-8
12. **Permission Specifics**: `system_admin` and `biomedical` can create and edit full asset records (`coordinator` is restricted to updating `requires_calibration`, `insurance_applicable`, and `remarks`). Calibration frequency edits and plan approvals are restricted to `system_admin`, `management`, and `coordinator` (`biomedical` receives HTTP `403`). `department_user` is scoped to their assigned department (`ICU` in demo data) across assets, complaints, PM, calibration, contracts, notifications, dashboard, reports, and global search, whereas `system_admin`, `biomedical`, `management`, and `coordinator` view all departments hospital-wide. `management` and `coordinator` cannot raise complaints (enforced server-side with HTTP `403`).
13. **Critical Complaint Escalation & SLA Evaluation**: APScheduler runs `alerts.py` daily (default `06:00` in configured `TIMEZONE`) and raises `critical_complaint` notifications when open critical complaint age exceeds `escalation_open_complaint_hours` (default `24`h) or breaches `compute_sla_status` against `critical_complaint_sla_hours` (default `4`h) / `non_critical_complaint_sla_hours` (default `24`h).
14. **Insurance Drawer**: Insurance summary is surfaced via a read-only slide-over panel (`InsuranceDrawer`) from `AssetDetailPage`, `AssetPicker`, and `ComplaintDetailPage`; creating and editing policies is handled via modal dialogs on `/insurance` and the Asset Insurance tab.
15. **Demo-Only Features**: The TopBar **Demo Clock** (`demo_as_of_date`, admin-only date override for demonstrating expiry/overdue alerts and dynamic schedule transitions) and the deterministic seed loader (`python -m app.seed.seed`) exist specifically for demonstration and verification.
16. **Reopen Clears `restored_at`**: Reopening a closed breakdown complaint clears both `closed_at` and `restored_at` (`None`) on the complaint row so downtime resumes as ongoing until re-restored.
17. **Immediate Asset Return to Service**: When a breakdown complaint is restored or closed (and no other unrestored critical complaints exist on the asset), `Asset.status` transitions immediately to `in_service` rather than requiring an extra post-repair sign-off step.
18. **Code Prefixes (`complaint_no_prefix` & `asset_code_prefix`)**: Complaint numbers are auto-generated using `complaint_no_prefix` (default `CMP`, e.g. `CMP-2026-0001`; `BD-` or another prefix can be configured in Settings). Asset codes are entered manually to match physical hospital asset tags rather than auto-generated, so `asset_code_prefix` (default `PHRC`) acts as a configurable hospital label prefix shown in Settings and used for the bulk-import template sample code.
19. **Monthly Maintenance `Uptime %` Display**: The `monthly-maintenance` backend report aggregates uptime/downtime in minutes per department rather than returning per-asset `uptime_seconds`/`downtime_seconds`, so `Uptime %` (`uptime / (uptime + downtime) * 100`, 1 decimal place) is computed on the frontend in `ReportDetailPage.tsx` (falling back to `100 - downtime_pct`) and highlighted in the summary strip and table.
+60
View File
@@ -0,0 +1,60 @@
# Poona Hospital AMS — 10-Minute End-to-End Demo Script
**Prerequisites**:
1. Run `python -m app.seed.seed` inside `backend/` to load realistic hospital demo data (60 assets, 30 complaints, 45 PM schedules, 20 calibration plans, 35 contracts, 20 warranties, 25 insurance policies, 3 demo items, 12 department visits, and 26 alerts).
2. Start backend (`uvicorn app.main:app --port 8000`) and frontend (`npm run dev` on `http://localhost:5173`), or run `docker compose up --build`.
3. All demo accounts use password **`Demo@123`**:
- **System Admin**: `admin@poona.demo`
- **Biomedical Engineer**: `bio@poona.demo`
- **Department User (ICU)**: `dept@poona.demo`
- **Management**: `mgmt@poona.demo`
- **Coordinator**: `coord@poona.demo`
---
## Step 1 — Login, Role Overview & Calibration Pop-up (1 min)
1. Open `http://localhost:5173/login`. Use Quick Demo Login or sign in as **Biomedical** (`bio@poona.demo` / `Demo@123`).
2. Observe the **Calibration Reminder Pop-up** (`CalibrationReminderModal`) surfacing upcoming/due/overdue calibrations once per login. Click **Go to Calibration** or dismiss it.
3. Point out the role-filtered sidebar (no Masters/Settings/Audit Log for Biomedical).
## Step 2 — Hospital Operations Dashboard & Global Quick Search (1 min)
1. On `/` (`DashboardPage`), review the 7 clickable KPI cards, the 4 Recharts visualizations (Complaints by Status, Complaints by Department, 6-Month Downtime Trend, PM Planned vs Completed), **Needs Attention**, and **Recent Complaints**.
2. In the TopBar search box, type `PHRC` or `Ventilator`. Observe the grouped **Assets** and **Complaints** dropdown; click an asset to jump directly to `/assets/:id`.
## Step 3 — Asset Register, 8-Tab Detail & Insurance Drawer (1 min)
1. Navigate to `/assets` and open an ICU asset (`/assets/:id`).
2. Walk through the tabs (**Overview**, **Contracts**, **Warranty**, **Insurance**, **PM**, **Calibration**, **Complaints**, **Documents**).
3. Click **View Insurance** to slide open `InsuranceDrawer` showing policy coverage in INR and attached policy PDF.
## Step 4 — Breakdown Complaint Lifecycle & Department Scoping (1.5 min)
1. Sign out and log in as **Department User (ICU)** (`dept@poona.demo` / `Demo@123`).
- Notice the ICU-scoped dashboard banner and asset/complaint lists limited to ICU.
- Click **Raise Complaint** (`/complaints`), select an ICU asset using `AssetPicker` (note warranty/coverage badge), enter a breakdown description, attach an image/PDF, and submit.
- Open a complaint detail (`/complaints/:id`) and point out the **read-only lock banner** on the Technical / CE / Spares section (`FORBIDDEN_TECHNICAL_FIELDS` for non-biomedical/admin roles).
2. Switch to **Biomedical** (`bio@poona.demo`), open the newly raised complaint, assign/attend/restore it, enter technical action & spares, and close it with closure remarks—confirm `Asset.status` syncs back to `in_service` and downtime is calculated in IST.
## Step 5 — Preventive Maintenance Table & Calendar Views (1 min)
1. Open `/pm` (`PMPage`). Review the KPI strip and toggle between **Table View** and the **7-column Mon–Sun Month Calendar View**.
2. Complete a due PM item (auto-advances next cycle using clamped `add_months`) or reschedule an upcoming PM item.
## Step 6 — Calibration Plan Approval Gate (1 min)
1. Open `/calibration` (`CalibrationPage`) as **Biomedical** (`bio@poona.demo`). Note that creating/completing calibrations (with certificate PDF upload) is enabled, whereas frequency approval controls are gated (`FORBIDDEN_CALIBRATION_APPROVAL`).
2. Switch to **Management** (`mgmt@poona.demo`) or **Coordinator** (`coord@poona.demo`) to approve a calibration plan's frequency.
## Step 7 — Contracts Renewal Chain, Warranties, Demo Equipment & Visits (1 min)
1. Open `/contracts` (`/contracts`) and renew an expiring AMC/CMC contract—observe the superseded badge on the prior contract and the intact renewal history chain.
2. Open `/demo-equipment` to view active vs overdue trial equipment and log a return.
3. Open `/visits` as **Biomedical** (`bio@poona.demo`) to review/log a department round linked to multiple assets and complaints; verify `dept@poona.demo` / `coord@poona.demo` cannot access `/visits`.
## Step 8 — Demo Clock ("As of Date") & Live Alert Engine (1 min)
1. Log in as **System Admin** (`admin@poona.demo`).
2. Use the TopBar **"As of Date"** Demo Clock to advance the date by +20 days.
3. Click **Run alert check now** in `/settings` (or `/notifications`), watch new deduplicated notifications appear in the TopBar bell counter and `/notifications` inbox, then reset Demo Date back to real time.
## Step 9 — 8 Operational Reports, Formula Transparency & Excel/CSV/Print (1 min)
1. Open `/reports` (`ReportsPage`) and click **Monthly Maintenance Summary** (`/reports/monthly-maintenance`).
2. Inspect the **"How this is calculated"** formula popover (`scheduled_hours_per_day`, `downtime_end_milestone`, `clip_downtime_to_month`), Recharts BarChart/PieChart, export `.xlsx` and `.csv`, and trigger **Print (A4)** preview.
## Step 10 — Audit Log Viewer & Rate-Limit Protection (0.5 min)
1. As **System Admin** (`admin@poona.demo`), open `/audit-logs` (`AuditLogsPage`) to filter historical entity mutations by Entity Type, User, Action, Date Range, and search query, and inspect the JSON diff modal.
2. Confirm `/audit-logs` is restricted to `system_admin` only (`403` for other roles) and `POST /api/auth/login` enforces sliding-window rate limiting (`429 RATE_LIMITED`).
+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.
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.
+18
View File
@@ -0,0 +1,18 @@
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
+22
View File
@@ -0,0 +1,22 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
client_max_body_size 15M;
location /api/ {
proxy_pass http://backend:8000/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
try_files $uri $uri/ /index.html;
}
}
+104
View File
@@ -33,6 +33,7 @@
"react-router-dom": "^6.28.0",
"recharts": "^2.13.3",
"tailwind-merge": "^2.5.4",
"xlsx": "^0.18.5",
"zod": "^3.23.8",
"zustand": "^4.5.5"
},
@@ -3505,6 +3506,15 @@
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/adler-32": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz",
"integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
@@ -3840,6 +3850,19 @@
],
"license": "CC-BY-4.0"
},
"node_modules/cfb": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz",
"integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"crc-32": "~1.2.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/chai": {
"version": "5.3.3",
"resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
@@ -3943,6 +3966,15 @@
"node": ">=6"
}
},
"node_modules/codepage": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz",
"integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -4000,6 +4032,18 @@
"dev": true,
"license": "MIT"
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
"license": "Apache-2.0",
"bin": {
"crc32": "bin/crc32.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -4835,6 +4879,15 @@
"node": ">= 6"
}
},
"node_modules/frac": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz",
"integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/fraction.js": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz",
@@ -6541,6 +6594,18 @@
"node": ">=0.10.0"
}
},
"node_modules/ssf": {
"version": "0.11.2",
"resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz",
"integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
"license": "Apache-2.0",
"dependencies": {
"frac": "~1.1.2"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/stackback": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
@@ -7283,6 +7348,24 @@
"node": ">=8"
}
},
"node_modules/wmf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz",
"integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz",
"integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
@@ -7315,6 +7398,27 @@
}
}
},
"node_modules/xlsx": {
"version": "0.18.5",
"resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz",
"integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"cfb": "~1.2.1",
"codepage": "~1.15.0",
"crc-32": "~1.2.1",
"ssf": "~0.11.2",
"wmf": "~1.0.1",
"word": "~0.3.0"
},
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
+1
View File
@@ -36,6 +36,7 @@
"react-router-dom": "^6.28.0",
"recharts": "^2.13.3",
"tailwind-merge": "^2.5.4",
"xlsx": "^0.18.5",
"zod": "^3.23.8",
"zustand": "^4.5.5"
},
+29 -15
View File
@@ -9,18 +9,20 @@ import { MastersPage } from "@/pages/MastersPage";
import { SettingsPage } from "@/pages/SettingsPage";
import { AssetsPage } from "@/pages/AssetsPage";
import { AssetDetailPage } from "@/pages/AssetDetailPage";
import {
DashboardPage,
ComplaintsPage,
PMPage,
CalibrationPage,
ContractsPage,
InsurancePage,
DemoEquipmentPage,
VisitsPage,
ReportsPage,
NotificationsPage,
} from "@/pages/stubs";
import { ComplaintsPage } from "@/pages/ComplaintsPage";
import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage";
import { PMPage } from "@/pages/PMPage";
import { CalibrationPage } from "@/pages/CalibrationPage";
import { ContractsPage } from "@/pages/ContractsPage";
import { InsurancePage } from "@/pages/InsurancePage";
import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
import { VisitsPage } from "@/pages/VisitsPage";
import { DashboardPage } from "@/pages/DashboardPage";
import { NotificationsPage } from "@/pages/NotificationsPage";
import { ReportsPage } from "@/pages/ReportsPage";
import { ReportDetailPage } from "@/pages/ReportDetailPage";
import { AuditLogsPage } from "@/pages/AuditLogsPage";
import { ToastProvider } from "@/components/ToastProvider";
import { useAuthStore } from "@/hooks/useAuth";
import { can, type Capability } from "@/lib/permissions";
@@ -84,6 +86,7 @@ function AppRoutes() {
<Route path="/assets" element={<AssetsPage />} />
<Route path="/assets/:id" element={<AssetDetailPage />} />
<Route path="/complaints" element={<ComplaintsPage />} />
<Route path="/complaints/:id" element={<ComplaintDetailPage />} />
<Route path="/pm" element={<PMPage />} />
<Route path="/calibration" element={<CalibrationPage />} />
<Route path="/contracts" element={<ContractsPage />} />
@@ -98,6 +101,7 @@ function AppRoutes() {
}
/>
<Route path="/reports" element={<ReportsPage />} />
<Route path="/reports/:reportKey" element={<ReportDetailPage />} />
<Route path="/notifications" element={<NotificationsPage />} />
<Route
path="/masters"
@@ -107,6 +111,14 @@ function AppRoutes() {
</RoleGuard>
}
/>
<Route
path="/audit-logs"
element={
<RoleGuard capability="manage_admin">
<AuditLogsPage />
</RoleGuard>
}
/>
<Route
path="/settings"
element={
@@ -125,9 +137,11 @@ function AppRoutes() {
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<AppRoutes />
</BrowserRouter>
<ToastProvider>
<BrowserRouter>
<AppRoutes />
</BrowserRouter>
</ToastProvider>
</QueryClientProvider>
);
}
+48
View File
@@ -225,6 +225,35 @@ export interface AssetCreatePayload {
export type AssetUpdatePayload = Partial<AssetCreatePayload>;
export interface BulkImportErrorItem {
row: number;
asset_code: string | null;
error: string;
}
export interface BulkImportPreviewRow {
row: number;
asset_code: string | null;
serial_no: string | null;
name: string | null;
category_name: string | null;
department_name: string | null;
location_name: string | null;
status: string | null;
valid: boolean;
error: string | null;
}
export interface BulkImportResult {
dry_run: boolean;
total_rows: number;
valid_count: number;
error_count: number;
created_count: number;
errors: BulkImportErrorItem[];
preview_rows: BulkImportPreviewRow[];
}
export const assetsApi = {
list: (params: AssetListParams = {}) => {
const qs = new URLSearchParams();
@@ -251,4 +280,23 @@ export const assetsApi = {
overview: (id: number) => api.get<AssetOverview>(`/assets/${id}/overview`),
create: (data: AssetCreatePayload) => api.post<AssetItem>("/assets", data),
update: (id: number, data: AssetUpdatePayload) => api.patch<AssetItem>(`/assets/${id}`, data),
downloadImportTemplate: async () => {
const { blob } = await api.downloadBlob("/assets/import-template");
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "asset_import_template.xlsx";
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
},
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
const formData = new FormData();
formData.append("file", file);
return api.upload<BulkImportResult>(
`/assets/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
formData
);
},
};
+45
View File
@@ -0,0 +1,45 @@
import { api } from "./client";
export interface AuditLogItem {
id: number;
entity_type: string;
entity_id: number;
action: string;
changes_json: string | null;
by_user_id: number | null;
by_user_name: string | null;
at: string;
}
export interface AuditLogsResponse {
items: AuditLogItem[];
total: number;
}
export interface AuditLogFilters {
entity_type?: string;
by_user_id?: number;
action?: string;
date_from?: string;
date_to?: string;
q?: string;
page?: number;
page_size?: number;
}
export const auditApi = {
list: (filters: AuditLogFilters = {}) => {
const params = new URLSearchParams();
if (filters.entity_type) params.set("entity_type", filters.entity_type);
if (filters.by_user_id != null) {
params.set("by_user_id", String(filters.by_user_id));
}
if (filters.action) params.set("action", filters.action);
if (filters.date_from) params.set("date_from", filters.date_from);
if (filters.date_to) params.set("date_to", filters.date_to);
if (filters.q) params.set("q", filters.q);
if (filters.page != null) params.set("page", String(filters.page));
params.set("page_size", String(filters.page_size ?? 200));
return api.get<AuditLogsResponse>(`/audit-logs?${params.toString()}`);
},
};
+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),
};
+153
View File
@@ -0,0 +1,153 @@
import { api } from "./client";
import type { AssetCriticality, AssetStatus } from "./assets";
export type CallStatus = "open" | "in_progress" | "closed";
export type TimestampField =
| "registered_at"
| "received_at"
| "attended_at"
| "restored_at"
| "closed_at"
| "ce_attended_at";
export interface ComplaintItem {
id: number;
complaint_no: string;
asset_id: number;
asset_code: string;
asset_name: string;
asset_status: AssetStatus | string;
department_id: number;
department_name: string | null;
location_name: string | null;
description: string;
breakdown_details: string | null;
priority: AssetCriticality | string;
notes: string | null;
registered_at: string;
registered_by_id: number;
registered_by_name: string | null;
received_by_id: number | null;
received_by_name: string | null;
received_at: string | null;
assigned_to_id: number | null;
assigned_to_name: string | null;
assigned_at: string | null;
attended_by_id: number | null;
attended_by_name: string | null;
attended_at: string | null;
restored_at: string | null;
closed_by_id: number | null;
closed_by_name: string | null;
closed_at: string | null;
call_status: CallStatus;
closure_remarks: string | null;
action_taken: string | null;
root_cause: string | null;
corrective_action: string | null;
lessons_learned: string | null;
ce_name: string | null;
ce_attended_at: string | null;
ce_action_taken: string | null;
spare_required: boolean;
spare_details: string | null;
spare_cost_estimate: number | null;
response_time_minutes: number | null;
downtime_minutes: number;
downtime_is_ongoing: boolean;
downtime_end_milestone: string;
response_start_setting: string;
ce_response_time_minutes: number | null;
updated_at: string;
}
export interface ComplaintEventItem {
id: number;
complaint_id: number;
event_type: string;
from_value: string | null;
to_value: string | null;
by_user_id: number | null;
by_user_name: string | null;
at: string;
note: string | null;
}
export interface ComplaintListParams {
q?: string;
department_id?: number;
asset_id?: number;
call_status?: CallStatus | "";
priority?: AssetCriticality | "";
assigned_to_id?: number;
closure_state?: "open_only" | "closed_only" | "";
date_from?: string;
date_to?: string;
page?: number;
page_size?: number;
}
export interface ComplaintCreatePayload {
asset_id: number;
description: string;
breakdown_details?: string | null;
priority: AssetCriticality;
notes?: string | null;
received_by_id?: number | null;
}
export interface ComplaintUpdatePayload {
description?: string;
breakdown_details?: string | null;
priority?: AssetCriticality;
notes?: string | null;
action_taken?: string | null;
root_cause?: string | null;
corrective_action?: string | null;
lessons_learned?: string | null;
ce_name?: string | null;
ce_attended_at?: string | null;
ce_action_taken?: string | null;
spare_required?: boolean;
spare_details?: string | null;
spare_cost_estimate?: number | null;
}
export const complaintsApi = {
list: (params: ComplaintListParams = {}) => {
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.call_status) qs.set("call_status", params.call_status);
if (params.priority) qs.set("priority", params.priority);
if (params.assigned_to_id) qs.set("assigned_to_id", String(params.assigned_to_id));
if (params.closure_state) qs.set("closure_state", params.closure_state);
if (params.date_from) qs.set("date_from", params.date_from);
if (params.date_to) qs.set("date_to", params.date_to);
qs.set("page", String(params.page ?? 1));
qs.set("page_size", String(params.page_size ?? 200));
return api.get<{ items: ComplaintItem[]; total: number }>(`/complaints?${qs.toString()}`);
},
create: (data: ComplaintCreatePayload) => api.post<ComplaintItem>("/complaints", data),
get: (id: number) => api.get<ComplaintItem>(`/complaints/${id}`),
events: (id: number) =>
api.get<{ items: ComplaintEventItem[]; total: number }>(`/complaints/${id}/events`),
update: (id: number, data: ComplaintUpdatePayload) =>
api.patch<ComplaintItem>(`/complaints/${id}`, data),
assign: (id: number, data: { assigned_to_id: number; note?: string }) =>
api.post<ComplaintItem>(`/complaints/${id}/assign`, data),
attend: (id: number, data: { attended_by_id?: number; note?: string } = {}) =>
api.post<ComplaintItem>(`/complaints/${id}/attend`, data),
restore: (id: number, data: { note?: string } = {}) =>
api.post<ComplaintItem>(`/complaints/${id}/restore`, data),
close: (id: number, data: { closure_remarks?: string } = {}) =>
api.post<ComplaintItem>(`/complaints/${id}/close`, data),
reopen: (id: number, data: { reason: string }) =>
api.post<ComplaintItem>(`/complaints/${id}/reopen`, data),
correctTimestamp: (
id: number,
data: { field: TimestampField; new_value: string; reason: string }
) => api.post<ComplaintItem>(`/complaints/${id}/correct-timestamp`, data),
};
+77
View File
@@ -0,0 +1,77 @@
import { api } from "./client";
export interface DashboardKPIs {
total_assets: number;
assets_under_repair: number;
open_complaints: number;
pm_due_this_month: number;
calibrations_due: number;
contracts_expiring: number;
equipment_on_demo: number;
}
export interface StatusCountItem {
status: string;
count: number;
}
export interface DeptComplaintCountItem {
department: string;
critical: number;
non_critical: number;
}
export interface MonthlyDowntimePoint {
month: string;
label: string;
downtime_minutes: number;
downtime_hours: number;
}
export interface MonthlyPMPoint {
month: string;
label: string;
planned: number;
completed: number;
}
export interface NeedsAttentionItem {
id: number;
type: string;
severity: string;
title: string;
message: string;
entity_type: string | null;
entity_id: number | null;
due_date: string | null;
link_url: string;
}
export interface RecentComplaintItem {
id: number;
complaint_no: string;
asset_code: string;
asset_name: string;
department_name: string | null;
priority: string;
call_status: string;
registered_at: string;
downtime_minutes: number;
downtime_is_ongoing: boolean;
}
export interface DashboardSummary {
department_scope: string | null;
effective_today: string;
kpis: DashboardKPIs;
complaints_by_status: StatusCountItem[];
complaints_by_department: DeptComplaintCountItem[];
monthly_downtime_trend: MonthlyDowntimePoint[];
pm_planned_vs_completed: MonthlyPMPoint[];
needs_attention: NeedsAttentionItem[];
recent_complaints: RecentComplaintItem[];
}
export const dashboardApi = {
summary: () => api.get<DashboardSummary>("/dashboard/summary"),
};
+17
View File
@@ -154,3 +154,20 @@ export const usersApi = {
) => api.patch<MasterUser>(`/users/${id}`, data),
remove: (id: number) => api.delete<void>(`/users/${id}`),
};
export interface UserLookupItem {
id: number;
name: string;
role: Role;
department_id: number | null;
}
export async function fetchUsersLookup(): Promise<{ items: UserLookupItem[]; total: number }> {
const res = await api.get<UserLookupItem[] | { items: UserLookupItem[]; total: number }>(
"/users/lookup"
);
if (Array.isArray(res)) {
return { items: res, total: res.length };
}
return res;
}
+68
View File
@@ -0,0 +1,68 @@
import { api } from "./client";
export type NotificationSeverity = "info" | "yellow" | "red";
export type NotificationType =
| "amc_expiry"
| "calibration_due"
| "pm_due"
| "insurance_expiry"
| "warranty_expiry"
| "demo_overdue"
| "critical_complaint"
| "sla_breach";
export interface NotificationItem {
id: number;
type: NotificationType | string;
severity: NotificationSeverity | string;
title: string;
message: string;
entity_type: string | null;
entity_id: number | null;
due_date: string | null;
created_at: string;
is_read: boolean;
read_at: string | null;
link_url: string;
}
export interface NotificationListResponse {
items: NotificationItem[];
total: number;
unread_count: number;
unread_calibration_count: number;
}
export interface NotificationListParams {
type?: string;
severity?: string;
unread_only?: boolean;
limit?: number;
page?: number;
page_size?: number;
}
export const notificationsApi = {
list: (params: NotificationListParams = {}) => {
const sp = new URLSearchParams();
if (params.type) sp.set("type", params.type);
if (params.severity) sp.set("severity", params.severity);
if (params.unread_only) sp.set("unread_only", "true");
if (params.limit != null) sp.set("limit", String(params.limit));
if (params.page != null) sp.set("page", String(params.page));
if (params.page_size != null) sp.set("page_size", String(params.page_size));
const qs = sp.toString();
return api.get<NotificationListResponse>(`/notifications${qs ? `?${qs}` : ""}`);
},
markRead: (id: number) =>
api.post<{ status: string; id: number }>(`/notifications/${id}/read`),
markAllRead: (type?: string) => {
const qs = type ? `?type=${encodeURIComponent(type)}` : "";
return api.post<{ status: string; marked_count?: number }>(
`/notifications/read-all${qs}`
);
},
runAlertsNow: () =>
api.post<{ created: number; evaluated_today: string }>("/alerts/run"),
};
+303
View File
@@ -0,0 +1,303 @@
import { api } from "./client";
import type { AlertSeverity, CoverageStatus } from "./assets";
export type ContractStatus = CoverageStatus | "superseded";
export type DemoStatus = "on_demo" | "overdue_return" | "returned";
export interface ContractItem {
id: number;
asset_id: number;
asset_code: string;
asset_name: string;
department_id: number;
department_name: string | null;
contract_type: string;
provider_id: number;
provider_name: string | null;
start_date: string;
end_date: string;
coverage_period_text: string | null;
renewed_from_id: number | null;
is_superseded: boolean;
status: ContractStatus | string;
severity: AlertSeverity | string;
days_to_expiry: number;
attachment_count: number;
remarks: string | null;
created_at: string;
}
export interface ContractListParams {
q?: string;
department_id?: number;
asset_id?: number;
provider_id?: number;
contract_type?: string;
status?: string;
include_superseded?: boolean;
page?: number;
page_size?: number;
}
export interface ContractCreatePayload {
asset_id: number;
contract_type: string;
provider_id: number;
start_date: string;
end_date: string;
coverage_period_text?: string | null;
remarks?: string | null;
}
export interface ContractRenewPayload {
contract_type?: string;
provider_id?: number;
start_date: string;
end_date: string;
coverage_period_text?: string | null;
remarks?: string | null;
}
export interface WarrantyItem {
id: number;
asset_id: number;
asset_code: string;
asset_name: string;
department_id: number;
department_name: string | null;
duration_months: number;
start_date: string;
end_date: string;
provider_id: number | null;
provider_name: string | null;
status: CoverageStatus | string;
severity: AlertSeverity | string;
days_to_expiry: number;
attachment_count: number;
remarks: string | null;
created_at: string;
}
export interface WarrantyListParams {
q?: string;
department_id?: number;
asset_id?: number;
status?: string;
page?: number;
page_size?: number;
}
export interface WarrantyCreatePayload {
asset_id: number;
duration_months: number;
start_date: string;
end_date: string;
provider_id?: number | null;
remarks?: string | null;
}
export interface InsuranceItem {
id: number;
asset_id: number;
asset_code: string;
asset_name: string;
department_id: number;
department_name: string | null;
insurer_id: number;
insurer_name: string | null;
policy_no: string;
start_date: string;
end_date: string;
coverage_amount: number | null;
status: CoverageStatus | string;
severity: AlertSeverity | string;
days_to_expiry: number;
attachment_count: number;
remarks: string | null;
created_at: string;
}
export interface InsuranceListParams {
q?: string;
department_id?: number;
asset_id?: number;
insurer_id?: number;
status?: string;
page?: number;
page_size?: number;
}
export interface InsuranceCreatePayload {
asset_id: number;
insurer_id: number;
policy_no: string;
start_date: string;
end_date: string;
coverage_amount?: number | null;
remarks?: string | null;
}
export interface DemoEquipmentItem {
id: number;
name: string;
equipment_type: string;
supplier_id: number;
supplier_name: string | null;
department_id: number;
department_name: string | null;
location_id: number | null;
location_name: string | null;
start_date: string;
expected_return_date: string;
actual_return_date: string | null;
status: DemoStatus | string;
severity: AlertSeverity | string;
days_remaining: number;
attachment_count: number;
remarks: string | null;
created_at: string;
}
export interface DemoListParams {
q?: string;
supplier_id?: number;
department_id?: number;
status?: string;
date_from?: string;
date_to?: string;
page?: number;
page_size?: number;
}
export interface DemoCreatePayload {
name: string;
equipment_type: string;
supplier_id: number;
department_id: number;
location_id?: number | null;
start_date: string;
expected_return_date: string;
remarks?: string | null;
}
export interface VisitAssetBrief {
id: number;
asset_code: string;
name: string;
}
export interface VisitComplaintBrief {
id: number;
complaint_no: string;
call_status: string;
priority: string;
description: string;
}
export interface VisitItem {
id: number;
department_id: number;
department_name: string | null;
visited_by_id: number;
visited_by_name: string | null;
visit_date: string;
observations: string;
assets: VisitAssetBrief[];
complaints: VisitComplaintBrief[];
created_at: string;
}
export interface VisitListParams {
q?: string;
department_id?: number;
visited_by_id?: number;
date_from?: string;
date_to?: string;
page?: number;
page_size?: number;
}
export interface VisitCreatePayload {
department_id: number;
visit_date: string;
observations: string;
asset_ids?: number[];
complaint_ids?: number[];
}
function toQS(params: Record<string, string | number | boolean | undefined>): string {
const sp = new URLSearchParams();
for (const [k, v] of Object.entries(params)) {
if (v === undefined || v === "") continue;
sp.set(k, String(v));
}
const s = sp.toString();
return s ? `?${s}` : "";
}
export const contractsApi = {
list: (params: ContractListParams = {}) =>
api.get<{ items: ContractItem[]; total: number }>(
`/contracts${toQS(params as Record<string, string | number | boolean | undefined>)}`
),
create: (data: ContractCreatePayload) => api.post<ContractItem>("/contracts", data),
update: (id: number, data: Partial<ContractCreatePayload>) =>
api.patch<ContractItem>(`/contracts/${id}`, data),
remove: (id: number) => api.delete<void>(`/contracts/${id}`),
renew: (id: number, data: ContractRenewPayload) =>
api.post<{ old_contract: ContractItem; new_contract: ContractItem }>(
`/contracts/${id}/renew`,
data
),
history: (assetId: number) =>
api.get<{ items: ContractItem[] }>(`/contracts/history/${assetId}`),
};
export const warrantiesApi = {
list: (params: WarrantyListParams = {}) =>
api.get<{ items: WarrantyItem[]; total: number }>(
`/warranties${toQS(params as Record<string, string | number | boolean | undefined>)}`
),
create: (data: WarrantyCreatePayload) => api.post<WarrantyItem>("/warranties", data),
update: (id: number, data: Partial<WarrantyCreatePayload>) =>
api.patch<WarrantyItem>(`/warranties/${id}`, data),
remove: (id: number) => api.delete<void>(`/warranties/${id}`),
};
export const insuranceApi = {
list: (params: InsuranceListParams = {}) =>
api.get<{ items: InsuranceItem[]; total: number }>(
`/insurance${toQS(params as Record<string, string | number | boolean | undefined>)}`
),
create: (data: InsuranceCreatePayload) => api.post<InsuranceItem>("/insurance", data),
update: (id: number, data: Partial<InsuranceCreatePayload>) =>
api.patch<InsuranceItem>(`/insurance/${id}`, data),
remove: (id: number) => api.delete<void>(`/insurance/${id}`),
};
export const demoEquipmentApi = {
list: (params: DemoListParams = {}) =>
api.get<{ items: DemoEquipmentItem[]; total: number }>(
`/demo-equipment${toQS(params as Record<string, string | number | boolean | undefined>)}`
),
create: (data: DemoCreatePayload) =>
api.post<DemoEquipmentItem>("/demo-equipment", data),
update: (id: number, data: Partial<DemoCreatePayload>) =>
api.patch<DemoEquipmentItem>(`/demo-equipment/${id}`, data),
remove: (id: number) => api.delete<void>(`/demo-equipment/${id}`),
markReturned: (id: number, data: { actual_return_date: string; remarks?: string | null }) =>
api.post<DemoEquipmentItem>(`/demo-equipment/${id}/return`, data),
};
export const visitsApi = {
list: (params: VisitListParams = {}) =>
api.get<{ items: VisitItem[]; total: number }>(
`/visits${toQS(params as Record<string, string | number | boolean | undefined>)}`
),
get: (id: number) => api.get<VisitItem>(`/visits/${id}`),
create: (data: VisitCreatePayload) => api.post<VisitItem>("/visits", data),
update: (id: number, data: Partial<VisitCreatePayload>) =>
api.patch<VisitItem>(`/visits/${id}`, data),
linkComplaint: (id: number, complaintId: number) =>
api.post<VisitItem>(`/visits/${id}/link-complaint`, { complaint_id: complaintId }),
};
+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
),
};
+143
View File
@@ -0,0 +1,143 @@
import { api } from "./client";
import type { Role } from "@/lib/permissions";
export type ReportKey =
| "monthly-maintenance"
| "monthly-department"
| "daily-visit"
| "breakdown-complaints"
| "pm-compliance"
| "calibration-due"
| "contracts-warranty"
| "demo-equipment";
export interface ReportColumn {
key: string;
label: string;
}
export interface FormulaInfo {
scheduled_hours_per_day: number;
downtime_end_milestone: string;
days_in_month: number;
uptime_formula: string;
downtime_formula: string;
}
export interface ReportChartPoint {
department: string;
downtime_hours: number;
uptime_hours: number;
}
export interface ReportPayload {
report_key: ReportKey | string;
title: string;
filters_applied: Record<string, string | number | null>;
formula_info?: FormulaInfo | null;
summary: Record<string, string | number>;
columns: ReportColumn[];
rows: Record<string, unknown>[];
chart_data?: ReportChartPoint[] | null;
}
export interface ReportMeta {
key: ReportKey;
title: string;
description: string;
category: string;
hiddenForRoles?: Role[];
}
export const REPORT_CATALOG: ReportMeta[] = [
{
key: "monthly-maintenance",
title: "Monthly Maintenance Summary",
description:
"Department-wise uptime vs downtime, clipped breakdown hours, distinct downtime days, and availability %.",
category: "Maintenance & Uptime",
},
{
key: "monthly-department",
title: "Monthly Department Report",
description:
"Asset health counts, under-repair equipment, outstanding complaints, visit counts, and requirement notes per department.",
category: "Department Operations",
},
{
key: "daily-visit",
title: "Daily Department Visit Report",
description:
"Daily biomedical round logs, equipment checked, observations, and linked breakdown complaints.",
category: "Department Operations",
hiddenForRoles: ["department_user", "coordinator"],
},
{
key: "breakdown-complaints",
title: "Breakdown / Complaint Report",
description:
"Full breakdown register with response time, total downtime, ongoing status, action taken, and closure remarks.",
category: "Breakdowns",
},
{
key: "pm-compliance",
title: "PM Compliance Report",
description:
"Planned vs completed preventive maintenance schedules across in-house and outsourced teams with compliance %.",
category: "Compliance & Schedules",
},
{
key: "calibration-due",
title: "Calibration Due Report",
description:
"Calibration status, due/completed dates, agencies, certificate numbers, and overdue tracking.",
category: "Compliance & Schedules",
},
{
key: "contracts-warranty",
title: "AMC / CMC & Warranty Report",
description:
"Active, expiring, expired, and superseded AMC/CMC contracts and equipment warranties with days to expiry.",
category: "Commercial & Coverage",
},
{
key: "demo-equipment",
title: "Demo Equipment Report",
description:
"Supplier trial equipment register highlighting expected return dates, returned units, and overdue days.",
category: "Commercial & Coverage",
},
];
export type ReportFilterParams = Record<string, string | number | undefined>;
function buildQuery(params: ReportFilterParams): string {
const sp = new URLSearchParams();
for (const [k, v] of Object.entries(params)) {
if (v === undefined || v === "") continue;
sp.set(k, String(v));
}
const qs = sp.toString();
return qs ? `?${qs}` : "";
}
export function fetchReport(key: ReportKey, params: ReportFilterParams = {}) {
return api.get<ReportPayload>(`/reports/${key}${buildQuery(params)}`);
}
export async function exportReport(
key: ReportKey,
format: "xlsx" | "csv",
params: ReportFilterParams = {}
) {
const qs = buildQuery({ ...params, format });
const { blob } = await api.downloadBlob(`/reports/${key}/export${qs}`);
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${key}.${format}`;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 10_000);
}
+32
View File
@@ -0,0 +1,32 @@
import { api } from "./client";
export interface SearchAssetItem {
id: number;
asset_code: string;
name: string;
serial_no: string | null;
department_name: string | null;
status: string;
}
export interface SearchComplaintItem {
id: number;
complaint_no: string;
asset_code: string | null;
asset_name: string | null;
department_name: string | null;
call_status: string;
priority: string;
}
export interface GlobalSearchResponse {
assets: SearchAssetItem[];
complaints: SearchComplaintItem[];
}
export const searchApi = {
query: (q: string) => {
const params = new URLSearchParams({ q });
return api.get<GlobalSearchResponse>(`/search?${params.toString()}`);
},
};
+9 -3
View File
@@ -83,8 +83,14 @@ export function AssetFormModal({
});
const departments = deptsQuery.data?.items ?? [];
const allLocations = locsQuery.data?.items ?? [];
const categories = catsQuery.data?.items ?? [];
const allLocations = useMemo(
() => locsQuery.data?.items ?? [],
[locsQuery.data?.items]
);
const categories = useMemo(
() => catsQuery.data?.items ?? [],
[catsQuery.data?.items]
);
const vendors = vendorsQuery.data?.items ?? [];
const defaultDeptId = editing?.department_id ?? departments[0]?.id ?? 0;
@@ -161,7 +167,7 @@ export function AssetFormModal({
remarks: "",
});
}
}, [open, editing, categories.length, defaultDeptId, defaultLocId, reset]);
}, [open, editing, categories, defaultDeptId, defaultLocId, reset]);
const watchedDeptId = Number(watch("department_id"));
const filteredLocations = useMemo(
+21 -2
View File
@@ -3,6 +3,7 @@ import { Search, X, ShieldCheck, Ban } from "lucide-react";
import { assetsApi, type AssetLookupItem } from "@/api/assets";
import { formatDate } from "@/lib/format";
import { CoverageBadge, AssetStatusBadge } from "./StatusBadge";
import { InsuranceDrawer } from "./InsuranceDrawer";
interface AssetPickerProps {
selectedAsset: AssetLookupItem | null;
@@ -24,6 +25,7 @@ export function AssetPicker({
const [results, setResults] = useState<AssetLookupItem[]>([]);
const [loading, setLoading] = useState(false);
const [open, setOpen] = useState(false);
const [insuranceOpen, setInsuranceOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -148,11 +150,28 @@ export function AssetPicker({
</div>
<div>
<div className="text-gray-500">Insurance</div>
<div className="font-medium text-gray-800">
{selectedAsset.insurance_summary || selectedAsset.insurance_status || "None"}
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium text-gray-800">
{selectedAsset.insurance_summary || selectedAsset.insurance_status || "None"}
</span>
<button
type="button"
onClick={() => setInsuranceOpen(true)}
className="text-xs font-medium text-[#1e3a8a] hover:underline"
>
View Insurance
</button>
</div>
</div>
</div>
{insuranceOpen && (
<InsuranceDrawer
open={insuranceOpen}
onClose={() => setInsuranceOpen(false)}
assetId={selectedAsset.id}
assetLabel={`${selectedAsset.asset_code} — ${selectedAsset.name}`}
/>
)}
</div>
);
}
+1 -18
View File
@@ -16,26 +16,9 @@ import {
} from "@/api/attachments";
import { ApiError } from "@/api/client";
import { formatDateTime } from "@/lib/format";
import { validateAttachmentFile } from "@/lib/validation";
import { Button } from "@/components/ui/button";
const MAX_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
const ALLOWED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".pdf"];
const ALLOWED_MIME_TYPES = ["image/jpeg", "image/png", "application/pdf"];
export function validateAttachmentFile(file: File): string | null {
const nameLower = file.name.toLowerCase();
const hasAllowedExt = ALLOWED_EXTENSIONS.some((ext) => nameLower.endsWith(ext));
const hasAllowedMime = !file.type || ALLOWED_MIME_TYPES.includes(file.type);
if (!hasAllowedExt || !hasAllowedMime) {
return "Invalid file type. Only JPG, PNG, and PDF files are allowed.";
}
if (file.size > MAX_SIZE_BYTES) {
return "File is too large. Maximum allowed size is 10 MB.";
}
return null;
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
@@ -0,0 +1,373 @@
import { useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import {
Download,
FileSpreadsheet,
Upload,
CheckCircle2,
AlertCircle,
X,
} from "lucide-react";
import { assetsApi, type BulkImportResult } from "@/api/assets";
import { ApiError } from "@/api/client";
import { Modal } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
interface BulkAssetImportModalProps {
open: boolean;
onClose: () => void;
}
const ACCEPTED_EXTS = [".xlsx", ".xls", ".csv"];
export function BulkAssetImportModal({ open, onClose }: BulkAssetImportModalProps) {
const qc = useQueryClient();
const fileInputRef = useRef<HTMLInputElement>(null);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [dragActive, setDragActive] = useState(false);
const [downloadingTemplate, setDownloadingTemplate] = useState(false);
const [validating, setValidating] = useState(false);
const [importing, setImporting] = useState(false);
const [skipInvalid, setSkipInvalid] = useState(false);
const [preview, setPreview] = useState<BulkImportResult | null>(null);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
function resetState() {
setSelectedFile(null);
setPreview(null);
setErrorMsg(null);
setSkipInvalid(false);
setValidating(false);
setImporting(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
function handleClose() {
if (importing) return;
resetState();
onClose();
}
async function handleDownloadTemplate() {
setDownloadingTemplate(true);
setErrorMsg(null);
try {
await assetsApi.downloadImportTemplate();
toast.success("Downloaded asset_import_template.xlsx");
} catch (err) {
const msg =
err instanceof ApiError
? err.detail
: "Failed to download import template.";
setErrorMsg(msg);
toast.error(msg);
} finally {
setDownloadingTemplate(false);
}
}
async function handleFileSelect(files: FileList | null) {
if (!files || files.length === 0) return;
const file = files[0];
const lower = file.name.toLowerCase();
if (!ACCEPTED_EXTS.some((ext) => lower.endsWith(ext))) {
setErrorMsg("Unsupported file type. Please upload an .xlsx, .xls, or .csv file.");
setSelectedFile(null);
setPreview(null);
return;
}
setSelectedFile(file);
setErrorMsg(null);
setPreview(null);
setSkipInvalid(false);
setValidating(true);
try {
const result = await assetsApi.bulkImport(file, true, false);
setPreview(result);
} catch (err) {
const msg =
err instanceof ApiError
? err.detail
: "Failed to validate import file.";
setErrorMsg(msg);
} finally {
setValidating(false);
}
}
async function handleConfirmImport() {
if (!selectedFile || !preview) return;
setImporting(true);
setErrorMsg(null);
try {
const result = await assetsApi.bulkImport(selectedFile, false, skipInvalid);
await Promise.all([
qc.invalidateQueries({ queryKey: ["assets"] }),
qc.invalidateQueries({ queryKey: ["dashboard"] }),
]);
toast.success(
`Imported ${result.created_count} asset${result.created_count === 1 ? "" : "s"}`
);
resetState();
onClose();
} catch (err) {
const msg =
err instanceof ApiError ? err.detail : "Bulk asset import failed.";
setErrorMsg(msg);
toast.error(msg);
} finally {
setImporting(false);
}
}
const canImport =
Boolean(selectedFile && preview) &&
!validating &&
!importing &&
preview!.valid_count > 0 &&
(preview!.error_count === 0 || skipInvalid);
return (
<Modal
open={open}
onOpenChange={(next) => {
if (!next) handleClose();
}}
title="Bulk Import Assets"
description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register multiple hospital assets at once."
className="max-w-4xl"
>
<div className="space-y-4">
{/* Step 1: Template Download */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-lg border border-blue-200 bg-blue-50/70 p-3.5">
<div className="flex items-start gap-2.5 text-xs text-blue-950">
<FileSpreadsheet className="h-5 w-5 text-[#1e3a8a] shrink-0 mt-0.5" />
<div>
<div className="font-semibold text-sm text-[#1e3a8a]">
Step 1: Download the Excel Template
</div>
<p className="mt-0.5 text-blue-900/90">
Fill equipment rows in the <strong>Assets</strong> sheet and check valid
departments, locations, categories, and suppliers in the{" "}
<strong>Master Reference</strong> sheet.
</p>
</div>
</div>
<Button
type="button"
variant="outline"
size="sm"
loading={downloadingTemplate}
onClick={handleDownloadTemplate}
className="shrink-0 bg-white"
>
<Download className="h-4 w-4 mr-1.5" />
Download Template (.xlsx)
</Button>
</div>
{/* Step 2: File Picker / Dropzone */}
<div
onDragOver={(e) => {
e.preventDefault();
setDragActive(true);
}}
onDragLeave={() => setDragActive(false)}
onDrop={(e) => {
e.preventDefault();
setDragActive(false);
void handleFileSelect(e.dataTransfer.files);
}}
className={cn(
"border-2 border-dashed rounded-lg p-5 text-center transition-colors",
dragActive
? "border-[#1e3a8a] bg-blue-50"
: "border-gray-300 bg-gray-50/60 hover:bg-gray-50"
)}
>
<input
ref={fileInputRef}
type="file"
accept=".xlsx,.xls,.csv"
aria-label="Upload asset spreadsheet"
onChange={(e) => void handleFileSelect(e.target.files)}
className="hidden"
/>
<Upload className="h-7 w-7 text-gray-400 mx-auto mb-2" />
<p className="text-sm font-medium text-gray-800">
{selectedFile ? selectedFile.name : "Drop your spreadsheet here, or browse"}
</p>
<p className="text-xs text-gray-500 mt-1">
Accepts <code>.xlsx</code>, <code>.xls</code>, or <code>.csv</code> — automatically validates rows before importing.
</p>
<div className="mt-3 flex items-center justify-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
disabled={validating || importing}
onClick={() => fileInputRef.current?.click()}
>
{selectedFile ? "Choose Another File" : "Select Spreadsheet"}
</Button>
{selectedFile && (
<Button
type="button"
variant="ghost"
size="sm"
disabled={validating || importing}
onClick={resetState}
>
<X className="h-3.5 w-3.5 mr-1" />
Clear
</Button>
)}
</div>
</div>
{validating && (
<div className="rounded-md border border-blue-200 bg-blue-50 px-3.5 py-2.5 text-xs text-blue-900">
Validating rows against hospital masters...
</div>
)}
{errorMsg && (
<div
role="alert"
className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800"
>
<AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
<span>{errorMsg}</span>
</div>
)}
{/* Step 3: Dry-run Validation Preview */}
{preview && (
<div className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-wrap items-center gap-2">
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700 border border-gray-200">
Total Rows: {preview.total_rows}
</span>
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
<CheckCircle2 className="h-3.5 w-3.5" />
Valid: {preview.valid_count}
</span>
<span
className={cn(
"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium border",
preview.error_count > 0
? "bg-red-100 text-red-800 border-red-200"
: "bg-gray-100 text-gray-600 border-gray-200"
)}
>
<AlertCircle className="h-3.5 w-3.5" />
Errors: {preview.error_count}
</span>
</div>
{preview.error_count > 0 && preview.valid_count > 0 && (
<label className="inline-flex items-center gap-2 text-xs font-medium text-gray-700 cursor-pointer">
<input
type="checkbox"
checked={skipInvalid}
onChange={(e) => setSkipInvalid(e.target.checked)}
className="rounded border-gray-300 text-[#1e3a8a] focus:ring-blue-500"
/>
Skip invalid rows and import valid rows only
</label>
)}
</div>
<div className="border border-gray-200 rounded-lg overflow-hidden">
<div className="max-h-64 overflow-auto">
<table className="w-full text-xs">
<thead className="bg-gray-50 border-b border-gray-200 sticky top-0">
<tr>
<th className="px-3 py-2 text-left font-medium text-gray-600">Row</th>
<th className="px-3 py-2 text-left font-medium text-gray-600">Asset Code</th>
<th className="px-3 py-2 text-left font-medium text-gray-600">Name</th>
<th className="px-3 py-2 text-left font-medium text-gray-600">Department</th>
<th className="px-3 py-2 text-left font-medium text-gray-600">Location</th>
<th className="px-3 py-2 text-left font-medium text-gray-600">Validation</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 bg-white">
{preview.preview_rows.length === 0 ? (
<tr>
<td colSpan={6} className="px-3 py-6 text-center text-gray-400">
No data rows found in spreadsheet.
</td>
</tr>
) : (
preview.preview_rows.map((r) => (
<tr
key={r.row}
className={r.valid ? "bg-white" : "bg-red-50/60"}
>
<td className="px-3 py-2 font-mono text-gray-500">{r.row}</td>
<td className="px-3 py-2 font-mono font-medium text-gray-900">
{r.asset_code || "—"}
</td>
<td className="px-3 py-2 text-gray-800">{r.name || "—"}</td>
<td className="px-3 py-2 text-gray-700">
{r.department_name || "—"}
</td>
<td className="px-3 py-2 text-gray-700">
{r.location_name || "—"}
</td>
<td className="px-3 py-2">
{r.valid ? (
<span className="inline-flex items-center gap-1 text-green-700 font-medium">
<CheckCircle2 className="h-3.5 w-3.5" />
Ready
</span>
) : (
<span className="inline-flex items-start gap-1 text-red-700">
<AlertCircle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
<span>{r.error || "Invalid row"}</span>
</span>
)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
)}
{/* Footer */}
<div className="flex flex-col-reverse sm:flex-row sm:items-center justify-end gap-2 pt-2 border-t border-gray-100">
<Button
type="button"
variant="outline"
size="sm"
disabled={importing}
onClick={handleClose}
>
Cancel
</Button>
<Button
type="button"
size="sm"
loading={importing}
disabled={!canImport}
onClick={handleConfirmImport}
>
<Upload className="h-4 w-4 mr-1.5" />
Import {preview?.valid_count ?? 0} Asset
{(preview?.valid_count ?? 0) === 1 ? "" : "s"}
</Button>
</div>
</div>
</Modal>
);
}
@@ -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 "@/lib/validation";
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>
);
}
@@ -0,0 +1,159 @@
import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, Clock, CheckCircle2, ExternalLink } from "lucide-react";
import { notificationsApi } from "@/api/notifications";
import { useAuthStore } from "@/hooks/useAuth";
import { formatDate } from "@/lib/format";
import { Modal } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { toast } from "@/lib/toast";
export function CalibrationReminderModal() {
const navigate = useNavigate();
const qc = useQueryClient();
const { user, token } = useAuthStore();
const [open, setOpen] = useState(false);
const promptedTokensRef = useRef<Set<string>>(new Set());
const sessionKey = token ? `cal_popup_shown:${token.slice(-16)}` : null;
const calNotifsQuery = useQuery({
queryKey: ["notifications", "calibration-login-popup", user?.id],
queryFn: () =>
notificationsApi.list({
type: "calibration_due",
unread_only: true,
limit: 25,
}),
enabled: Boolean(user && token),
});
const items = calNotifsQuery.data?.items ?? [];
useEffect(() => {
if (!token || !user || items.length === 0) return;
const alreadyShownInRef = promptedTokensRef.current.has(token);
let alreadyShownInSession = false;
try {
alreadyShownInSession = Boolean(
sessionKey && sessionStorage.getItem(sessionKey)
);
} catch {
alreadyShownInSession = false;
}
if (!alreadyShownInRef && !alreadyShownInSession) {
promptedTokensRef.current.add(token);
try {
if (sessionKey) sessionStorage.setItem(sessionKey, "1");
} catch {
// ignore storage errors
}
setOpen(true);
}
}, [token, user, items.length, sessionKey]);
const acknowledgeMutation = useMutation({
mutationFn: () => notificationsApi.markAllRead("calibration_due"),
onSuccess: async () => {
await qc.invalidateQueries({ queryKey: ["notifications"] });
await qc.invalidateQueries({ queryKey: ["dashboard"] });
toast.success("Calibration reminders acknowledged");
setOpen(false);
},
onError: () => {
toast.error("Failed to acknowledge calibration reminders");
},
});
if (!open || items.length === 0) return null;
return (
<Modal
open={open}
onOpenChange={(o) => !o && setOpen(false)}
title={`Calibration Reminders (${items.length} Unread)`}
className="max-w-xl"
>
<div className="space-y-4">
<p className="text-sm text-gray-600">
The following equipment calibration schedules are due or overdue and require
attention:
</p>
<div className="max-h-72 overflow-y-auto divide-y divide-gray-100 border border-gray-200 rounded-lg">
{items.map((n) => {
const isRed = n.severity === "red";
return (
<div
key={n.id}
className="p-3 flex items-start gap-2.5 bg-white hover:bg-gray-50"
>
{isRed ? (
<AlertTriangle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
) : (
<Clock className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />
)}
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-semibold text-gray-900 truncate">
{n.title}
</span>
<span
className={`text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase ${
isRed
? "bg-red-100 text-red-800"
: "bg-amber-100 text-amber-800"
}`}
>
{n.severity}
</span>
</div>
<p className="text-xs text-gray-600 mt-0.5">{n.message}</p>
{n.due_date && (
<div className="text-[11px] text-gray-500 mt-1">
Due Date: <strong>{formatDate(n.due_date)}</strong>
</div>
)}
</div>
</div>
);
})}
</div>
<div className="flex flex-wrap items-center justify-between gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
setOpen(false);
navigate("/calibration");
}}
>
<ExternalLink className="h-3.5 w-3.5 mr-1.5" />
Open Calibration Register
</Button>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
onClick={() => setOpen(false)}
>
Remind Me Later
</Button>
<Button
type="button"
loading={acknowledgeMutation.isPending}
onClick={() => acknowledgeMutation.mutate()}
>
<CheckCircle2 className="h-4 w-4 mr-1.5" />
Acknowledge &amp; Mark Read
</Button>
</div>
</div>
</div>
</Modal>
);
}
+69
View File
@@ -0,0 +1,69 @@
import { AlertTriangle } from "lucide-react";
import { Modal } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
export interface ConfirmDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
message: string;
confirmLabel?: string;
cancelLabel?: string;
variant?: "danger" | "default";
loading?: boolean;
onConfirm: () => void | Promise<void>;
}
export function ConfirmDialog({
open,
onOpenChange,
title,
message,
confirmLabel = "Confirm",
cancelLabel = "Cancel",
variant = "danger",
loading = false,
onConfirm,
}: ConfirmDialogProps) {
return (
<Modal
open={open}
onOpenChange={(next) => {
if (!loading) onOpenChange(next);
}}
title={title}
description={message}
className="max-w-md"
>
<div className="space-y-5">
{variant === "danger" && (
<div className="flex items-start gap-3 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800">
<AlertTriangle className="h-4 w-4 shrink-0 text-red-600 mt-0.5" />
<span>This action cannot be undone.</span>
</div>
)}
<div className="flex items-center justify-end gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
disabled={loading}
onClick={() => onOpenChange(false)}
>
{cancelLabel}
</Button>
<Button
type="button"
variant={variant === "danger" ? "danger" : "default"}
size="sm"
loading={loading}
onClick={() => void onConfirm()}
>
{confirmLabel}
</Button>
</div>
</div>
</Modal>
);
}
@@ -1,8 +1,17 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import { ColumnDef } from "@tanstack/react-table";
import * as XLSX from "xlsx";
import { DataTable } from "./DataTable";
vi.mock("xlsx", async () => {
const actual = await vi.importActual<typeof import("xlsx")>("xlsx");
return {
...actual,
writeFile: vi.fn(),
};
});
interface RowItem {
code: string;
name: string;
@@ -19,8 +28,19 @@ const data: RowItem[] = [
];
describe("DataTable", () => {
it("renders rows and filters globally", () => {
render(<DataTable data={data} columns={columns} globalFilterPlaceholder="Search..." />);
beforeEach(() => {
vi.clearAllMocks();
});
it("renders rows, filters globally, and exports visible rows to Excel (.xlsx)", () => {
render(
<DataTable
data={data}
columns={columns}
globalFilterPlaceholder="Search..."
exportFilename="test-assets"
/>
);
expect(screen.getByText("Ventilator")).toBeInTheDocument();
expect(screen.getByText("Monitor")).toBeInTheDocument();
@@ -29,5 +49,17 @@ describe("DataTable", () => {
expect(screen.getByText("Ventilator")).toBeInTheDocument();
expect(screen.queryByText("Monitor")).not.toBeInTheDocument();
const exportBtn = screen.getByRole("button", {
name: /Export current view to Excel/i,
});
expect(exportBtn).toHaveTextContent("Export Excel (.xlsx)");
fireEvent.click(exportBtn);
expect(XLSX.writeFile).toHaveBeenCalledTimes(1);
expect(XLSX.writeFile).toHaveBeenCalledWith(
expect.objectContaining({ SheetNames: ["Data"] }),
"test-assets.xlsx"
);
});
});
+84 -47
View File
@@ -11,9 +11,18 @@ import {
VisibilityState,
PaginationState,
FilterFn,
type Table as TanStackTable,
} from "@tanstack/react-table";
import { useState, useMemo } from "react";
import { ChevronUp, ChevronDown, ChevronsUpDown, Download, Eye, Search } from "lucide-react";
import { useState } from "react";
import * as XLSX from "xlsx";
import {
ChevronUp,
ChevronDown,
ChevronsUpDown,
FileSpreadsheet,
Eye,
Search,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
@@ -25,23 +34,43 @@ interface DataTableProps<TData> {
emptyAction?: React.ReactNode;
globalFilterPlaceholder?: string;
onRowClick?: (row: TData) => void;
getRowClassName?: (row: TData) => string;
exportFilename?: string;
}
function exportToCsv<TData>(data: TData[], filename: string) {
if (!data.length) return;
const headers = Object.keys(data[0] as object);
const rows = data.map((row) =>
headers.map((h) => JSON.stringify((row as Record<string, unknown>)[h] ?? "")).join(",")
);
const csv = [headers.join(","), ...rows].join("\n");
const blob = new Blob([csv], { type: "text/csv" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${filename}.csv`;
a.click();
URL.revokeObjectURL(url);
function formatExcelCell(val: unknown): string | number {
if (val === null || val === undefined) return "";
if (typeof val === "boolean") return val ? "Yes" : "No";
if (typeof val === "number") return Number.isFinite(val) ? val : "";
if (typeof val === "string") return val;
return JSON.stringify(val);
}
function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
const rows = table.getPrePaginationRowModel().rows;
if (!rows.length) return;
const visibleCols = table
.getVisibleLeafColumns()
.filter((col) => col.id !== "actions");
if (!visibleCols.length) return;
const exportRows = rows.map((row) => {
const record: Record<string, string | number> = {};
for (const col of visibleCols) {
const headerLabel =
typeof col.columnDef.header === "string"
? col.columnDef.header
: col.id;
record[headerLabel] = formatExcelCell(row.getValue(col.id));
}
return record;
});
const ws = XLSX.utils.json_to_sheet(exportRows);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Data");
XLSX.writeFile(wb, `${filename}.xlsx`);
}
export function DataTable<TData>({
@@ -52,6 +81,7 @@ export function DataTable<TData>({
emptyAction,
globalFilterPlaceholder = "Search...",
onRowClick,
getRowClassName,
exportFilename = "export",
}: DataTableProps<TData>) {
const [sorting, setSorting] = useState<SortingState>([]);
@@ -86,47 +116,53 @@ export function DataTable<TData>({
const visibleRows = table.getRowModel().rows;
const filteredRows = table.getFilteredRowModel().rows;
const allFilteredData = useMemo(
() => filteredRows.map((r) => r.original),
[filteredRows]
);
return (
<div className="space-y-3">
{/* Toolbar */}
<div className="flex items-center gap-2 flex-wrap">
<div className="relative flex-1 min-w-48">
<div className="flex flex-col sm:flex-row sm:items-center gap-2">
<div className="relative flex-1 min-w-0">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
<input
value={globalFilter}
onChange={(e) => setGlobalFilter(e.target.value)}
placeholder={globalFilterPlaceholder}
aria-label={globalFilterPlaceholder}
className="w-full pl-9 pr-4 py-1.5 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="relative">
<Button variant="outline" size="sm" onClick={() => setShowColVis(!showColVis)}>
<Eye className="h-4 w-4 mr-1" /> Columns
<div className="flex items-center gap-2 flex-wrap">
<div className="relative">
<Button variant="outline" size="sm" onClick={() => setShowColVis(!showColVis)}>
<Eye className="h-4 w-4 mr-1" /> Columns
</Button>
{showColVis && (
<div className="absolute right-0 mt-1 w-48 bg-white border border-gray-200 rounded-md shadow-lg z-20 p-2">
{table.getAllLeafColumns().map((col) => (
<label key={col.id} className="flex items-center gap-2 px-2 py-1 hover:bg-gray-50 rounded cursor-pointer text-sm">
<input
type="checkbox"
checked={col.getIsVisible()}
onChange={col.getToggleVisibilityHandler()}
className="rounded"
/>
{typeof col.columnDef.header === "string"
? col.columnDef.header
: col.id}
</label>
))}
</div>
)}
</div>
<Button
variant="outline"
size="sm"
aria-label="Export current view to Excel"
onClick={() => exportToExcel(table, exportFilename)}
>
<FileSpreadsheet className="h-4 w-4 mr-1" /> Export Excel (.xlsx)
</Button>
{showColVis && (
<div className="absolute right-0 mt-1 w-48 bg-white border border-gray-200 rounded-md shadow-lg z-20 p-2">
{table.getAllLeafColumns().map((col) => (
<label key={col.id} className="flex items-center gap-2 px-2 py-1 hover:bg-gray-50 rounded cursor-pointer text-sm">
<input
type="checkbox"
checked={col.getIsVisible()}
onChange={col.getToggleVisibilityHandler()}
className="rounded"
/>
{String(col.columnDef.header ?? col.id)}
</label>
))}
</div>
)}
</div>
<Button variant="outline" size="sm" onClick={() => exportToCsv(allFilteredData, exportFilename)}>
<Download className="h-4 w-4 mr-1" /> CSV (current view)
</Button>
</div>
{/* Table */}
@@ -137,7 +173,7 @@ export function DataTable<TData>({
{table.getHeaderGroups().map((hg) => (
<tr key={hg.id}>
{hg.headers.map((header) => (
<th key={header.id} className="text-left font-medium text-gray-600 px-4 py-3">
<th key={header.id} className="text-left font-medium text-gray-600 px-2.5 py-2 sm:px-4 sm:py-3">
{header.isPlaceholder ? null : (
<div className="space-y-1">
{/* Sortable header */}
@@ -182,7 +218,7 @@ export function DataTable<TData>({
[...Array(5)].map((_, i) => (
<tr key={i}>
{columns.map((_, j) => (
<td key={j} className="px-4 py-3">
<td key={j} className="px-2.5 py-2 sm:px-4 sm:py-3">
<div className="h-4 bg-gray-100 rounded animate-pulse" />
</td>
))}
@@ -203,12 +239,13 @@ export function DataTable<TData>({
key={row.id}
className={cn(
"hover:bg-blue-50/50 transition-colors",
getRowClassName?.(row.original),
onRowClick && "cursor-pointer"
)}
onClick={() => onRowClick?.(row.original)}
>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className="px-4 py-3 text-gray-700">
<td key={cell.id} className="px-2.5 py-2 sm:px-4 sm:py-3 text-gray-700">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
@@ -221,7 +258,7 @@ export function DataTable<TData>({
{/* Pagination */}
{!loading && visibleRows.length > 0 && (
<div className="flex items-center justify-between px-4 py-3 border-t border-gray-200 bg-gray-50 text-sm text-gray-600">
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 px-3 sm:px-4 py-3 border-t border-gray-200 bg-gray-50 text-sm text-gray-600">
<span>
{filteredRows.length} record{filteredRows.length !== 1 ? "s" : ""}
{globalFilter || columnFilters.length ? " (filtered)" : ""}
+180
View File
@@ -0,0 +1,180 @@
import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { X, ShieldCheck, AlertCircle, ExternalLink } from "lucide-react";
import { insuranceApi } from "@/api/phase5";
import { useAuthStore } from "@/hooks/useAuth";
import { can } from "@/lib/permissions";
import { formatDate, formatINR } from "@/lib/format";
import { ExpiryChip } from "@/components/StatusBadge";
import { Attachments } from "@/components/Attachments";
import { Button } from "@/components/ui/button";
interface InsuranceDrawerProps {
open: boolean;
onClose: () => void;
assetId: number | null;
assetLabel?: string;
}
export function InsuranceDrawer({
open,
onClose,
assetId,
assetLabel,
}: InsuranceDrawerProps) {
const role = useAuthStore((s) => s.user?.role);
const canManage = can(role, "manage_calibration_contracts");
const policiesQuery = useQuery({
queryKey: ["insurance", "asset-drawer", assetId],
queryFn: () => insuranceApi.list({ asset_id: assetId!, page_size: 200 }),
enabled: open && Boolean(assetId),
});
useEffect(() => {
if (!open) return;
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") onClose();
}
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [open, onClose]);
if (!open || !assetId) return null;
const policies = policiesQuery.data?.items ?? [];
return (
<div
className="fixed inset-0 z-50 flex justify-end bg-black/40"
role="dialog"
aria-modal="true"
aria-label="Asset Insurance Policies"
onClick={onClose}
>
<div
className="w-full max-w-lg bg-white h-full shadow-2xl border-l border-gray-200 flex flex-col"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 bg-gray-50">
<div className="min-w-0">
<div className="flex items-center gap-2 text-sm font-semibold text-gray-900">
<ShieldCheck className="h-4 w-4 text-[#1e3a8a] shrink-0" />
<span>Asset Insurance</span>
</div>
{assetLabel && (
<p className="text-xs text-gray-500 truncate mt-0.5">{assetLabel}</p>
)}
</div>
<button
type="button"
onClick={onClose}
aria-label="Close insurance drawer"
className="p-1.5 rounded-md text-gray-500 hover:text-gray-800 hover:bg-gray-200"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-5 space-y-4">
{policiesQuery.isLoading ? (
<div className="space-y-3">
<div className="h-28 bg-gray-100 rounded-lg animate-pulse" />
<div className="h-28 bg-gray-100 rounded-lg animate-pulse" />
</div>
) : policiesQuery.isError ? (
<div className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 p-3 text-sm text-red-700">
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
<span>Failed to load insurance policies for this asset.</span>
</div>
) : policies.length === 0 ? (
<div className="text-center py-10 bg-gray-50 border border-dashed border-gray-200 rounded-lg space-y-2">
<ShieldCheck className="h-8 w-8 text-gray-300 mx-auto" />
<p className="text-sm font-medium text-gray-700">
No insurance policies recorded for this asset.
</p>
<p className="text-xs text-gray-500">
Policies can be added from the Insurance register.
</p>
</div>
) : (
policies.map((p) => (
<div
key={p.id}
className="rounded-lg border border-gray-200 bg-white p-4 space-y-3 shadow-sm"
>
<div className="flex items-start justify-between gap-2">
<div>
<div className="font-mono text-sm font-bold text-[#1e3a8a]">
{p.policy_no}
</div>
<div className="text-xs text-gray-600 mt-0.5">
{p.insurer_name || `Insurer #${p.insurer_id}`}
</div>
</div>
<ExpiryChip
daysToExpiry={p.days_to_expiry}
status={p.status}
severity={p.severity}
/>
</div>
<div className="grid grid-cols-3 gap-2 text-xs bg-gray-50 rounded-md p-2.5 border border-gray-100">
<div>
<div className="text-gray-500">Start</div>
<div className="font-medium text-gray-900">
{formatDate(p.start_date)}
</div>
</div>
<div>
<div className="text-gray-500">End</div>
<div className="font-medium text-gray-900">
{formatDate(p.end_date)}
</div>
</div>
<div>
<div className="text-gray-500">Coverage</div>
<div className="font-medium text-gray-900">
{formatINR(p.coverage_amount)}
</div>
</div>
</div>
{p.remarks && (
<p className="text-xs text-gray-600">
<span className="font-medium">Remarks:</span> {p.remarks}
</p>
)}
<div className="pt-2 border-t border-gray-100">
<div className="text-xs font-semibold text-gray-700 mb-1.5">
Policy Certificates &amp; Documents
</div>
<Attachments
entityType="insurance"
entityId={p.id}
canUpload={canManage}
canDelete={canManage}
/>
</div>
</div>
))
)}
</div>
<div className="px-5 py-3 border-t border-gray-200 bg-gray-50 flex items-center justify-between gap-2">
<Link to={`/insurance`} onClick={onClose}>
<Button variant="outline" size="sm">
<ExternalLink className="h-3.5 w-3.5 mr-1.5" />
Open Insurance Register
</Button>
</Link>
<Button variant="outline" size="sm" onClick={onClose}>
Close
</Button>
</div>
</div>
</div>
);
}
+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>
);
}
@@ -0,0 +1,298 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { AlertCircle, Clock, Paperclip, X } from "lucide-react";
import { Modal } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { AssetPicker } from "@/components/AssetPicker";
import { validateAttachmentFile } from "@/lib/validation";
import { ApiError } from "@/api/client";
import { assetsApi, type AssetLookupItem, type AssetCriticality } from "@/api/assets";
import { complaintsApi, type ComplaintItem } from "@/api/complaints";
import { attachmentsApi } from "@/api/attachments";
import { fetchUsersLookup } from "@/api/masters";
import { useAuthStore } from "@/hooks/useAuth";
const complaintSchema = z.object({
description: z.string().trim().min(1, "Problem description is required"),
breakdown_details: z.string().optional(),
priority: z.enum(["critical", "non_critical"]),
notes: z.string().optional(),
received_by_id: z.string().optional(),
});
type ComplaintFormValues = z.infer<typeof complaintSchema>;
interface RaiseComplaintModalProps {
open: boolean;
onClose: () => void;
initialAssetId?: number | null;
initialDescription?: string;
onCreated?: (complaint: ComplaintItem) => Promise<void> | void;
navigateOnCreate?: boolean;
}
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";
export function RaiseComplaintModal({
open,
onClose,
initialAssetId = null,
initialDescription = "",
onCreated,
navigateOnCreate = true,
}: RaiseComplaintModalProps) {
const navigate = useNavigate();
const qc = useQueryClient();
const user = useAuthStore((s) => s.user);
const isDeptUser = user?.role === "department_user";
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
const [files, setFiles] = useState<File[]>([]);
const [serverError, setServerError] = useState<string | null>(null);
const usersQuery = useQuery({
queryKey: ["users-lookup"],
queryFn: fetchUsersLookup,
enabled: open,
});
const {
register,
handleSubmit,
reset,
formState: { errors, isSubmitting },
} = useForm<ComplaintFormValues>({
resolver: zodResolver(complaintSchema),
defaultValues: {
description: "",
breakdown_details: "",
priority: "non_critical",
notes: "",
received_by_id: user?.id ? String(user.id) : "",
},
});
useEffect(() => {
if (!open) return;
setFiles([]);
setServerError(null);
reset({
description: initialDescription,
breakdown_details: "",
priority: "non_critical",
notes: "",
received_by_id: user?.id ? String(user.id) : "",
});
if (initialAssetId) {
let cancelled = false;
assetsApi
.get(initialAssetId)
.then((a) => {
if (cancelled) return;
setSelectedAsset({
...a,
contract_summary: a.contract_type
? `${a.contract_type} (${a.contract_status})`
: "None",
insurance_summary: a.insurance_status || "None",
});
})
.catch(() => {
if (!cancelled) setSelectedAsset(null);
});
return () => {
cancelled = true;
};
} else {
setSelectedAsset(null);
}
}, [open, user?.id, initialAssetId, initialDescription, reset]);
function handleFilePick(e: React.ChangeEvent<HTMLInputElement>) {
const picked = Array.from(e.target.files ?? []);
e.target.value = "";
for (const f of picked) {
const err = validateAttachmentFile(f);
if (err) {
setServerError(`${f.name}: ${err}`);
return;
}
}
setServerError(null);
setFiles((prev) => [...prev, ...picked]);
}
async function onSubmit(values: ComplaintFormValues) {
if (!selectedAsset) {
setServerError("Please select an asset first.");
return;
}
setServerError(null);
try {
const created = await complaintsApi.create({
asset_id: selectedAsset.id,
description: values.description.trim(),
breakdown_details: values.breakdown_details?.trim() || null,
priority: values.priority as AssetCriticality,
notes: values.notes?.trim() || null,
received_by_id: values.received_by_id ? Number(values.received_by_id) : null,
});
for (const file of files) {
await attachmentsApi.upload("complaint", created.id, file);
}
await qc.invalidateQueries({ queryKey: ["complaints"] });
await qc.invalidateQueries({ queryKey: ["assets"] });
if (onCreated) {
await onCreated(created);
}
onClose();
if (navigateOnCreate) {
navigate(`/complaints/${created.id}`);
}
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to register complaint.");
}
}
const users = usersQuery.data?.items ?? [];
return (
<Modal
open={open}
onOpenChange={(o) => !o && onClose()}
title="Raise Breakdown / Complaint"
className="max-w-2xl"
>
{serverError && (
<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>{serverError}</span>
</div>
)}
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<label className={labelCls}>Select Asset *</label>
<AssetPicker
selectedAsset={selectedAsset}
onSelect={setSelectedAsset}
departmentId={isDeptUser ? user?.department_id ?? undefined : undefined}
/>
</div>
<div className="flex items-center gap-2 rounded-md bg-gray-50 border border-gray-200 px-3 py-2 text-xs text-gray-600">
<Clock className="h-4 w-4 text-gray-400 shrink-0" />
<span>Registered At: Auto-captured by server on submit</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className={labelCls}>Priority *</label>
<select {...register("priority")} className={inputCls}>
<option value="non_critical">Non-Critical</option>
<option value="critical">Critical (Emergency / Life Support)</option>
</select>
</div>
<div>
<label className={labelCls}>Received By</label>
<select {...register("received_by_id")} className={inputCls}>
<option value="">Current User</option>
{users.map((u) => (
<option key={u.id} value={String(u.id)}>
{u.name}
</option>
))}
</select>
</div>
</div>
<div>
<label className={labelCls}>Complaint Description *</label>
<textarea
{...register("description")}
rows={2}
placeholder="Brief summary of the breakdown or issue..."
className={inputCls}
/>
{errors.description && (
<p className="text-xs text-red-600 mt-1">{errors.description.message}</p>
)}
</div>
<div>
<label className={labelCls}>Breakdown Details</label>
<textarea
{...register("breakdown_details")}
rows={2}
placeholder="Error codes, observed symptoms, clinical impact..."
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Additional Notes</label>
<input
{...register("notes")}
placeholder="Optional caller contact or bay number..."
className={inputCls}
/>
</div>
{/* Multi-file photo/PDF picker */}
<div>
<label className={labelCls}>Photos / Supporting Documents (Optional)</label>
<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 JPG, PNG, or PDF (max 10 MB each)
<input
type="file"
multiple
accept=".jpg,.jpeg,.png,.pdf"
onChange={handleFilePick}
className="hidden"
/>
</label>
{files.length > 0 && (
<ul className="mt-2 space-y-1">
{files.map((f, idx) => (
<li
key={`${f.name}-${idx}`}
className="flex items-center justify-between text-xs bg-gray-50 border border-gray-200 rounded px-2.5 py-1.5"
>
<span className="truncate">{f.name}</span>
<button
type="button"
onClick={() => setFiles((prev) => prev.filter((_, i) => i !== idx))}
className="text-gray-400 hover:text-red-600 ml-2"
>
<X className="h-3.5 w-3.5" />
</button>
</li>
))}
</ul>
)}
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" loading={isSubmitting}>
Submit Complaint
</Button>
</div>
</form>
</Modal>
);
}
+224
View File
@@ -2,8 +2,10 @@ import {
CheckCircle2,
Wrench,
AlertTriangle,
AlertCircle,
Ban,
Clock,
CalendarClock,
ShieldAlert,
MinusCircle,
} from "lucide-react";
@@ -71,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({
status,
severity,
@@ -199,3 +261,165 @@ export function CriticalityBadge({
</span>
);
}
export function CallStatusBadge({
status,
className,
}: {
status: "open" | "in_progress" | "closed" | string;
className?: string;
}) {
const map: Record<string, { label: string; cls: string; icon: React.ReactNode }> = {
open: {
label: "Open",
cls: "bg-red-100 text-red-800 border border-red-200",
icon: <AlertCircle className="h-3 w-3 shrink-0" />,
},
in_progress: {
label: "In Progress",
cls: "bg-amber-100 text-amber-800 border border-amber-200",
icon: <Clock className="h-3 w-3 shrink-0" />,
},
closed: {
label: "Closed",
cls: "bg-green-100 text-green-800 border border-green-200",
icon: <CheckCircle2 className="h-3 w-3 shrink-0" />,
},
};
const cfg = map[status] ?? {
label: status,
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 ExpiryChip({
daysToExpiry,
status,
severity,
className,
}: {
daysToExpiry: number;
status: string;
severity?: string;
className?: string;
}) {
if (status === "superseded") {
return (
<span
className={cn(
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-gray-100 text-gray-600 border border-gray-300",
className
)}
>
<MinusCircle className="h-3 w-3 shrink-0" />
Superseded
</span>
);
}
if (status === "expired" || daysToExpiry < 0) {
return (
<span
className={cn(
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-red-100 text-red-800 border border-red-200",
className
)}
>
<AlertCircle className="h-3 w-3 shrink-0" />
Expired
</span>
);
}
if (status === "expiring") {
const isRed = severity === "red";
return (
<span
className={cn(
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap border",
isRed
? "bg-red-100 text-red-800 border-red-200"
: "bg-amber-100 text-amber-800 border-amber-200",
className
)}
>
<Clock className="h-3 w-3 shrink-0" />
{daysToExpiry} {daysToExpiry === 1 ? "day" : "days"} left
</span>
);
}
return (
<span
className={cn(
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-green-100 text-green-800 border border-green-200",
className
)}
>
<CheckCircle2 className="h-3 w-3 shrink-0" />
Active
</span>
);
}
export function DemoStatusBadge({
status,
daysRemaining,
className,
}: {
status: string;
daysRemaining?: number;
className?: string;
}) {
if (status === "returned") {
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 bg-green-100 text-green-800 border border-green-200",
className
)}
>
<CheckCircle2 className="h-3 w-3 shrink-0" />
Returned
</span>
);
}
if (status === "overdue_return") {
const overdueDays =
daysRemaining != null && daysRemaining < 0 ? Math.abs(daysRemaining) : null;
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 bg-red-100 text-red-800 border border-red-200",
className
)}
>
<AlertTriangle className="h-3 w-3 shrink-0" />
{overdueDays != null ? `Overdue by ${overdueDays}d` : "Overdue Return"}
</span>
);
}
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 bg-blue-100 text-blue-800 border border-blue-200",
className
)}
>
<Clock className="h-3 w-3 shrink-0" />
On Demo
</span>
);
}
+61
View File
@@ -0,0 +1,61 @@
import { CheckCircle2, Info, AlertTriangle, AlertCircle, X } from "lucide-react";
import { useToastStore, type ToastVariant } from "@/lib/toast";
const VARIANT_CLS: Record<ToastVariant, string> = {
success: "bg-emerald-50 border-emerald-300 text-emerald-900",
info: "bg-blue-50 border-blue-300 text-blue-900",
warning: "bg-amber-50 border-amber-300 text-amber-900",
error: "bg-red-50 border-red-300 text-red-900",
};
function VariantIcon({ variant }: { variant: ToastVariant }) {
switch (variant) {
case "success":
return <CheckCircle2 className="h-4 w-4 text-emerald-600 shrink-0 mt-0.5" />;
case "warning":
return <AlertTriangle className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />;
case "error":
return <AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />;
default:
return <Info className="h-4 w-4 text-blue-600 shrink-0 mt-0.5" />;
}
}
export function ToastProvider({ children }: { children?: React.ReactNode }) {
const { toasts, dismiss } = useToastStore();
return (
<>
{children}
{toasts.length > 0 && (
<div
aria-live="polite"
className="fixed bottom-4 right-4 z-[60] flex flex-col gap-2 w-full max-w-sm pointer-events-none px-4 sm:px-0"
>
{toasts.map((t) => (
<div
key={t.id}
className={`pointer-events-auto flex items-start gap-2.5 rounded-lg border p-3.5 shadow-lg transition-all ${VARIANT_CLS[t.variant]}`}
>
<VariantIcon variant={t.variant} />
<div className="flex-1 min-w-0">
<div className="text-xs font-semibold">{t.title}</div>
{t.description && (
<div className="text-xs opacity-90 mt-0.5">{t.description}</div>
)}
</div>
<button
type="button"
onClick={() => dismiss(t.id)}
aria-label="Dismiss notification"
className="p-0.5 rounded hover:bg-black/5 shrink-0"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
))}
</div>
)}
</>
);
}
+11 -3
View File
@@ -1,17 +1,25 @@
import { useState } from "react";
import { Outlet } from "react-router-dom";
import { Sidebar } from "./Sidebar";
import { TopBar } from "./TopBar";
import { CalibrationReminderModal } from "@/components/CalibrationReminderModal";
export function AppShell() {
const [mobileNavOpen, setMobileNavOpen] = useState(false);
return (
<div className="flex min-h-screen bg-gray-50">
<Sidebar />
<Sidebar
mobileOpen={mobileNavOpen}
onClose={() => setMobileNavOpen(false)}
/>
<div className="flex-1 flex flex-col min-w-0">
<TopBar />
<main className="flex-1 p-6 overflow-auto">
<TopBar onMenuClick={() => setMobileNavOpen(true)} />
<main className="flex-1 p-3 sm:p-4 lg:p-6 overflow-auto">
<Outlet />
</main>
</div>
<CalibrationReminderModal />
</div>
);
}
+49 -6
View File
@@ -12,8 +12,10 @@ import {
BarChart3,
Bell,
Database,
History,
Settings,
ChevronRight,
X,
type LucideIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
@@ -71,10 +73,16 @@ const NAV_ITEMS: NavItem[] = [
},
{ to: "/notifications", label: "Notifications", icon: Bell },
{ to: "/masters", label: "Masters", icon: Database, capability: "manage_admin" },
{ to: "/audit-logs", label: "Audit Log", icon: History, capability: "manage_admin" },
{ to: "/settings", label: "Settings", icon: Settings, capability: "manage_admin" },
];
export function Sidebar() {
interface SidebarProps {
mobileOpen?: boolean;
onClose?: () => void;
}
export function Sidebar({ mobileOpen, onClose }: SidebarProps = {}) {
const user = useAuthStore((s) => s.user);
const role = user?.role;
@@ -84,10 +92,23 @@ export function Sidebar() {
return true;
});
return (
<aside className="w-56 lg:w-64 shrink-0 min-h-screen bg-[#1e3a8a] text-white flex flex-col">
const asideContent = (
<aside
aria-label="Primary Navigation"
className="w-56 lg:w-64 shrink-0 min-h-screen bg-[#1e3a8a] text-white flex flex-col"
>
{/* Logo */}
<div className="px-4 py-4 border-b border-blue-700 space-y-2">
<div className="px-4 py-4 border-b border-blue-700 space-y-2 relative">
{onClose && (
<button
type="button"
onClick={onClose}
aria-label="Close navigation menu"
className="lg:hidden absolute right-2 top-2 p-1 rounded text-blue-200 hover:text-white hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white"
>
<X className="h-4 w-4" />
</button>
)}
<div className="bg-white rounded-lg p-2">
<img
src="/logo.jpg"
@@ -107,9 +128,10 @@ export function Sidebar() {
key={to}
to={to}
end={to === "/"}
onClick={() => onClose?.()}
className={({ isActive }) =>
cn(
"flex items-center gap-3 px-3 py-2.5 rounded-md text-sm transition-colors group",
"flex items-center gap-3 px-3 py-2.5 rounded-md text-sm transition-colors group focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white",
isActive
? "bg-blue-700 text-white"
: "text-blue-100 hover:bg-blue-700/50 hover:text-white"
@@ -125,8 +147,29 @@ export function Sidebar() {
{/* Footer */}
<div className="px-4 py-3 border-t border-blue-700 text-xs text-blue-300">
Phase 1 — Foundation
Poona Hospital AMS • v1.0
</div>
</aside>
);
// When controlled by AppShell, hide desktop rail on small screens and render slide-over drawer when open
if (mobileOpen === undefined) {
return asideContent;
}
return (
<>
<div className="hidden lg:flex shrink-0">{asideContent}</div>
{mobileOpen && (
<div className="fixed inset-0 z-40 flex lg:hidden">
<div
className="fixed inset-0 bg-black/40"
onClick={onClose}
aria-hidden="true"
/>
<div className="relative z-50 flex">{asideContent}</div>
</div>
)}
</>
);
}
+498 -33
View File
@@ -1,45 +1,231 @@
import { useState, useEffect } from "react";
import { useState, useEffect, useRef, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { Search, Bell, ChevronDown, User, LogOut, CalendarClock, RotateCcw } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
Search,
Bell,
ChevronDown,
User,
LogOut,
CalendarClock,
RotateCcw,
Play,
CheckCheck,
AlertTriangle,
Info,
Clock,
Menu,
X,
Package,
AlertCircle,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { formatDate } from "@/lib/format";
import { formatDate, formatRelative } from "@/lib/format";
import { ROLE_LABELS } from "@/lib/permissions";
import { useAuthStore } from "@/hooks/useAuth";
import { settingsApi } from "@/api/settings";
import { notificationsApi, type NotificationItem } from "@/api/notifications";
import { searchApi } from "@/api/search";
import { Badge } from "@/components/ui/badge";
import { AssetStatusBadge, CallStatusBadge } from "@/components/StatusBadge";
import { toast } from "@/lib/toast";
interface TopBarProps {
title?: string;
onMenuClick?: () => void;
}
export function TopBar({ title }: TopBarProps) {
export function TopBar({ title, onMenuClick }: TopBarProps) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
const [menuOpen, setMenuOpen] = useState(false);
const [bellOpen, setBellOpen] = useState(false);
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
const [savingDate, setSavingDate] = useState(false);
const [runningAlerts, setRunningAlerts] = useState(false);
const [searchInput, setSearchInput] = useState("");
const [debouncedQuery, setDebouncedQuery] = useState("");
const [searchOpen, setSearchOpen] = useState(false);
const bellContainerRef = useRef<HTMLDivElement>(null);
const searchContainerRef = useRef<HTMLDivElement>(null);
const userMenuRef = useRef<HTMLDivElement>(null);
const seenIdsRef = useRef<Set<number> | null>(null);
useEffect(() => {
setDateInput(demoAsOfDate ?? "");
}, [demoAsOfDate]);
useEffect(() => {
const trimmed = searchInput.trim();
if (trimmed.length < 2) {
setDebouncedQuery("");
return;
}
const timer = window.setTimeout(() => {
setDebouncedQuery(trimmed);
}, 200);
return () => window.clearTimeout(timer);
}, [searchInput]);
useEffect(() => {
function handleOutside(e: MouseEvent) {
const target = e.target as Node;
if (
bellContainerRef.current &&
!bellContainerRef.current.contains(target)
) {
setBellOpen(false);
}
if (
searchContainerRef.current &&
!searchContainerRef.current.contains(target)
) {
setSearchOpen(false);
}
if (userMenuRef.current && !userMenuRef.current.contains(target)) {
setMenuOpen(false);
}
}
function handleKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
setSearchOpen(false);
setBellOpen(false);
setMenuOpen(false);
}
}
document.addEventListener("mousedown", handleOutside);
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("mousedown", handleOutside);
document.removeEventListener("keydown", handleKeyDown);
};
}, []);
const searchQuery = useQuery({
queryKey: ["global-search", debouncedQuery, user?.id],
queryFn: () => searchApi.query(debouncedQuery),
enabled: Boolean(user) && debouncedQuery.length >= 2,
staleTime: 10_000,
});
const isAdmin = user?.role === "system_admin";
const bellQuery = useQuery({
queryKey: ["notifications", "bell", user?.id],
queryFn: () => notificationsApi.list({ limit: 10 }),
enabled: Boolean(user),
refetchInterval: 60_000,
});
const bellItems = useMemo(
() => bellQuery.data?.items ?? [],
[bellQuery.data?.items]
);
const unreadCount = bellQuery.data?.unread_count ?? 0;
// Detect newly arrived unread notifications while app is open
useEffect(() => {
if (!bellQuery.data) return;
const currentIds = new Set(bellItems.map((n) => n.id));
if (seenIdsRef.current === null) {
seenIdsRef.current = currentIds;
return;
}
const newlyArrived = bellItems.filter(
(n) => !n.is_read && !seenIdsRef.current!.has(n.id)
);
for (const n of newlyArrived.slice(0, 2)) {
if (n.severity === "red") {
toast.error(n.title, n.message);
} else if (n.severity === "yellow") {
toast.warning(n.title, n.message);
} else {
toast.info(n.title, n.message);
}
}
seenIdsRef.current = currentIds;
}, [bellQuery.data, bellItems]);
const markReadMutation = useMutation({
mutationFn: (id: number) => notificationsApi.markRead(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["notifications"] });
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
},
});
const markAllReadMutation = useMutation({
mutationFn: () => notificationsApi.markAllRead(),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["notifications"] });
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
toast.success("All notifications marked as read");
},
});
async function invalidateDateSensitiveQueries() {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["notifications"] }),
queryClient.invalidateQueries({ queryKey: ["dashboard"] }),
queryClient.invalidateQueries({ queryKey: ["pm-records"] }),
queryClient.invalidateQueries({ queryKey: ["calibration-records"] }),
queryClient.invalidateQueries({ queryKey: ["contracts"] }),
queryClient.invalidateQueries({ queryKey: ["warranties"] }),
queryClient.invalidateQueries({ queryKey: ["insurance"] }),
queryClient.invalidateQueries({ queryKey: ["demo-equipment"] }),
queryClient.invalidateQueries({ queryKey: ["assets"] }),
queryClient.invalidateQueries(),
]);
}
async function handleDemoDateUpdate(newDate: string | null) {
setSavingDate(true);
try {
const res = await settingsApi.setDemoDate(newDate);
setDemoAsOfDate(res.demo_as_of_date ?? null);
setDateInput(res.demo_as_of_date ?? "");
await queryClient.invalidateQueries();
await invalidateDateSensitiveQueries();
toast.info(
res.demo_as_of_date
? `Demo clock set to ${formatDate(res.demo_as_of_date)}`
: "Demo clock reset to today"
);
} finally {
setSavingDate(false);
}
}
async function handleRunAlertsNow() {
setRunningAlerts(true);
try {
const res = await notificationsApi.runAlertsNow();
await queryClient.invalidateQueries({ queryKey: ["notifications"] });
await queryClient.invalidateQueries({ queryKey: ["dashboard"] });
toast.success(
`Alert check completed (${formatDate(res.evaluated_today)})`,
`${res.created} new alert${res.created === 1 ? "" : "s"} created.`
);
} catch {
toast.error("Failed to run alert check");
} finally {
setRunningAlerts(false);
}
}
function handleNotificationClick(n: NotificationItem) {
setBellOpen(false);
if (!n.is_read) {
markReadMutation.mutate(n.id);
}
if (n.link_url) {
navigate(n.link_url);
}
}
function handleSignOut() {
setMenuOpen(false);
logout();
@@ -47,18 +233,174 @@ export function TopBar({ title }: TopBarProps) {
}
return (
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-4 py-2 gap-3 sticky top-0 z-10">
{/* Page title */}
{title && <h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">{title}</h1>}
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-3 sm:px-4 py-2 gap-2 sm:gap-3 sticky top-0 z-10">
{/* Mobile/tablet nav toggle */}
{onMenuClick && (
<button
type="button"
onClick={onMenuClick}
aria-label="Open navigation menu"
className="lg:hidden p-1.5 rounded-md text-gray-600 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
>
<Menu className="h-5 w-5" />
</button>
)}
{/* Global search placeholder */}
<div className={cn("relative", title ? "" : "flex-1 max-w-xs sm:max-w-sm")}>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
{/* Page title */}
{title && (
<h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">
{title}
</h1>
)}
{/* Live Global Quick Search */}
<div
ref={searchContainerRef}
className={cn(
"relative order-last lg:order-none w-full lg:w-auto",
title ? "lg:w-72" : "lg:flex-1 lg:max-w-md"
)}
>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
<input
type="text"
placeholder="Search assets, complaints... (Phase 8)"
className="w-full pl-9 pr-4 py-1.5 text-sm border border-gray-200 rounded-md bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white"
aria-label="Search assets and complaints"
value={searchInput}
onChange={(e) => {
const val = e.target.value;
setSearchInput(val);
setSearchOpen(val.trim().length >= 2);
}}
onFocus={() => {
if (searchInput.trim().length >= 2) {
setSearchOpen(true);
}
}}
placeholder="Search assets, complaints..."
className="w-full pl-9 pr-8 py-1.5 text-sm border border-gray-200 rounded-md bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white"
/>
{searchInput && (
<button
type="button"
aria-label="Clear search"
onClick={() => {
setSearchInput("");
setDebouncedQuery("");
setSearchOpen(false);
}}
className="absolute right-2 top-1/2 -translate-y-1/2 p-0.5 rounded text-gray-400 hover:text-gray-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
>
<X className="h-3.5 w-3.5" />
</button>
)}
{searchOpen && searchInput.trim().length >= 2 && (
<div
role="listbox"
aria-label="Global search results"
className="absolute left-0 right-0 mt-1.5 bg-white border border-gray-200 rounded-lg shadow-xl z-30 max-h-96 overflow-y-auto divide-y divide-gray-100"
>
{searchQuery.isFetching && !searchQuery.data ? (
<div className="px-4 py-6 text-center text-xs text-gray-500">
Searching assets &amp; complaints...
</div>
) : searchQuery.isError ? (
<div className="px-4 py-5 text-center text-xs text-red-600">
Unable to load search results.
</div>
) : (
(() => {
const assets = searchQuery.data?.assets ?? [];
const complaints = searchQuery.data?.complaints ?? [];
if (assets.length === 0 && complaints.length === 0) {
return (
<div className="px-4 py-6 text-center text-xs text-gray-500">
No matching assets or complaints found.
</div>
);
}
return (
<>
{assets.length > 0 && (
<div className="py-1.5">
<div className="px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500 flex items-center gap-1.5">
<Package className="h-3.5 w-3.5 text-[#1e3a8a]" />
Assets ({assets.length})
</div>
{assets.map((asset) => (
<button
key={`asset-${asset.id}`}
type="button"
role="option"
onClick={() => {
setSearchOpen(false);
navigate(`/assets/${asset.id}`);
}}
className="w-full text-left px-3 py-2 hover:bg-blue-50/70 focus-visible:outline-none focus-visible:bg-blue-50 flex items-center justify-between gap-2 transition-colors"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="font-mono text-xs font-semibold text-[#1e3a8a]">
{asset.asset_code}
</span>
<span className="text-xs font-medium text-gray-900 truncate">
{asset.name}
</span>
</div>
<div className="text-[11px] text-gray-500 truncate mt-0.5">
{asset.department_name ?? "No Dept"}
{asset.serial_no ? ` • SN: ${asset.serial_no}` : ""}
</div>
</div>
<AssetStatusBadge status={asset.status} />
</button>
))}
</div>
)}
{complaints.length > 0 && (
<div className="py-1.5">
<div className="px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500 flex items-center gap-1.5">
<AlertCircle className="h-3.5 w-3.5 text-red-600" />
Complaints ({complaints.length})
</div>
{complaints.map((c) => (
<button
key={`complaint-${c.id}`}
type="button"
role="option"
onClick={() => {
setSearchOpen(false);
navigate(`/complaints/${c.id}`);
}}
className="w-full text-left px-3 py-2 hover:bg-blue-50/70 focus-visible:outline-none focus-visible:bg-blue-50 flex items-center justify-between gap-2 transition-colors"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="font-mono text-xs font-semibold text-gray-900">
{c.complaint_no}
</span>
<span className="text-xs text-gray-700 truncate">
{c.asset_code
? `${c.asset_code}${c.asset_name ? ` — ${c.asset_name}` : ""}`
: c.asset_name ?? "Equipment"}
</span>
</div>
<div className="text-[11px] text-gray-500 truncate mt-0.5">
{c.department_name ?? "—"} • Priority: {c.priority}
</div>
</div>
<CallStatusBadge status={c.call_status} />
</button>
))}
</div>
)}
</>
);
})()
)}
</div>
)}
</div>
{/* Active Demo Date Pill */}
@@ -69,10 +411,12 @@ export function TopBar({ title }: TopBarProps) {
</span>
)}
{/* Admin Demo Clock Picker */}
{/* Admin Demo Clock Picker + Run Alert Check */}
{isAdmin && (
<div className="flex items-center gap-1.5 bg-gray-50 border border-gray-200 rounded-md px-2 py-1 text-xs">
<span className="text-gray-500 font-medium hidden md:inline">As of Date:</span>
<div className="w-full xl:w-auto order-last xl:order-none flex items-center gap-1.5 bg-gray-50 border border-gray-200 rounded-md px-2 py-1 text-xs flex-wrap">
<span className="text-gray-500 font-medium hidden md:inline">
As of Date:
</span>
<input
type="date"
aria-label="As of Date"
@@ -100,32 +444,136 @@ export function TopBar({ title }: TopBarProps) {
<span className="hidden lg:inline">Reset</span>
</button>
)}
<button
type="button"
disabled={runningAlerts}
onClick={handleRunAlertsNow}
className="inline-flex items-center gap-1 px-2 py-0.5 rounded border border-blue-300 bg-blue-50 text-[#1e3a8a] hover:bg-blue-100 disabled:opacity-40 font-medium"
title="Run alert engine immediately for current effective date"
>
<Play className="h-3 w-3" />
<span>{runningAlerts ? "Running..." : "Run alert check now"}</span>
</button>
</div>
)}
{/* Notification bell placeholder */}
<button
type="button"
onClick={() => navigate("/notifications")}
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-500 ml-auto"
aria-label="Notifications"
>
<Bell className="h-5 w-5" />
<span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-red-500" />
</button>
{/* Right utility cluster (Bell + User Menu) */}
<div className="ml-auto flex items-center gap-1.5 sm:gap-2">
{/* Live Notification Bell & Dropdown */}
<div ref={bellContainerRef} className="relative">
<button
type="button"
onClick={() => setBellOpen((o) => !o)}
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
aria-label="Notifications"
aria-expanded={bellOpen}
>
<Bell className="h-5 w-5" />
{unreadCount > 0 && (
<span className="absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] px-1 rounded-full bg-red-600 text-white text-[10px] font-bold flex items-center justify-center leading-none">
{unreadCount > 99 ? "99+" : unreadCount}
</span>
)}
</button>
{bellOpen && (
<div className="absolute right-0 mt-1.5 w-80 sm:w-96 bg-white border border-gray-200 rounded-lg shadow-xl z-30 overflow-hidden">
<div className="flex items-center justify-between px-3.5 py-2.5 border-b border-gray-100 bg-gray-50">
<div className="text-xs font-semibold text-gray-800">
Notifications{" "}
{unreadCount > 0 && (
<span className="ml-1 text-red-600">({unreadCount} unread)</span>
)}
</div>
{unreadCount > 0 && (
<button
type="button"
onClick={() => markAllReadMutation.mutate()}
className="inline-flex items-center gap-1 text-[11px] font-medium text-[#1e3a8a] hover:underline"
>
<CheckCheck className="h-3.5 w-3.5" />
Mark all read
</button>
)}
</div>
<div className="max-h-80 overflow-y-auto divide-y divide-gray-100">
{bellItems.length === 0 ? (
<div className="py-8 text-center text-xs text-gray-400">
No notifications yet.
</div>
) : (
bellItems.map((n) => (
<button
key={n.id}
type="button"
onClick={() => handleNotificationClick(n)}
className={cn(
"w-full text-left px-3.5 py-2.5 hover:bg-gray-50 flex items-start gap-2.5 transition-colors",
!n.is_read && "bg-blue-50/40"
)}
>
<SeverityIcon severity={n.severity} />
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-2">
<span
className={cn(
"text-xs truncate",
!n.is_read
? "font-semibold text-gray-900"
: "font-medium text-gray-700"
)}
>
{n.title}
</span>
{!n.is_read && (
<span className="h-2 w-2 rounded-full bg-blue-600 shrink-0" />
)}
</div>
<p className="text-[11px] text-gray-600 line-clamp-2 mt-0.5">
{n.message}
</p>
<div className="text-[10px] text-gray-400 mt-1">
{formatRelative(n.created_at)}
</div>
</div>
</button>
))
)}
</div>
<div className="px-3.5 py-2 border-t border-gray-100 bg-gray-50 text-center">
<button
type="button"
onClick={() => {
setBellOpen(false);
navigate("/notifications");
}}
className="text-xs font-medium text-[#1e3a8a] hover:underline"
>
View all notifications →
</button>
</div>
</div>
)}
</div>
{/* User menu */}
<div className="relative">
<div ref={userMenuRef} className="relative">
<button
type="button"
onClick={() => setMenuOpen((o) => !o)}
className="flex items-center gap-2 px-2.5 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700"
aria-label="User menu"
aria-expanded={menuOpen}
className="flex items-center gap-2 px-2.5 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
>
<div className="h-7 w-7 rounded-full bg-[#1e3a8a] flex items-center justify-center text-white text-xs font-bold shrink-0">
<User className="h-4 w-4" />
</div>
<div className="hidden sm:flex flex-col items-start leading-tight">
<span className="font-medium text-gray-800 text-xs">{user?.name ?? "User"}</span>
<span className="font-medium text-gray-800 text-xs">
{user?.name ?? "User"}
</span>
<span className="text-[10px] text-gray-500">
{user?.role ? ROLE_LABELS[user.role] : ""}
{user?.department_name ? ` • ${user.department_name}` : ""}
@@ -137,11 +585,17 @@ export function TopBar({ title }: TopBarProps) {
{menuOpen && (
<div className="absolute right-0 mt-1 w-60 bg-white border border-gray-200 rounded-md shadow-lg z-30 py-2">
<div className="px-3 py-2 border-b border-gray-100 space-y-1">
<div className="text-sm font-medium text-gray-900 truncate">{user?.name}</div>
<div className="text-sm font-medium text-gray-900 truncate">
{user?.name}
</div>
<div className="text-xs text-gray-500 truncate">{user?.email}</div>
<div className="flex items-center gap-1.5 flex-wrap pt-0.5">
{user?.role && <Badge variant="info">{ROLE_LABELS[user.role]}</Badge>}
{user?.department_name && <Badge variant="outline">{user.department_name}</Badge>}
{user?.role && (
<Badge variant="info">{ROLE_LABELS[user.role]}</Badge>
)}
{user?.department_name && (
<Badge variant="outline">{user.department_name}</Badge>
)}
</div>
</div>
<button
@@ -154,7 +608,18 @@ export function TopBar({ title }: TopBarProps) {
</button>
</div>
)}
</div>
</div>
</header>
);
}
function SeverityIcon({ severity }: { severity: string }) {
if (severity === "red") {
return <AlertTriangle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />;
}
if (severity === "yellow") {
return <Clock className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />;
}
return <Info className="h-4 w-4 text-blue-600 shrink-0 mt-0.5" />;
}
+1 -1
View File
@@ -25,7 +25,7 @@ export function Modal({
<DialogPrimitive.Overlay className="fixed inset-0 z-40 bg-black/40 backdrop-blur-[1px]" />
<DialogPrimitive.Content
className={cn(
"fixed left-1/2 top-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-lg bg-white p-6 shadow-xl border border-gray-200 max-h-[90vh] overflow-y-auto",
"fixed left-1/2 top-1/2 z-50 w-[95vw] sm:w-full max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-lg bg-white p-4 sm:p-6 shadow-xl border border-gray-200 max-h-[90vh] overflow-y-auto",
className
)}
>
+41
View File
@@ -10,3 +10,44 @@
@apply bg-gray-50 text-gray-900 antialiased;
}
}
@media print {
@page {
size: A4 landscape;
margin: 12mm;
}
aside,
header,
.no-print {
display: none !important;
}
body {
background: #ffffff !important;
color: #111827 !important;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
main {
padding: 0 !important;
overflow: visible !important;
}
table {
border-collapse: collapse !important;
width: 100% !important;
}
th,
td {
border: 1px solid #d1d5db !important;
font-size: 10px !important;
padding: 4px 6px !important;
}
.print-break-inside-avoid {
break-inside: avoid;
}
}
-1
View File
@@ -89,7 +89,6 @@ const ROLE_CAPABILITIES: Record<Role, ReadonlySet<Capability>> = {
coordinator: new Set<Capability>([
"edit_asset_contracts_only",
"view_assets",
"raise_complaint",
"handle_complaint",
"view_pm",
"manage_calibration_contracts",
+40
View File
@@ -0,0 +1,40 @@
import { create } from "zustand";
export type ToastVariant = "success" | "info" | "warning" | "error";
export interface ToastEntry {
id: string;
title: string;
description?: string;
variant: ToastVariant;
}
interface ToastState {
toasts: ToastEntry[];
push: (t: Omit<ToastEntry, "id">) => void;
dismiss: (id: string) => void;
}
export const useToastStore = create<ToastState>((set) => ({
toasts: [],
push: (entry) => {
const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
set((s) => ({ toasts: [...s.toasts.slice(-4), { ...entry, id }] }));
setTimeout(() => {
set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) }));
}, 5000);
},
dismiss: (id) =>
set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })),
}));
export const toast = {
success: (title: string, description?: string) =>
useToastStore.getState().push({ title, description, variant: "success" }),
info: (title: string, description?: string) =>
useToastStore.getState().push({ title, description, variant: "info" }),
warning: (title: string, description?: string) =>
useToastStore.getState().push({ title, description, variant: "warning" }),
error: (title: string, description?: string) =>
useToastStore.getState().push({ title, description, variant: "error" }),
};
+17
View File
@@ -0,0 +1,17 @@
const MAX_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
const ALLOWED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".pdf"];
const ALLOWED_MIME_TYPES = ["image/jpeg", "image/png", "application/pdf"];
export function validateAttachmentFile(file: File): string | null {
const nameLower = file.name.toLowerCase();
const hasAllowedExt = ALLOWED_EXTENSIONS.some((ext) => nameLower.endsWith(ext));
const hasAllowedMime = !file.type || ALLOWED_MIME_TYPES.includes(file.type);
if (!hasAllowedExt || !hasAllowedMime) {
return "Invalid file type. Only JPG, PNG, and PDF files are allowed.";
}
if (file.size > MAX_SIZE_BYTES) {
return "File is too large. Maximum allowed size is 10 MB.";
}
return null;
}

Some files were not shown because too many files have changed in this diff Show More