Compare commits
29
Commits
ee437e3adf
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
221cc8918f | ||
|
|
51e4b39c33 | ||
|
|
9276064d18 | ||
|
|
b8639bc52a | ||
|
|
cb47017eac | ||
|
|
5f649e3e4c | ||
|
|
c086833163 | ||
|
|
026da64e71 | ||
|
|
041a4075dd | ||
|
|
b6465708f0 | ||
|
|
f356442900 | ||
|
|
ee9390a2a0 | ||
|
|
13fd84a53c | ||
|
|
5d98aa57cb | ||
|
|
8ebdd0142c | ||
|
|
640ae9c1b4 | ||
|
|
d9ca4bbb02 | ||
|
|
cd9eb27a98 | ||
|
|
594407d404 | ||
|
|
1cf218ca00 | ||
|
|
e2a6fa601e | ||
|
|
5027c0766e | ||
|
|
22fad38280 | ||
|
|
0a2db8454d | ||
|
|
0b0f550eff | ||
|
|
aec1b6ad41 | ||
|
|
ba4777b182 | ||
|
|
d3f22ba444 | ||
|
|
905f6735a7 |
@@ -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
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
+24
-2
@@ -1,10 +1,19 @@
|
||||
backend/data/ams.db
|
||||
backend/data/test.db
|
||||
# SQLite databases
|
||||
backend/data/*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db
|
||||
|
||||
# Data directories
|
||||
backend/data/backups/
|
||||
backend/data/uploads/*
|
||||
!backend/data/uploads/.gitkeep
|
||||
backend/data/*
|
||||
!backend/data/.gitkeep
|
||||
!backend/data/uploads/
|
||||
!backend/data/backups/
|
||||
|
||||
# Python
|
||||
.venv/
|
||||
backend/.venv/
|
||||
.pytest_cache/
|
||||
@@ -13,8 +22,21 @@ __pycache__/
|
||||
**/__pycache__/
|
||||
**/*.pyc
|
||||
*.pyc
|
||||
|
||||
# Frontend
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/*.tsbuildinfo
|
||||
*.tsbuildinfo
|
||||
**/*.tsbuildinfo
|
||||
|
||||
# Archives
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
|
||||
# Environment & OS
|
||||
.env
|
||||
*.env.local
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
.PHONY: dev backend frontend test seed install
|
||||
.PHONY: dev backend frontend test seed install package
|
||||
|
||||
ifeq ($(OS),Windows_NT)
|
||||
VENV_BIN := .venv/Scripts
|
||||
@@ -27,3 +27,6 @@ install:
|
||||
$(PYTHON_SYS) -m venv backend/.venv
|
||||
"backend/$(VENV_BIN)/pip" install -r backend/requirements.txt
|
||||
cd frontend && npm install
|
||||
|
||||
package:
|
||||
git archive --format=zip --output=../poona-ams-delivery.zip HEAD
|
||||
|
||||
@@ -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,82 @@ 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 & UAT Sign-off Matrix](docs/ACCEPTANCE_CHECKLIST.md)
|
||||
- [Role-Based User Guide](docs/USER_GUIDE.md)
|
||||
- [Assumptions, Retention & Governance Policies](docs/ASSUMPTIONS.md)
|
||||
|
||||
## Database Backup & Disaster Recovery
|
||||
|
||||
The application includes an automated, online backup utility in `backend/scripts/backup.py` that utilizes SQLite's safe online backup API (`sqlite3.Connection.backup`) to capture a transactionally consistent snapshot of the database alongside all uploaded attachment files without requiring downtime.
|
||||
|
||||
### Running a Manual Backup
|
||||
```bash
|
||||
cd backend
|
||||
# Windows:
|
||||
.venv\Scripts\python.exe scripts/backup.py backup
|
||||
# macOS/Linux:
|
||||
python scripts/backup.py backup
|
||||
```
|
||||
- Creates a timestamped archive: `backend/data/backups/ams_backup_YYYYMMDD_HHMMSS.zip` containing `ams.db` and the `uploads/` folder.
|
||||
- Runs `PRAGMA integrity_check` automatically before bundling.
|
||||
- Retains the latest 7 backups by default (`--keep N` flag configurable).
|
||||
|
||||
### Verifying Backup Integrity
|
||||
```bash
|
||||
cd backend
|
||||
python scripts/backup.py verify data/backups/ams_backup_20261113_174700.zip
|
||||
```
|
||||
|
||||
### Restoring from a Backup
|
||||
```bash
|
||||
cd backend
|
||||
python scripts/backup.py restore data/backups/ams_backup_YYYYMMDD_HHMMSS.zip
|
||||
```
|
||||
- Validates SQLite integrity before restoring.
|
||||
- Automatically saves a `.safety_pre_restore_<timestamp>.bak` of the active database before overwriting.
|
||||
- Unpacks attachments directly into `backend/data/uploads/`.
|
||||
|
||||
### Automated Nightly Backups
|
||||
To schedule automatic nightly backups at 01:00 AM:
|
||||
- **Linux / Docker (cron):**
|
||||
```cron
|
||||
0 1 * * * cd /path/to/poona-ams/backend && /path/to/poona-ams/backend/.venv/bin/python scripts/backup.py backup >> /var/log/ams_backup.log 2>&1
|
||||
```
|
||||
- **Windows (Task Scheduler / PowerShell):**
|
||||
```powershell
|
||||
schtasks /create /tn "PoonaAMS_NightlyBackup" /tr "powershell -ExecutionPolicy Bypass -Command 'cd C:\path\to\poona-ams\backend; .\.venv\Scripts\python.exe scripts\backup.py backup'" /sc daily /st 01:00
|
||||
```
|
||||
|
||||
## Demo Accounts
|
||||
| Email | Password | Role |
|
||||
|---|---|---|
|
||||
@@ -58,19 +126,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
|
||||
|
||||
@@ -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"]
|
||||
@@ -31,6 +31,15 @@ def get_current_user(
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if user is None or not user.is_active:
|
||||
raise credentials_exception
|
||||
|
||||
token_tv = payload.get("tv", 0)
|
||||
user_tv = getattr(user, "token_version", 0)
|
||||
if token_tv != user_tv:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been invalidated. Please log in again.",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import logging
|
||||
from sqlalchemy.engine import Engine
|
||||
from ..models import Base
|
||||
|
||||
logger = logging.getLogger("poona_ams")
|
||||
|
||||
|
||||
def run_sqlite_migrations(engine: Engine) -> None:
|
||||
"""
|
||||
Auto-migrate SQLite database schema additions for existing databases.
|
||||
SQLite create_all() creates missing tables but does not alter existing
|
||||
tables to add newly defined columns. This reconciles table columns
|
||||
safely on startup without losing existing data.
|
||||
"""
|
||||
if engine.dialect.name != "sqlite":
|
||||
return
|
||||
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
existing_tables = {
|
||||
row[0]
|
||||
for row in conn.exec_driver_sql(
|
||||
"SELECT name FROM sqlite_master WHERE type='table'"
|
||||
).fetchall()
|
||||
}
|
||||
|
||||
for table_name, table in Base.metadata.tables.items():
|
||||
if table_name not in existing_tables:
|
||||
continue
|
||||
|
||||
existing_cols = {
|
||||
row[1]
|
||||
for row in conn.exec_driver_sql(
|
||||
f"PRAGMA table_info({table_name})"
|
||||
).fetchall()
|
||||
}
|
||||
|
||||
for col in table.columns:
|
||||
if col.name not in existing_cols:
|
||||
col_type = col.type.compile(engine.dialect)
|
||||
if col.name == "token_version":
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} INTEGER DEFAULT 0 NOT NULL"
|
||||
else:
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} {col_type}"
|
||||
logger.info("Auto-migrating SQLite: %s", sql)
|
||||
conn.exec_driver_sql(sql)
|
||||
except Exception:
|
||||
logger.exception("Failed running SQLite auto-migrations.")
|
||||
raise
|
||||
@@ -1,9 +1,77 @@
|
||||
from datetime import timedelta
|
||||
import bcrypt
|
||||
from fastapi import HTTPException, status
|
||||
from jose import JWTError, jwt
|
||||
from .config import settings
|
||||
from .time_utils import utc_now
|
||||
|
||||
BLOCKLIST_PASSWORDS = {
|
||||
"123456",
|
||||
"12345678",
|
||||
"password",
|
||||
"password1",
|
||||
"qwerty123",
|
||||
"admin123",
|
||||
"welcome1",
|
||||
}
|
||||
|
||||
|
||||
def validate_password(password: str, email: str | None = None) -> None:
|
||||
"""Validate password rules:
|
||||
- Length: at least 8, at most 128 characters.
|
||||
- Characters: at least one letter and at least one digit. (Special characters allowed, not required. Case insensitive.)
|
||||
- Must NOT start or end with a space (reject with a clear message, do not silently strip).
|
||||
- Blocklist (case-insensitive): '123456', '12345678', 'password', 'password1', 'qwerty123', 'admin123', 'welcome1'.
|
||||
(NOTE: demo password 'demo@123' must remain allowed)
|
||||
- Must not contain the user's username/email local-part if length >= 4 (case-insensitive).
|
||||
"""
|
||||
if not isinstance(password, str):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must be a string.",
|
||||
)
|
||||
|
||||
if password.startswith(" ") or password.endswith(" "):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must not start or end with a space.",
|
||||
)
|
||||
|
||||
if len(password) < 8:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must be at least 8 characters long.",
|
||||
)
|
||||
|
||||
if len(password) > 128:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must be at most 128 characters long.",
|
||||
)
|
||||
|
||||
has_letter = any(c.isalpha() for c in password)
|
||||
has_digit = any(c.isdigit() for c in password)
|
||||
if not has_letter or not has_digit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must contain at least one letter and at least one digit.",
|
||||
)
|
||||
|
||||
lower_pass = password.lower()
|
||||
if lower_pass in BLOCKLIST_PASSWORDS:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password is too common or easily guessable.",
|
||||
)
|
||||
|
||||
if email:
|
||||
local_part = email.split("@")[0].strip().lower()
|
||||
if len(local_part) >= 4 and local_part in lower_pass:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must not contain your email username.",
|
||||
)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
if not plain or not hashed:
|
||||
@@ -24,6 +92,8 @@ def hash_password(plain: str) -> str:
|
||||
|
||||
def create_access_token(data: dict, expires_minutes: int | None = None) -> str:
|
||||
to_encode = data.copy()
|
||||
if "tv" not in to_encode:
|
||||
to_encode["tv"] = 0
|
||||
expire = utc_now() + timedelta(minutes=expires_minutes or settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
to_encode["exp"] = expire
|
||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
|
||||
@@ -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"
|
||||
|
||||
+82
-3
@@ -1,13 +1,41 @@
|
||||
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 .core.migrations import run_sqlite_migrations
|
||||
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,15 +45,53 @@ 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)
|
||||
run_sqlite_migrations(engine)
|
||||
with SessionLocal() as db:
|
||||
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 +128,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,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)
|
||||
|
||||
@@ -11,22 +11,24 @@ 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_team: Mapped[Optional[str]] = mapped_column(String(100), 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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -67,6 +67,7 @@ class User(Base):
|
||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
role: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
department_id: Mapped[Optional[int]] = mapped_column(ForeignKey("departments.id"), nullable=True)
|
||||
token_version: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
|
||||
|
||||
@@ -27,11 +27,12 @@ class DemoEquipment(Base):
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
equipment_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
serial_no: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
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,15 +49,17 @@ 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)
|
||||
new_requirements: 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)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
|
||||
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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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)),
|
||||
}
|
||||
|
||||
|
||||
@@ -361,6 +371,8 @@ def list_assets(
|
||||
supplier_id: Optional[int] = None,
|
||||
status_filter: Optional[str] = Query(None, alias="status"),
|
||||
criticality: Optional[str] = None,
|
||||
requires_calibration: Optional[bool] = None,
|
||||
insurance_applicable: Optional[bool] = None,
|
||||
warranty_status: Optional[str] = None,
|
||||
contract_status: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
@@ -391,6 +403,10 @@ def list_assets(
|
||||
query = query.filter(Asset.status == status_filter)
|
||||
if criticality:
|
||||
query = query.filter(Asset.criticality == criticality)
|
||||
if requires_calibration is not None:
|
||||
query = query.filter(Asset.requires_calibration.is_(requires_calibration))
|
||||
if insurance_applicable is not None:
|
||||
query = query.filter(Asset.insurance_applicable.is_(insurance_applicable))
|
||||
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
@@ -504,6 +520,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 +821,19 @@ def get_asset_overview(
|
||||
|
||||
pm_rec_rows = (
|
||||
db.query(PMRecord)
|
||||
.options(joinedload(PMRecord.schedule))
|
||||
.filter(PMRecord.asset_id == asset.id)
|
||||
.order_by(PMRecord.planned_date.desc(), PMRecord.id.desc())
|
||||
.all()
|
||||
)
|
||||
pm_rec_out = []
|
||||
for r in pm_rec_rows:
|
||||
st, sev = compute_schedule_status(r.planned_date, r.status, today, leads["pm"], leads["red"])
|
||||
pm_lead = (
|
||||
leads["pm_in_house"]
|
||||
if r.schedule and r.schedule.service_mode == "in_house"
|
||||
else leads["pm_outsourced"]
|
||||
)
|
||||
st, sev = compute_schedule_status(r.planned_date, r.status, today, pm_lead, leads["red"])
|
||||
pm_rec_out.append(
|
||||
PMRecordSummaryOut(
|
||||
id=r.id,
|
||||
|
||||
@@ -0,0 +1,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,
|
||||
}
|
||||
@@ -1,15 +1,53 @@
|
||||
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.security import create_access_token, verify_password
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.security import create_access_token, hash_password, validate_password, verify_password
|
||||
from ..models.masters import User
|
||||
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
|
||||
from ..services.settings_service import get_demo_as_of_date
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
current_password: str
|
||||
new_password: str = Field(..., max_length=128)
|
||||
|
||||
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(
|
||||
id=user.id,
|
||||
@@ -24,8 +62,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))
|
||||
@@ -43,7 +83,11 @@ def login(payload: LoginRequest, db: Session = Depends(get_db)):
|
||||
detail="User account is inactive.",
|
||||
)
|
||||
|
||||
token = create_access_token({"sub": str(user.id), "role": user.role})
|
||||
token = create_access_token({
|
||||
"sub": str(user.id),
|
||||
"role": user.role,
|
||||
"tv": user.token_version,
|
||||
})
|
||||
return TokenResponse(
|
||||
access_token=token,
|
||||
token_type="bearer",
|
||||
@@ -57,3 +101,37 @@ def get_me(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
return _build_user_out(current_user, db)
|
||||
|
||||
|
||||
@router.post("/change-password")
|
||||
def change_password(
|
||||
payload: ChangePasswordRequest,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if not verify_password(payload.current_password, current_user.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Current password is incorrect.",
|
||||
)
|
||||
if payload.new_password == payload.current_password:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="New password must be different.",
|
||||
)
|
||||
validate_password(payload.new_password, email=current_user.email)
|
||||
current_user.password_hash = hash_password(payload.new_password)
|
||||
current_user.token_version = (current_user.token_version or 0) + 1
|
||||
db.commit()
|
||||
db.refresh(current_user)
|
||||
|
||||
new_token = create_access_token({
|
||||
"sub": str(current_user.id),
|
||||
"role": current_user.role,
|
||||
"tv": current_user.token_version,
|
||||
})
|
||||
return {
|
||||
"message": "Password changed successfully.",
|
||||
"access_token": new_token,
|
||||
"token_type": "bearer",
|
||||
}
|
||||
|
||||
@@ -0,0 +1,682 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
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.bulk_templates import build_calibration_template_xlsx, process_calibration_import
|
||||
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("/import-template")
|
||||
def download_calibration_import_template(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
buf = build_calibration_template_xlsx(db)
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": 'attachment; filename="calibration_import_template.xlsx"'},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/bulk-import")
|
||||
def bulk_import_calibration(
|
||||
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, Role.coordinator, Role.management)
|
||||
),
|
||||
):
|
||||
content = file.file.read()
|
||||
return process_calibration_import(
|
||||
db=db,
|
||||
filename=file.filename or "calibration.xlsx",
|
||||
content=content,
|
||||
user_id=current_user.id,
|
||||
dry_run=dry_run,
|
||||
skip_invalid=skip_invalid,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/plans", response_model=CalibrationPlanListOut)
|
||||
def list_calibration_plans(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
agency_id: Optional[int] = None,
|
||||
is_active: Optional[bool] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
query = (
|
||||
db.query(CalibrationPlan)
|
||||
.join(Asset, CalibrationPlan.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, CalibrationPlan.agency_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
|
||||
joinedload(CalibrationPlan.agency),
|
||||
joinedload(CalibrationPlan.approved_by),
|
||||
)
|
||||
)
|
||||
if current_user.role == Role.department_user.value:
|
||||
query = query.filter(Asset.department_id == current_user.department_id)
|
||||
elif department_id is not None:
|
||||
query = query.filter(Asset.department_id == department_id)
|
||||
|
||||
if agency_id is not None:
|
||||
query = query.filter(CalibrationPlan.agency_id == agency_id)
|
||||
if is_active is not None:
|
||||
query = query.filter(CalibrationPlan.is_active.is_(is_active))
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(CalibrationPlan.next_due_date.asc(), CalibrationPlan.id.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return CalibrationPlanListOut(items=[_to_plan_out(p) for p in rows], total=total)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/plans/from-asset/{asset_id}",
|
||||
response_model=CalibrationPlanOut,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
def create_calibration_plan_from_asset(
|
||||
asset_id: int,
|
||||
payload: CalibrationPlanCreateFromAsset,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(
|
||||
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
|
||||
),
|
||||
):
|
||||
asset = db.query(Asset).filter(Asset.id == asset_id).first()
|
||||
if asset is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
|
||||
existing = db.query(CalibrationPlan.id).filter(CalibrationPlan.asset_id == asset_id).first()
|
||||
if existing is not None:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Calibration plan already exists for this asset.",
|
||||
code="DUPLICATE_CALIBRATION_PLAN",
|
||||
)
|
||||
|
||||
if payload.approve and current_user.role not in APPROVER_ROLES:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only management, system_admin, or coordinator can approve calibration frequency.",
|
||||
code="FORBIDDEN_CALIBRATION_APPROVAL",
|
||||
)
|
||||
|
||||
if payload.agency_id is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
|
||||
|
||||
today = effective_today(db)
|
||||
plan = _create_plan_and_initial_record(
|
||||
db,
|
||||
asset=asset,
|
||||
frequency_months=payload.frequency_months,
|
||||
calibrations_per_year=payload.calibrations_per_year,
|
||||
agency_id=payload.agency_id,
|
||||
next_due_date=payload.next_due_date,
|
||||
approve=payload.approve,
|
||||
current_user=current_user,
|
||||
today=today,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_plan_with_joins(db, plan.id)
|
||||
return _to_plan_out(loaded)
|
||||
|
||||
|
||||
@router.post("/plans/bulk-from-assets", response_model=CalibrationPlanBulkOut)
|
||||
def bulk_create_calibration_plans(
|
||||
payload: CalibrationPlanBulkCreateIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(
|
||||
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
|
||||
),
|
||||
):
|
||||
if payload.approve and current_user.role not in APPROVER_ROLES:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only management, system_admin, or coordinator can approve calibration frequency.",
|
||||
code="FORBIDDEN_CALIBRATION_APPROVAL",
|
||||
)
|
||||
|
||||
if payload.agency_id is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
|
||||
|
||||
unique_ids = list(dict.fromkeys(payload.asset_ids))
|
||||
assets_by_id = {a.id: a for a in db.query(Asset).filter(Asset.id.in_(unique_ids)).all()}
|
||||
existing_asset_ids = {
|
||||
row[0]
|
||||
for row in db.query(CalibrationPlan.asset_id)
|
||||
.filter(CalibrationPlan.asset_id.in_(unique_ids))
|
||||
.all()
|
||||
}
|
||||
|
||||
today = effective_today(db)
|
||||
created_ids: list[int] = []
|
||||
skipped_ids: list[int] = []
|
||||
|
||||
for aid in unique_ids:
|
||||
asset = assets_by_id.get(aid)
|
||||
if asset is None or aid in existing_asset_ids:
|
||||
skipped_ids.append(aid)
|
||||
continue
|
||||
plan = _create_plan_and_initial_record(
|
||||
db,
|
||||
asset=asset,
|
||||
frequency_months=payload.frequency_months,
|
||||
calibrations_per_year=payload.calibrations_per_year,
|
||||
agency_id=payload.agency_id,
|
||||
next_due_date=payload.next_due_date,
|
||||
approve=payload.approve,
|
||||
current_user=current_user,
|
||||
today=today,
|
||||
)
|
||||
created_ids.append(plan.id)
|
||||
existing_asset_ids.add(aid)
|
||||
|
||||
db.commit()
|
||||
|
||||
created_out: list[CalibrationPlanOut] = []
|
||||
if created_ids:
|
||||
loaded_plans = (
|
||||
db.query(CalibrationPlan)
|
||||
.options(
|
||||
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
|
||||
joinedload(CalibrationPlan.agency),
|
||||
joinedload(CalibrationPlan.approved_by),
|
||||
)
|
||||
.filter(CalibrationPlan.id.in_(created_ids))
|
||||
.all()
|
||||
)
|
||||
by_id = {p.id: p for p in loaded_plans}
|
||||
created_out = [_to_plan_out(by_id[pid]) for pid in created_ids if pid in by_id]
|
||||
|
||||
return CalibrationPlanBulkOut(created=created_out, skipped_asset_ids=skipped_ids)
|
||||
|
||||
|
||||
@router.put("/plans/{plan_id}", response_model=CalibrationPlanOut)
|
||||
def update_calibration_plan(
|
||||
plan_id: int,
|
||||
payload: CalibrationPlanUpdateIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(
|
||||
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
|
||||
),
|
||||
):
|
||||
plan = db.query(CalibrationPlan).filter(CalibrationPlan.id == plan_id).first()
|
||||
if plan is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration plan not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
if current_user.role == Role.biomedical.value:
|
||||
if (
|
||||
("frequency_months" in data and data["frequency_months"] is not None)
|
||||
or ("calibrations_per_year" in data and data["calibrations_per_year"] is not None)
|
||||
):
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Biomedical users cannot modify calibration frequency; management, coordinator, or system_admin approval is required.",
|
||||
code="FORBIDDEN_CALIBRATION_APPROVAL",
|
||||
)
|
||||
|
||||
if "agency_id" in data and data["agency_id"] is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == data["agency_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
|
||||
|
||||
if "frequency_months" in data and data["frequency_months"] is not None and "calibrations_per_year" not in data:
|
||||
data["calibrations_per_year"] = _default_per_year(data["frequency_months"])
|
||||
|
||||
old_due_date = plan.next_due_date
|
||||
old_agency_id = plan.agency_id
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
for k, v in data.items():
|
||||
if v is None and k in ("frequency_months", "calibrations_per_year", "next_due_date", "is_active"):
|
||||
continue
|
||||
old_val = getattr(plan, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(plan, k, v)
|
||||
plan.updated_by_id = current_user.id
|
||||
|
||||
if plan.next_due_date != old_due_date or plan.agency_id != old_agency_id:
|
||||
open_rec = (
|
||||
db.query(CalibrationRecord)
|
||||
.filter(CalibrationRecord.plan_id == plan.id, CalibrationRecord.status.is_(None))
|
||||
.order_by(CalibrationRecord.due_date.desc(), CalibrationRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_rec is not None:
|
||||
open_rec.due_date = plan.next_due_date
|
||||
open_rec.agency_id = plan.agency_id
|
||||
open_rec.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="calibration_plan",
|
||||
entity_id=plan.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_plan_with_joins(db, plan.id)
|
||||
return _to_plan_out(loaded)
|
||||
|
||||
|
||||
@router.post("/plans/{plan_id}/approve", response_model=CalibrationPlanOut)
|
||||
def approve_calibration_plan(
|
||||
plan_id: int,
|
||||
payload: Optional[CalibrationPlanApproveIn] = Body(default=None),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.management, Role.system_admin, Role.coordinator)),
|
||||
):
|
||||
plan = db.query(CalibrationPlan).filter(CalibrationPlan.id == plan_id).first()
|
||||
if plan is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration plan not found.")
|
||||
|
||||
today = effective_today(db)
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
|
||||
if payload is not None:
|
||||
if payload.frequency_months is not None and payload.frequency_months != plan.frequency_months:
|
||||
changes["frequency_months"] = {"from": plan.frequency_months, "to": payload.frequency_months}
|
||||
plan.frequency_months = payload.frequency_months
|
||||
if payload.calibrations_per_year is None:
|
||||
new_per_year = _default_per_year(payload.frequency_months)
|
||||
if new_per_year != plan.calibrations_per_year:
|
||||
changes["calibrations_per_year"] = {"from": plan.calibrations_per_year, "to": new_per_year}
|
||||
plan.calibrations_per_year = new_per_year
|
||||
if payload.calibrations_per_year is not None and payload.calibrations_per_year != plan.calibrations_per_year:
|
||||
changes["calibrations_per_year"] = {"from": plan.calibrations_per_year, "to": payload.calibrations_per_year}
|
||||
plan.calibrations_per_year = payload.calibrations_per_year
|
||||
|
||||
plan.approved_by_id = current_user.id
|
||||
plan.approved_on = today
|
||||
plan.updated_by_id = current_user.id
|
||||
changes["approved_by_id"] = {"to": current_user.id}
|
||||
changes["approved_on"] = {"to": str(today)}
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="calibration_plan",
|
||||
entity_id=plan.id,
|
||||
action="approve",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_plan_with_joins(db, plan.id)
|
||||
return _to_plan_out(loaded)
|
||||
|
||||
|
||||
@router.get("/records", response_model=CalibrationRecordListOut)
|
||||
def list_calibration_records(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
agency_id: Optional[int] = None,
|
||||
status_filter: Optional[CalibrationStatusFilter] = Query(None, alias="status"),
|
||||
due_from: Optional[date] = None,
|
||||
due_to: Optional[date] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
leads = _cal_lead_settings(db)
|
||||
|
||||
query = (
|
||||
db.query(CalibrationRecord)
|
||||
.join(CalibrationPlan, CalibrationRecord.plan_id == CalibrationPlan.id)
|
||||
.join(Asset, CalibrationRecord.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, CalibrationRecord.agency_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(CalibrationRecord.asset).joinedload(Asset.department),
|
||||
joinedload(CalibrationRecord.asset).joinedload(Asset.location),
|
||||
joinedload(CalibrationRecord.agency),
|
||||
joinedload(CalibrationRecord.plan).joinedload(CalibrationPlan.approved_by),
|
||||
)
|
||||
)
|
||||
|
||||
if current_user.role == Role.department_user.value:
|
||||
query = query.filter(Asset.department_id == current_user.department_id)
|
||||
elif department_id is not None:
|
||||
query = query.filter(Asset.department_id == department_id)
|
||||
|
||||
if asset_id is not None:
|
||||
query = query.filter(CalibrationRecord.asset_id == asset_id)
|
||||
if agency_id is not None:
|
||||
query = query.filter(CalibrationRecord.agency_id == agency_id)
|
||||
if due_from is not None:
|
||||
query = query.filter(CalibrationRecord.due_date >= due_from)
|
||||
if due_to is not None:
|
||||
query = query.filter(CalibrationRecord.due_date <= due_to)
|
||||
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
CalibrationRecord.certificate_no.ilike(like),
|
||||
CalibrationRecord.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(CalibrationRecord.due_date.asc(), CalibrationRecord.id.asc()).all()
|
||||
computed_all = [_to_record_out(r, today, leads) for r in rows]
|
||||
|
||||
summary = CalibrationRecordSummaryCounts(
|
||||
upcoming=sum(1 for item in computed_all if item.status == "upcoming"),
|
||||
due=sum(1 for item in computed_all if item.status == "due"),
|
||||
overdue=sum(1 for item in computed_all if item.status == "overdue"),
|
||||
completed=sum(1 for item in computed_all if item.status == "completed"),
|
||||
)
|
||||
|
||||
if status_filter is not None:
|
||||
filtered = [item for item in computed_all if item.status == status_filter]
|
||||
else:
|
||||
filtered = computed_all
|
||||
|
||||
total = len(filtered)
|
||||
start = (page - 1) * page_size
|
||||
paginated = filtered[start : start + page_size]
|
||||
|
||||
return CalibrationRecordListOut(items=paginated, total=total, summary=summary)
|
||||
|
||||
|
||||
@router.post("/records/{record_id}/complete", response_model=CalibrationRecordCompleteOut)
|
||||
def complete_calibration_record(
|
||||
record_id: int,
|
||||
payload: CalibrationRecordCompleteIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
rec = _load_record_with_joins(db, record_id)
|
||||
if rec is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration record not found.")
|
||||
|
||||
if rec.status == "completed":
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Calibration record is already completed.",
|
||||
code="INVALID_CALIBRATION_STATUS",
|
||||
)
|
||||
|
||||
clean_cert = payload.certificate_no.strip()
|
||||
if not clean_cert:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="certificate_no cannot be blank.",
|
||||
)
|
||||
|
||||
if payload.agency_id is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
|
||||
rec.agency_id = payload.agency_id
|
||||
|
||||
rec.status = "completed"
|
||||
rec.completed_date = payload.completed_date
|
||||
rec.certificate_no = clean_cert
|
||||
rec.remarks = payload.remarks.strip() if payload.remarks and payload.remarks.strip() else None
|
||||
rec.updated_by_id = current_user.id
|
||||
|
||||
plan = rec.plan
|
||||
next_due = add_months(payload.completed_date, plan.frequency_months)
|
||||
plan.next_due_date = next_due
|
||||
plan.updated_by_id = current_user.id
|
||||
|
||||
next_rec = CalibrationRecord(
|
||||
asset_id=plan.asset_id,
|
||||
plan_id=plan.id,
|
||||
due_date=next_due,
|
||||
agency_id=rec.agency_id if rec.agency_id is not None else plan.agency_id,
|
||||
status=None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(next_rec)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="calibration_record",
|
||||
entity_id=rec.id,
|
||||
action="complete",
|
||||
changes={
|
||||
"completed_date": str(payload.completed_date),
|
||||
"certificate_no": clean_cert,
|
||||
"next_due_date": str(next_due),
|
||||
"next_record_id": next_rec.id,
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
today = effective_today(db)
|
||||
leads = _cal_lead_settings(db)
|
||||
loaded_completed = _load_record_with_joins(db, rec.id)
|
||||
loaded_next = _load_record_with_joins(db, next_rec.id)
|
||||
return CalibrationRecordCompleteOut(
|
||||
completed_record=_to_record_out(loaded_completed, today, leads),
|
||||
next_record=_to_record_out(loaded_next, today, leads),
|
||||
)
|
||||
@@ -0,0 +1,843 @@
|
||||
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_team=c.assigned_team,
|
||||
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,
|
||||
location_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 location_id is not None:
|
||||
query = query.filter(Asset.location_id == location_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,
|
||||
assigned_team=payload.assigned_team,
|
||||
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)
|
||||
if payload.assigned_to_id is None and not payload.assigned_team:
|
||||
raise HTTPException(status_code=422, detail="Either assigned_to_id or assigned_team must be provided.")
|
||||
|
||||
assignee: Optional[User] = None
|
||||
target_name = payload.assigned_team or ""
|
||||
if payload.assigned_to_id is not None:
|
||||
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.")
|
||||
target_name = assignee.name
|
||||
if payload.assigned_team:
|
||||
target_name = f"{assignee.name} ({payload.assigned_team})"
|
||||
|
||||
old_name: Optional[str] = None
|
||||
event_type = "assigned"
|
||||
if comp.assigned_to_id is not None or comp.assigned_team:
|
||||
event_type = "reassigned"
|
||||
if comp.assigned_to_id is not None:
|
||||
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)
|
||||
if comp.assigned_team:
|
||||
old_name = f"{old_name} ({comp.assigned_team})" if old_name else comp.assigned_team
|
||||
|
||||
now = utc_now()
|
||||
if assignee:
|
||||
comp.assigned_to_id = assignee.id
|
||||
if payload.assigned_team is not None:
|
||||
comp.assigned_team = payload.assigned_team.strip() or None
|
||||
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=target_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": comp.assigned_to_id,
|
||||
"assigned_team": comp.assigned_team,
|
||||
"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))
|
||||
@@ -0,0 +1,446 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
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.bulk_templates import build_contracts_template_xlsx, process_contracts_import
|
||||
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"),
|
||||
expiry_from: Optional[date] = None,
|
||||
expiry_to: Optional[date] = None,
|
||||
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 expiry_from is not None:
|
||||
query = query.filter(Contract.end_date >= expiry_from)
|
||||
if expiry_to is not None:
|
||||
query = query.filter(Contract.end_date <= expiry_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),
|
||||
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.get("/import-template")
|
||||
def download_contracts_import_template(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
buf = build_contracts_template_xlsx(db)
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": 'attachment; filename="contracts_import_template.xlsx"'},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/bulk-import")
|
||||
def bulk_import_contracts(
|
||||
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, Role.coordinator)),
|
||||
):
|
||||
content = file.file.read()
|
||||
return process_contracts_import(
|
||||
db=db,
|
||||
filename=file.filename or "contracts.xlsx",
|
||||
content=content,
|
||||
user_id=current_user.id,
|
||||
dry_run=dry_run,
|
||||
skip_invalid=skip_invalid,
|
||||
)
|
||||
|
||||
|
||||
@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.")
|
||||
|
||||
existing_contract = (
|
||||
db.query(Contract.id)
|
||||
.filter(
|
||||
Contract.asset_id == payload.asset_id,
|
||||
Contract.contract_type == payload.contract_type,
|
||||
Contract.start_date == payload.start_date,
|
||||
Contract.end_date == payload.end_date,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing_contract:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="A contract with the same asset, type and dates already exists.",
|
||||
)
|
||||
|
||||
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),
|
||||
)
|
||||
@@ -0,0 +1,336 @@
|
||||
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.scoping import resolve_department_scope
|
||||
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)
|
||||
|
||||
scope = resolve_department_scope(current_user)
|
||||
if scope.is_empty:
|
||||
cur_month_start = date(today.year, today.month, 1)
|
||||
months_seq = [add_months(cur_month_start, offset) for offset in range(-5, 1)]
|
||||
return DashboardSummaryOut(
|
||||
department_scope="Unassigned Department",
|
||||
effective_today=today,
|
||||
kpis=DashboardKPIs(
|
||||
total_assets=0,
|
||||
assets_under_repair=0,
|
||||
open_complaints=0,
|
||||
pm_due_this_month=0,
|
||||
calibrations_due=0,
|
||||
contracts_expiring=0,
|
||||
equipment_on_demo=0,
|
||||
),
|
||||
complaints_by_status=[
|
||||
ComplaintsByStatusItem(status="open", count=0),
|
||||
ComplaintsByStatusItem(status="in_progress", count=0),
|
||||
ComplaintsByStatusItem(status="closed", count=0),
|
||||
],
|
||||
complaints_by_department=[],
|
||||
monthly_downtime_trend=[
|
||||
MonthlyDowntimeItem(
|
||||
month=f"{m.year:04d}-{m.month:02d}",
|
||||
label=m.strftime("%b %Y"),
|
||||
downtime_minutes=0,
|
||||
downtime_hours=0.0,
|
||||
)
|
||||
for m in months_seq
|
||||
],
|
||||
pm_planned_vs_completed=[
|
||||
MonthlyPMComparisonItem(
|
||||
month=f"{m.year:04d}-{m.month:02d}",
|
||||
label=m.strftime("%b %Y"),
|
||||
planned=0,
|
||||
completed=0,
|
||||
)
|
||||
for m in months_seq
|
||||
],
|
||||
needs_attention=[],
|
||||
recent_complaints=[],
|
||||
)
|
||||
|
||||
scoped_dept_id: int | None = scope.department_id
|
||||
dept_scope_name: str | None = None
|
||||
if scoped_dept_id is not None:
|
||||
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,
|
||||
)
|
||||
@@ -0,0 +1,325 @@
|
||||
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,
|
||||
serial_no=item.serial_no,
|
||||
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(),
|
||||
serial_no=payload.serial_no.strip() if payload.serial_no else None,
|
||||
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)
|
||||
@@ -0,0 +1,332 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import func, 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.bulk_templates import build_insurance_template_xlsx, process_insurance_import
|
||||
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"),
|
||||
expiry_from: Optional[date] = None,
|
||||
expiry_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)
|
||||
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 expiry_from is not None:
|
||||
query = query.filter(InsurancePolicy.end_date >= expiry_from)
|
||||
if expiry_to is not None:
|
||||
query = query.filter(InsurancePolicy.end_date <= expiry_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),
|
||||
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.get("/import-template")
|
||||
def download_insurance_import_template(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
buf = build_insurance_template_xlsx(db)
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": 'attachment; filename="insurance_import_template.xlsx"'},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/bulk-import")
|
||||
def bulk_import_insurance(
|
||||
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, Role.coordinator)),
|
||||
):
|
||||
content = file.file.read()
|
||||
return process_insurance_import(
|
||||
db=db,
|
||||
filename=file.filename or "insurance.xlsx",
|
||||
content=content,
|
||||
user_id=current_user.id,
|
||||
dry_run=dry_run,
|
||||
skip_invalid=skip_invalid,
|
||||
)
|
||||
|
||||
|
||||
@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.",
|
||||
)
|
||||
|
||||
existing_policy = (
|
||||
db.query(InsurancePolicy.id)
|
||||
.filter(func.lower(func.trim(InsurancePolicy.policy_no)) == clean_policy_no.lower())
|
||||
.first()
|
||||
)
|
||||
if existing_policy:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Policy number already exists.",
|
||||
)
|
||||
|
||||
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)
|
||||
@@ -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)
|
||||
@@ -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),
|
||||
)
|
||||
@@ -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}"',
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,88 @@
|
||||
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
|
||||
from ..services.scoping import resolve_department_scope
|
||||
|
||||
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": []}
|
||||
|
||||
scope = resolve_department_scope(current_user)
|
||||
if scope.is_empty:
|
||||
return {"assets": [], "complaints": []}
|
||||
|
||||
pattern = f"%{term}%"
|
||||
|
||||
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 scope.department_id is not None:
|
||||
asset_q = asset_q.filter(Asset.department_id == scope.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 scope.department_id is not None:
|
||||
complaint_q = complaint_q.filter(Asset.department_id == scope.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
|
||||
],
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user, require_roles
|
||||
from ..core.security import hash_password
|
||||
from ..core.security import hash_password, validate_password
|
||||
from ..models.masters import Department, User
|
||||
from ..schemas.masters import (
|
||||
PaginatedOut,
|
||||
@@ -19,6 +20,10 @@ from ..services.permissions import Role
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
class ResetPasswordRequest(BaseModel):
|
||||
new_password: str = Field(..., max_length=128)
|
||||
|
||||
|
||||
def _user_list_out(user: User) -> UserListOut:
|
||||
return UserListOut(
|
||||
id=user.id,
|
||||
@@ -57,7 +62,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 +73,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)
|
||||
@@ -77,11 +82,19 @@ def create_user(
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
if payload.role == "department_user" and payload.department_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Department is required for department_user role.",
|
||||
)
|
||||
|
||||
if payload.department_id is not None:
|
||||
dept = db.query(Department).filter(Department.id == payload.department_id).first()
|
||||
if dept is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
|
||||
validate_password(payload.password, email=payload.email)
|
||||
|
||||
user = User(
|
||||
name=payload.name.strip(),
|
||||
email=payload.email.strip().lower(),
|
||||
@@ -108,13 +121,52 @@ def update_user(
|
||||
user_id: int,
|
||||
payload: UserUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
# Department user validation
|
||||
target_role = data.get("role", user.role)
|
||||
target_dept = data.get("department_id", user.department_id)
|
||||
if target_role == "department_user" and target_dept is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Department is required for department_user role.",
|
||||
)
|
||||
|
||||
# Prevent self-deactivation or changing own admin role
|
||||
if user.id == current_user.id:
|
||||
if "is_active" in data and not data["is_active"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot deactivate your own administrator account.",
|
||||
)
|
||||
if "role" in data and data["role"] != "system_admin":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot change the role of your own administrator account.",
|
||||
)
|
||||
|
||||
# Prevent deactivating or demoting the last active system admin
|
||||
if user.role == "system_admin" and (
|
||||
("is_active" in data and not data["is_active"])
|
||||
or ("role" in data and data["role"] != "system_admin")
|
||||
):
|
||||
active_admins = (
|
||||
db.query(User)
|
||||
.filter(User.role == "system_admin", User.is_active.is_(True), User.id != user.id)
|
||||
.count()
|
||||
)
|
||||
if active_admins == 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot deactivate or change role: system must have at least one active system administrator.",
|
||||
)
|
||||
|
||||
if "department_id" in data and data["department_id"] is not None:
|
||||
dept = db.query(Department).filter(Department.id == data["department_id"]).first()
|
||||
if dept is None:
|
||||
@@ -125,13 +177,10 @@ def update_user(
|
||||
data["email"] = data["email"].strip().lower()
|
||||
|
||||
password = data.pop("password", None)
|
||||
if password is not None and password.strip():
|
||||
if len(password) < 4:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must be at least 4 characters.",
|
||||
)
|
||||
if password is not None and password != "":
|
||||
validate_password(password, email=data.get("email", user.email))
|
||||
user.password_hash = hash_password(password)
|
||||
user.token_version = (user.token_version or 0) + 1
|
||||
|
||||
for k, v in data.items():
|
||||
setattr(user, k, v)
|
||||
@@ -153,12 +202,48 @@ def update_user(
|
||||
def delete_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
if user_id == current_user.id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot delete your own administrator account.",
|
||||
)
|
||||
|
||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||
|
||||
if user.role == "system_admin":
|
||||
active_admins = (
|
||||
db.query(User)
|
||||
.filter(User.role == "system_admin", User.is_active.is_(True), User.id != user.id)
|
||||
.count()
|
||||
)
|
||||
if active_admins == 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot delete the only active system administrator account.",
|
||||
)
|
||||
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return _user_list_out(user)
|
||||
|
||||
|
||||
@router.post("/{user_id}/reset-password")
|
||||
def reset_user_password(
|
||||
user_id: int,
|
||||
payload: ResetPasswordRequest,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||
validate_password(payload.new_password, email=user.email)
|
||||
user.password_hash = hash_password(payload.new_password)
|
||||
user.token_version = (user.token_version or 0) + 1
|
||||
db.commit()
|
||||
return {"message": f"Password for {user.name} has been reset successfully."}
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
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,
|
||||
new_requirements=v.new_requirements,
|
||||
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,
|
||||
new_requirements=payload.new_requirements.strip() if payload.new_requirements else None,
|
||||
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
|
||||
if "new_requirements" in data:
|
||||
req = data["new_requirements"]
|
||||
visit.new_requirements = req.strip() if isinstance(req, str) and req.strip() else None
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,274 @@
|
||||
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"),
|
||||
expiry_from: Optional[date] = None,
|
||||
expiry_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)
|
||||
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 expiry_from is not None:
|
||||
query = query.filter(Warranty.end_date >= expiry_from)
|
||||
if expiry_to is not None:
|
||||
query = query.filter(Warranty.end_date <= expiry_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),
|
||||
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)
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
from datetime import date
|
||||
from typing import Literal, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
CalibrationStatusFilter = Literal["upcoming", "due", "overdue", "completed"]
|
||||
|
||||
|
||||
class CalibrationPlanCreateFromAsset(BaseModel):
|
||||
frequency_months: int = Field(..., ge=1, le=120)
|
||||
calibrations_per_year: Optional[int] = Field(None, ge=1, le=24)
|
||||
agency_id: Optional[int] = None
|
||||
next_due_date: date
|
||||
approve: bool = False
|
||||
|
||||
|
||||
class CalibrationPlanBulkCreateIn(BaseModel):
|
||||
asset_ids: list[int] = Field(..., min_length=1)
|
||||
frequency_months: int = Field(..., ge=1, le=120)
|
||||
calibrations_per_year: Optional[int] = Field(None, ge=1, le=24)
|
||||
agency_id: Optional[int] = None
|
||||
next_due_date: date
|
||||
approve: bool = False
|
||||
|
||||
|
||||
class CalibrationPlanUpdateIn(BaseModel):
|
||||
frequency_months: Optional[int] = Field(None, ge=1, le=120)
|
||||
calibrations_per_year: Optional[int] = Field(None, ge=1, le=24)
|
||||
agency_id: Optional[int] = None
|
||||
next_due_date: Optional[date] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class CalibrationPlanApproveIn(BaseModel):
|
||||
frequency_months: Optional[int] = Field(None, ge=1, le=120)
|
||||
calibrations_per_year: Optional[int] = Field(None, ge=1, le=24)
|
||||
|
||||
|
||||
class CalibrationPlanOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
asset_id: int
|
||||
asset_code: str
|
||||
asset_name: str
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
frequency_months: int
|
||||
calibrations_per_year: int
|
||||
agency_id: Optional[int] = None
|
||||
agency_name: Optional[str] = None
|
||||
approved_by_id: Optional[int] = None
|
||||
approved_by_name: Optional[str] = None
|
||||
approved_on: Optional[date] = None
|
||||
next_due_date: date
|
||||
is_active: bool
|
||||
|
||||
|
||||
class CalibrationPlanListOut(BaseModel):
|
||||
items: list[CalibrationPlanOut]
|
||||
total: int
|
||||
|
||||
|
||||
class CalibrationPlanBulkOut(BaseModel):
|
||||
created: list[CalibrationPlanOut]
|
||||
skipped_asset_ids: list[int]
|
||||
|
||||
|
||||
class CalibrationRecordSummaryCounts(BaseModel):
|
||||
upcoming: int
|
||||
due: int
|
||||
overdue: int
|
||||
completed: int
|
||||
|
||||
|
||||
class CalibrationRecordOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
plan_id: int
|
||||
asset_id: int
|
||||
asset_code: str
|
||||
asset_name: str
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
location_name: Optional[str] = None
|
||||
due_date: date
|
||||
completed_date: Optional[date] = None
|
||||
agency_id: Optional[int] = None
|
||||
agency_name: Optional[str] = None
|
||||
certificate_no: Optional[str] = None
|
||||
remarks: Optional[str] = None
|
||||
status: str
|
||||
severity: str
|
||||
frequency_months: int
|
||||
approved_by_name: Optional[str] = None
|
||||
approved_on: Optional[date] = None
|
||||
|
||||
|
||||
class CalibrationRecordListOut(BaseModel):
|
||||
items: list[CalibrationRecordOut]
|
||||
total: int
|
||||
summary: CalibrationRecordSummaryCounts
|
||||
|
||||
|
||||
class CalibrationRecordCompleteIn(BaseModel):
|
||||
completed_date: date
|
||||
certificate_no: str = Field(..., min_length=1)
|
||||
agency_id: Optional[int] = None
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class CalibrationRecordCompleteOut(BaseModel):
|
||||
completed_record: CalibrationRecordOut
|
||||
next_record: CalibrationRecordOut
|
||||
@@ -0,0 +1,153 @@
|
||||
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
|
||||
assigned_team: 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
|
||||
assigned_team: 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: Optional[int] = None
|
||||
assigned_team: Optional[str] = None
|
||||
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_team: 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
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -0,0 +1,64 @@
|
||||
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)
|
||||
serial_no: Optional[str] = None
|
||||
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)
|
||||
serial_no: Optional[str] = None
|
||||
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
|
||||
serial_no: Optional[str] = None
|
||||
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
|
||||
@@ -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
|
||||
@@ -123,7 +123,7 @@ class VendorOut(BaseModel):
|
||||
class UserCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=150)
|
||||
email: str = Field(..., min_length=3, max_length=200)
|
||||
password: str = Field(..., min_length=4, max_length=128)
|
||||
password: str = Field(..., max_length=128)
|
||||
role: UserRole
|
||||
department_id: Optional[int] = None
|
||||
is_active: bool = True
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,61 @@
|
||||
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)
|
||||
new_requirements: Optional[str] = None
|
||||
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)
|
||||
new_requirements: Optional[str] = None
|
||||
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
|
||||
new_requirements: 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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
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 (and not yet restored)
|
||||
crit_complaints = (
|
||||
db.query(Complaint)
|
||||
.options(joinedload(Complaint.asset))
|
||||
.filter(
|
||||
Complaint.call_status != "closed",
|
||||
Complaint.priority == "critical",
|
||||
Complaint.restored_at.is_(None),
|
||||
)
|
||||
.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
|
||||
@@ -0,0 +1,523 @@
|
||||
import csv
|
||||
from datetime import date, datetime, timedelta
|
||||
from io import BytesIO, StringIO
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
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(name="Calibri", size=11, color="FFFFFF", bold=True)
|
||||
_HEADER_BORDER = Border(
|
||||
left=Side(style="thin", color="334155"),
|
||||
right=Side(style="thin", color="334155"),
|
||||
top=Side(style="thin", color="334155"),
|
||||
bottom=Side(style="medium", color="0F172A"),
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
cell.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(IMPORT_COLUMNS))}1"
|
||||
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",
|
||||
]
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ref = wb.create_sheet(title="Master Reference")
|
||||
ref.row_dimensions[1].height = 26
|
||||
ref.views.sheetView[0].showGridLines = True
|
||||
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
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = _HEADER_BORDER
|
||||
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 ""
|
||||
if isinstance(val, float) and val.is_integer():
|
||||
return str(int(val))
|
||||
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
|
||||
if isinstance(val, (int, float)) and 20000 <= val <= 80000:
|
||||
try:
|
||||
return (datetime(1899, 12, 30) + timedelta(days=int(val))).date(), None
|
||||
except Exception:
|
||||
pass
|
||||
text = str(val).strip()
|
||||
for fmt in (
|
||||
"%Y-%m-%d",
|
||||
"%d-%b-%Y",
|
||||
"%d/%m/%Y",
|
||||
"%m/%d/%Y",
|
||||
"%Y/%m/%d",
|
||||
"%d-%m-%Y",
|
||||
"%d.%m.%Y",
|
||||
"%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
|
||||
if isinstance(val, (int, float)):
|
||||
if val < 0:
|
||||
return None, f"{field_name} cannot be negative"
|
||||
return float(val), None
|
||||
cleaned = re.sub(r"[₹$,\s]|(?i:rs\.?|inr)", "", str(val).strip())
|
||||
if not cleaned:
|
||||
return None, None
|
||||
try:
|
||||
parsed = float(cleaned)
|
||||
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.worksheets[0]
|
||||
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
|
||||
@@ -14,6 +15,8 @@ from ..models import (
|
||||
Contract,
|
||||
DemoEquipment,
|
||||
InsurancePolicy,
|
||||
PMRecord,
|
||||
PMSchedule,
|
||||
User,
|
||||
Warranty,
|
||||
)
|
||||
@@ -28,6 +31,7 @@ ALLOWED_ENTITY_TYPES: set[str] = {
|
||||
"demo_equipment",
|
||||
"asset",
|
||||
"warranty",
|
||||
"pm_record",
|
||||
}
|
||||
|
||||
EXT_TO_MIME: dict[str, str] = {
|
||||
@@ -49,6 +53,7 @@ COORDINATOR_UPLOAD_ENTITIES: set[str] = {
|
||||
"insurance",
|
||||
"warranty",
|
||||
"demo_equipment",
|
||||
"pm_record",
|
||||
}
|
||||
|
||||
|
||||
@@ -127,6 +132,17 @@ def resolve_entity_department_id(db: Session, entity_type: str, entity_id: int)
|
||||
raise CodedHTTPException(status_code=404, detail="Calibration record not found.", code="NOT_FOUND")
|
||||
return obj.asset.department_id
|
||||
|
||||
if entity_type == "pm_record":
|
||||
obj = (
|
||||
db.query(PMRecord)
|
||||
.options(joinedload(PMRecord.schedule).joinedload(PMSchedule.asset))
|
||||
.filter(PMRecord.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="PM record not found.", code="NOT_FOUND")
|
||||
return obj.schedule.asset.department_id
|
||||
|
||||
raise CodedHTTPException(status_code=400, detail="Unsupported entity_type.", code="INVALID_ENTITY_TYPE")
|
||||
|
||||
|
||||
@@ -302,3 +318,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}
|
||||
|
||||
@@ -0,0 +1,986 @@
|
||||
"""
|
||||
Poona Hospital Asset Management System
|
||||
Bulk Import Template Builders for Contracts, Calibration Plans, and Insurance Policies.
|
||||
"""
|
||||
|
||||
import csv
|
||||
from datetime import date, datetime, timedelta
|
||||
from io import BytesIO, StringIO
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.time_utils import add_months, effective_today
|
||||
from ..models import (
|
||||
Asset,
|
||||
CalibrationPlan,
|
||||
CalibrationRecord,
|
||||
Contract,
|
||||
Department,
|
||||
InsurancePolicy,
|
||||
Vendor,
|
||||
)
|
||||
from .audit import log_audit
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||
_HEADER_FONT = Font(name="Calibri", size=11, color="FFFFFF", bold=True)
|
||||
_REF_HEADER_FILL = PatternFill(start_color="334155", end_color="334155", fill_type="solid")
|
||||
_HEADER_BORDER = Border(
|
||||
left=Side(style="thin", color="334155"),
|
||||
right=Side(style="thin", color="334155"),
|
||||
top=Side(style="thin", color="334155"),
|
||||
bottom=Side(style="medium", color="0F172A"),
|
||||
)
|
||||
|
||||
|
||||
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_contracts_template_xlsx(db: Session) -> BytesIO:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Contracts"
|
||||
|
||||
cols = [
|
||||
"asset_code",
|
||||
"provider_name",
|
||||
"contract_type",
|
||||
"start_date",
|
||||
"end_date",
|
||||
"cost",
|
||||
"coverage_details",
|
||||
"remarks",
|
||||
]
|
||||
for col_idx, col_name in enumerate(cols, start=1):
|
||||
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||
c.fill = _HEADER_FILL
|
||||
c.font = _HEADER_FONT
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).order_by(Vendor.name).all()
|
||||
|
||||
sample_asset = assets[0] if assets else None
|
||||
sample_vendor = vendors[0] if vendors else None
|
||||
sample_row = [
|
||||
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||
sample_vendor.name if sample_vendor else "Wipro GE Healthcare Pvt Ltd",
|
||||
"CMC",
|
||||
"2026-01-01",
|
||||
"2026-12-31",
|
||||
75000,
|
||||
"Comprehensive maintenance with all spare parts included",
|
||||
"Annual contract renewal",
|
||||
]
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ws_ref = wb.create_sheet(title="Master Reference")
|
||||
ws_ref.row_dimensions[1].height = 26
|
||||
ws_ref.views.sheetView[0].showGridLines = True
|
||||
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||
|
||||
ws_ref.cell(row=1, column=5, value="Vendor / Provider").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=5).font = _HEADER_FONT
|
||||
|
||||
ws_ref.cell(row=1, column=7, value="Valid Contract Types").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=7).font = _HEADER_FONT
|
||||
|
||||
for r_idx, a in enumerate(assets[:100], start=2):
|
||||
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||
|
||||
for r_idx, v in enumerate(vendors, start=2):
|
||||
ws_ref.cell(row=r_idx, column=5, value=v.name)
|
||||
|
||||
for r_idx, ct in enumerate(["AMC", "CMC", "OTHER"], start=2):
|
||||
ws_ref.cell(row=r_idx, column=7, value=ct)
|
||||
|
||||
_auto_fit_columns(ws_ref)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def build_calibration_template_xlsx(db: Session) -> BytesIO:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Calibration Plans"
|
||||
|
||||
cols = [
|
||||
"asset_code",
|
||||
"frequency_months",
|
||||
"agency_name",
|
||||
"scope",
|
||||
"standards",
|
||||
"remarks",
|
||||
]
|
||||
for col_idx, col_name in enumerate(cols, start=1):
|
||||
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||
c.fill = _HEADER_FILL
|
||||
c.font = _HEADER_FONT
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
assets = (
|
||||
db.query(Asset)
|
||||
.join(Department)
|
||||
.filter(Asset.status != "condemned", Asset.requires_calibration.is_(True))
|
||||
.order_by(Asset.asset_code)
|
||||
.all()
|
||||
)
|
||||
if not assets:
|
||||
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).order_by(Vendor.name).all()
|
||||
sample_asset = assets[0] if assets else None
|
||||
sample_vendor = vendors[0] if vendors else None
|
||||
|
||||
sample_row = [
|
||||
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||
12,
|
||||
sample_vendor.name if sample_vendor else "National Calibration Laboratory",
|
||||
"Pressure and Flow accuracy verification",
|
||||
"ISO/IEC 17025 accredited",
|
||||
"Annual calibration plan",
|
||||
]
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ws_ref = wb.create_sheet(title="Master Reference")
|
||||
ws_ref.row_dimensions[1].height = 26
|
||||
ws_ref.views.sheetView[0].showGridLines = True
|
||||
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||
|
||||
ws_ref.cell(row=1, column=5, value="Calibration Agencies").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=5).font = _HEADER_FONT
|
||||
|
||||
ws_ref.cell(row=1, column=7, value="Recommended Frequencies").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=7).font = _HEADER_FONT
|
||||
|
||||
for r_idx, a in enumerate(assets[:100], start=2):
|
||||
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||
|
||||
for r_idx, v in enumerate(vendors, start=2):
|
||||
ws_ref.cell(row=r_idx, column=5, value=v.name)
|
||||
|
||||
for r_idx, freq in enumerate(["3 (Quarterly)", "6 (Semi-Annual)", "12 (Annual)", "24 (Biennial)"], start=2):
|
||||
ws_ref.cell(row=r_idx, column=7, value=freq)
|
||||
|
||||
_auto_fit_columns(ws_ref)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Insurance Policies"
|
||||
|
||||
cols = [
|
||||
"asset_code",
|
||||
"insurer_name",
|
||||
"policy_number",
|
||||
"start_date",
|
||||
"end_date",
|
||||
"insured_value",
|
||||
"premium",
|
||||
"remarks",
|
||||
]
|
||||
for col_idx, col_name in enumerate(cols, start=1):
|
||||
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||
c.fill = _HEADER_FILL
|
||||
c.font = _HEADER_FONT
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||
sample_asset = assets[0] if assets else None
|
||||
|
||||
sample_row = [
|
||||
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||
"New India Assurance Co. Ltd",
|
||||
"NIA-MH-2026-MED-4412",
|
||||
"2026-04-01",
|
||||
"2027-03-31",
|
||||
1500000,
|
||||
18500,
|
||||
"Annual hospital equipment comprehensive policy",
|
||||
]
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ws_ref = wb.create_sheet(title="Master Reference")
|
||||
ws_ref.row_dimensions[1].height = 26
|
||||
ws_ref.views.sheetView[0].showGridLines = True
|
||||
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||
|
||||
for r_idx, a in enumerate(assets[:100], start=2):
|
||||
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||
|
||||
_auto_fit_columns(ws_ref)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def _clean_str(val: Any) -> str:
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float) and val.is_integer():
|
||||
return str(int(val))
|
||||
return str(val).strip()
|
||||
|
||||
|
||||
def _parse_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, f"Missing required field '{field_name}'"
|
||||
if isinstance(val, datetime):
|
||||
return val.date(), None
|
||||
if isinstance(val, date):
|
||||
return val, None
|
||||
if isinstance(val, (int, float)) and 20000 <= val <= 80000:
|
||||
try:
|
||||
return (datetime(1899, 12, 30) + timedelta(days=int(val))).date(), None
|
||||
except Exception:
|
||||
pass
|
||||
text = str(val).strip()
|
||||
for fmt in (
|
||||
"%Y-%m-%d",
|
||||
"%d-%b-%Y",
|
||||
"%d/%m/%Y",
|
||||
"%m/%d/%Y",
|
||||
"%Y/%m/%d",
|
||||
"%d-%m-%Y",
|
||||
"%d.%m.%Y",
|
||||
"%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_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
|
||||
if isinstance(val, (int, float)):
|
||||
if val < 0:
|
||||
return None, f"{field_name} cannot be negative"
|
||||
return float(val), None
|
||||
cleaned = re.sub(r"[₹$,\s]|(?i:rs\.?|inr)", "", str(val).strip())
|
||||
if not cleaned:
|
||||
return None, None
|
||||
try:
|
||||
parsed = float(cleaned)
|
||||
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 _parse_positive_int(val: Any, field_name: str) -> tuple[int | None, str | None]:
|
||||
if val is None or (isinstance(val, str) and not val.strip()):
|
||||
return None, f"Missing required field '{field_name}'"
|
||||
if isinstance(val, (int, float)):
|
||||
parsed = int(val)
|
||||
if parsed <= 0:
|
||||
return None, f"{field_name} must be greater than 0"
|
||||
return parsed, None
|
||||
cleaned = re.sub(r"[,\s]|(?i:months?|yrs?|years?)", "", str(val).strip())
|
||||
try:
|
||||
parsed = int(float(cleaned))
|
||||
except (TypeError, ValueError):
|
||||
return None, f"Invalid {field_name} '{val}' (must be an integer)"
|
||||
if parsed <= 0:
|
||||
return None, f"{field_name} must be greater than 0"
|
||||
return parsed, None
|
||||
|
||||
|
||||
def _extract_rows(filename: str, content: bytes, sheet_name: str | None = None) -> list[tuple[int, dict[str, Any]]]:
|
||||
ext = Path(filename or "").suffix.lower()
|
||||
if ext not in (".xlsx", ".csv", ".xls"):
|
||||
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 in (".xlsx", ".xls"):
|
||||
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.worksheets[0]
|
||||
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(" ", "_").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(" ", "_").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_contracts_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, sheet_name="Contracts")
|
||||
|
||||
assets = db.query(Asset).all()
|
||||
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {}
|
||||
for v in vendors:
|
||||
vendor_lookup[v.name.strip().lower()] = v
|
||||
|
||||
existing_contracts = {
|
||||
(c.asset_id, (c.contract_type or "").upper(), c.start_date, c.end_date)
|
||||
for c in db.query(Contract.asset_id, Contract.contract_type, Contract.start_date, Contract.end_date).all()
|
||||
}
|
||||
seen_contracts_in_file: dict[tuple[int, str, date, date], int] = {}
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
preview_rows: list[dict[str, Any]] = []
|
||||
valid_records: list[dict[str, Any]] = []
|
||||
|
||||
for row_idx, row_dict in raw_rows:
|
||||
row_errors: list[str] = []
|
||||
|
||||
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||
provider_name = _clean_str(
|
||||
row_dict.get("provider_name")
|
||||
or row_dict.get("vendor_name")
|
||||
or row_dict.get("provider")
|
||||
or row_dict.get("vendor")
|
||||
)
|
||||
contract_type_raw = _clean_str(row_dict.get("contract_type")).upper()
|
||||
start_date_val = row_dict.get("start_date")
|
||||
end_date_val = row_dict.get("end_date")
|
||||
cost_val = row_dict.get("cost")
|
||||
coverage_details = _clean_str(row_dict.get("coverage_details") or row_dict.get("coverage_period_text"))
|
||||
remarks = _clean_str(row_dict.get("remarks"))
|
||||
|
||||
target_asset = None
|
||||
if not asset_code:
|
||||
row_errors.append("Missing required field 'asset_code'")
|
||||
else:
|
||||
target_asset = asset_lookup.get(asset_code.lower())
|
||||
if not target_asset:
|
||||
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||
|
||||
target_vendor = None
|
||||
if not provider_name:
|
||||
row_errors.append("Missing required field 'provider_name'")
|
||||
else:
|
||||
target_vendor = vendor_lookup.get(provider_name.lower())
|
||||
if not target_vendor:
|
||||
row_errors.append(f"Provider vendor '{provider_name}' not found")
|
||||
|
||||
if not contract_type_raw:
|
||||
row_errors.append("Missing required field 'contract_type'")
|
||||
elif contract_type_raw not in ("AMC", "CMC", "OTHER"):
|
||||
row_errors.append(f"Invalid contract_type '{contract_type_raw}' (expected AMC, CMC, or OTHER)")
|
||||
|
||||
start_date, s_err = _parse_date(start_date_val, "start_date")
|
||||
if s_err:
|
||||
row_errors.append(s_err)
|
||||
|
||||
end_date, e_err = _parse_date(end_date_val, "end_date")
|
||||
if e_err:
|
||||
row_errors.append(e_err)
|
||||
|
||||
if start_date and end_date and end_date < start_date:
|
||||
row_errors.append("end_date cannot be earlier than start_date")
|
||||
|
||||
if target_asset and contract_type_raw in ("AMC", "CMC", "OTHER") and start_date and end_date and end_date >= start_date:
|
||||
key = (target_asset.id, contract_type_raw, start_date, end_date)
|
||||
if key in seen_contracts_in_file:
|
||||
row_errors.append(f"Duplicate of row {seen_contracts_in_file[key]} in this file.")
|
||||
elif key in existing_contracts:
|
||||
row_errors.append("Already exists in the system.")
|
||||
seen_contracts_in_file[key] = row_idx
|
||||
else:
|
||||
seen_contracts_in_file[key] = row_idx
|
||||
|
||||
cost, c_err = _parse_optional_float(cost_val, "cost")
|
||||
if c_err:
|
||||
row_errors.append(c_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, "message": err_text})
|
||||
else:
|
||||
combined_remarks = remarks
|
||||
if cost is not None and cost > 0:
|
||||
cost_str = f"Cost: ₹{cost:,.2f}"
|
||||
combined_remarks = f"{remarks} ({cost_str})" if remarks else cost_str
|
||||
|
||||
valid_records.append({
|
||||
"asset_id": target_asset.id,
|
||||
"provider_id": target_vendor.id,
|
||||
"contract_type": contract_type_raw,
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"coverage_period_text": coverage_details or f"{start_date} to {end_date}",
|
||||
"remarks": combined_remarks or None,
|
||||
})
|
||||
|
||||
preview_rows.append({
|
||||
"row": row_idx,
|
||||
"data": {
|
||||
"asset_code": asset_code,
|
||||
"provider_name": provider_name,
|
||||
"contract_type": contract_type_raw,
|
||||
"start_date": str(start_date) if start_date else str(start_date_val or ""),
|
||||
"end_date": str(end_date) if end_date else str(end_date_val or ""),
|
||||
"cost": cost,
|
||||
"coverage_details": coverage_details,
|
||||
"remarks": remarks,
|
||||
},
|
||||
"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_records:
|
||||
for item in valid_records:
|
||||
contract = Contract(
|
||||
asset_id=item["asset_id"],
|
||||
provider_id=item["provider_id"],
|
||||
contract_type=item["contract_type"],
|
||||
start_date=item["start_date"],
|
||||
end_date=item["end_date"],
|
||||
coverage_period_text=item["coverage_period_text"],
|
||||
renewed_from_id=None,
|
||||
is_superseded=False,
|
||||
remarks=item["remarks"],
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(contract)
|
||||
db.flush()
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=contract.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": item["asset_id"],
|
||||
"contract_type": item["contract_type"],
|
||||
"provider_id": item["provider_id"],
|
||||
"start_date": str(item["start_date"]),
|
||||
"end_date": str(item["end_date"]),
|
||||
"source": "bulk_import",
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
created_count = len(valid_records)
|
||||
|
||||
return {
|
||||
"dry_run": dry_run,
|
||||
"total_rows": len(raw_rows),
|
||||
"valid_count": len(valid_records),
|
||||
"error_count": len(errors),
|
||||
"created_count": created_count,
|
||||
"errors": errors,
|
||||
"preview_rows": preview_rows,
|
||||
}
|
||||
|
||||
|
||||
def process_calibration_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, sheet_name="Calibration Plans")
|
||||
|
||||
assets = db.query(Asset).all()
|
||||
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||
|
||||
existing_plan_asset_ids = {p.asset_id for p in db.query(CalibrationPlan.asset_id).all()}
|
||||
seen_asset_ids: dict[int, int] = {}
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {}
|
||||
for v in vendors:
|
||||
vendor_lookup[v.name.strip().lower()] = v
|
||||
|
||||
today = effective_today(db)
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
preview_rows: list[dict[str, Any]] = []
|
||||
valid_records: list[dict[str, Any]] = []
|
||||
|
||||
for row_idx, row_dict in raw_rows:
|
||||
row_errors: list[str] = []
|
||||
|
||||
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||
freq_val = row_dict.get("frequency_months")
|
||||
agency_name = _clean_str(
|
||||
row_dict.get("agency_name")
|
||||
or row_dict.get("vendor_name")
|
||||
or row_dict.get("agency")
|
||||
)
|
||||
next_due_val = row_dict.get("next_due_date")
|
||||
scope = _clean_str(row_dict.get("scope"))
|
||||
standards = _clean_str(row_dict.get("standards"))
|
||||
remarks = _clean_str(row_dict.get("remarks"))
|
||||
|
||||
target_asset = None
|
||||
if not asset_code:
|
||||
row_errors.append("Missing required field 'asset_code'")
|
||||
else:
|
||||
target_asset = asset_lookup.get(asset_code.lower())
|
||||
if not target_asset:
|
||||
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||
elif target_asset.id in seen_asset_ids:
|
||||
row_errors.append(f"Duplicate of row {seen_asset_ids[target_asset.id]} in this file.")
|
||||
elif target_asset.id in existing_plan_asset_ids:
|
||||
row_errors.append("Asset already has a calibration plan.")
|
||||
seen_asset_ids[target_asset.id] = row_idx
|
||||
else:
|
||||
seen_asset_ids[target_asset.id] = row_idx
|
||||
|
||||
freq_months, f_err = _parse_positive_int(freq_val, "frequency_months")
|
||||
if f_err:
|
||||
row_errors.append(f_err)
|
||||
|
||||
target_agency = None
|
||||
if agency_name:
|
||||
target_agency = vendor_lookup.get(agency_name.lower())
|
||||
if not target_agency:
|
||||
row_errors.append(f"Calibration agency vendor '{agency_name}' not found")
|
||||
|
||||
due_date = None
|
||||
if next_due_val:
|
||||
d_parsed, d_err = _parse_date(next_due_val, "next_due_date")
|
||||
if d_err:
|
||||
row_errors.append(d_err)
|
||||
else:
|
||||
due_date = d_parsed
|
||||
elif freq_months:
|
||||
due_date = add_months(today, freq_months)
|
||||
|
||||
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, "message": err_text})
|
||||
else:
|
||||
valid_records.append({
|
||||
"asset": target_asset,
|
||||
"frequency_months": freq_months,
|
||||
"agency_id": target_agency.id if target_agency else None,
|
||||
"next_due_date": due_date,
|
||||
"remarks": remarks,
|
||||
})
|
||||
|
||||
preview_rows.append({
|
||||
"row": row_idx,
|
||||
"data": {
|
||||
"asset_code": asset_code,
|
||||
"frequency_months": freq_months if freq_months else freq_val,
|
||||
"agency_name": agency_name,
|
||||
"next_due_date": str(due_date) if due_date else str(next_due_val or ""),
|
||||
"scope": scope,
|
||||
"standards": standards,
|
||||
"remarks": remarks,
|
||||
},
|
||||
"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_records:
|
||||
for item in valid_records:
|
||||
asset = item["asset"]
|
||||
freq = item["frequency_months"]
|
||||
agency_id = item["agency_id"]
|
||||
due_date = item["next_due_date"]
|
||||
per_year = max(1, round(12 / freq))
|
||||
|
||||
asset.requires_calibration = True
|
||||
asset.updated_by_id = user_id
|
||||
|
||||
plan = CalibrationPlan(
|
||||
asset_id=asset.id,
|
||||
frequency_months=freq,
|
||||
calibrations_per_year=per_year,
|
||||
agency_id=agency_id,
|
||||
approved_by_id=user_id,
|
||||
approved_on=today,
|
||||
next_due_date=due_date,
|
||||
is_active=True,
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(plan)
|
||||
db.flush()
|
||||
|
||||
initial_rec = CalibrationRecord(
|
||||
asset_id=asset.id,
|
||||
plan_id=plan.id,
|
||||
due_date=due_date,
|
||||
agency_id=agency_id,
|
||||
status=None,
|
||||
created_by_id=user_id,
|
||||
updated_by_id=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": freq,
|
||||
"calibrations_per_year": per_year,
|
||||
"next_due_date": str(due_date),
|
||||
"approved": True,
|
||||
"initial_record_id": initial_rec.id,
|
||||
"source": "bulk_import",
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
created_count = len(valid_records)
|
||||
|
||||
return {
|
||||
"dry_run": dry_run,
|
||||
"total_rows": len(raw_rows),
|
||||
"valid_count": len(valid_records),
|
||||
"error_count": len(errors),
|
||||
"created_count": created_count,
|
||||
"errors": errors,
|
||||
"preview_rows": preview_rows,
|
||||
}
|
||||
|
||||
|
||||
def process_insurance_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, sheet_name="Insurance Policies")
|
||||
|
||||
assets = db.query(Asset).all()
|
||||
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {}
|
||||
for v in vendors:
|
||||
vendor_lookup[v.name.strip().lower()] = v
|
||||
|
||||
existing_policies = {
|
||||
p[0].strip().lower()
|
||||
for p in db.query(InsurancePolicy.policy_no).all()
|
||||
if p[0] and p[0].strip()
|
||||
}
|
||||
seen_policies_in_file: dict[str, int] = {}
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
preview_rows: list[dict[str, Any]] = []
|
||||
valid_records: list[dict[str, Any]] = []
|
||||
|
||||
for row_idx, row_dict in raw_rows:
|
||||
row_errors: list[str] = []
|
||||
|
||||
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||
insurer_name = _clean_str(
|
||||
row_dict.get("insurer_name")
|
||||
or row_dict.get("vendor_name")
|
||||
or row_dict.get("insurer")
|
||||
or row_dict.get("vendor")
|
||||
)
|
||||
policy_no = _clean_str(
|
||||
row_dict.get("policy_number")
|
||||
or row_dict.get("policy_no")
|
||||
or row_dict.get("policy_num")
|
||||
)
|
||||
start_date_val = row_dict.get("start_date")
|
||||
end_date_val = row_dict.get("end_date")
|
||||
insured_val = row_dict.get("insured_value") or row_dict.get("coverage_amount")
|
||||
premium_val = row_dict.get("premium")
|
||||
remarks = _clean_str(row_dict.get("remarks"))
|
||||
|
||||
target_asset = None
|
||||
if not asset_code:
|
||||
row_errors.append("Missing required field 'asset_code'")
|
||||
else:
|
||||
target_asset = asset_lookup.get(asset_code.lower())
|
||||
if not target_asset:
|
||||
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||
|
||||
target_vendor = None
|
||||
if not insurer_name:
|
||||
row_errors.append("Missing required field 'insurer_name'")
|
||||
else:
|
||||
target_vendor = vendor_lookup.get(insurer_name.lower())
|
||||
if not target_vendor:
|
||||
row_errors.append(f"Insurer vendor '{insurer_name}' not found")
|
||||
|
||||
if not policy_no:
|
||||
row_errors.append("Missing required field 'policy_number'")
|
||||
else:
|
||||
pol_key = policy_no.strip().lower()
|
||||
if pol_key in seen_policies_in_file:
|
||||
row_errors.append(f"Duplicate of row {seen_policies_in_file[pol_key]} in this file.")
|
||||
elif pol_key in existing_policies:
|
||||
row_errors.append("Already exists in the system.")
|
||||
seen_policies_in_file[pol_key] = row_idx
|
||||
else:
|
||||
seen_policies_in_file[pol_key] = row_idx
|
||||
|
||||
start_date, s_err = _parse_date(start_date_val, "start_date")
|
||||
if s_err:
|
||||
row_errors.append(s_err)
|
||||
|
||||
end_date, e_err = _parse_date(end_date_val, "end_date")
|
||||
if e_err:
|
||||
row_errors.append(e_err)
|
||||
|
||||
if start_date and end_date and end_date < start_date:
|
||||
row_errors.append("end_date cannot be earlier than start_date")
|
||||
|
||||
coverage_amount, ca_err = _parse_optional_float(insured_val, "insured_value")
|
||||
if ca_err:
|
||||
row_errors.append(ca_err)
|
||||
|
||||
premium, p_err = _parse_optional_float(premium_val, "premium")
|
||||
if p_err:
|
||||
row_errors.append(p_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, "message": err_text})
|
||||
else:
|
||||
combined_remarks = remarks
|
||||
if premium is not None and premium > 0:
|
||||
p_str = f"Premium: ₹{premium:,.2f}"
|
||||
combined_remarks = f"{remarks} ({p_str})" if remarks else p_str
|
||||
|
||||
valid_records.append({
|
||||
"asset": target_asset,
|
||||
"insurer_id": target_vendor.id,
|
||||
"policy_no": policy_no,
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"coverage_amount": coverage_amount,
|
||||
"remarks": combined_remarks or None,
|
||||
})
|
||||
|
||||
preview_rows.append({
|
||||
"row": row_idx,
|
||||
"data": {
|
||||
"asset_code": asset_code,
|
||||
"insurer_name": insurer_name,
|
||||
"policy_number": policy_no,
|
||||
"start_date": str(start_date) if start_date else str(start_date_val or ""),
|
||||
"end_date": str(end_date) if end_date else str(end_date_val or ""),
|
||||
"insured_value": coverage_amount,
|
||||
"premium": premium,
|
||||
"remarks": remarks,
|
||||
},
|
||||
"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_records:
|
||||
for item in valid_records:
|
||||
asset = item["asset"]
|
||||
asset.insurance_applicable = True
|
||||
asset.updated_by_id = user_id
|
||||
|
||||
policy = InsurancePolicy(
|
||||
asset_id=asset.id,
|
||||
insurer_id=item["insurer_id"],
|
||||
policy_no=item["policy_no"],
|
||||
start_date=item["start_date"],
|
||||
end_date=item["end_date"],
|
||||
coverage_amount=item["coverage_amount"],
|
||||
remarks=item["remarks"],
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(policy)
|
||||
db.flush()
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="insurance_policy",
|
||||
entity_id=policy.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": asset.id,
|
||||
"insurer_id": item["insurer_id"],
|
||||
"policy_no": item["policy_no"],
|
||||
"start_date": str(item["start_date"]),
|
||||
"end_date": str(item["end_date"]),
|
||||
"coverage_amount": item["coverage_amount"],
|
||||
"source": "bulk_import",
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
created_count = len(valid_records)
|
||||
|
||||
return {
|
||||
"dry_run": dry_run,
|
||||
"total_rows": len(raw_rows),
|
||||
"valid_count": len(valid_records),
|
||||
"error_count": len(errors),
|
||||
"created_count": created_count,
|
||||
"errors": errors,
|
||||
"preview_rows": preview_rows,
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import csv
|
||||
from io import BytesIO, StringIO
|
||||
import re
|
||||
from typing import Any
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from ..core.time_utils import format_datetime, utc_now
|
||||
|
||||
|
||||
def _sanitize_sheet_title(title: str) -> str:
|
||||
"""Sanitize Excel sheet title to comply with openpyxl / Excel naming rules."""
|
||||
cleaned = re.sub(r'[\\/*?:\[\]]', '_', title or "Report").strip()
|
||||
return cleaned[:31] or "Report"
|
||||
|
||||
|
||||
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())
|
||||
|
||||
|
||||
# Styling constants for executive Excel reports
|
||||
_NAVY_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||
_ZEBRA_FILL = PatternFill(start_color="F8FAFC", end_color="F8FAFC", fill_type="solid")
|
||||
_WHITE_FILL = PatternFill(start_color="FFFFFF", end_color="FFFFFF", fill_type="solid")
|
||||
_SUMMARY_FILL = PatternFill(start_color="EFF6FF", end_color="EFF6FF", fill_type="solid")
|
||||
_TOTAL_FILL = PatternFill(start_color="F1F5F9", end_color="F1F5F9", fill_type="solid")
|
||||
|
||||
_TITLE_FONT = Font(name="Calibri", size=14, bold=True, color="0F172A")
|
||||
_META_FONT = Font(name="Calibri", size=9, italic=True, color="475569")
|
||||
_SUMMARY_FONT = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
||||
_HEADER_FONT = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
|
||||
_DATA_FONT = Font(name="Calibri", size=10, color="0F172A")
|
||||
_TOTAL_FONT = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
||||
|
||||
_THIN_SIDE = Side(style="thin", color="CBD5E1")
|
||||
_CELL_BORDER = Border(left=_THIN_SIDE, right=_THIN_SIDE, top=_THIN_SIDE, bottom=_THIN_SIDE)
|
||||
_HEADER_BORDER = Border(
|
||||
left=Side(style="thin", color="334155"),
|
||||
right=Side(style="thin", color="334155"),
|
||||
top=Side(style="thin", color="334155"),
|
||||
bottom=Side(style="medium", color="0F172A"),
|
||||
)
|
||||
_TOTAL_BORDER = Border(
|
||||
left=_THIN_SIDE,
|
||||
right=_THIN_SIDE,
|
||||
top=Side(style="thin", color="94A3B8"),
|
||||
bottom=Side(style="double", color="1E3A8A"),
|
||||
)
|
||||
|
||||
|
||||
def _detect_cell_format(col_key: str, col_label: str, val: Any) -> tuple[Alignment, str | None]:
|
||||
"""Determine alignment and Excel number format from column metadata and value."""
|
||||
key_lower = col_key.lower()
|
||||
lbl_lower = col_label.lower()
|
||||
|
||||
# Currency / Financial costs
|
||||
if any(k in key_lower or k in lbl_lower for k in ["cost", "value", "price", "amount", "budget", "estimate"]):
|
||||
align = Alignment(horizontal="right", vertical="center")
|
||||
num_fmt = '"₹"#,##0.00' if isinstance(val, float) else '"₹"#,##0'
|
||||
return align, num_fmt
|
||||
|
||||
# Percentages
|
||||
if any(k in key_lower or k in lbl_lower for k in ["pct", "percent", "rate", "uptime"]):
|
||||
align = Alignment(horizontal="right", vertical="center")
|
||||
num_fmt = '0.0"%"' if isinstance(val, (int, float)) else None
|
||||
return align, num_fmt
|
||||
|
||||
# Numeric counts / durations / minutes
|
||||
if isinstance(val, (int, float)) and not isinstance(val, bool):
|
||||
align = Alignment(horizontal="right", vertical="center")
|
||||
num_fmt = "#,##0" if isinstance(val, int) else "#,##0.0"
|
||||
return align, num_fmt
|
||||
|
||||
# Dates, codes, status, IDs, booleans
|
||||
if any(k in key_lower or k in lbl_lower for k in ["date", "code", "no", "status", "priority", "criticality", "mode"]):
|
||||
align = Alignment(horizontal="center", vertical="center")
|
||||
return align, None
|
||||
|
||||
# Text / Names / Descriptions
|
||||
align = Alignment(horizontal="left", vertical="center")
|
||||
return align, None
|
||||
|
||||
|
||||
def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = _sanitize_sheet_title(report_payload.get("title", "Report"))
|
||||
|
||||
# Explicitly show grid lines in Excel view
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
|
||||
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", {}))
|
||||
|
||||
# Row 1: Hospital Title
|
||||
ws.row_dimensions[1].height = 28
|
||||
c1 = ws.cell(row=1, column=1, value=title_text)
|
||||
c1.font = _TITLE_FONT
|
||||
c1.alignment = Alignment(vertical="center")
|
||||
|
||||
# Row 2: Metadata & Filters
|
||||
ws.row_dimensions[2].height = 18
|
||||
c2 = ws.cell(row=2, column=1, value=meta_text)
|
||||
c2.font = _META_FONT
|
||||
c2.alignment = Alignment(vertical="center")
|
||||
|
||||
# Row 3: Summary KPIs strip
|
||||
ws.row_dimensions[3].height = 24
|
||||
c3 = ws.cell(row=3, column=1, value=summary_text)
|
||||
c3.font = _SUMMARY_FONT
|
||||
c3.fill = _SUMMARY_FILL
|
||||
c3.border = Border(
|
||||
top=Side(style="thin", color="BFDBFE"),
|
||||
bottom=Side(style="thin", color="BFDBFE"),
|
||||
left=Side(style="thin", color="BFDBFE"),
|
||||
right=Side(style="thin", color="BFDBFE"),
|
||||
)
|
||||
c3.alignment = Alignment(vertical="center", indent=1)
|
||||
|
||||
# Row 4: Spacer
|
||||
ws.row_dimensions[4].height = 10
|
||||
|
||||
columns: list[dict[str, str]] = report_payload.get("columns", [])
|
||||
rows: list[dict[str, Any]] = report_payload.get("rows", [])
|
||||
|
||||
# Span summary strip styling across header columns
|
||||
if columns and len(columns) > 1:
|
||||
for c_idx in range(2, len(columns) + 1):
|
||||
sc = ws.cell(row=3, column=c_idx)
|
||||
sc.fill = _SUMMARY_FILL
|
||||
sc.border = Border(
|
||||
top=Side(style="thin", color="BFDBFE"),
|
||||
bottom=Side(style="thin", color="BFDBFE"),
|
||||
left=Side(style="thin", color="BFDBFE"),
|
||||
right=Side(style="thin", color="BFDBFE"),
|
||||
)
|
||||
|
||||
header_row = 5
|
||||
ws.row_dimensions[header_row].height = 28
|
||||
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 = _NAVY_HEADER_FILL
|
||||
cell.font = _HEADER_FONT
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
cell.border = _HEADER_BORDER
|
||||
col_widths.append(len(str(col["label"])))
|
||||
|
||||
# Freeze header panes
|
||||
ws.freeze_panes = "A6"
|
||||
|
||||
# Data rows
|
||||
last_data_row = header_row
|
||||
for r_offset, row_data in enumerate(rows):
|
||||
excel_row = header_row + 1 + r_offset
|
||||
last_data_row = excel_row
|
||||
ws.row_dimensions[excel_row].height = 20
|
||||
row_fill = _ZEBRA_FILL if r_offset % 2 == 1 else _WHITE_FILL
|
||||
|
||||
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"
|
||||
|
||||
cell = ws.cell(row=excel_row, column=c_idx, value=val)
|
||||
cell.fill = row_fill
|
||||
cell.font = _DATA_FONT
|
||||
cell.border = _CELL_BORDER
|
||||
|
||||
align, num_fmt = _detect_cell_format(col["key"], col["label"], val)
|
||||
cell.alignment = align
|
||||
if num_fmt and isinstance(val, (int, float)):
|
||||
cell.number_format = num_fmt
|
||||
|
||||
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
|
||||
|
||||
# Add native Excel AutoFilter on header row
|
||||
if columns:
|
||||
last_col_letter = get_column_letter(len(columns))
|
||||
ws.auto_filter.ref = f"A{header_row}:{last_col_letter}{last_data_row}"
|
||||
|
||||
# Total summary row at bottom
|
||||
if rows:
|
||||
summary_row = last_data_row + 1
|
||||
ws.row_dimensions[summary_row].height = 22
|
||||
for c_idx in range(1, len(columns) + 1):
|
||||
tot_cell = ws.cell(row=summary_row, column=c_idx)
|
||||
tot_cell.fill = _TOTAL_FILL
|
||||
tot_cell.border = _TOTAL_BORDER
|
||||
tot_cell.font = _TOTAL_FONT
|
||||
if c_idx == 1:
|
||||
tot_cell.value = f"Total Records: {len(rows)}"
|
||||
tot_cell.alignment = Alignment(horizontal="left", vertical="center")
|
||||
else:
|
||||
tot_cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
|
||||
for c_idx, width in enumerate(col_widths, start=1):
|
||||
ws.column_dimensions[get_column_letter(c_idx)].width = min(50, max(14, width + 4))
|
||||
|
||||
# Pre-configure page setup for professional A4 Landscape printing / PDF conversion from Excel
|
||||
try:
|
||||
ws.page_setup.orientation = ws.ORIENTATION_LANDSCAPE
|
||||
ws.page_setup.paperSize = ws.PAPERSIZE_A4
|
||||
ws.page_setup.fitToPage = True
|
||||
ws.page_setup.fitToWidth = 1
|
||||
ws.page_setup.fitToHeight = 0
|
||||
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
||||
ws.print_title_rows = f"{header_row}:{header_row}"
|
||||
ws.oddHeader.left.text = "&BPoona Hospital & Research Centre&B"
|
||||
ws.oddHeader.right.text = report_payload.get("title", "Operational Report")
|
||||
ws.oddFooter.left.text = "Confidential • Biomedical Asset Management System"
|
||||
ws.oddFooter.right.text = "Page &P of &N"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
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
|
||||
@@ -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}"
|
||||
@@ -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",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,45 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from ..models import User
|
||||
from .permissions import Role
|
||||
|
||||
|
||||
@dataclass
|
||||
class DepartmentScope:
|
||||
is_unconstrained: bool
|
||||
department_id: Optional[int]
|
||||
is_empty: bool
|
||||
|
||||
|
||||
def resolve_department_scope(
|
||||
user: User,
|
||||
requested_dept_id: Optional[int] = None,
|
||||
) -> DepartmentScope:
|
||||
"""Resolve department scoping based on user role and assigned department.
|
||||
|
||||
Rules:
|
||||
- If user.role != 'department_user': unconstrained, department_id=requested_dept_id, is_empty=False.
|
||||
- If user.role == 'department_user' and user.department_id is None: is_empty=True, department_id=None, is_unconstrained=False.
|
||||
- If user.role == 'department_user' and user.department_id is not None: is_empty=False, department_id=user.department_id
|
||||
(requested_dept_id is ignored, cannot widen or change), is_unconstrained=False.
|
||||
"""
|
||||
if user.role != Role.department_user.value:
|
||||
return DepartmentScope(
|
||||
is_unconstrained=True,
|
||||
department_id=requested_dept_id,
|
||||
is_empty=False,
|
||||
)
|
||||
|
||||
if user.department_id is None:
|
||||
return DepartmentScope(
|
||||
is_unconstrained=False,
|
||||
department_id=None,
|
||||
is_empty=True,
|
||||
)
|
||||
|
||||
return DepartmentScope(
|
||||
is_unconstrained=False,
|
||||
department_id=user.department_id,
|
||||
is_empty=False,
|
||||
)
|
||||
@@ -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,146 @@ 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,
|
||||
},
|
||||
{
|
||||
"key": "alert_repeat_days",
|
||||
"type": "int",
|
||||
"default": 3,
|
||||
"label": "Overdue Alert Reminder Repeat Days",
|
||||
"description": "Interval in days to repeat notifications for active overdue breakdown and maintenance alerts.",
|
||||
"min": 1,
|
||||
"max": 30,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "smtp_enabled",
|
||||
"type": "bool",
|
||||
"default": False,
|
||||
"label": "Enable Email Notifications (SMTP)",
|
||||
"description": "Enable automated email delivery for high-severity alerts once mail server is configured.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "smtp_host",
|
||||
"type": "str",
|
||||
"default": "",
|
||||
"label": "SMTP Host",
|
||||
"description": "Hospital outbound mail server hostname (e.g. smtp.poonahospital.org).",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "smtp_port",
|
||||
"type": "int",
|
||||
"default": 587,
|
||||
"label": "SMTP Port",
|
||||
"description": "SMTP port (usually 587 for STARTTLS or 465 for SSL).",
|
||||
"min": 1,
|
||||
"max": 65535,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "smtp_from_email",
|
||||
"type": "str",
|
||||
"default": "ams-alerts@poonahospital.org",
|
||||
"label": "SMTP From Email Address",
|
||||
"description": "Sender email address displayed on alert notifications.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
]
|
||||
|
||||
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
|
||||
@@ -243,15 +383,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:
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[pytest]
|
||||
# Tests share a session-scoped SQLite DB; run sequentially (no -n / no xdist).
|
||||
# asyncio_mode silences the pytest-asyncio deprecation warning that causes
|
||||
# PowerShell to report exit code 1 even when all tests pass.
|
||||
asyncio_mode = strict
|
||||
asyncio_default_fixture_loop_scope = function
|
||||
filterwarnings =
|
||||
ignore::pytest.PytestDeprecationWarning
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Poona Hospital Asset Management System (AMS)
|
||||
Database & Attachments Backup and Disaster Recovery Utility.
|
||||
|
||||
Features:
|
||||
- Online SQLite backup via sqlite3.Connection.backup (transactionally consistent, no locks)
|
||||
- Bundles ams.db (and db.sqlite3) + uploads/ directory into a single timestamped archive (.tar.gz or .zip)
|
||||
- PRAGMA integrity_check validation
|
||||
- Retention policy rotation (retains the latest N backups, default: 7)
|
||||
- Safe restore functionality with pre-restore fallback safety copy
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sqlite3
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
logger = logging.getLogger("ams_backup")
|
||||
|
||||
|
||||
def get_db_path(db_url: str | None, backend_dir: Path) -> Path:
|
||||
"""Resolve database URL to a filesystem Path.
|
||||
|
||||
Rules:
|
||||
- If db_url is empty, None, or starts with 'sqlite:///:memory:', fall back to backend_dir / 'data' / 'ams.db'
|
||||
- If it starts with 'sqlite:////' (4 slashes, absolute path), strip 'sqlite:///' and return Path('/app/data/ams.db') (absolute)
|
||||
- If it starts with 'sqlite:///' (3 slashes), strip 'sqlite:///' and:
|
||||
- if the remainder starts with '/' (absolute), return Path(remainder)
|
||||
- if the remainder starts with './' or is a relative path, return (backend_dir / remainder).resolve()
|
||||
- If it is not a sqlite URL, fall back to backend_dir / 'data' / 'ams.db'
|
||||
"""
|
||||
if not db_url or not db_url.strip() or db_url.strip().startswith("sqlite:///:memory:"):
|
||||
return backend_dir / "data" / "ams.db"
|
||||
|
||||
clean_url = db_url.strip()
|
||||
if not clean_url.startswith("sqlite:///"):
|
||||
return backend_dir / "data" / "ams.db"
|
||||
|
||||
remainder = clean_url[len("sqlite:///"):]
|
||||
if not remainder or remainder == ":memory:":
|
||||
return backend_dir / "data" / "ams.db"
|
||||
|
||||
if remainder.startswith("/"):
|
||||
return Path(remainder)
|
||||
|
||||
p = Path(remainder)
|
||||
if p.is_absolute():
|
||||
return p
|
||||
|
||||
return (backend_dir / remainder).resolve()
|
||||
|
||||
|
||||
def get_default_paths() -> tuple[Path, Path, Path]:
|
||||
script_dir = Path(__file__).resolve().parent
|
||||
backend_dir = script_dir.parent
|
||||
data_dir = backend_dir / "data"
|
||||
|
||||
db_url = os.environ.get("DATABASE_URL", "").strip()
|
||||
db_path = get_db_path(db_url, backend_dir)
|
||||
|
||||
upload_env = os.environ.get("UPLOAD_DIR", "").strip()
|
||||
if upload_env:
|
||||
uploads_dir = Path(upload_env)
|
||||
if not uploads_dir.is_absolute():
|
||||
uploads_dir = backend_dir / uploads_dir
|
||||
else:
|
||||
uploads_dir = data_dir / "uploads"
|
||||
|
||||
backups_dir = data_dir / "backups"
|
||||
return db_path, uploads_dir, backups_dir
|
||||
|
||||
|
||||
def verify_sqlite_db(db_file: Path) -> bool:
|
||||
"""Run PRAGMA integrity_check on a SQLite file."""
|
||||
if not db_file.exists():
|
||||
logger.error("DB file not found for verification: %s", db_file)
|
||||
return False
|
||||
try:
|
||||
conn = sqlite3.connect(str(db_file))
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("PRAGMA integrity_check;")
|
||||
rows = cursor.fetchall()
|
||||
conn.close()
|
||||
if len(rows) == 1 and rows[0][0] == "ok":
|
||||
logger.info("SQLite integrity check PASSED for: %s", db_file.name)
|
||||
return True
|
||||
logger.error("SQLite integrity check FAILED: %s", rows)
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.error("Error verifying SQLite database: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def create_backup(
|
||||
db_path: Path | None = None,
|
||||
uploads_dir: Path | None = None,
|
||||
dest_dir: Path | None = None,
|
||||
backups_dir: Path | None = None,
|
||||
keep_count: int = 7,
|
||||
archive_format: str = "tar.gz",
|
||||
) -> Path | None:
|
||||
"""Create a consistent online backup of SQLite DB and attachments into a .tar.gz or .zip archive."""
|
||||
backend_dir = Path(__file__).resolve().parent.parent
|
||||
if db_path is None:
|
||||
db_url = os.environ.get("DATABASE_URL")
|
||||
db_path = get_db_path(db_url, backend_dir)
|
||||
|
||||
target_dir = dest_dir or backups_dir or (backend_dir / "data" / "backups")
|
||||
|
||||
if not db_path.exists():
|
||||
logger.error("Source database does not exist at %s", db_path)
|
||||
return None
|
||||
|
||||
if uploads_dir is None:
|
||||
upload_env = os.environ.get("UPLOAD_DIR", "").strip()
|
||||
uploads_dir = Path(upload_env) if upload_env else (backend_dir / "data" / "uploads")
|
||||
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
is_tar = archive_format in ("tar.gz", "tar", "tgz")
|
||||
ext = "tar.gz" if is_tar else "zip"
|
||||
backup_file_path = target_dir / f"ams_backup_{timestamp}.{ext}"
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
temp_db_path = Path(temp_dir) / "ams.db"
|
||||
|
||||
# 1. Perform online SQLite backup
|
||||
logger.info("Starting online backup of %s ...", db_path)
|
||||
src_conn = sqlite3.connect(f"file:{db_path.resolve()}?mode=ro", uri=True)
|
||||
dest_conn = sqlite3.connect(str(temp_db_path))
|
||||
with dest_conn:
|
||||
src_conn.backup(dest_conn)
|
||||
dest_conn.close()
|
||||
src_conn.close()
|
||||
|
||||
# 2. Verify backed-up database
|
||||
if not verify_sqlite_db(temp_db_path):
|
||||
logger.error("Integrity check failed on temporary backup. Aborting.")
|
||||
return None
|
||||
|
||||
# 3. Create archive
|
||||
logger.info("Creating backup archive: %s", backup_file_path)
|
||||
if is_tar:
|
||||
with tarfile.open(backup_file_path, "w:gz") as tf:
|
||||
# Add database under both ams.db and db.sqlite3 for compatibility
|
||||
tf.add(temp_db_path, arcname="db.sqlite3")
|
||||
tf.add(temp_db_path, arcname="ams.db")
|
||||
if uploads_dir.exists():
|
||||
file_count = 0
|
||||
for root, _, files in os.walk(uploads_dir):
|
||||
for file in files:
|
||||
full_path = Path(root) / file
|
||||
rel_path = full_path.relative_to(uploads_dir)
|
||||
tf.add(full_path, arcname=f"uploads/{rel_path}")
|
||||
file_count += 1
|
||||
logger.info("Archived %d attachment files from %s", file_count, uploads_dir)
|
||||
else:
|
||||
logger.warning("Uploads directory %s does not exist; skipping files.", uploads_dir)
|
||||
else:
|
||||
with zipfile.ZipFile(backup_file_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.write(temp_db_path, arcname="ams.db")
|
||||
zf.write(temp_db_path, arcname="db.sqlite3")
|
||||
if uploads_dir.exists():
|
||||
file_count = 0
|
||||
for root, _, files in os.walk(uploads_dir):
|
||||
for file in files:
|
||||
full_path = Path(root) / file
|
||||
rel_path = full_path.relative_to(uploads_dir)
|
||||
zf.write(full_path, arcname=f"uploads/{rel_path}")
|
||||
file_count += 1
|
||||
logger.info("Archived %d attachment files from %s", file_count, uploads_dir)
|
||||
else:
|
||||
logger.warning("Uploads directory %s does not exist; skipping files.", uploads_dir)
|
||||
|
||||
size_mb = backup_file_path.stat().st_size / (1024 * 1024)
|
||||
logger.info("Backup successfully completed! File: %s (%.2f MB)", backup_file_path, size_mb)
|
||||
|
||||
# 4. Enforce retention policy
|
||||
if keep_count > 0:
|
||||
existing_backups = sorted(
|
||||
list(target_dir.glob("ams_backup_*.tar.gz")) + list(target_dir.glob("ams_backup_*.zip")),
|
||||
key=lambda p: p.stat().st_mtime,
|
||||
reverse=True,
|
||||
)
|
||||
if len(existing_backups) > keep_count:
|
||||
for old_backup in existing_backups[keep_count:]:
|
||||
logger.info("Retention policy: removing old backup %s", old_backup.name)
|
||||
try:
|
||||
old_backup.unlink()
|
||||
except OSError as e:
|
||||
logger.warning("Failed to remove old backup %s: %s", old_backup, e)
|
||||
|
||||
return backup_file_path
|
||||
|
||||
|
||||
run_backup = create_backup
|
||||
|
||||
|
||||
def run_restore(
|
||||
backup_archive: Path,
|
||||
db_path: Path,
|
||||
uploads_dir: Path,
|
||||
) -> bool:
|
||||
"""Restore database and uploads from a backup archive (.tar.gz or .zip) with pre-restore safety copy."""
|
||||
if not backup_archive.exists():
|
||||
logger.error("Backup archive %s not found.", backup_archive)
|
||||
return False
|
||||
|
||||
logger.info("Restoring from archive: %s", backup_archive)
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Extract archive
|
||||
try:
|
||||
if str(backup_archive).endswith((".tar.gz", ".tgz")):
|
||||
with tarfile.open(backup_archive, "r:gz") as tf:
|
||||
tf.extractall(temp_dir)
|
||||
else:
|
||||
with zipfile.ZipFile(backup_archive, "r") as zf:
|
||||
zf.extractall(temp_dir)
|
||||
except Exception as e:
|
||||
logger.error("Failed to read backup archive: %s", e)
|
||||
return False
|
||||
|
||||
extracted_db = Path(temp_dir) / "ams.db"
|
||||
if not extracted_db.exists():
|
||||
extracted_db = Path(temp_dir) / "db.sqlite3"
|
||||
if not extracted_db.exists():
|
||||
logger.error("Archive does not contain ams.db or db.sqlite3. Invalid backup.")
|
||||
return False
|
||||
|
||||
if not verify_sqlite_db(extracted_db):
|
||||
logger.error("Restored database failed integrity verification. Aborting restore.")
|
||||
return False
|
||||
|
||||
# Safety backup of current db if exists
|
||||
if db_path.exists():
|
||||
safety_copy = db_path.with_suffix(f".safety_pre_restore_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.bak")
|
||||
logger.info("Creating safety copy of existing DB: %s", safety_copy)
|
||||
shutil.copy2(db_path, safety_copy)
|
||||
|
||||
# Copy restored DB into place
|
||||
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(extracted_db, db_path)
|
||||
logger.info("Database restored successfully to %s", db_path)
|
||||
|
||||
# Restore uploads
|
||||
extracted_uploads = Path(temp_dir) / "uploads"
|
||||
if extracted_uploads.exists():
|
||||
uploads_dir.mkdir(parents=True, exist_ok=True)
|
||||
restored_count = 0
|
||||
for root, _, files in os.walk(extracted_uploads):
|
||||
for file in files:
|
||||
src_f = Path(root) / file
|
||||
rel_p = src_f.relative_to(extracted_uploads)
|
||||
dest_f = uploads_dir / rel_p
|
||||
dest_f.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(src_f, dest_f)
|
||||
restored_count += 1
|
||||
logger.info("Restored %d attachment files to %s", restored_count, uploads_dir)
|
||||
|
||||
logger.info("Restore process completed successfully.")
|
||||
return True
|
||||
|
||||
|
||||
def main() -> int:
|
||||
default_db, default_uploads, default_backups = get_default_paths()
|
||||
|
||||
parser = argparse.ArgumentParser(description="Poona Hospital AMS Backup & Recovery Utility")
|
||||
subparsers = parser.add_subparsers(dest="command", help="Command to execute")
|
||||
|
||||
# Backup command
|
||||
backup_parser = subparsers.add_parser("backup", help="Create a backup archive of DB and uploads")
|
||||
backup_parser.add_argument("--db", type=Path, default=default_db, help="Path to SQLite ams.db")
|
||||
backup_parser.add_argument("--uploads", type=Path, default=default_uploads, help="Path to uploads directory")
|
||||
backup_parser.add_argument("--dest", type=Path, default=default_backups, help="Destination directory for backups")
|
||||
backup_parser.add_argument("--keep", type=int, default=7, help="Number of latest backups to retain (0 to disable)")
|
||||
backup_parser.add_argument("--format", choices=["tar.gz", "zip"], default="tar.gz", help="Archive format")
|
||||
|
||||
# Restore command
|
||||
restore_parser = subparsers.add_parser("restore", help="Restore DB and uploads from a backup archive")
|
||||
restore_parser.add_argument("archive", type=Path, help="Path to backup archive (.tar.gz or .zip)")
|
||||
restore_parser.add_argument("--db", type=Path, default=default_db, help="Destination path for ams.db")
|
||||
restore_parser.add_argument("--uploads", type=Path, default=default_uploads, help="Destination directory for uploads")
|
||||
|
||||
# Verify command
|
||||
verify_parser = subparsers.add_parser("verify", help="Verify the integrity of a backup archive or SQLite DB")
|
||||
verify_parser.add_argument("target", type=Path, help="Path to archive (.tar.gz or .zip) or .db file to verify")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Default to backup if no command provided
|
||||
if not args.command:
|
||||
result = create_backup(default_db, default_uploads, default_backups, keep_count=7, archive_format="tar.gz")
|
||||
return 0 if result is not None else 1
|
||||
|
||||
if args.command == "backup":
|
||||
result = create_backup(args.db, args.uploads, args.dest, keep_count=args.keep, archive_format=args.format)
|
||||
return 0 if result is not None else 1
|
||||
|
||||
if args.command == "restore":
|
||||
success = run_restore(args.archive, args.db, args.uploads)
|
||||
return 0 if success else 1
|
||||
|
||||
if args.command == "verify":
|
||||
target = args.target
|
||||
if str(target).endswith((".tar.gz", ".tgz")):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
with tarfile.open(target, "r:gz") as tf:
|
||||
names = tf.getnames()
|
||||
db_name = "ams.db" if "ams.db" in names else ("db.sqlite3" if "db.sqlite3" in names else None)
|
||||
if not db_name:
|
||||
logger.error("Archive does not contain ams.db or db.sqlite3")
|
||||
return 1
|
||||
tf.extract(db_name, td)
|
||||
db_file = Path(td) / db_name
|
||||
return 0 if verify_sqlite_db(db_file) else 1
|
||||
elif target.suffix == ".zip":
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
with zipfile.ZipFile(target, "r") as zf:
|
||||
names = zf.namelist()
|
||||
db_name = "ams.db" if "ams.db" in names else ("db.sqlite3" if "db.sqlite3" in names else None)
|
||||
if not db_name:
|
||||
logger.error("ZIP does not contain ams.db or db.sqlite3")
|
||||
return 1
|
||||
zf.extract(db_name, td)
|
||||
db_file = Path(td) / db_name
|
||||
return 0 if verify_sqlite_db(db_file) else 1
|
||||
elif target.suffix in (".db", ".sqlite", ".sqlite3"):
|
||||
return 0 if verify_sqlite_db(target) else 1
|
||||
else:
|
||||
logger.error("Target must be a .tar.gz/.zip archive or .db file")
|
||||
return 1
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -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()
|
||||
|
||||
@@ -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 wb.sheetnames == ["Assets", "Example", "Master Reference"]
|
||||
assert wb["Example"].cell(row=1, column=1).value == "Example only - this sheet is ignored on import"
|
||||
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["Example"]
|
||||
headers = [wb_tmpl["Assets"].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"
|
||||
@@ -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(
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tarfile
|
||||
import pytest
|
||||
|
||||
from scripts.backup import create_backup, get_db_path
|
||||
|
||||
|
||||
def test_get_db_path_relative_dot_slash():
|
||||
backend_dir = Path("/mock/backend").resolve()
|
||||
p = get_db_path("sqlite:///./data/ams.db", backend_dir)
|
||||
assert p == (backend_dir / "data" / "ams.db").resolve()
|
||||
|
||||
|
||||
def test_get_db_path_relative_plain():
|
||||
backend_dir = Path("/mock/backend").resolve()
|
||||
p = get_db_path("sqlite:///data/ams.db", backend_dir)
|
||||
assert p == (backend_dir / "data" / "ams.db").resolve()
|
||||
|
||||
|
||||
def test_get_db_path_absolute_app():
|
||||
backend_dir = Path("/mock/backend").resolve()
|
||||
p = get_db_path("sqlite:////app/data/ams.db", backend_dir)
|
||||
assert p == Path("/app/data/ams.db")
|
||||
|
||||
|
||||
def test_get_db_path_absolute_tmp():
|
||||
backend_dir = Path("/mock/backend").resolve()
|
||||
p = get_db_path("sqlite:////tmp/x/custom.db", backend_dir)
|
||||
assert p == Path("/tmp/x/custom.db")
|
||||
|
||||
|
||||
def test_get_db_path_fallbacks():
|
||||
backend_dir = Path("/mock/backend").resolve()
|
||||
default_expected = backend_dir / "data" / "ams.db"
|
||||
assert get_db_path(None, backend_dir) == default_expected
|
||||
assert get_db_path("", backend_dir) == default_expected
|
||||
assert get_db_path("sqlite:///:memory:", backend_dir) == default_expected
|
||||
assert get_db_path("postgresql://localhost/ams", backend_dir) == default_expected
|
||||
|
||||
|
||||
def test_create_backup_real_temp_sqlite_file(tmp_path):
|
||||
# Create real SQLite file
|
||||
db_file = tmp_path / "source.db"
|
||||
conn = sqlite3.connect(str(db_file))
|
||||
cur = conn.cursor()
|
||||
cur.execute("CREATE TABLE test_table (id INTEGER PRIMARY KEY, note TEXT);")
|
||||
cur.execute("INSERT INTO test_table (note) VALUES ('backup test');")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
uploads_dir = tmp_path / "uploads"
|
||||
uploads_dir.mkdir()
|
||||
(uploads_dir / "sample.pdf").write_bytes(b"%PDF-1.4 sample content")
|
||||
|
||||
dest_dir = tmp_path / "backups"
|
||||
dest_dir.mkdir()
|
||||
|
||||
# Run backup producing a .tar.gz
|
||||
archive_path = create_backup(
|
||||
db_path=db_file,
|
||||
uploads_dir=uploads_dir,
|
||||
dest_dir=dest_dir,
|
||||
archive_format="tar.gz",
|
||||
)
|
||||
assert archive_path is not None
|
||||
assert archive_path.exists()
|
||||
assert str(archive_path).endswith(".tar.gz")
|
||||
|
||||
# Verify that the tar.gz is valid and contains db.sqlite3
|
||||
with tarfile.open(archive_path, "r:gz") as tf:
|
||||
names = tf.getnames()
|
||||
assert "db.sqlite3" in names
|
||||
assert "ams.db" in names
|
||||
assert any("uploads/sample.pdf" in n for n in names)
|
||||
@@ -0,0 +1,239 @@
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.models import Asset, CalibrationPlan, CalibrationRecord, Contract, InsurancePolicy, Vendor
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_extra_import_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("extra_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(sheet_name: str, headers: list[str], rows: list[list[object]]) -> bytes:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = sheet_name
|
||||
ws.append(headers)
|
||||
for r in rows:
|
||||
ws.append(r)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_contracts_bulk_import_lifecycle(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset is not None
|
||||
assert vendor is not None
|
||||
|
||||
headers = [
|
||||
"asset_code",
|
||||
"provider_name",
|
||||
"contract_type",
|
||||
"start_date",
|
||||
"end_date",
|
||||
"cost",
|
||||
"coverage_details",
|
||||
"remarks",
|
||||
]
|
||||
|
||||
# 1 valid, 1 invalid (invalid contract_type)
|
||||
rows = [
|
||||
[
|
||||
asset.asset_code,
|
||||
vendor.name,
|
||||
"CMC",
|
||||
"2026-01-01",
|
||||
"2026-12-31",
|
||||
85000,
|
||||
"All parts included",
|
||||
"Annual contract",
|
||||
],
|
||||
[
|
||||
asset.asset_code,
|
||||
vendor.name,
|
||||
"INVALID_TYPE",
|
||||
"2026-01-01",
|
||||
"2026-12-31",
|
||||
50000,
|
||||
"Test",
|
||||
"Test remarks",
|
||||
],
|
||||
]
|
||||
|
||||
xlsx_bytes = _make_xlsx_bytes("Contracts", headers, rows)
|
||||
|
||||
# Dry run
|
||||
res = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["dry_run"] is True
|
||||
assert data["total_rows"] == 2
|
||||
assert data["valid_count"] == 1
|
||||
assert data["error_count"] == 1
|
||||
assert data["created_count"] == 0
|
||||
|
||||
# Fail commit without skip_invalid
|
||||
res_fail = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false&skip_invalid=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_fail.status_code == 400
|
||||
|
||||
# Commit with skip_invalid
|
||||
res_commit = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_commit.status_code == 200
|
||||
commit_data = res_commit.json()
|
||||
assert commit_data["created_count"] == 1
|
||||
|
||||
created_contract = (
|
||||
db.query(Contract)
|
||||
.filter(Contract.asset_id == asset.id, Contract.contract_type == "CMC")
|
||||
.order_by(Contract.id.desc())
|
||||
.first()
|
||||
)
|
||||
assert created_contract is not None
|
||||
assert created_contract.provider_id == vendor.id
|
||||
|
||||
|
||||
def test_calibration_bulk_import_lifecycle(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
# Find asset without calibration plan
|
||||
existing_plan_ids = [p.asset_id for p in db.query(CalibrationPlan.asset_id).all()]
|
||||
asset = db.query(Asset).filter(Asset.id.notin_(existing_plan_ids)).first()
|
||||
assert asset is not None
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert vendor is not None
|
||||
|
||||
headers = [
|
||||
"asset_code",
|
||||
"frequency_months",
|
||||
"agency_name",
|
||||
"scope",
|
||||
"standards",
|
||||
"remarks",
|
||||
]
|
||||
|
||||
rows = [
|
||||
[
|
||||
asset.asset_code,
|
||||
12,
|
||||
vendor.name,
|
||||
"Accuracy verification",
|
||||
"ISO 17025",
|
||||
"Imported plan",
|
||||
],
|
||||
]
|
||||
|
||||
xlsx_bytes = _make_xlsx_bytes("Calibration Plans", headers, rows)
|
||||
|
||||
# Dry run
|
||||
res = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["valid_count"] == 1
|
||||
assert data["error_count"] == 0
|
||||
|
||||
# Commit
|
||||
res_commit = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_commit.status_code == 200
|
||||
assert res_commit.json()["created_count"] == 1
|
||||
|
||||
plan = db.query(CalibrationPlan).filter(CalibrationPlan.asset_id == asset.id).first()
|
||||
assert plan is not None
|
||||
assert plan.frequency_months == 12
|
||||
|
||||
record = db.query(CalibrationRecord).filter(CalibrationRecord.plan_id == plan.id).first()
|
||||
assert record is not None
|
||||
|
||||
|
||||
def test_insurance_bulk_import_lifecycle(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset is not None
|
||||
assert vendor is not None
|
||||
|
||||
headers = [
|
||||
"asset_code",
|
||||
"insurer_name",
|
||||
"policy_number",
|
||||
"start_date",
|
||||
"end_date",
|
||||
"insured_value",
|
||||
"premium",
|
||||
"remarks",
|
||||
]
|
||||
|
||||
rows = [
|
||||
[
|
||||
asset.asset_code,
|
||||
vendor.name,
|
||||
"POL-TEST-9999",
|
||||
"2026-04-01",
|
||||
"2027-03-31",
|
||||
1200000,
|
||||
15000,
|
||||
"Annual equipment insurance",
|
||||
],
|
||||
]
|
||||
|
||||
xlsx_bytes = _make_xlsx_bytes("Insurance Policies", headers, rows)
|
||||
|
||||
# Dry run
|
||||
res = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["valid_count"] == 1
|
||||
assert data["error_count"] == 0
|
||||
|
||||
# Commit
|
||||
res_commit = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_commit.status_code == 200
|
||||
assert res_commit.json()["created_count"] == 1
|
||||
|
||||
pol = db.query(InsurancePolicy).filter(InsurancePolicy.policy_no == "POL-TEST-9999").first()
|
||||
assert pol is not None
|
||||
assert pol.coverage_amount == 1200000
|
||||
assert pol.asset_id == asset.id
|
||||
|
||||
@@ -0,0 +1,601 @@
|
||||
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 == []
|
||||
|
||||
# When open > 24h, unrestored complaint triggers critical_complaint alert,
|
||||
# but restored complaint does NOT trigger it even if not closed yet
|
||||
past_26h = now - timedelta(hours=26)
|
||||
c_unrestored.registered_at = past_26h
|
||||
c_restored.registered_at = past_26h
|
||||
db.commit()
|
||||
run_alert_check(db)
|
||||
db.commit()
|
||||
|
||||
crit_unrestored_26h = (
|
||||
db.query(Notification)
|
||||
.filter(
|
||||
Notification.type == "critical_complaint",
|
||||
Notification.entity_type == "complaint",
|
||||
Notification.entity_id == cid_unrestored,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
assert len(crit_unrestored_26h) == 1
|
||||
assert "Critical Complaint Open > 24h" in crit_unrestored_26h[0].title
|
||||
|
||||
crit_restored_26h = (
|
||||
db.query(Notification)
|
||||
.filter(
|
||||
Notification.type == "critical_complaint",
|
||||
Notification.entity_type == "complaint",
|
||||
Notification.entity_id == cid_restored,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
assert crit_restored_26h == []
|
||||
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,234 @@
|
||||
from io import BytesIO
|
||||
from datetime import date, timedelta
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import Asset, Department, Location, PMRecord, PMSchedule, Vendor
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def _seed(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("uploads")
|
||||
seed_database(db, upload_dir=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
|
||||
token = res.json()["access_token"]
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def test_pm_record_attachment_upload_and_download(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
pm_rec = db.query(PMRecord).first()
|
||||
assert pm_rec is not None
|
||||
|
||||
# Valid PDF file upload against pm_record
|
||||
fake_pdf = b"%PDF-1.4 sample pm service report job sheet content"
|
||||
files = {"file": ("pm_service_report.pdf", BytesIO(fake_pdf), "application/pdf")}
|
||||
data = {"entity_type": "pm_record", "entity_id": str(pm_rec.id)}
|
||||
|
||||
upload_res = client.post("/api/attachments", headers=bio_headers, data=data, files=files)
|
||||
assert upload_res.status_code == 201, upload_res.text
|
||||
att_data = upload_res.json()
|
||||
att_id = att_data["id"]
|
||||
assert att_data["entity_type"] == "pm_record"
|
||||
assert att_data["original_name"] == "pm_service_report.pdf"
|
||||
|
||||
# List attachments for pm_record
|
||||
list_res = client.get(
|
||||
f"/api/attachments?entity_type=pm_record&entity_id={pm_rec.id}",
|
||||
headers=bio_headers,
|
||||
)
|
||||
assert list_res.status_code == 200
|
||||
assert any(item["id"] == att_id for item in list_res.json()["items"])
|
||||
|
||||
# Download attachment
|
||||
dl_res = client.get(f"/api/attachments/{att_id}/download", headers=bio_headers)
|
||||
assert dl_res.status_code == 200
|
||||
assert dl_res.content == fake_pdf
|
||||
|
||||
|
||||
def test_complaint_assigned_team_and_location_filter(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
asset = db.query(Asset).filter(Asset.location_id.isnot(None)).first()
|
||||
assert asset is not None
|
||||
|
||||
# 1. Raise complaint with assigned_team
|
||||
res = client.post(
|
||||
"/api/complaints",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"description": "Ventilator screen flickering",
|
||||
"priority": "non_critical",
|
||||
"assigned_team": "Biomedical Clinical Support",
|
||||
},
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
c_data = res.json()
|
||||
cid = c_data["id"]
|
||||
assert c_data["assigned_team"] == "Biomedical Clinical Support"
|
||||
|
||||
# 2. Assign team via /assign endpoint
|
||||
assign_res = client.post(
|
||||
f"/api/complaints/{cid}/assign",
|
||||
headers=bio_headers,
|
||||
json={"assigned_team": "External Vendor Tier 2 Team", "note": "Assigned to specialized vendor team"},
|
||||
)
|
||||
assert assign_res.status_code == 200, assign_res.text
|
||||
assert assign_res.json()["assigned_team"] == "External Vendor Tier 2 Team"
|
||||
|
||||
# 3. Filter by location_id
|
||||
loc_res = client.get(
|
||||
f"/api/complaints?location_id={asset.location_id}",
|
||||
headers=bio_headers,
|
||||
)
|
||||
assert loc_res.status_code == 200
|
||||
items = loc_res.json()["items"]
|
||||
assert any(c["id"] == cid for c in items)
|
||||
|
||||
|
||||
def test_demo_equipment_serial_no(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept = db.query(Department).first()
|
||||
vendor = db.query(Vendor).first()
|
||||
today = effective_today(db)
|
||||
|
||||
# Create demo equipment with serial_no
|
||||
res = client.post(
|
||||
"/api/demo-equipment",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"name": "Trial Dialysis Unit",
|
||||
"equipment_type": "Dialysis",
|
||||
"serial_no": "DEMO-SN-DIAL-901",
|
||||
"supplier_id": vendor.id,
|
||||
"department_id": dept.id,
|
||||
"start_date": str(today),
|
||||
"expected_return_date": str(today + timedelta(days=14)),
|
||||
"remarks": "Evaluation unit on 14-day trial",
|
||||
},
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
demo_data = res.json()
|
||||
demo_id = demo_data["id"]
|
||||
assert demo_data["serial_no"] == "DEMO-SN-DIAL-901"
|
||||
|
||||
# List demo equipment
|
||||
list_res = client.get(f"/api/demo-equipment?department_id={dept.id}", headers=bio_headers)
|
||||
assert list_res.status_code == 200
|
||||
found = next((item for item in list_res.json()["items"] if item["id"] == demo_id), None)
|
||||
assert found is not None
|
||||
assert found["serial_no"] == "DEMO-SN-DIAL-901"
|
||||
|
||||
|
||||
def test_department_visit_new_requirements_and_monthly_report(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
dept = db.query(Department).first()
|
||||
today = effective_today(db)
|
||||
|
||||
# Create visit with new_requirements
|
||||
req_text = "Urgent: Requesting 2 additional Infusion Pumps for Bed 3 & 4"
|
||||
res = client.post(
|
||||
"/api/visits",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"department_id": dept.id,
|
||||
"visit_date": str(today),
|
||||
"observations": "All ICU ventilators functioning normally; routine checks complete.",
|
||||
"new_requirements": req_text,
|
||||
},
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
v_data = res.json()
|
||||
assert v_data["new_requirements"] == req_text
|
||||
|
||||
# Monthly Department Report reflects new requirements
|
||||
month_str = today.strftime("%Y-%m")
|
||||
rep_res = client.get(
|
||||
f"/api/reports/monthly-department?month={month_str}&department_id={dept.id}",
|
||||
headers=mgmt_headers,
|
||||
)
|
||||
assert rep_res.status_code == 200, rep_res.text
|
||||
rows = rep_res.json()["rows"]
|
||||
dept_row = next((r for r in rows if r["department_id"] == dept.id), None)
|
||||
assert dept_row is not None
|
||||
assert req_text in dept_row["new_equipment_requirements"]
|
||||
|
||||
|
||||
def test_asset_calibration_and_insurance_filters(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
# Filter calibration applicable
|
||||
res_cal_yes = client.get("/api/assets?requires_calibration=true", headers=bio_headers)
|
||||
assert res_cal_yes.status_code == 200
|
||||
for a in res_cal_yes.json()["items"]:
|
||||
assert a["requires_calibration"] is True
|
||||
|
||||
res_cal_no = client.get("/api/assets?requires_calibration=false", headers=bio_headers)
|
||||
assert res_cal_no.status_code == 200
|
||||
for a in res_cal_no.json()["items"]:
|
||||
assert a["requires_calibration"] is False
|
||||
|
||||
# Filter insurance applicable
|
||||
res_ins_yes = client.get("/api/assets?insurance_applicable=true", headers=bio_headers)
|
||||
assert res_ins_yes.status_code == 200
|
||||
for a in res_ins_yes.json()["items"]:
|
||||
assert a["insurance_applicable"] is True
|
||||
|
||||
|
||||
def test_bulk_import_templates_endpoints(client):
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
|
||||
# Contracts template
|
||||
r_c = client.get("/api/contracts/import-template", headers=coord_headers)
|
||||
assert r_c.status_code == 200
|
||||
assert r_c.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
assert len(r_c.content) > 1000
|
||||
|
||||
# Calibration template
|
||||
r_cal = client.get("/api/calibration/import-template", headers=coord_headers)
|
||||
assert r_cal.status_code == 200
|
||||
assert r_cal.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
assert len(r_cal.content) > 1000
|
||||
|
||||
# Insurance template
|
||||
r_ins = client.get("/api/insurance/import-template", headers=coord_headers)
|
||||
assert r_ins.status_code == 200
|
||||
assert r_ins.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
assert len(r_ins.content) > 1000
|
||||
|
||||
|
||||
def test_sqlite_auto_migration_reconciles_missing_columns():
|
||||
from sqlalchemy import create_engine
|
||||
from app.core.migrations import run_sqlite_migrations
|
||||
|
||||
test_eng = create_engine("sqlite:///:memory:")
|
||||
with test_eng.begin() as conn:
|
||||
# Create complaints table without assigned_team column
|
||||
conn.exec_driver_sql(
|
||||
"CREATE TABLE complaints ("
|
||||
"id INTEGER PRIMARY KEY, "
|
||||
"complaint_no VARCHAR(50), "
|
||||
"asset_id INTEGER, "
|
||||
"description TEXT, "
|
||||
"priority VARCHAR(50), "
|
||||
"registered_at DATETIME, "
|
||||
"registered_by_id INTEGER, "
|
||||
"received_by_id INTEGER, "
|
||||
"call_status VARCHAR(50)"
|
||||
")"
|
||||
)
|
||||
cols_before = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()}
|
||||
assert "assigned_team" not in cols_before
|
||||
|
||||
# Run auto-migration
|
||||
run_sqlite_migrations(test_eng)
|
||||
|
||||
with test_eng.begin() as conn:
|
||||
cols_after = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()}
|
||||
assert "assigned_team" in cols_after
|
||||
@@ -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"])
|
||||
@@ -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
|
||||
@@ -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}"
|
||||
@@ -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},
|
||||
)
|
||||
@@ -0,0 +1,275 @@
|
||||
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
|
||||
|
||||
|
||||
def test_all_eight_reports_export_xlsx_and_csv(client):
|
||||
"""Verify that all 8 reports export cleanly as both XLSX and CSV without title/slash errors."""
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
for key in ALL_REPORT_KEYS:
|
||||
# Test XLSX export
|
||||
xlsx_res = client.get(
|
||||
f"/api/reports/{key}/export?format=xlsx",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert xlsx_res.status_code == 200, f"XLSX export failed for {key}: {xlsx_res.text}"
|
||||
assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"]
|
||||
assert f'filename="{key}.xlsx"' in xlsx_res.headers["content-disposition"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(xlsx_res.content))
|
||||
ws = wb.active
|
||||
assert ws is not None
|
||||
assert "/" not in ws.title and "\\" not in ws.title
|
||||
assert len(ws.title) <= 31
|
||||
|
||||
# Test CSV export
|
||||
csv_res = client.get(
|
||||
f"/api/reports/{key}/export?format=csv",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert csv_res.status_code == 200, f"CSV export failed for {key}: {csv_res.text}"
|
||||
assert "text/csv" in csv_res.headers["content-type"]
|
||||
assert f'filename="{key}.csv"' in csv_res.headers["content-disposition"]
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
from io import BytesIO
|
||||
from datetime import date
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.models import Asset, CalibrationPlan, Contract, Department, InsurancePolicy, Vendor
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task1_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task1_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str = "admin@poona.demo") -> 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(sheet_name: str, headers: list[str], rows: list[list]) -> bytes:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = sheet_name
|
||||
ws.append(headers)
|
||||
for r in rows:
|
||||
ws.append(r)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_contracts_api_duplicate_409(client, db):
|
||||
headers = _auth_headers(client)
|
||||
asset = db.query(Asset).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset and vendor
|
||||
|
||||
payload = {
|
||||
"asset_id": asset.id,
|
||||
"contract_type": "AMC",
|
||||
"provider_id": vendor.id,
|
||||
"start_date": "2026-01-01",
|
||||
"end_date": "2026-12-31",
|
||||
"coverage_period_text": "2026 Annual AMC",
|
||||
}
|
||||
# First creation should succeed
|
||||
res1 = client.post("/api/contracts", json=payload, headers=headers)
|
||||
assert res1.status_code == 201
|
||||
contract_id = res1.json()["id"]
|
||||
|
||||
# Second creation with identical asset, type, start_date, end_date must return 409
|
||||
res2 = client.post("/api/contracts", json=payload, headers=headers)
|
||||
assert res2.status_code == 409
|
||||
assert res2.json()["detail"] == "A contract with the same asset, type and dates already exists."
|
||||
|
||||
# Renewal must still work
|
||||
renew_payload = {
|
||||
"start_date": "2027-01-01",
|
||||
"end_date": "2027-12-31",
|
||||
"contract_type": "AMC",
|
||||
"coverage_period_text": "2027 Annual Renewal",
|
||||
}
|
||||
res_renew = client.post(f"/api/contracts/{contract_id}/renew", json=renew_payload, headers=headers)
|
||||
assert res_renew.status_code == 200
|
||||
assert res_renew.json()["new_contract"]["start_date"] == "2027-01-01"
|
||||
|
||||
|
||||
def test_insurance_api_duplicate_409(client, db):
|
||||
headers = _auth_headers(client)
|
||||
asset = db.query(Asset).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset and vendor
|
||||
|
||||
policy_no = "POL-DUP-TEST-999"
|
||||
payload = {
|
||||
"asset_id": asset.id,
|
||||
"insurer_id": vendor.id,
|
||||
"policy_no": f" {policy_no} ",
|
||||
"start_date": "2026-04-01",
|
||||
"end_date": "2027-03-31",
|
||||
"coverage_amount": 500000.0,
|
||||
}
|
||||
# First creation succeeds
|
||||
res1 = client.post("/api/insurance", json=payload, headers=headers)
|
||||
assert res1.status_code == 201
|
||||
|
||||
# Exact duplicate (case-insensitive and trimmed) must return 409
|
||||
dup_payload = {
|
||||
"asset_id": asset.id,
|
||||
"insurer_id": vendor.id,
|
||||
"policy_no": f"pol-dup-test-999 ",
|
||||
"start_date": "2026-04-01",
|
||||
"end_date": "2027-03-31",
|
||||
}
|
||||
res2 = client.post("/api/insurance", json=dup_payload, headers=headers)
|
||||
assert res2.status_code == 409
|
||||
assert res2.json()["detail"] == "Policy number already exists."
|
||||
|
||||
|
||||
def test_contracts_bulk_import_in_file_and_db_duplicates(client, db):
|
||||
headers = _auth_headers(client)
|
||||
asset = db.query(Asset).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset and vendor
|
||||
|
||||
xlsx_headers = ["asset_code", "provider_name", "contract_type", "start_date", "end_date", "cost", "coverage_details", "remarks"]
|
||||
rows = [
|
||||
[asset.asset_code, vendor.name, "AMC", "2028-01-01", "2028-12-31", 10000, "Coverage", "Remark 1"],
|
||||
[asset.asset_code, vendor.name, "AMC", "2028-01-01", "2028-12-31", 10000, "Coverage", "Remark 2"],
|
||||
]
|
||||
file_bytes = _make_xlsx_bytes("Contracts", xlsx_headers, rows)
|
||||
|
||||
# Dry run should flag row 3 as duplicate of row 2
|
||||
res_dry = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=true",
|
||||
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_dry.status_code == 200
|
||||
dry_data = res_dry.json()
|
||||
assert dry_data["valid_count"] == 1
|
||||
assert dry_data["error_count"] == 1
|
||||
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
|
||||
|
||||
# Import with skip_invalid=true creates exactly 1 record
|
||||
res_imp1 = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp1.status_code == 200
|
||||
assert res_imp1.json()["created_count"] == 1
|
||||
|
||||
# Second import of the same file creates 0 records and reports DB duplicates
|
||||
res_imp2 = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp2.status_code == 200
|
||||
data2 = res_imp2.json()
|
||||
assert data2["created_count"] == 0
|
||||
assert data2["error_count"] == 2
|
||||
messages = [e["message"] for e in data2["errors"]]
|
||||
assert any("Already exists in the system." in m for m in messages)
|
||||
assert any("Duplicate of row 2 in this file." in m for m in messages)
|
||||
|
||||
|
||||
def test_insurance_bulk_import_in_file_and_db_duplicates(client, db):
|
||||
headers = _auth_headers(client)
|
||||
asset = db.query(Asset).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset and vendor
|
||||
|
||||
xlsx_headers = ["asset_code", "insurer_name", "policy_number", "start_date", "end_date", "insured_value", "premium", "remarks"]
|
||||
rows = [
|
||||
[asset.asset_code, vendor.name, "POL-BULK-101", "2028-01-01", "2028-12-31", 200000, 5000, "Policy row 2"],
|
||||
[asset.asset_code, vendor.name, " pol-bulk-101 ", "2028-01-01", "2028-12-31", 200000, 5000, "Policy row 3"],
|
||||
]
|
||||
file_bytes = _make_xlsx_bytes("Insurance Policies", xlsx_headers, rows)
|
||||
|
||||
# Dry run should flag row 3 as duplicate of row 2
|
||||
res_dry = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=true",
|
||||
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_dry.status_code == 200
|
||||
dry_data = res_dry.json()
|
||||
assert dry_data["valid_count"] == 1
|
||||
assert dry_data["error_count"] == 1
|
||||
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
|
||||
|
||||
# Import with skip_invalid=true creates 1 record
|
||||
res_imp1 = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp1.status_code == 200
|
||||
assert res_imp1.json()["created_count"] == 1
|
||||
|
||||
# Second import creates 0 records
|
||||
res_imp2 = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp2.status_code == 200
|
||||
data2 = res_imp2.json()
|
||||
assert data2["created_count"] == 0
|
||||
assert data2["error_count"] == 2
|
||||
messages = [e["message"] for e in data2["errors"]]
|
||||
assert any("Already exists in the system." in m for m in messages)
|
||||
assert any("Duplicate of row 2 in this file." in m for m in messages)
|
||||
|
||||
|
||||
def test_calibration_bulk_import_in_file_and_existing_plan(client, db):
|
||||
headers = _auth_headers(client)
|
||||
from app.models import CalibrationPlan
|
||||
planned_ids = {p.asset_id for p in db.query(CalibrationPlan.asset_id).all()}
|
||||
asset = db.query(Asset).filter(~Asset.id.in_(planned_ids)).first()
|
||||
if not asset:
|
||||
dept = db.query(Department).first()
|
||||
asset = Asset(
|
||||
asset_code="PHRC-TEST-CAL-99",
|
||||
name="Test Cal Asset",
|
||||
department_id=dept.id,
|
||||
status="in_service",
|
||||
requires_calibration=True,
|
||||
)
|
||||
db.add(asset)
|
||||
db.commit()
|
||||
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
|
||||
xlsx_headers = ["asset_code", "frequency_months", "agency_name", "next_due_date", "scope", "standards", "remarks"]
|
||||
rows = [
|
||||
[asset.asset_code, 12, vendor.name if vendor else "", "2028-06-01", "Accredited scope", "ISO 17025", "Cal row 2"],
|
||||
[asset.asset_code, 6, vendor.name if vendor else "", "2028-06-01", "Accredited scope", "ISO 17025", "Cal row 3"],
|
||||
]
|
||||
file_bytes = _make_xlsx_bytes("Calibration Plans", xlsx_headers, rows)
|
||||
|
||||
# Dry run flags row 3 as duplicate of row 2
|
||||
res_dry = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=true",
|
||||
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_dry.status_code == 200
|
||||
dry_data = res_dry.json()
|
||||
assert dry_data["valid_count"] == 1
|
||||
assert dry_data["error_count"] == 1
|
||||
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
|
||||
|
||||
# Import with skip_invalid=true creates 1 record
|
||||
res_imp1 = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp1.status_code == 200
|
||||
assert res_imp1.json()["created_count"] == 1
|
||||
|
||||
# Second import creates 0 records and reports "Asset already has a calibration plan."
|
||||
res_imp2 = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp2.status_code == 200
|
||||
data2 = res_imp2.json()
|
||||
assert data2["created_count"] == 0
|
||||
assert data2["error_count"] == 2
|
||||
messages = [e["message"] for e in data2["errors"]]
|
||||
assert any("Asset already has a calibration plan." in m for m in messages)
|
||||
assert any("Duplicate of row 2 in this file." in m for m in messages)
|
||||
@@ -0,0 +1,89 @@
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task2_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task2_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str = "admin@poona.demo") -> 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']}"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"template_url,import_url,file_field,filename,expected_sheet1",
|
||||
[
|
||||
(
|
||||
"/api/assets/import-template",
|
||||
"/api/assets/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"asset_template.xlsx",
|
||||
"Assets",
|
||||
),
|
||||
(
|
||||
"/api/contracts/import-template",
|
||||
"/api/contracts/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"contracts_template.xlsx",
|
||||
"Contracts",
|
||||
),
|
||||
(
|
||||
"/api/calibration/import-template",
|
||||
"/api/calibration/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"calibration_template.xlsx",
|
||||
"Calibration Plans",
|
||||
),
|
||||
(
|
||||
"/api/insurance/import-template",
|
||||
"/api/insurance/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"insurance_template.xlsx",
|
||||
"Insurance Policies",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_download_template_and_upload_unchanged_dry_run_zero_rows(
|
||||
client, template_url, import_url, file_field, filename, expected_sheet1
|
||||
):
|
||||
headers = _auth_headers(client)
|
||||
|
||||
# 1. Download template
|
||||
dl_res = client.get(template_url, headers=headers)
|
||||
assert dl_res.status_code == 200
|
||||
content = dl_res.content
|
||||
|
||||
# 2. Verify sheet structure
|
||||
wb = openpyxl.load_workbook(BytesIO(content))
|
||||
assert wb.sheetnames == [expected_sheet1, "Example", "Master Reference"]
|
||||
|
||||
ws1 = wb[expected_sheet1]
|
||||
# First sheet has only header row (max_row == 1)
|
||||
assert ws1.max_row == 1
|
||||
|
||||
ws2 = wb["Example"]
|
||||
# Second sheet has disclaimer on row 1
|
||||
assert ws2.cell(row=1, column=1).value == "Example only - this sheet is ignored on import"
|
||||
# Second sheet has sample row on row 2
|
||||
assert ws2.cell(row=2, column=1).value is not None
|
||||
|
||||
# 3. Upload unchanged template with dry_run=true: must return total_rows == 0
|
||||
up_res = client.post(
|
||||
import_url,
|
||||
headers=headers,
|
||||
files={file_field: (filename, content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert up_res.status_code == 200, up_res.text
|
||||
data = up_res.json()
|
||||
assert data["total_rows"] == 0
|
||||
assert data["valid_count"] == 0
|
||||
assert data["error_count"] == 0
|
||||
assert data["created_count"] == 0
|
||||
@@ -0,0 +1,165 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from app.core.security import validate_password
|
||||
from app.models.masters import User
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task4_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task4_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str = "admin@poona.demo") -> 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_validate_password_unit():
|
||||
# 1. Short password (< 8)
|
||||
with pytest.raises(Exception) as exc1:
|
||||
validate_password("Short1", email="user@hospital.com")
|
||||
assert "at least 8 characters" in str(exc1.value)
|
||||
|
||||
# 2. No digits
|
||||
with pytest.raises(Exception) as exc2:
|
||||
validate_password("NoDigitsHere", email="user@hospital.com")
|
||||
assert "at least one letter and at least one digit" in str(exc2.value)
|
||||
|
||||
# 3. No letters
|
||||
with pytest.raises(Exception) as exc3:
|
||||
validate_password("1234567890", email="user@hospital.com")
|
||||
assert "at least one letter and at least one digit" in str(exc3.value)
|
||||
|
||||
# 4. Leading / trailing space
|
||||
with pytest.raises(Exception) as exc4a:
|
||||
validate_password(" Secret123", email="user@hospital.com")
|
||||
assert "space" in str(exc4a.value)
|
||||
|
||||
with pytest.raises(Exception) as exc4b:
|
||||
validate_password("Secret123 ", email="user@hospital.com")
|
||||
assert "space" in str(exc4b.value)
|
||||
|
||||
# 5. Blocklisted passwords
|
||||
for bad in ("12345678", "password", "password1", "qwerty123", "admin123", "welcome1"):
|
||||
with pytest.raises(Exception) as exc5:
|
||||
validate_password(bad, email="user@hospital.com")
|
||||
assert "easily guessable" in str(exc5.value) or "at least 8" in str(exc5.value) or "at least one" in str(exc5.value)
|
||||
|
||||
# 6. Demo password MUST be allowed
|
||||
validate_password("demo@123", email="admin@poona.demo")
|
||||
validate_password("Demo@123", email="admin@poona.demo")
|
||||
|
||||
# 7. Contains email local part (>= 4 chars)
|
||||
with pytest.raises(Exception) as exc7:
|
||||
validate_password("Secureadmin123", email="admin@poona.demo")
|
||||
assert "username" in str(exc7.value).lower()
|
||||
|
||||
# Short local part (< 4 chars) does NOT trigger username check
|
||||
validate_password("Securebio123", email="bio@poona.demo")
|
||||
|
||||
|
||||
def test_api_create_user_password_validation(client, db):
|
||||
headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
# Rejected: no digit
|
||||
res_bad = client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Test User",
|
||||
"email": "test_pw_rule@poona.demo",
|
||||
"password": "NoDigitsPassword",
|
||||
"role": "biomedical",
|
||||
},
|
||||
)
|
||||
assert res_bad.status_code == 422
|
||||
assert "letter and at least one digit" in res_bad.json()["detail"]
|
||||
|
||||
# Rejected: contains email username "tester123"
|
||||
res_username = client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Test User 2",
|
||||
"email": "tester123@poona.demo",
|
||||
"password": "tester123Password1",
|
||||
"role": "biomedical",
|
||||
},
|
||||
)
|
||||
assert res_username.status_code == 422
|
||||
assert "username" in res_username.json()["detail"].lower()
|
||||
|
||||
# Accepted: valid password with letters and numbers
|
||||
res_ok = client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Test User 3",
|
||||
"email": "validuser@poona.demo",
|
||||
"password": "ValidPassword123",
|
||||
"role": "biomedical",
|
||||
},
|
||||
)
|
||||
assert res_ok.status_code == 201
|
||||
user_id = res_ok.json()["id"]
|
||||
|
||||
# Reset password with leading space rejected
|
||||
res_reset_bad = client.post(
|
||||
f"/api/users/{user_id}/reset-password",
|
||||
headers=headers,
|
||||
json={"new_password": " LeadingSpace123"},
|
||||
)
|
||||
assert res_reset_bad.status_code == 422
|
||||
assert "space" in res_reset_bad.json()["detail"]
|
||||
|
||||
# Reset password with valid password succeeds
|
||||
res_reset_ok = client.post(
|
||||
f"/api/users/{user_id}/reset-password",
|
||||
headers=headers,
|
||||
json={"new_password": "NewValidSecret456"},
|
||||
)
|
||||
assert res_reset_ok.status_code == 200
|
||||
|
||||
|
||||
def test_api_change_password_validation(client, db):
|
||||
# Log in as bio user
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
# Reject new == current
|
||||
res_same = client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=bio_headers,
|
||||
json={"current_password": "Demo@123", "new_password": "Demo@123"},
|
||||
)
|
||||
assert res_same.status_code == 422
|
||||
assert res_same.json()["detail"] == "New password must be different."
|
||||
|
||||
# Reject trailing space
|
||||
res_space = client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=bio_headers,
|
||||
json={"current_password": "Demo@123", "new_password": "NewSecretPass1 "},
|
||||
)
|
||||
assert res_space.status_code == 422
|
||||
assert "space" in res_space.json()["detail"]
|
||||
|
||||
# Reject blocklisted password
|
||||
res_block = client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=bio_headers,
|
||||
json={"current_password": "Demo@123", "new_password": "password1"},
|
||||
)
|
||||
assert res_block.status_code == 422
|
||||
|
||||
# Accept valid change
|
||||
res_ok = client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=bio_headers,
|
||||
json={"current_password": "Demo@123", "new_password": "BrandNewSecret789"},
|
||||
)
|
||||
assert res_ok.status_code == 200
|
||||
assert res_ok.json()["message"] == "Password changed successfully."
|
||||
@@ -0,0 +1,133 @@
|
||||
import pytest
|
||||
from app.core.security import hash_password
|
||||
from app.models import Asset, Department, User
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.scoping import DepartmentScope, resolve_department_scope
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task6_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task6_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_resolve_department_scope_rules():
|
||||
# Admin is unconstrained
|
||||
admin_user = User(role="system_admin", department_id=None)
|
||||
scope = resolve_department_scope(admin_user, requested_dept_id=5)
|
||||
assert scope == DepartmentScope(is_unconstrained=True, department_id=5, is_empty=False)
|
||||
|
||||
# Department user with department_id=None is empty
|
||||
unassigned = User(role="department_user", department_id=None)
|
||||
scope_empty = resolve_department_scope(unassigned, requested_dept_id=5)
|
||||
assert scope_empty == DepartmentScope(is_unconstrained=False, department_id=None, is_empty=True)
|
||||
|
||||
# Department user with assigned department cannot be overridden
|
||||
assigned = User(role="department_user", department_id=1)
|
||||
scope_assigned = resolve_department_scope(assigned, requested_dept_id=99)
|
||||
assert scope_assigned == DepartmentScope(is_unconstrained=False, department_id=1, is_empty=False)
|
||||
|
||||
|
||||
def test_unassigned_department_user_sees_zero_records(client, db):
|
||||
# Create a department_user with department_id = None
|
||||
email = "unassigned_dept_user@poona.demo"
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
user = User(
|
||||
email=email,
|
||||
name="Unassigned Dept User",
|
||||
password_hash=hash_password("Demo@123"),
|
||||
role="department_user",
|
||||
department_id=None,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
else:
|
||||
user.department_id = None
|
||||
db.commit()
|
||||
|
||||
headers = _auth_headers(client, email)
|
||||
|
||||
# 1. Dashboard summary has all-zero counters
|
||||
dash_res = client.get("/api/dashboard/summary", headers=headers)
|
||||
assert dash_res.status_code == 200
|
||||
dash_data = dash_res.json()
|
||||
kpis = dash_data["kpis"]
|
||||
assert kpis["total_assets"] == 0
|
||||
assert kpis["assets_under_repair"] == 0
|
||||
assert kpis["open_complaints"] == 0
|
||||
assert kpis["pm_due_this_month"] == 0
|
||||
assert kpis["calibrations_due"] == 0
|
||||
assert kpis["contracts_expiring"] == 0
|
||||
assert kpis["equipment_on_demo"] == 0
|
||||
assert len(dash_data["recent_complaints"]) == 0
|
||||
assert len(dash_data["needs_attention"]) == 0
|
||||
|
||||
# 2. Global search returns 0 assets and 0 complaints
|
||||
search_res = client.get("/api/search?q=card", headers=headers)
|
||||
assert search_res.status_code == 200
|
||||
search_data = search_res.json()
|
||||
assert search_data["assets"] == []
|
||||
assert search_data["complaints"] == []
|
||||
|
||||
# 3. All accessible report endpoints return 0 rows for this user
|
||||
report_keys = [
|
||||
"equipment-inventory",
|
||||
"monthly-maintenance",
|
||||
"monthly-department",
|
||||
"breakdown-complaints",
|
||||
"pm-compliance",
|
||||
"calibration-due",
|
||||
"contracts-warranty",
|
||||
"demo-equipment",
|
||||
]
|
||||
for key in report_keys:
|
||||
rep_res = client.get(f"/api/reports/{key}", headers=headers)
|
||||
assert rep_res.status_code == 200, f"{key} failed: {rep_res.text}"
|
||||
body = rep_res.json()
|
||||
assert len(body["rows"]) == 0, f"Expected 0 rows for {key}, got {len(body['rows'])}"
|
||||
|
||||
|
||||
def test_assigned_department_user_scoping_ignores_query_param(client, db):
|
||||
# Get two distinct departments that have assets
|
||||
depts = db.query(Department).filter(Department.is_active.is_(True)).all()
|
||||
assert len(depts) >= 2
|
||||
dept1, dept2 = depts[0], depts[1]
|
||||
|
||||
email = "dept1_scoped_user@poona.demo"
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
user = User(
|
||||
email=email,
|
||||
name="Dept1 Scoped User",
|
||||
password_hash=hash_password("Demo@123"),
|
||||
role="department_user",
|
||||
department_id=dept1.id,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
else:
|
||||
user.department_id = dept1.id
|
||||
db.commit()
|
||||
|
||||
headers = _auth_headers(client, email)
|
||||
|
||||
# Calling with ?department_id=dept2.id MUST be ignored and scoped strictly to dept1
|
||||
res = client.get(
|
||||
f"/api/reports/equipment-inventory?department_id={dept2.id}",
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["filters_applied"]["department_id"] == dept1.id
|
||||
for row in body["rows"]:
|
||||
assert row["department_id"] == dept1.id
|
||||
@@ -0,0 +1,91 @@
|
||||
import pytest
|
||||
from app.models import User
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task7_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task7_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def test_token_invalidation_on_change_password_and_admin_reset(client, db):
|
||||
# 1. Login as user and save the initial token
|
||||
user_email = "bio@poona.demo"
|
||||
login_res = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user_email, "password": "Demo@123"},
|
||||
)
|
||||
assert login_res.status_code == 200
|
||||
old_token = login_res.json()["access_token"]
|
||||
|
||||
# Verify initial token works
|
||||
me_res1 = client.get(
|
||||
"/api/auth/me",
|
||||
headers={"Authorization": f"Bearer {old_token}"},
|
||||
)
|
||||
assert me_res1.status_code == 200
|
||||
assert me_res1.json()["email"] == user_email
|
||||
|
||||
# 2. Call POST /api/auth/change-password
|
||||
change_res = client.post(
|
||||
"/api/auth/change-password",
|
||||
headers={"Authorization": f"Bearer {old_token}"},
|
||||
json={"current_password": "Demo@123", "new_password": "NewSecurePass99"},
|
||||
)
|
||||
assert change_res.status_code == 200, change_res.text
|
||||
change_data = change_res.json()
|
||||
assert "access_token" in change_data
|
||||
assert change_data["token_type"] == "bearer"
|
||||
new_token = change_data["access_token"]
|
||||
|
||||
# 3. Assert the old token now gets 401 on an authenticated endpoint
|
||||
old_token_res = client.get(
|
||||
"/api/auth/me",
|
||||
headers={"Authorization": f"Bearer {old_token}"},
|
||||
)
|
||||
assert old_token_res.status_code == 401
|
||||
assert "Token has been invalidated" in old_token_res.json()["detail"]
|
||||
|
||||
# 4. Assert the new token returned by change-password works
|
||||
new_token_res = client.get(
|
||||
"/api/auth/me",
|
||||
headers={"Authorization": f"Bearer {new_token}"},
|
||||
)
|
||||
assert new_token_res.status_code == 200
|
||||
assert new_token_res.json()["email"] == user_email
|
||||
|
||||
# 5. Login as admin, reset that user's password
|
||||
admin_login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "admin@poona.demo", "password": "Demo@123"},
|
||||
)
|
||||
assert admin_login.status_code == 200
|
||||
admin_token = admin_login.json()["access_token"]
|
||||
|
||||
target_user = db.query(User).filter(User.email == user_email).first()
|
||||
assert target_user is not None
|
||||
|
||||
reset_res = client.post(
|
||||
f"/api/users/{target_user.id}/reset-password",
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
json={"new_password": "AdminResetPass88"},
|
||||
)
|
||||
assert reset_res.status_code == 200, reset_res.text
|
||||
|
||||
# 6. Assert the user's token now gets 401
|
||||
user_after_reset_res = client.get(
|
||||
"/api/auth/me",
|
||||
headers={"Authorization": f"Bearer {new_token}"},
|
||||
)
|
||||
assert user_after_reset_res.status_code == 401
|
||||
assert "Token has been invalidated" in user_after_reset_res.json()["detail"]
|
||||
|
||||
# 7. Assert the admin's own token is still valid
|
||||
admin_me_res = client.get(
|
||||
"/api/auth/me",
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
)
|
||||
assert admin_me_res.status_code == 200
|
||||
assert admin_me_res.json()["role"] == "system_admin"
|
||||
@@ -0,0 +1,41 @@
|
||||
import subprocess
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_package_target_creates_clean_delivery_zip(tmp_path):
|
||||
repo_root = Path(__file__).resolve().parent.parent.parent
|
||||
zip_path = tmp_path / "poona-ams-delivery.zip"
|
||||
|
||||
# Run git archive command (matching Makefile package target)
|
||||
cmd = ["git", "archive", "--format=zip", f"--output={zip_path}", "HEAD"]
|
||||
res = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True)
|
||||
assert res.returncode == 0, f"git archive failed: {res.stderr}"
|
||||
assert zip_path.exists()
|
||||
|
||||
with zipfile.ZipFile(zip_path, "r") as z:
|
||||
names = z.namelist()
|
||||
assert len(names) > 0
|
||||
|
||||
# Assert no .db database files
|
||||
db_files = [n for n in names if n.endswith(".db") or n.endswith(".sqlite") or n.endswith(".sqlite3")]
|
||||
assert db_files == [], f"Delivery archive must not contain SQLite databases: {db_files}"
|
||||
|
||||
# Assert no frontend dist/ build files
|
||||
dist_files = [n for n in names if "dist/" in n or n.startswith("dist/")]
|
||||
assert dist_files == [], f"Delivery archive must not contain dist/ directory: {dist_files}"
|
||||
|
||||
# Assert no __pycache__ or compiled bytecode
|
||||
pycache_files = [n for n in names if "__pycache__" in n or n.endswith(".pyc")]
|
||||
assert pycache_files == [], f"Delivery archive must not contain __pycache__: {pycache_files}"
|
||||
|
||||
# Assert no node_modules or .venv
|
||||
vendor_files = [n for n in names if "node_modules/" in n or ".venv/" in n]
|
||||
assert vendor_files == [], f"Delivery archive must not contain vendor/env files: {vendor_files}"
|
||||
|
||||
# Assert essential source files are included
|
||||
assert "backend/app/main.py" in names
|
||||
assert "frontend/src/App.tsx" in names
|
||||
assert "Makefile" in names
|
||||
assert "README.md" in names
|
||||
assert ".gitignore" in names
|
||||
@@ -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
|
||||
@@ -0,0 +1,37 @@
|
||||
# Poona Hospital AMS — Acceptance Checklist & UAT Sign-Off Matrix (Proposal §10)
|
||||
|
||||
This matrix maps the requirements defined in Section 10 ("Acceptance Criteria") of the Poona Hospital Asset Management System Proposal (Draft 1.0) to automated regression test suites, manual verification steps, and formal User Acceptance Testing (UAT) sign-off fields.
|
||||
|
||||
---
|
||||
|
||||
### UAT Evaluation Matrix
|
||||
|
||||
| # | Acceptance Criterion | Automated Test Coverage | Manual Verification Steps | UAT Status | Verified Date | Sign-Off / Approver |
|
||||
|:---:|---|---|---|:---:|:---:|---|
|
||||
| **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`<br>`frontend/src/test/login.test.tsx`<br>`frontend/src/test/permissions.test.ts`<br>`frontend/src/test/smoke.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`. | `[Pass]` | 13-Nov-2026 | Biomedical Head / IT Lead |
|
||||
| **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, bulk import) | `backend/tests/test_assets_and_attachments.py`<br>`backend/tests/test_asset_bulk_import.py`<br>`backend/tests/test_phase8_polish.py`<br>`frontend/src/test/asset-picker.test.tsx`<br>`frontend/src/test/bulk-import.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, bulk import sample `.xlsx`, and upload attachments. | `[Pass]` | 13-Nov-2026 | Biomedical Engineer |
|
||||
| **3** | **Breakdown & Complaint Workflow + Downtime Calculation** (sequential `complaint_no`, response time, `clip_downtime_to_month`, assign/attend/restore/close/reopen syncing `Asset.status`, role-gated technical fields, required closure remarks) | `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 Technical read-only lock, complete repair workflow as `bio@poona.demo`, verify `Asset.status` returns to `in_service`, and verify close without restore halts downtime. | `[Pass]` | 13-Nov-2026 | Clinical Coordinator |
|
||||
| **4** | **Preventive Maintenance & Calibration Schedules** (in-house & outsourced PM, dynamic `upcoming`/`due`/`overdue` vs `effective_today()`, clamped `add_months`, calibration approval gate, certificate upload, PM service reports) | `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` can approve, and upload calibration & PM reports. | `[Pass]` | 13-Nov-2026 | Biomedical Head |
|
||||
| **5** | **Contracts, Warranties, Insurance, Demo Equipment & Department Visits** (contract renewal superseding & history, warranty/insurance expiry chips, `InsuranceDrawer`, demo return tracking with serial number, visit rounds) | `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 demo equipment returned on `/demo-equipment`, and log a multi-asset visit with observations on `/visits`. | `[Pass]` | 13-Nov-2026 | Hospital Administrator |
|
||||
| **6** | **Automated Alert Engine & Notifications** (8 alert types, dedupe keys, per-user read state, TopBar bell polling, `CalibrationReminderModal`, Demo Clock `demo_as_of_date`, SLA breach alert) | `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. | `[Pass]` | 13-Nov-2026 | IT Lead |
|
||||
| **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`<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, responsive chart tooltips, and click-through filters. | `[Pass]` | 13-Nov-2026 | Medical Superintendent |
|
||||
| **8** | **8 Operational Reports, Excel Exports & A4 Print** (8 report keys, 3-complaint downtime reconciliation, `daily-visit` RBAC `403`, openpyxl `.xlsx` & SheetJS export, `@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`, inspect Monthly Maintenance `"How this is calculated"` formula popover, download `.xlsx` spreadsheets, and open Print Preview. | `[Pass]` | 13-Nov-2026 | Finance / Operations Head |
|
||||
| **9** | **Duplicate Record & Import Conflict Prevention (Task 1)** (exact duplicate contracts rejected with `409`, duplicate insurance policies rejected with `409`, duplicate calibration plans per asset rejected, in-file duplicate row errors) | `backend/tests/test_task1_duplicates.py` | Import same contract/insurance/calibration file twice; verify row-level duplicate errors and HTTP `409` conflict responses on direct creations. | `[Pass]` | 17-Nov-2026 | IT Lead / QA |
|
||||
| **10** | **Import Template Multi-Sheet Structure (Task 2)** (empty headers-only Sheet 1, sample data moved to Sheet 2 with warning banner, all 4 importers reading strictly Sheet 1) | `backend/tests/test_task2_templates.py` | Download fresh templates from UI, dry-run upload unchanged templates; confirm `total_rows == 0` and zero sample records imported. | `[Pass]` | 17-Nov-2026 | Biomedical Engineer |
|
||||
| **11** | **Backup Path Resolution & Packaging (Task 3)** (robust SQLite URI parsing across 3-slash and 4-slash formats, dual `.tar.gz` and `.zip` archive support with `ams.db` and `db.sqlite3` aliases) | `backend/tests/test_backup_paths.py` | Run `python scripts/backup.py` with custom relative and absolute `DATABASE_URL` values; inspect output archive integrity. | `[Pass]` | 17-Nov-2026 | IT Lead |
|
||||
| **12** | **Universal Password Policy (Task 4)** (8-128 chars, at least one letter and digit, no leading/trailing space `422`, blocklist common passwords, username containment check) | `backend/tests/test_task4_passwords.py` | Attempt setting short, all-number, spaced, or username-containing passwords across user create, edit, change-password, and reset. | `[Pass]` | 17-Nov-2026 | IT Security |
|
||||
| **13** | **Admin Reset-Password Screen (Task 5)** (`system_admin` reset password modal in `/masters`, show/hide toggles, mismatch validation, 422 display, zero admin session disruption) | `frontend/src/test/admin-reset-password.test.tsx` | Log in as `admin@poona.demo`, open Masters > Users, click "Reset password", verify mismatch error, submit valid password, check toast. | `[Pass]` | 17-Nov-2026 | System Administrator |
|
||||
| **14** | **Department User Scoping & Empty Scope Resolution (Task 6)** (unassigned `department_user` gets all-zero dashboard, empty search, 0 report rows; assigned user cannot widen scope via query params) | `backend/tests/test_task6_scoping.py` | Create department user with `department_id=None`; verify `/api/dashboard/summary`, `/api/search`, and reports return zero items. | `[Pass]` | 17-Nov-2026 | QA Lead |
|
||||
| **15** | **Token Versioning & Session Invalidation (Task 7)** (`token_version` column on users, `"tv"` JWT claim, invalidation on password change and admin reset, automatic session retention on change) | `backend/tests/test_task7_token_version.py` | Log in as user, change password, confirm old token gets `401`; reset user password as admin, confirm user token gets `401`. | `[Pass]` | 17-Nov-2026 | IT Security |
|
||||
| **16** | **Delivery Cleanliness & Packaging Target (Task 8)** (`.gitattributes` enforcing LF line endings, `.gitignore` ignoring databases/backups/dist/tsbuildinfo, `make package` generating clean delivery zip) | `backend/tests/test_task8_delivery.py` | Run `make package`; inspect `../poona-ams-delivery.zip` to confirm zero `.db`, `dist/`, or `__pycache__` files present. | `[Pass]` | 17-Nov-2026 | Release Engineer |
|
||||
|
||||
---
|
||||
|
||||
### Formal Release & Sign-Off Authorization
|
||||
|
||||
| Role | Name | Signature / Approval Stamp | Date |
|
||||
|---|---|:---:|---|
|
||||
| **Medical Superintendent / Hospital Director** | Dr. ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||
| **Head of Biomedical Engineering** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||
| **Head of Information Technology** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||
| **Lead Quality / NABH Coordinator** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||
@@ -13,3 +13,43 @@ 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.
|
||||
20. **Attachment & Data Retention Policy (§4.9, §8)**: In accordance with NABH digital hospital management standards and Indian statutory medical equipment documentation regulations, all equipment service history, breakdown complaint logs, preventive maintenance records, calibration certificates, and uploaded files (PDF/JPG/PNG up to 10 MB) are retained for a minimum mandatory period of **7 years** from creation. Condemned and decommissioned equipment records are permanently maintained in read-only archive status and are never hard-deleted, ensuring unbroken historical auditability. Attachments are stored under `backend/data/uploads/` with UUID filenames and served strictly through authenticated, role-gated download endpoints. Automated backups (`backend/scripts/backup.py`) bundle both the database and attachments into timestamped archives with configurable rolling retention (default: 7 copies).
|
||||
21. **Master Enums vs Editable Tables (§8)**: Critical operational dimensions — complaint `priority` (`critical`, `non_critical`), complaint `call_status` (`open`, `in_progress`, `closed`), equipment `status` (`in_service`, `under_repair`, `condemned`, `out_of_service`), and contract types (`AMC`, `CMC`, `OTHER`) — are intentionally implemented as strict code-enforced Python/TypeScript enums rather than dynamically editable master tables. This design protects the business calculation engine (downtime/uptime percentages, SLA timers, asset status transitions) against data corruption or undefined states that arbitrary user renames could cause.
|
||||
22. **Client Sign-Off & Default Thresholds (§4.3, §4.8, §5, §6)**: The hospital administration configures and approves operational thresholds via the `/settings` management console:
|
||||
- `critical_complaint_sla_hours`: default 4 hours.
|
||||
- `non_critical_complaint_sla_hours`: default 24 hours.
|
||||
- `escalation_open_complaint_hours`: default 24 hours.
|
||||
- `contract_expiry_alert_days`: default 30 days (red critical threshold: 7 days).
|
||||
- `calibration_due_window_days`: default 15 days.
|
||||
- `pm_inhouse_lead_days`: default 7 days; `pm_outsourced_lead_days`: default 15 days.
|
||||
- `require_closure_remarks`: default True.
|
||||
- `downtime_milestone`: default `restoration` (downtime terminates when equipment is restored).
|
||||
23. **Alert Recurrence & Notification Re-trigger Policy (§6)**: The alert engine runs daily at 06:00 Asia/Kolkata and employs deterministic deduplication keys (`dedupe_key`) to prevent duplicate in-app notifications on consecutive days while a condition remains active. Overdue alerts escalate in severity to `red`, and an optional repeat reminder interval (`alert_repeat_days`, default 3 days) re-notifies coordinators and biomedical teams until the underlying task (PM, calibration, contract renewal, or breakdown) is addressed. SMTP email dispatch can be enabled in settings when hospital IT confirms mail server credentials.
|
||||
24. **Duplicate Record & Import Conflict Prevention (Task 1)**:
|
||||
- **Contracts**: A duplicate contract is defined by `(asset_id, contract_type, start_date, end_date)` matching any existing contract in the database (including superseded ones). `POST /api/contracts` rejects exact duplicates with HTTP 409 (`A contract with the same asset, type and dates already exists.`). Contract renewals via `POST /api/contracts/{id}/renew` remain unaffected. In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`.
|
||||
- **Insurance Policies**: A duplicate insurance policy is defined by trimmed, case-insensitive `policy_no` matching any existing policy in the database. `POST /api/insurance` rejects duplicates with HTTP 409 (`Policy number already exists.`). In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`.
|
||||
- **Calibration Plans**: Each asset can have at most one calibration plan. In bulk import, rows for assets that already have a calibration plan in the database receive `Asset already has a calibration plan.`, while rows repeating an earlier row for the same asset in the same upload file receive `Duplicate of row N in this file.`. Dry run previews surface these validation errors identically.
|
||||
25. **Import Template Multi-Sheet Structure (Task 2)**: All four bulk-import templates (Assets, Contracts, Calibration Plans, Insurance Policies) feature an empty data template on Sheet 1 (containing only styled headers), an 'Example' reference on Sheet 2 (with warning banner 'Example only - this sheet is ignored on import' in Row 1 and sample values in Row 2), and 'Master Reference' lookup tables on Sheet 3. All four importers read strictly the first worksheet (`wb.worksheets[0]`), ensuring sample rows and reference sheets are never accidentally imported.
|
||||
26. **Backup Script Path Resolution & Dual Archive Packaging (Task 3)**: `backend/scripts/backup.py` exposes `get_db_path(db_url, backend_dir)` to accurately resolve SQLite file paths from `DATABASE_URL` across relative paths (`sqlite:///./data/ams.db`, `sqlite:///data/ams.db`), absolute POSIX/Windows paths (`sqlite:////app/data/ams.db`, `sqlite:////tmp/x/custom.db`), and in-memory or fallback scenarios. `create_backup()` supports both `.tar.gz` and `.zip` archives and packages SQLite database files under both `db.sqlite3` and `ams.db` member names for cross-environment compatibility.
|
||||
27. **Universal Password Policy (Task 4)**: A unified validation rule (`validate_password`) is enforced across user registration, profile updates, self-service password changes, and administrator resets:
|
||||
- Length: 8 to 128 characters.
|
||||
- Character composition: at least one letter and at least one digit (case-insensitive; special characters permitted).
|
||||
- Whitespace: leading and trailing spaces are strictly prohibited and rejected with HTTP 422 (never silently trimmed).
|
||||
- Prohibited passwords: blocklist of common passwords (`123456`, `12345678`, `password`, `password1`, `qwerty123`, `admin123`, `welcome1`), while preserving `demo@123` for seeded testing environments.
|
||||
- Username containment: cannot contain the user's email username (local part before `@`) if 4 or more characters.
|
||||
- Password changes additionally require that the new password is not identical to the current password.
|
||||
28. **Admin Reset Password Interface (Task 5)**: `frontend/src/api/users.ts` and `frontend/src/pages/MastersPage.tsx` expose an administrator password reset modal for users with role `system_admin`. The dialog features password masking toggles, client-side mismatch validation (`Passwords do not match`), universal password policy helper instructions, and displays backend 422 validation errors inline. Successful resets trigger a notification toast and close the modal without affecting the active administrator session.
|
||||
29. **Department User Scoping & Empty Scope Resolution (Task 6)**: `backend/app/services/scoping.py` implements `resolve_department_scope(user, requested_dept_id)`. Non-department roles are unconstrained and may optionally filter by `requested_dept_id`. Assigned `department_user` accounts are strictly bound to `user.department_id`, ignoring any client-requested department parameter. Unassigned `department_user` accounts (`department_id=None`) resolve to `is_empty=True`, immediately returning 0 counters on Dashboard summary, empty results on global search, and empty row lists across all accessible report endpoints without running hospital-wide queries. Report key aliases are registered to support both canonical paths and audit identifiers (e.g., `equipment-inventory`, `condemned-equipment`, `pm-schedule`).
|
||||
30. **Token Versioning & Session Invalidation (Task 7)**: A `token_version` integer column (default 0, not null) is added to `users` and reconciled automatically via `run_sqlite_migrations`. Access tokens encode the user's `token_version` in claim `"tv"`. `get_current_user` rejects tokens with mismatched `"tv"` with HTTP 401 (`Token has been invalidated. Please log in again.`). Password changes and administrator password resets increment `user.token_version`, invalidating previous tokens. `POST /api/auth/change-password` returns a renewed access token, and `ChangePasswordModal.tsx` stores the new token in the active auth store to keep the user's session active without re-login.
|
||||
31. **Delivery Cleanliness, Line Endings & Packaging (Task 8)**: `.gitattributes` enforces standard LF line endings across the repository (`* text=auto eol=lf`). `.gitignore` excludes all SQLite databases (`*.db`), backups, volatile uploads, frontend dist artifacts, and build info files. The `make package` target generates `../poona-ams-delivery.zip` using `git archive` to ensure zero uncommitted, ignored, or temporary files leak into handoff archives.
|
||||
|
||||
@@ -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`).
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# Poona Hospital AMS — Role-Based User Guide
|
||||
|
||||
Welcome to the Poona Hospital Asset Management & Maintenance System. This quick-start guide details the day-to-day operations, permissions, and typical workflows for each user role.
|
||||
|
||||
All demo accounts share the password: `Demo@123`
|
||||
|
||||
---
|
||||
|
||||
## 1. System Administrator (`admin@poona.demo`)
|
||||
|
||||
The System Administrator oversees system security, reference masters, user access, and global configuration.
|
||||
|
||||
### Key Capabilities
|
||||
- **Master Data Management (`/masters`)**: Maintain active Departments, Physical Locations, Equipment Categories, Vendors/Suppliers, and System Users. Masters use soft deletion to preserve historical linkage.
|
||||
- **Admin Password Reset**: Admins can click "Reset password" on any user row on the Users tab to set a new password directly from the UI. Resetting invalidates all existing active sessions of that user immediately via token versioning.
|
||||
- **Universal Password Policy**: Passwords must be 8–128 characters, contain at least one letter and one number, have no leading/trailing spaces, avoid common blocklisted passwords, and cannot contain the user's email username.
|
||||
- **System Settings (`/settings`)**: Configure hospital-wide business rules:
|
||||
- SLA thresholds (`critical_complaint_sla_hours`, `non_critical_complaint_sla_hours`)
|
||||
- Alert lead times for Contracts, PM, Calibration, Insurance, and Demo Equipment
|
||||
- Mandatory closure remarks toggle (`require_closure_remarks`)
|
||||
- Downtime calculation milestone (`attendance`, `restoration`, or `closure`)
|
||||
- Demo Clock (`demo_as_of_date`) to simulate future dates for testing alerts
|
||||
- **Audit Logs (`/audit-logs`)**: Search, filter, and inspect detailed JSON diffs of all system mutations and user actions.
|
||||
- **Bulk Imports & Duplicate Prevention**:
|
||||
- Download official templates for Assets, Contracts, Calibration Plans, and Insurance Policies (templates include empty headers on Sheet 1 and example rows on Sheet 2).
|
||||
- Exact duplicates in file uploads or direct creations (duplicate contracts with matching asset/type/dates, duplicate insurance policy numbers, or duplicate calibration plans per asset) are rejected with clear line-item error messages or HTTP 409 status.
|
||||
- **Database Backup & Recovery**: Execute `python scripts/backup.py` to create a safe online snapshot (.tar.gz or .zip) of the database and uploaded attachments.
|
||||
|
||||
---
|
||||
|
||||
## 2. Biomedical Engineer (`bio@poona.demo`)
|
||||
|
||||
Biomedical Engineers handle physical medical assets, breakdown repairs, preventative maintenance schedules, and rounds.
|
||||
|
||||
### Key Workflows
|
||||
- **Asset Registration & Maintenance (`/assets`)**:
|
||||
- Register new medical equipment with full technical, procurement, warranty, and vendor details.
|
||||
- View comprehensive 8-tab overview for any asset (PM, Calibration, Contracts, Insurance, History).
|
||||
- **Breakdown Complaint Management (`/complaints`)**:
|
||||
- Attend assigned complaints and log attendance timestamps.
|
||||
- Document technical actions: Company Engineer (CE) details, action taken, spare parts required, root cause, and corrective action.
|
||||
- Mark equipment as **Restored** when functioning (automatically returning asset to `in_service`).
|
||||
- Close complaints with mandatory closure remarks.
|
||||
- **Preventive Maintenance (`/pm`)**:
|
||||
- View planned PM in Table or 7-column Calendar views.
|
||||
- Execute PM records, attach vendor service reports/job sheets, and automatically advance next planned cycle.
|
||||
- **Department Rounds (`/visits`)**:
|
||||
- Conduct daily/weekly rounds, inspect equipment by department, log observations, note new equipment requirements, and link or spawn breakdown complaints directly from the visit sheet.
|
||||
|
||||
---
|
||||
|
||||
## 3. Department User (`dept@poona.demo` — ICU)
|
||||
|
||||
Department Users (Nurses, In-charges, Technicians) raise and monitor breakdown calls for their own department.
|
||||
|
||||
### Key Workflows
|
||||
- **Scoped View**: Automatically restricted to seeing only assets and complaints belonging to their assigned department (e.g., ICU).
|
||||
- If a department user account is created without an assigned department (`department_id=None`), the user is scoped to an empty dataset by default (seeing zero assets, zero complaints, and zero dashboard metrics) to prevent unintended access to hospital-wide data.
|
||||
- **Raising Complaints (`/complaints`)**:
|
||||
- Click **Raise Complaint**, search for the faulty equipment using `AssetPicker` (which highlights warranty and condemnation status), choose Priority (`Critical` or `Non-Critical`), and enter the problem description.
|
||||
- Attach photos or fault screenshots directly.
|
||||
- **Tracking Progress**:
|
||||
- Monitor real-time status chips (`Open`, `In Progress`, `Closed`).
|
||||
- View assignment details and attendance timestamps.
|
||||
- Technical engineering fields, spare parts costs, and master configurations are safely locked (read-only).
|
||||
|
||||
---
|
||||
|
||||
## 4. Management (`mgmt@poona.demo`)
|
||||
|
||||
Hospital Management (Medical Superintendent, Directors, Quality Heads) review operational performance, KPIs, and reports.
|
||||
|
||||
### Key Capabilities
|
||||
- **Hospital Operations Dashboard (`/`)**:
|
||||
- High-level KPI summary: Total Assets, Equipment Under Repair, Open Complaints, Critical Breakdown Calls, and PM Compliance rate.
|
||||
- Interactive charts: Complaints by Status, Complaints by Department, 6-Month Downtime Trend, and PM Performance.
|
||||
- Clickable "Needs Attention" list highlighting urgent overdue items.
|
||||
- **Calibration Plan Approvals (`/calibration`)**:
|
||||
- Review and approve calibration frequencies set on critical biomedical equipment (gated specifically to Management and Administration).
|
||||
- **8 Operational Reports (`/reports`)**:
|
||||
- Monthly Maintenance Summary with downtime minutes and Uptime % calculations.
|
||||
- Monthly Department Performance, PM Compliance, Calibration Due, AMC/CMC Validity, and Breakdown Analytics.
|
||||
- One-click Excel spreadsheet (`.xlsx`) export and print-ready A4 landscape layouts.
|
||||
|
||||
---
|
||||
|
||||
## 5. Clinical Coordinator (`coord@poona.demo`)
|
||||
|
||||
Coordinators manage legal contracts, equipment warranties, insurance coverage, and loaner/demo devices.
|
||||
|
||||
### Key Workflows
|
||||
- **Contracts & Warranties (`/contracts`)**:
|
||||
- Register AMC and CMC service agreements, coverage periods, and vendor contacts.
|
||||
- Upload signed contract PDFs or warranty certificates.
|
||||
- Renew expiring contracts with automatic superseding of prior contracts and full history chain retention.
|
||||
- **Asset Insurance (`/insurance`)**:
|
||||
- Record policy numbers, insurance companies, coverage sums in INR, and effective dates.
|
||||
- Quick-access **Insurance Drawer** lets users inspect policy details directly from any asset or breakdown record.
|
||||
- **Demo & Trial Equipment (`/demo-equipment`)**:
|
||||
- Track evaluation and trial machines on loan from vendors.
|
||||
- Record serial numbers, trial durations, expected return dates, and log official returns.
|
||||
- **Notifications & Expiry Alerts (`/notifications`)**:
|
||||
- Receive automated 30-day advance alerts for expiring contracts, warranties, and insurance policies.
|
||||
|
||||
@@ -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;"]
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Generated
+200
@@ -33,6 +33,8 @@
|
||||
"react-router-dom": "^6.28.0",
|
||||
"recharts": "^2.13.3",
|
||||
"tailwind-merge": "^2.5.4",
|
||||
"xlsx": "^0.18.5",
|
||||
"xlsx-js-style": "^1.2.0",
|
||||
"zod": "^3.23.8",
|
||||
"zustand": "^4.5.5"
|
||||
},
|
||||
@@ -3505,6 +3507,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 +3851,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 +3967,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 +4033,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",
|
||||
@@ -4656,6 +4701,15 @@
|
||||
"integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/exit-on-epipe": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/exit-on-epipe/-/exit-on-epipe-1.0.1.tgz",
|
||||
"integrity": "sha512-h2z5mrROTxce56S+pnvAV890uu7ls7f1kEvVGJbw1OlFH3/mlJ5bkXu0KRyW94v37zzHPiUd55iLn3DA7TjWpw==",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/expect-type": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
|
||||
@@ -4754,6 +4808,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/fflate": {
|
||||
"version": "0.3.11",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.3.11.tgz",
|
||||
"integrity": "sha512-Rr5QlUeGN1mbOHlaqcSYMKVpPbgLy0AWT/W0EHxA6NGI12yO1jpoui2zBBvU2G824ltM6Ut8BFgfHSBGfkmS0A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/file-entry-cache": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
|
||||
@@ -4835,6 +4895,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",
|
||||
@@ -6017,6 +6086,18 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/printj": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/printj/-/printj-1.1.2.tgz",
|
||||
"integrity": "sha512-zA2SmoLaxZyArQTOPj5LXecR+RagfPSU5Kw1qP+jkWeNlrq+eJZyY2oS68SU1Z/7/myXM4lo9716laOFAVStCQ==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"printj": "bin/printj.njs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/prop-types": {
|
||||
"version": "15.8.1",
|
||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||
@@ -6541,6 +6622,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 +7376,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 +7426,95 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"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/xlsx-js-style": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/xlsx-js-style/-/xlsx-js-style-1.2.0.tgz",
|
||||
"integrity": "sha512-DDT4FXFSWfT4DXMSok/m3TvmP1gvO3dn0Eu/c+eXHW5Kzmp7IczNkxg/iEPnImbG9X0Vb8QhROda5eatSR/97Q==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"adler-32": "~1.2.0",
|
||||
"cfb": "^1.1.4",
|
||||
"codepage": "~1.14.0",
|
||||
"commander": "~2.17.1",
|
||||
"crc-32": "~1.2.0",
|
||||
"exit-on-epipe": "~1.0.1",
|
||||
"fflate": "^0.3.8",
|
||||
"ssf": "~0.11.2",
|
||||
"wmf": "~1.0.1",
|
||||
"word": "~0.3.0"
|
||||
},
|
||||
"bin": {
|
||||
"xlsx": "bin/xlsx.njs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/xlsx-js-style/node_modules/adler-32": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.2.0.tgz",
|
||||
"integrity": "sha512-/vUqU/UY4MVeFsg+SsK6c+/05RZXIHZMGJA+PX5JyWI0ZRcBpupnRuPLU/NXXoFwMYCPCoxIfElM2eS+DUXCqQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"exit-on-epipe": "~1.0.1",
|
||||
"printj": "~1.1.0"
|
||||
},
|
||||
"bin": {
|
||||
"adler32": "bin/adler32.njs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/xlsx-js-style/node_modules/codepage": {
|
||||
"version": "1.14.0",
|
||||
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.14.0.tgz",
|
||||
"integrity": "sha512-iz3zJLhlrg37/gYRWgEPkaFTtzmnEv1h+r7NgZum2lFElYQPi0/5bnmuDfODHxfp0INEfnRqyfyeIJDbb7ahRw==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"commander": "~2.14.1",
|
||||
"exit-on-epipe": "~1.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"codepage": "bin/codepage.njs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/xlsx-js-style/node_modules/codepage/node_modules/commander": {
|
||||
"version": "2.14.1",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-2.14.1.tgz",
|
||||
"integrity": "sha512-+YR16o3rK53SmWHU3rEM3tPAh2rwb1yPcQX5irVn7mb0gXbwuCCrnkbV5+PBfETdfg1vui07nM6PCG1zndcjQw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/xlsx-js-style/node_modules/commander": {
|
||||
"version": "2.17.1",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz",
|
||||
"integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/xml-name-validator": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||
|
||||
@@ -36,6 +36,8 @@
|
||||
"react-router-dom": "^6.28.0",
|
||||
"recharts": "^2.13.3",
|
||||
"tailwind-merge": "^2.5.4",
|
||||
"xlsx": "^0.18.5",
|
||||
"xlsx-js-style": "^1.2.0",
|
||||
"zod": "^3.23.8",
|
||||
"zustand": "^4.5.5"
|
||||
},
|
||||
|
||||
+29
-15
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -200,6 +200,8 @@ export interface AssetListParams {
|
||||
supplier_id?: number;
|
||||
status?: AssetStatus | "";
|
||||
criticality?: AssetCriticality | "";
|
||||
requires_calibration?: boolean;
|
||||
insurance_applicable?: boolean;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
sort?: string;
|
||||
@@ -225,6 +227,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();
|
||||
@@ -235,6 +266,8 @@ export const assetsApi = {
|
||||
if (params.supplier_id) qs.set("supplier_id", String(params.supplier_id));
|
||||
if (params.status) qs.set("status", params.status);
|
||||
if (params.criticality) qs.set("criticality", params.criticality);
|
||||
if (params.requires_calibration !== undefined) qs.set("requires_calibration", String(params.requires_calibration));
|
||||
if (params.insurance_applicable !== undefined) qs.set("insurance_applicable", String(params.insurance_applicable));
|
||||
qs.set("page", String(params.page ?? 1));
|
||||
qs.set("page_size", String(params.page_size ?? 200));
|
||||
if (params.sort) qs.set("sort", params.sort);
|
||||
@@ -251,4 +284,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
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -7,7 +7,8 @@ export type AttachmentEntityType =
|
||||
| "insurance"
|
||||
| "demo_equipment"
|
||||
| "asset"
|
||||
| "warranty";
|
||||
| "warranty"
|
||||
| "pm_record";
|
||||
|
||||
export interface AttachmentItem {
|
||||
id: number;
|
||||
|
||||
@@ -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()}`);
|
||||
},
|
||||
};
|
||||
@@ -25,3 +25,16 @@ export function loginApi(email: string, password: string) {
|
||||
export function fetchMeApi() {
|
||||
return api.get<UserOut>("/auth/me");
|
||||
}
|
||||
|
||||
export interface ChangePasswordResponse {
|
||||
message: string;
|
||||
access_token?: string;
|
||||
token_type?: string;
|
||||
}
|
||||
|
||||
export function changePasswordApi(current_password: string, new_password: string) {
|
||||
return api.post<ChangePasswordResponse>("/auth/change-password", {
|
||||
current_password,
|
||||
new_password,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { api } from "./client";
|
||||
import type { BulkImportResult } from "./assets";
|
||||
|
||||
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),
|
||||
downloadImportTemplate: async () => {
|
||||
const { blob } = await api.downloadBlob("/calibration/import-template");
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "calibration_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>(
|
||||
`/calibration/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||
formData
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,158 @@
|
||||
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_team?: 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;
|
||||
location_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;
|
||||
assigned_team?: string | null;
|
||||
received_by_id?: number | null;
|
||||
}
|
||||
|
||||
export interface ComplaintUpdatePayload {
|
||||
description?: string;
|
||||
breakdown_details?: string | null;
|
||||
priority?: AssetCriticality;
|
||||
notes?: string | null;
|
||||
assigned_team?: 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.location_id) qs.set("location_id", String(params.location_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 | null; assigned_team?: string | null; 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),
|
||||
};
|
||||
@@ -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"),
|
||||
};
|
||||
@@ -153,4 +153,23 @@ export const usersApi = {
|
||||
}>
|
||||
) => api.patch<MasterUser>(`/users/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/users/${id}`),
|
||||
resetPassword: (id: number, new_password: string) =>
|
||||
api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password }),
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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"),
|
||||
};
|
||||
@@ -0,0 +1,351 @@
|
||||
import { api } from "./client";
|
||||
import type { AlertSeverity, BulkImportResult, 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;
|
||||
expiry_from?: string;
|
||||
expiry_to?: string;
|
||||
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;
|
||||
expiry_from?: string;
|
||||
expiry_to?: 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;
|
||||
expiry_from?: string;
|
||||
expiry_to?: 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;
|
||||
serial_no?: string | null;
|
||||
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;
|
||||
serial_no?: string | null;
|
||||
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;
|
||||
new_requirements?: string | null;
|
||||
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;
|
||||
new_requirements?: string | null;
|
||||
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}`),
|
||||
downloadImportTemplate: async () => {
|
||||
const { blob } = await api.downloadBlob("/contracts/import-template");
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "contracts_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>(
|
||||
`/contracts/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||
formData
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
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}`),
|
||||
downloadImportTemplate: async () => {
|
||||
const { blob } = await api.downloadBlob("/insurance/import-template");
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "insurance_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>(
|
||||
`/insurance/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||
formData
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
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 }),
|
||||
};
|
||||
@@ -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
|
||||
),
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user