initial commit
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
# 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
|
||||
|
||||
# Optional local AI narrative provider (none | ollama | openai_compatible)
|
||||
# Default is "none" (deterministic rule-based summaries; no model required)
|
||||
AI_PROVIDER=none
|
||||
AI_BASE_URL=http://localhost:11434
|
||||
AI_MODEL=
|
||||
AI_API_KEY=
|
||||
AI_TIMEOUT_SECONDS=25
|
||||
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
# 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/
|
||||
**/.pytest_cache/
|
||||
__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
|
||||
@@ -0,0 +1,17 @@
|
||||
# Agent Operating Rules — Poona Hospital AMS
|
||||
|
||||
- Build exactly what the plan and proposal describe. **Out of scope:** QR codes, barcode scanning, SMS/WhatsApp, any AI/LLM features, payment/rent/depreciation modules, multi-hospital tenancy, mobile native apps.
|
||||
- Work phase by phase. Do not start the next phase until told. Commit at the end of each phase with message `phase-N: <summary>`.
|
||||
- Never invent requirements. Where the proposal says "to be confirmed", implement it as an editable setting with the default given in section 4 and log it in `docs/ASSUMPTIONS.md`.
|
||||
- Store all timestamps in UTC; display in Asia/Kolkata with format `DD-MMM-YYYY HH:mm` (dates only: `DD-MMM-YYYY`). One shared formatting helper on the frontend (src/lib/format.ts); one on the backend (app/core/time_utils.py).
|
||||
- Business calculations live in pure functions in `backend/app/services/` with unit tests. Routers stay thin.
|
||||
- Permissions are enforced on the server (including field-level). The UI hides or disables controls as a convenience only.
|
||||
- No secrets in code. Demo passwords exist only in the seed script and the README.
|
||||
- Keep dependencies minimal and pinned.
|
||||
- After each phase update README.md.
|
||||
- If something is ambiguous and blocking, make the most reasonable choice, record it in `docs/ASSUMPTIONS.md`, and continue.
|
||||
|
||||
## Implementation Notes
|
||||
- N1: When renewing a contract, add `is_superseded: bool = False` to the contracts model and set True on the old contract when renewing, so history filtering works cleanly.
|
||||
- N2: `calibration_records.status` and `pm_records.status` values `upcoming`/`due`/`overdue` are NEVER stored in the DB; only `completed` is persisted. The Pydantic response schema computes them from due_date and effective_today().
|
||||
- N3: SQLite engine must use `check_same_thread=False`, WAL mode, and busy_timeout=5000ms. APScheduler jobs must use `get_scheduler_db()` context manager — never a request session.
|
||||
@@ -0,0 +1,32 @@
|
||||
.PHONY: dev backend frontend test seed install package
|
||||
|
||||
ifeq ($(OS),Windows_NT)
|
||||
VENV_BIN := .venv/Scripts
|
||||
PYTHON_SYS := python
|
||||
else
|
||||
VENV_BIN := .venv/bin
|
||||
PYTHON_SYS := python3
|
||||
endif
|
||||
|
||||
dev:
|
||||
$(MAKE) -j2 backend frontend
|
||||
|
||||
backend:
|
||||
cd backend && "$(VENV_BIN)/uvicorn" app.main:app --reload --port 8000
|
||||
|
||||
frontend:
|
||||
cd frontend && npm run dev
|
||||
|
||||
test:
|
||||
cd backend && "$(VENV_BIN)/python" -m pytest tests/ -v
|
||||
|
||||
seed:
|
||||
cd backend && "$(VENV_BIN)/python" -m app.seed.seed
|
||||
|
||||
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
|
||||
@@ -0,0 +1,168 @@
|
||||
# Poona Hospital Asset Management System
|
||||
|
||||

|
||||
|
||||
A centralized Hospital Asset Management and Maintenance System for Poona Hospital and Research Centre.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
- Python 3.11+
|
||||
- Node.js 18+
|
||||
|
||||
### Backend
|
||||
```bash
|
||||
cd backend
|
||||
python -m venv .venv
|
||||
|
||||
# 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
|
||||
|
||||
### Frontend
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
- App: http://localhost:5173
|
||||
|
||||
### Run both servers (with Make)
|
||||
```bash
|
||||
make dev
|
||||
```
|
||||
|
||||
### Run tests
|
||||
```bash
|
||||
# Backend (activate .venv first: Windows .venv\Scripts\activate | macOS/Linux source .venv/bin/activate)
|
||||
cd backend
|
||||
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
|
||||
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`).
|
||||
|
||||
### AI Report Environment Variables (Optional)
|
||||
All numbers and suggestions in the AI Report (`/reports/ai`) are computed deterministically in Python, and the full feature works out of the box with no language model installed (`AI_PROVIDER=none`, showing deterministic rule-based summaries). To optionally enable a hospital-hosted local model for narrative wording, set these optional environment variables in `.env` or `docker-compose.yml`:
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `AI_PROVIDER` | `none` | Narrative provider: `none`, `ollama`, or `openai_compatible` (hospital-controlled local endpoint only) |
|
||||
| `AI_BASE_URL` | `http://localhost:11434` | Base URL for Ollama (`POST /api/chat`) or OpenAI-compatible server (`POST /v1/chat/completions`) |
|
||||
| `AI_MODEL` | *(empty)* | Model name installed on the local server (e.g. `llama3.2`, `qwen2.5:7b`) |
|
||||
| `AI_API_KEY` | *(empty)* | Optional Bearer token for a local `openai_compatible` endpoint |
|
||||
| `AI_TIMEOUT_SECONDS` | `25` | HTTP timeout in seconds before falling back to rule-based narrative |
|
||||
|
||||
Once configured, a System Admin can enable narratives via `/settings` → **AI and cost analysis** → **Enable AI Narrative (`ai_enabled`)**.
|
||||
|
||||
## 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 |
|
||||
|---|---|---|
|
||||
| admin@poona.demo | Demo@123 | System Admin |
|
||||
| bio@poona.demo | Demo@123 | Biomedical |
|
||||
| dept@poona.demo | Demo@123 | Department User (ICU) |
|
||||
| mgmt@poona.demo | Demo@123 | Management |
|
||||
| coord@poona.demo | Demo@123 | Coordinator |
|
||||
|
||||
## 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
|
||||
- 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 (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, 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"]
|
||||
@@ -0,0 +1,20 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
DATABASE_URL: str = "sqlite:///./data/ams.db"
|
||||
SECRET_KEY: str = "change-me-in-production-32-chars-min"
|
||||
UPLOAD_DIR: str = "./data/uploads"
|
||||
TIMEZONE: str = "Asia/Kolkata"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 480
|
||||
ALGORITHM: str = "HS256"
|
||||
MAX_UPLOAD_SIZE_MB: int = 10
|
||||
AI_PROVIDER: str = "none" # none | ollama | openai_compatible
|
||||
AI_BASE_URL: str = "http://localhost:11434"
|
||||
AI_MODEL: str = ""
|
||||
AI_API_KEY: str = ""
|
||||
AI_TIMEOUT_SECONDS: int = 300
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,42 @@
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from contextlib import contextmanager
|
||||
from .config import settings
|
||||
|
||||
engine = create_engine(
|
||||
settings.DATABASE_URL,
|
||||
connect_args={"check_same_thread": False},
|
||||
)
|
||||
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def set_sqlite_pragmas(dbapi_conn, connection_record):
|
||||
cursor = dbapi_conn.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.close()
|
||||
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_scheduler_db() -> Session:
|
||||
"""Short-lived session for APScheduler jobs — never share with request sessions."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,57 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError
|
||||
from sqlalchemy.orm import Session
|
||||
from .db import get_db
|
||||
from .security import decode_token
|
||||
from ..models.masters import User
|
||||
from ..services.permissions import Role
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
||||
|
||||
|
||||
def get_current_user(
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
try:
|
||||
payload = decode_token(token)
|
||||
sub = payload.get("sub")
|
||||
if sub is None:
|
||||
raise credentials_exception
|
||||
user_id = int(sub)
|
||||
except (JWTError, ValueError, TypeError):
|
||||
raise credentials_exception
|
||||
|
||||
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
|
||||
|
||||
|
||||
def require_roles(*roles: Role | str):
|
||||
allowed = {r.value if isinstance(r, Role) else r for r in roles}
|
||||
|
||||
def _dependency(current_user: User = Depends(get_current_user)) -> User:
|
||||
if current_user.role not in allowed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Insufficient permissions for this action.",
|
||||
)
|
||||
return current_user
|
||||
|
||||
return _dependency
|
||||
@@ -0,0 +1,16 @@
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
class CodedHTTPException(HTTPException):
|
||||
def __init__(self, status_code: int, detail: str, code: str):
|
||||
super().__init__(status_code=status_code, detail=detail)
|
||||
self.code = code
|
||||
|
||||
|
||||
async def coded_http_exception_handler(request: Request, exc: CodedHTTPException) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={"detail": exc.detail, "code": exc.code},
|
||||
headers=exc.headers,
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
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"
|
||||
elif col.name == "acquisition_mode":
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} VARCHAR(20) DEFAULT 'purchased'"
|
||||
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
|
||||
@@ -0,0 +1,103 @@
|
||||
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:
|
||||
return False
|
||||
try:
|
||||
return bcrypt.checkpw(
|
||||
plain.encode("utf-8")[:72],
|
||||
hashed.encode("utf-8"),
|
||||
)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def hash_password(plain: str) -> str:
|
||||
hashed = bcrypt.hashpw(plain.encode("utf-8")[:72], bcrypt.gensalt())
|
||||
return hashed.decode("utf-8")
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def decode_token(token: str) -> dict:
|
||||
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
@@ -0,0 +1,97 @@
|
||||
import calendar
|
||||
from datetime import date, datetime, timezone
|
||||
import json
|
||||
import pytz
|
||||
from .config import settings
|
||||
|
||||
try:
|
||||
KOLKATA = pytz.timezone(settings.TIMEZONE)
|
||||
except Exception:
|
||||
KOLKATA = pytz.timezone("Asia/Kolkata")
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _read_demo_date_from_db(db) -> date | None:
|
||||
from ..models.masters import Setting
|
||||
|
||||
row = db.query(Setting).filter(Setting.key == "demo_as_of_date").first()
|
||||
if row and row.value_json:
|
||||
val = json.loads(row.value_json)
|
||||
if isinstance(val, str) and val.strip():
|
||||
return date.fromisoformat(val.strip())
|
||||
return None
|
||||
|
||||
|
||||
def effective_today(db=None) -> date:
|
||||
"""Returns demo_as_of_date from settings if set, else real today (Asia/Kolkata)."""
|
||||
try:
|
||||
if db is not None:
|
||||
demo_date = _read_demo_date_from_db(db)
|
||||
if demo_date is not None:
|
||||
return demo_date
|
||||
else:
|
||||
from .db import SessionLocal
|
||||
|
||||
with SessionLocal() as session:
|
||||
demo_date = _read_demo_date_from_db(session)
|
||||
if demo_date is not None:
|
||||
return demo_date
|
||||
except Exception:
|
||||
pass
|
||||
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)
|
||||
|
||||
|
||||
def format_datetime(dt: datetime | None) -> str | None:
|
||||
if dt is None:
|
||||
return None
|
||||
local = to_kolkata(dt) if dt.tzinfo else KOLKATA.localize(dt)
|
||||
return local.strftime("%d-%b-%Y %H:%M")
|
||||
|
||||
|
||||
def format_date(d: date | None) -> str | None:
|
||||
if d is None:
|
||||
return 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"
|
||||
minutes = int(minutes)
|
||||
d, rem = divmod(minutes, 1440)
|
||||
h, m = divmod(rem, 60)
|
||||
parts = []
|
||||
if d:
|
||||
parts.append(f"{d}d")
|
||||
if h:
|
||||
parts.append(f"{h}h")
|
||||
if m or not parts:
|
||||
parts.append(f"{m}m")
|
||||
return " ".join(parts)
|
||||
@@ -0,0 +1,145 @@
|
||||
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.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 (
|
||||
ai_reports,
|
||||
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(
|
||||
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
||||
level=logging.INFO,
|
||||
)
|
||||
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.")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if scheduler is not None:
|
||||
scheduler.shutdown(wait=False)
|
||||
logger.info("APScheduler stopped.")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Poona Hospital AMS",
|
||||
version="0.1.0",
|
||||
docs_url="/docs",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.add_exception_handler(CodedHTTPException, coded_http_exception_handler)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
logger.error(f"Unhandled exception: {traceback.format_exc()}")
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={"detail": "An internal error occurred.", "code": "INTERNAL_ERROR"},
|
||||
)
|
||||
|
||||
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(auth.router, prefix="/api")
|
||||
app.include_router(settings.router, prefix="/api")
|
||||
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(ai_reports.router, prefix="/api")
|
||||
app.include_router(search.router, prefix="/api")
|
||||
app.include_router(audit.router, prefix="/api")
|
||||
@@ -0,0 +1,41 @@
|
||||
from .base import Base
|
||||
from .masters import Category, Department, Location, Setting, User, Vendor
|
||||
from .assets import Asset, Contract, InsurancePolicy, Warranty
|
||||
from .maintenance import CalibrationPlan, CalibrationRecord, PMRecord, PMSchedule
|
||||
from .complaints import Complaint, ComplaintEvent
|
||||
from .operations import (
|
||||
DemoEquipment,
|
||||
DepartmentVisit,
|
||||
department_visit_assets,
|
||||
department_visit_complaints,
|
||||
)
|
||||
from .system import AISummary, Attachment, AuditLog, Notification, NotificationRead
|
||||
|
||||
__all__ = [
|
||||
"Base",
|
||||
"Department",
|
||||
"Location",
|
||||
"Category",
|
||||
"Vendor",
|
||||
"User",
|
||||
"Setting",
|
||||
"Asset",
|
||||
"Contract",
|
||||
"Warranty",
|
||||
"InsurancePolicy",
|
||||
"CalibrationPlan",
|
||||
"CalibrationRecord",
|
||||
"PMSchedule",
|
||||
"PMRecord",
|
||||
"Complaint",
|
||||
"ComplaintEvent",
|
||||
"DemoEquipment",
|
||||
"DepartmentVisit",
|
||||
"department_visit_assets",
|
||||
"department_visit_complaints",
|
||||
"Attachment",
|
||||
"Notification",
|
||||
"NotificationRead",
|
||||
"AuditLog",
|
||||
"AISummary",
|
||||
]
|
||||
@@ -0,0 +1,103 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
from sqlalchemy import Boolean, Date, DateTime, Float, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from .base import Base
|
||||
from ..core.time_utils import utc_now
|
||||
|
||||
|
||||
class Asset(Base):
|
||||
__tablename__ = "assets"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
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"), 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)
|
||||
acquisition_mode: Mapped[Optional[str]] = mapped_column(String(20), default="purchased", server_default="purchased", nullable=True)
|
||||
monthly_rent: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
useful_life_years: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
salvage_pct: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
depreciation_method: Mapped[Optional[str]] = mapped_column(String(30), 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", 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)
|
||||
remarks: 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)
|
||||
|
||||
category = relationship("Category")
|
||||
department = relationship("Department")
|
||||
location = relationship("Location")
|
||||
supplier = relationship("Vendor")
|
||||
|
||||
|
||||
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"), 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, index=True, nullable=False)
|
||||
end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
|
||||
contract_value: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
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)
|
||||
remarks: 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)
|
||||
|
||||
asset = relationship("Asset")
|
||||
provider = relationship("Vendor")
|
||||
|
||||
|
||||
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"), index=True, nullable=False)
|
||||
duration_months: Mapped[int] = mapped_column(Integer, 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)
|
||||
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)
|
||||
|
||||
asset = relationship("Asset")
|
||||
provider = relationship("Vendor")
|
||||
|
||||
|
||||
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"), 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, 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)
|
||||
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)
|
||||
|
||||
asset = relationship("Asset")
|
||||
insurer = relationship("Vendor")
|
||||
@@ -0,0 +1,5 @@
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
@@ -0,0 +1,65 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from .base import Base
|
||||
from ..core.time_utils import utc_now
|
||||
|
||||
|
||||
class Complaint(Base):
|
||||
__tablename__ = "complaints"
|
||||
|
||||
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"), 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, 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)
|
||||
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", 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)
|
||||
corrective_action: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
lessons_learned: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
ce_name: Mapped[Optional[str]] = mapped_column(String(150), nullable=True)
|
||||
ce_attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
ce_action_taken: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
spare_required: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
spare_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
spare_cost_estimate: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
repair_cost: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
coverage_tag: Mapped[Optional[str]] = mapped_column(String(30), index=True, nullable=True)
|
||||
coverage_contract_id: Mapped[Optional[int]] = mapped_column(ForeignKey("contracts.id"), nullable=True)
|
||||
coverage_provider_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.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)
|
||||
|
||||
asset = relationship("Asset")
|
||||
|
||||
|
||||
class ComplaintEvent(Base):
|
||||
__tablename__ = "complaint_events"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
complaint_id: Mapped[int] = mapped_column(ForeignKey("complaints.id"), nullable=False)
|
||||
event_type: Mapped[str] = mapped_column(String(60), nullable=False)
|
||||
from_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
to_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
by_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||
note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
complaint = relationship("Complaint")
|
||||
@@ -0,0 +1,96 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
from sqlalchemy import Boolean, Date, DateTime, Float, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from .base import Base
|
||||
from ..core.time_utils import utc_now
|
||||
|
||||
|
||||
class CalibrationPlan(Base):
|
||||
__tablename__ = "calibration_plans"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), unique=True, nullable=False)
|
||||
frequency_months: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
calibrations_per_year: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
agency_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
|
||||
approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
approved_on: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
next_due_date: Mapped[date] = mapped_column(Date, 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)
|
||||
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)
|
||||
|
||||
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"), 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)
|
||||
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
# Only "completed" is persisted; upcoming/due/overdue are computed at read time.
|
||||
status: Mapped[Optional[str]] = mapped_column(String(30), 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)
|
||||
|
||||
asset = relationship("Asset")
|
||||
plan = relationship("CalibrationPlan")
|
||||
agency = relationship("Vendor")
|
||||
|
||||
|
||||
class PMSchedule(Base):
|
||||
__tablename__ = "pm_schedules"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
|
||||
service_mode: Mapped[str] = mapped_column(String(30), nullable=False)
|
||||
frequency_months: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
responsible_team: Mapped[Optional[str]] = mapped_column(String(150), nullable=True)
|
||||
provider_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
|
||||
contract_id: Mapped[Optional[int]] = mapped_column(ForeignKey("contracts.id"), nullable=True)
|
||||
cost_per_visit: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
next_planned_date: Mapped[date] = mapped_column(Date, 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)
|
||||
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)
|
||||
|
||||
asset = relationship("Asset")
|
||||
provider = relationship("Vendor")
|
||||
contract = relationship("Contract")
|
||||
|
||||
|
||||
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"), 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)
|
||||
service_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
rescheduled_to: Mapped[Optional[date]] = mapped_column(Date, 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)
|
||||
|
||||
schedule = relationship("PMSchedule")
|
||||
asset = relationship("Asset")
|
||||
@@ -0,0 +1,85 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from .base import Base
|
||||
from ..core.time_utils import utc_now
|
||||
|
||||
|
||||
class Department(Base):
|
||||
__tablename__ = "departments"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(150), unique=True, nullable=False)
|
||||
code: Mapped[str] = mapped_column(String(30), unique=True, nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
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)
|
||||
|
||||
|
||||
class Location(Base):
|
||||
__tablename__ = "locations"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(150), nullable=False)
|
||||
floor_wing: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
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)
|
||||
|
||||
department: Mapped["Department"] = relationship("Department")
|
||||
|
||||
|
||||
class Category(Base):
|
||||
__tablename__ = "categories"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(150), unique=True, nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
default_useful_life_years: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
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)
|
||||
|
||||
|
||||
class Vendor(Base):
|
||||
__tablename__ = "vendors"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
vendor_type: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
contact_person: Mapped[Optional[str]] = mapped_column(String(150), nullable=True)
|
||||
phone: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
email: Mapped[Optional[str]] = mapped_column(String(150), nullable=True)
|
||||
address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
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)
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(150), nullable=False)
|
||||
email: Mapped[str] = mapped_column(String(200), unique=True, index=True, nullable=False)
|
||||
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)
|
||||
|
||||
department: Mapped[Optional["Department"]] = relationship("Department")
|
||||
|
||||
|
||||
class Setting(Base):
|
||||
__tablename__ = "settings"
|
||||
|
||||
key: Mapped[str] = mapped_column(String(100), primary_key=True)
|
||||
value_json: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
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)
|
||||
@@ -0,0 +1,65 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
from sqlalchemy import Column, Date, DateTime, ForeignKey, Integer, String, Table, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from .base import Base
|
||||
from ..core.time_utils import utc_now
|
||||
|
||||
|
||||
department_visit_assets = Table(
|
||||
"department_visit_assets",
|
||||
Base.metadata,
|
||||
Column("visit_id", ForeignKey("department_visits.id"), primary_key=True),
|
||||
Column("asset_id", ForeignKey("assets.id"), primary_key=True),
|
||||
)
|
||||
|
||||
department_visit_complaints = Table(
|
||||
"department_visit_complaints",
|
||||
Base.metadata,
|
||||
Column("visit_id", ForeignKey("department_visits.id"), primary_key=True),
|
||||
Column("complaint_id", ForeignKey("complaints.id"), primary_key=True),
|
||||
)
|
||||
|
||||
|
||||
class DemoEquipment(Base):
|
||||
__tablename__ = "demo_equipment"
|
||||
|
||||
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"), 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, 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)
|
||||
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)
|
||||
|
||||
supplier = relationship("Vendor")
|
||||
department = relationship("Department")
|
||||
location = relationship("Location")
|
||||
|
||||
|
||||
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"), index=True, nullable=False)
|
||||
visited_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), 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)
|
||||
@@ -0,0 +1,76 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from .base import Base
|
||||
from ..core.time_utils import utc_now
|
||||
|
||||
|
||||
class Attachment(Base):
|
||||
__tablename__ = "attachments"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
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)
|
||||
size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
uploaded_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
uploaded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||
|
||||
|
||||
class Notification(Base):
|
||||
__tablename__ = "notifications"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
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)
|
||||
entity_type: Mapped[str] = mapped_column(String(60), nullable=False)
|
||||
entity_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
due_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
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, index=True, nullable=False)
|
||||
|
||||
|
||||
class NotificationRead(Base):
|
||||
__tablename__ = "notification_reads"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("notification_id", "user_id", name="uq_notification_user_read"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
notification_id: Mapped[int] = mapped_column(ForeignKey("notifications.id"), nullable=False)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
read_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||
|
||||
|
||||
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), 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"), index=True, nullable=True)
|
||||
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False)
|
||||
|
||||
|
||||
class AISummary(Base):
|
||||
__tablename__ = "ai_summaries"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
section: Mapped[str] = mapped_column(String(50), index=True, nullable=False)
|
||||
filters_hash: Mapped[str] = mapped_column(String(64), index=True, nullable=False)
|
||||
data_hash: Mapped[str] = mapped_column(String(64), index=True, nullable=False)
|
||||
source: Mapped[str] = mapped_column(String(30), nullable=False)
|
||||
model: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
validated: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
payload_json: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True)
|
||||
@@ -0,0 +1,45 @@
|
||||
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",
|
||||
"audit",
|
||||
"auth",
|
||||
"calibration",
|
||||
"complaints",
|
||||
"contracts",
|
||||
"dashboard",
|
||||
"demo_equipment",
|
||||
"health",
|
||||
"insurance",
|
||||
"masters",
|
||||
"notifications",
|
||||
"pm",
|
||||
"reports",
|
||||
"search",
|
||||
"settings",
|
||||
"users",
|
||||
"visits",
|
||||
"warranties",
|
||||
]
|
||||
@@ -0,0 +1,599 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import require_roles
|
||||
from ..models import User
|
||||
from ..services.ai_metrics import (
|
||||
compute_breakdown_frequency_from_dataset,
|
||||
compute_comparison_from_dataset,
|
||||
compute_depreciation_from_dataset,
|
||||
compute_efficiency_from_dataset,
|
||||
format_inr,
|
||||
load_ai_dataset,
|
||||
make_metric,
|
||||
resolve_period,
|
||||
)
|
||||
from ..services.ai_narrative import get_or_generate_narrative
|
||||
from ..services.ai_provider import get_ai_status
|
||||
from ..services.ai_suggestions import generate_suggestions
|
||||
from ..services.exports import build_ai_xlsx, build_csv
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(prefix="/ai", tags=["ai"])
|
||||
|
||||
AI_VIEW_ROLES = (
|
||||
Role.system_admin,
|
||||
Role.biomedical,
|
||||
Role.management,
|
||||
Role.coordinator,
|
||||
)
|
||||
|
||||
SECTION_ALIASES: dict[str, str] = {
|
||||
"summary": "summary",
|
||||
"comparison": "comparison",
|
||||
"depreciation": "depreciation",
|
||||
"efficiency": "efficiency",
|
||||
"breakdown-frequency": "breakdown_frequency",
|
||||
"breakdown_frequency": "breakdown_frequency",
|
||||
}
|
||||
|
||||
|
||||
class RegenerateNarrativeRequest(BaseModel):
|
||||
section: str
|
||||
filters: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
def _ai_query_params(
|
||||
period: Literal["3m", "6m", "12m", "custom"] = Query("12m"),
|
||||
date_from: Optional[date] = Query(None),
|
||||
date_to: Optional[date] = Query(None),
|
||||
department_id: Optional[int] = Query(None),
|
||||
category_id: Optional[int] = Query(None),
|
||||
) -> dict[str, Any]:
|
||||
if period == "custom" and date_from and date_to and date_from > date_to:
|
||||
raise HTTPException(status_code=422, detail="date_from must be on or before date_to.")
|
||||
return {
|
||||
"period": period,
|
||||
"date_from": date_from,
|
||||
"date_to": date_to,
|
||||
"department_id": department_id,
|
||||
"category_id": category_id,
|
||||
}
|
||||
|
||||
|
||||
def _parse_optional_date(val: Any) -> Optional[date]:
|
||||
if val is None or val == "":
|
||||
return None
|
||||
if isinstance(val, date):
|
||||
return val
|
||||
try:
|
||||
return date.fromisoformat(str(val)[:10])
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=422, detail=f"Invalid date value: {val}")
|
||||
|
||||
|
||||
def _filters_echo(dataset: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
|
||||
echo: dict[str, Any] = {
|
||||
"period": params.get("period", "12m"),
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
}
|
||||
if params.get("department_id") is not None:
|
||||
echo["department_id"] = int(params["department_id"])
|
||||
if params.get("category_id") is not None:
|
||||
echo["category_id"] = int(params["category_id"])
|
||||
return echo
|
||||
|
||||
|
||||
def _load_scoped_dataset(db: Session, user: User, params: dict[str, Any]) -> dict[str, Any]:
|
||||
period = str(params.get("period") or "12m")
|
||||
if period not in ("3m", "6m", "12m", "custom"):
|
||||
raise HTTPException(status_code=422, detail="period must be one of 3m, 6m, 12m, custom.")
|
||||
d_from = _parse_optional_date(params.get("date_from"))
|
||||
d_to = _parse_optional_date(params.get("date_to"))
|
||||
if period == "custom" and d_from and d_to and d_from > d_to:
|
||||
raise HTTPException(status_code=422, detail="date_from must be on or before date_to.")
|
||||
dept_id = int(params["department_id"]) if params.get("department_id") not in (None, "") else None
|
||||
cat_id = int(params["category_id"]) if params.get("category_id") not in (None, "") else None
|
||||
|
||||
p_start, p_end = resolve_period(db, period=period, date_from=d_from, date_to=d_to)
|
||||
return load_ai_dataset(
|
||||
db,
|
||||
user,
|
||||
p_start,
|
||||
p_end,
|
||||
department_id=dept_id,
|
||||
category_id=cat_id,
|
||||
)
|
||||
|
||||
|
||||
def _build_section_bundle(
|
||||
db: Session,
|
||||
user: User,
|
||||
canonical_section: str,
|
||||
params: dict[str, Any],
|
||||
*,
|
||||
force_regenerate: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
dataset = _load_scoped_dataset(db, user, params)
|
||||
echo = _filters_echo(dataset, params)
|
||||
|
||||
if canonical_section == "comparison":
|
||||
data = compute_comparison_from_dataset(dataset)
|
||||
narrative = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
echo,
|
||||
data["metrics"],
|
||||
section_data=data,
|
||||
user_id=user.id,
|
||||
force_regenerate=force_regenerate,
|
||||
)
|
||||
return {
|
||||
**data,
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"narrative": narrative,
|
||||
}
|
||||
|
||||
if canonical_section == "depreciation":
|
||||
data = compute_depreciation_from_dataset(dataset)
|
||||
narrative = get_or_generate_narrative(
|
||||
db,
|
||||
"depreciation",
|
||||
echo,
|
||||
data["metrics"],
|
||||
section_data=data,
|
||||
user_id=user.id,
|
||||
force_regenerate=force_regenerate,
|
||||
)
|
||||
return {
|
||||
**data,
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"narrative": narrative,
|
||||
}
|
||||
|
||||
if canonical_section == "efficiency":
|
||||
data = compute_efficiency_from_dataset(dataset)
|
||||
narrative = get_or_generate_narrative(
|
||||
db,
|
||||
"efficiency",
|
||||
echo,
|
||||
data["metrics"],
|
||||
section_data=data,
|
||||
user_id=user.id,
|
||||
force_regenerate=force_regenerate,
|
||||
)
|
||||
return {
|
||||
**data,
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"narrative": narrative,
|
||||
}
|
||||
|
||||
if canonical_section == "breakdown_frequency":
|
||||
data = compute_breakdown_frequency_from_dataset(dataset)
|
||||
narrative = get_or_generate_narrative(
|
||||
db,
|
||||
"breakdown_frequency",
|
||||
echo,
|
||||
data["metrics"],
|
||||
section_data=data,
|
||||
user_id=user.id,
|
||||
force_regenerate=force_regenerate,
|
||||
)
|
||||
return {
|
||||
**data,
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"narrative": narrative,
|
||||
}
|
||||
|
||||
# Whole-report summary
|
||||
cmp_data = compute_comparison_from_dataset(dataset)
|
||||
dep_data = compute_depreciation_from_dataset(dataset)
|
||||
eff_data = compute_efficiency_from_dataset(dataset)
|
||||
bf_data = compute_breakdown_frequency_from_dataset(dataset)
|
||||
sug_data = generate_suggestions(
|
||||
dataset,
|
||||
comparison=cmp_data,
|
||||
depreciation_data=dep_data,
|
||||
efficiency_data=eff_data,
|
||||
breakdown_data=bf_data,
|
||||
)
|
||||
|
||||
# Collect headline metrics from all 4 sections + suggestion count
|
||||
headline_ids = {
|
||||
"m_cmp_horizon_years",
|
||||
"m_cmp_latest_count",
|
||||
"m_cmp_inhouse_wins",
|
||||
"m_cmp_outsourced_wins",
|
||||
"m_cmp_rent_wins",
|
||||
"m_dep_total_purchase_value",
|
||||
"m_dep_total_book_value",
|
||||
"m_dep_total_accumulated",
|
||||
"m_dep_total_maintenance",
|
||||
"m_dep_fully_depreciated_count",
|
||||
"m_dep_review_flag_count",
|
||||
"m_eff_avg_uptime",
|
||||
"m_eff_mttr",
|
||||
"m_eff_mtbf",
|
||||
"m_eff_pm_compliance",
|
||||
"m_eff_score_overall",
|
||||
"m_bf_total_breakdowns",
|
||||
"m_bf_assets_in_scope",
|
||||
"m_bf_avg_per_equipment",
|
||||
"m_bf_repeat_failure_assets",
|
||||
}
|
||||
summary_metrics: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
for sec_obj in (cmp_data, dep_data, eff_data, bf_data):
|
||||
for m in sec_obj.get("metrics", []):
|
||||
if m["id"] in headline_ids and m["id"] not in seen:
|
||||
summary_metrics.append(m)
|
||||
seen.add(m["id"])
|
||||
summary_metrics.append(
|
||||
make_metric("m_sug_total_count", "Total Advisory Suggestions", len(sug_data["suggestions"]), "count")
|
||||
)
|
||||
|
||||
narrative = get_or_generate_narrative(
|
||||
db,
|
||||
"summary",
|
||||
echo,
|
||||
summary_metrics,
|
||||
suggestions=sug_data["suggestions"],
|
||||
user_id=user.id,
|
||||
force_regenerate=force_regenerate,
|
||||
)
|
||||
|
||||
how_calculated = {
|
||||
"formulas": (
|
||||
cmp_data["how_calculated"]["formulas"]
|
||||
+ dep_data["how_calculated"]["formulas"]
|
||||
+ eff_data["how_calculated"]["formulas"]
|
||||
+ bf_data["how_calculated"]["formulas"]
|
||||
),
|
||||
"weights": eff_data["how_calculated"].get("weights", {}),
|
||||
"settings_used": {
|
||||
**cmp_data["how_calculated"].get("settings_used", {}),
|
||||
**dep_data["how_calculated"].get("settings_used", {}),
|
||||
**eff_data["how_calculated"].get("settings_used", {}),
|
||||
**bf_data["how_calculated"].get("settings_used", {}),
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
"section": "summary",
|
||||
"title": "AI Report Executive Summary",
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"sections": {
|
||||
"comparison": cmp_data["summary"],
|
||||
"depreciation": dep_data["summary"],
|
||||
"efficiency": eff_data["summary"],
|
||||
"breakdown_frequency": bf_data["summary"],
|
||||
},
|
||||
"suggestions": sug_data["suggestions"],
|
||||
"suggestions_evidence": sug_data["evidence"],
|
||||
"metrics": summary_metrics,
|
||||
"narrative": narrative,
|
||||
"how_calculated": how_calculated,
|
||||
}
|
||||
|
||||
|
||||
def _build_export_payload(canonical_section: str, bundle: dict[str, Any]) -> dict[str, Any]:
|
||||
if canonical_section == "comparison":
|
||||
columns = [
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "asset_name", "label": "Equipment Name"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "category_name", "label": "Category"},
|
||||
{"key": "purchase_value", "label": "Purchase Price"},
|
||||
{"key": "in_house_display", "label": "In-House Cost"},
|
||||
{"key": "outsourced_display", "label": "Outsourced Cost"},
|
||||
{"key": "rent_display", "label": "Rent Cost"},
|
||||
{"key": "lowest_scenario_label", "label": "Lowest Option"},
|
||||
{"key": "savings_vs_next", "label": "Difference vs Next"},
|
||||
]
|
||||
rows = []
|
||||
for r in bundle["rows"]:
|
||||
rows.append(
|
||||
{
|
||||
"asset_code": r["asset_code"],
|
||||
"asset_name": r["asset_name"],
|
||||
"department_name": r["department_name"],
|
||||
"category_name": r["category_name"],
|
||||
"purchase_value": r["purchase_value"] if r["purchase_value"] is not None else "Insufficient data: purchase_value",
|
||||
"in_house_display": r["in_house_cost"] if r["in_house_cost"] is not None else (r["in_house_reason"] or "Insufficient data"),
|
||||
"outsourced_display": r["outsourced_cost"] if r["outsourced_cost"] is not None else (r["outsourced_reason"] or "Insufficient data"),
|
||||
"rent_display": r["rent_cost"] if r["rent_cost"] is not None else (r["rent_reason"] or "Insufficient data"),
|
||||
"lowest_scenario_label": r["lowest_scenario_label"] or "Insufficient data",
|
||||
"savings_vs_next": r["savings_vs_next"] if r["savings_vs_next"] is not None else "—",
|
||||
}
|
||||
)
|
||||
return {
|
||||
"title": bundle["title"],
|
||||
"filters_applied": bundle["filters_applied"],
|
||||
"summary": bundle["summary"],
|
||||
"columns": columns,
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
if canonical_section == "depreciation":
|
||||
columns = [
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "asset_name", "label": "Equipment Name"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "category_name", "label": "Category"},
|
||||
{"key": "acquisition_mode", "label": "Mode"},
|
||||
{"key": "purchase_value", "label": "Purchase Value"},
|
||||
{"key": "method", "label": "Method"},
|
||||
{"key": "book_value", "label": "Book Value"},
|
||||
{"key": "accumulated_depreciation", "label": "Accumulated Depreciation"},
|
||||
{"key": "maintenance_cost", "label": "Maintenance Cost"},
|
||||
{"key": "maintenance_ratio_pct", "label": "Maintenance Ratio %"},
|
||||
{"key": "lifetime_cost", "label": "Lifetime Cost"},
|
||||
{"key": "review_flag", "label": "Replacement Review"},
|
||||
]
|
||||
rows = []
|
||||
for r in bundle["rows"]:
|
||||
ratio_pct = round(r["maintenance_ratio"] * 100.0, 1) if r["maintenance_ratio"] is not None else None
|
||||
rows.append(
|
||||
{
|
||||
"asset_code": r["asset_code"],
|
||||
"asset_name": r["asset_name"],
|
||||
"department_name": r["department_name"],
|
||||
"category_name": r["category_name"],
|
||||
"acquisition_mode": r["acquisition_mode"],
|
||||
"purchase_value": r["purchase_value"] if r["purchase_value"] is not None else (r["depreciation_reason"] or "Insufficient data"),
|
||||
"method": r["method"] or (r["depreciation_reason"] or "N/A"),
|
||||
"book_value": r["book_value"] if r["book_value"] is not None else (r["depreciation_reason"] or "N/A"),
|
||||
"accumulated_depreciation": r["accumulated_depreciation"] if r["accumulated_depreciation"] is not None else "N/A",
|
||||
"maintenance_cost": r["maintenance_cost"],
|
||||
"maintenance_ratio_pct": ratio_pct if ratio_pct is not None else "N/A",
|
||||
"lifetime_cost": r["lifetime_cost"] if r["lifetime_cost"] is not None else "N/A",
|
||||
"review_flag": bool(r["review_flag"]),
|
||||
}
|
||||
)
|
||||
return {
|
||||
"title": bundle["title"],
|
||||
"filters_applied": bundle["filters_applied"],
|
||||
"summary": bundle["summary"],
|
||||
"columns": columns,
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
if canonical_section == "efficiency":
|
||||
columns = [
|
||||
{"key": "group_type", "label": "Group Type"},
|
||||
{"key": "group", "label": "Department / Category"},
|
||||
{"key": "assets_in_scope", "label": "Assets"},
|
||||
{"key": "uptime_pct", "label": "Uptime %"},
|
||||
{"key": "pm_compliance_pct", "label": "PM Compliance %"},
|
||||
{"key": "response_score", "label": "Response Score"},
|
||||
{"key": "repeat_free_score", "label": "Repeat-Free Score"},
|
||||
{"key": "mttr_hours", "label": "MTTR (hrs)"},
|
||||
{"key": "mtbf_display", "label": "MTBF (hrs)"},
|
||||
{"key": "efficiency_score", "label": "Efficiency Score"},
|
||||
]
|
||||
rows = []
|
||||
for r in bundle["rows"]:
|
||||
rows.append(
|
||||
{
|
||||
"group_type": str(r.get("group_type", "")).title(),
|
||||
"group": r.get("group", ""),
|
||||
"assets_in_scope": r.get("assets_in_scope", 0),
|
||||
"uptime_pct": r.get("uptime_pct"),
|
||||
"pm_compliance_pct": r.get("pm_compliance_pct"),
|
||||
"response_score": r.get("response_score"),
|
||||
"repeat_free_score": r.get("repeat_free_score"),
|
||||
"mttr_hours": r.get("mttr_hours") if r.get("mttr_hours") is not None else "—",
|
||||
"mtbf_display": r.get("mtbf_hours") if r.get("mtbf_hours") is not None else "No failures",
|
||||
"efficiency_score": r.get("efficiency_score"),
|
||||
}
|
||||
)
|
||||
return {
|
||||
"title": bundle["title"],
|
||||
"filters_applied": bundle["filters_applied"],
|
||||
"summary": bundle["summary"],
|
||||
"columns": columns,
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
if canonical_section == "breakdown_frequency":
|
||||
columns = [
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "asset_name", "label": "Equipment Name"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "category_name", "label": "Category"},
|
||||
{"key": "breakdown_count", "label": "Breakdowns in Period"},
|
||||
{"key": "avg_downtime_hours", "label": "Avg Downtime (hrs)"},
|
||||
{"key": "repeat_window_count", "label": "Breakdowns in Repeat Window"},
|
||||
{"key": "repeat_failure", "label": "Repeat Failure"},
|
||||
]
|
||||
return {
|
||||
"title": bundle["title"],
|
||||
"filters_applied": bundle["filters_applied"],
|
||||
"summary": bundle["summary"],
|
||||
"columns": columns,
|
||||
"rows": bundle["rows"],
|
||||
}
|
||||
|
||||
# summary
|
||||
columns = [
|
||||
{"key": "metric_id", "label": "Metric ID"},
|
||||
{"key": "label", "label": "Headline Metric"},
|
||||
{"key": "formatted", "label": "Value"},
|
||||
]
|
||||
rows = [
|
||||
{"metric_id": m["id"], "label": m["label"], "formatted": m["formatted"]}
|
||||
for m in bundle.get("metrics", [])
|
||||
]
|
||||
return {
|
||||
"title": bundle["title"],
|
||||
"filters_applied": bundle["filters_applied"],
|
||||
"summary": {
|
||||
"suggestions": len(bundle.get("suggestions", [])),
|
||||
"headline_metrics": len(rows),
|
||||
},
|
||||
"columns": columns,
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
def ai_status(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
status = get_ai_status(db)
|
||||
# Only system_admin sees provider/model internals; other roles get only enabled+reachable.
|
||||
if current_user.role != Role.system_admin:
|
||||
return {
|
||||
"enabled": status["enabled"],
|
||||
"ai_enabled_setting": status["ai_enabled_setting"],
|
||||
"provider": None,
|
||||
"model": None,
|
||||
"reachable": status["reachable"],
|
||||
}
|
||||
return status
|
||||
|
||||
|
||||
@router.get("/summary")
|
||||
def ai_summary(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
return _build_section_bundle(db, current_user, "summary", params)
|
||||
|
||||
|
||||
@router.get("/comparison")
|
||||
def ai_comparison(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
return _build_section_bundle(db, current_user, "comparison", params)
|
||||
|
||||
|
||||
@router.get("/depreciation")
|
||||
def ai_depreciation(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
return _build_section_bundle(db, current_user, "depreciation", params)
|
||||
|
||||
|
||||
@router.get("/efficiency")
|
||||
def ai_efficiency(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
return _build_section_bundle(db, current_user, "efficiency", params)
|
||||
|
||||
|
||||
@router.get("/breakdown-frequency")
|
||||
def ai_breakdown_frequency(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
return _build_section_bundle(db, current_user, "breakdown_frequency", params)
|
||||
|
||||
|
||||
@router.get("/suggestions")
|
||||
def ai_suggestions(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
dataset = _load_scoped_dataset(db, current_user, params)
|
||||
echo = _filters_echo(dataset, params)
|
||||
res = generate_suggestions(dataset)
|
||||
return {
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"total": len(res["suggestions"]),
|
||||
"suggestions": res["suggestions"],
|
||||
"evidence": res["evidence"],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/narrative/regenerate")
|
||||
def ai_regenerate_narrative(
|
||||
body: RegenerateNarrativeRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
canonical = SECTION_ALIASES.get((body.section or "").strip().lower())
|
||||
if not canonical:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Unknown AI section '{body.section}'. Expected one of: summary, comparison, depreciation, efficiency, breakdown-frequency.",
|
||||
)
|
||||
params = {
|
||||
"period": body.filters.get("period", "12m"),
|
||||
"date_from": body.filters.get("date_from"),
|
||||
"date_to": body.filters.get("date_to"),
|
||||
"department_id": body.filters.get("department_id"),
|
||||
"category_id": body.filters.get("category_id"),
|
||||
}
|
||||
bundle = _build_section_bundle(db, current_user, canonical, params, force_regenerate=True)
|
||||
return {
|
||||
"section": canonical,
|
||||
"narrative": bundle["narrative"],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{section}/export")
|
||||
def ai_export_section(
|
||||
section: str,
|
||||
format: Literal["xlsx", "csv"] = Query("xlsx"),
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
canonical = SECTION_ALIASES.get((section or "").strip().lower())
|
||||
if not canonical:
|
||||
raise HTTPException(status_code=404, detail=f"Unknown AI report section '{section}'.")
|
||||
|
||||
bundle = _build_section_bundle(db, current_user, canonical, params)
|
||||
export_payload = _build_export_payload(canonical, bundle)
|
||||
if format == "csv":
|
||||
buf = build_csv(export_payload)
|
||||
media_type = "text/csv; charset=utf-8"
|
||||
else:
|
||||
buf = build_ai_xlsx(
|
||||
export_payload,
|
||||
evidence=bundle.get("metrics", []),
|
||||
how_calculated=bundle.get("how_calculated", {}),
|
||||
)
|
||||
media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
filename = f"ai-{canonical.replace('_', '-')}.{format}"
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{filename}"',
|
||||
},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,967 @@
|
||||
from datetime import date
|
||||
from typing import Any, Optional
|
||||
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
|
||||
|
||||
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, format_date
|
||||
from ..models import (
|
||||
Asset,
|
||||
Attachment,
|
||||
CalibrationPlan,
|
||||
CalibrationRecord,
|
||||
Category,
|
||||
Complaint,
|
||||
Contract,
|
||||
Department,
|
||||
InsurancePolicy,
|
||||
Location,
|
||||
PMRecord,
|
||||
PMSchedule,
|
||||
User,
|
||||
Vendor,
|
||||
Warranty,
|
||||
)
|
||||
from ..schemas.assets import (
|
||||
AssetCreate,
|
||||
AssetListOut,
|
||||
AssetLookupListOut,
|
||||
AssetLookupOut,
|
||||
AssetOut,
|
||||
AssetOverviewOut,
|
||||
AssetUpdate,
|
||||
AttachmentSummaryOut,
|
||||
CalibrationPlanSummaryOut,
|
||||
CalibrationRecordSummaryOut,
|
||||
ComplaintSummaryOut,
|
||||
ContractSummaryOut,
|
||||
CoverageOut,
|
||||
InsuranceSummaryOut,
|
||||
PMRecordSummaryOut,
|
||||
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.coverage import get_coverage, get_coverage_map
|
||||
from ..services.permissions import Role, maybe_strip_costs_response
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/assets", tags=["assets"])
|
||||
|
||||
COORDINATOR_ALLOWED_FIELDS = {"requires_calibration", "insurance_applicable", "remarks"}
|
||||
|
||||
|
||||
def _lead_settings(db: Session) -> dict[str, int]:
|
||||
return {
|
||||
"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",
|
||||
get_setting_value(db, "calibration_lead_days", 15),
|
||||
)
|
||||
),
|
||||
"pm": int(get_setting_value(db, "pm_due_window_days")),
|
||||
"pm_in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)),
|
||||
"pm_outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
|
||||
"red": int(get_setting_value(db, "red_threshold_days", 7)),
|
||||
}
|
||||
|
||||
|
||||
def _preload_latest_relations(db: Session, asset_ids: list[int]) -> dict[str, dict[int, Any]]:
|
||||
if not asset_ids:
|
||||
return {
|
||||
"warranty": {},
|
||||
"contract": {},
|
||||
"insurance": {},
|
||||
"cal_plan": {},
|
||||
"cal_open_rec": {},
|
||||
"cal_last_rec": {},
|
||||
}
|
||||
|
||||
warranties: dict[int, Warranty] = {}
|
||||
for w in (
|
||||
db.query(Warranty)
|
||||
.filter(Warranty.asset_id.in_(asset_ids))
|
||||
.order_by(Warranty.end_date.desc(), Warranty.id.desc())
|
||||
.all()
|
||||
):
|
||||
if w.asset_id not in warranties:
|
||||
warranties[w.asset_id] = w
|
||||
|
||||
contracts: dict[int, Contract] = {}
|
||||
for c in (
|
||||
db.query(Contract)
|
||||
.filter(Contract.asset_id.in_(asset_ids), Contract.is_superseded.is_(False))
|
||||
.order_by(Contract.end_date.desc(), Contract.id.desc())
|
||||
.all()
|
||||
):
|
||||
if c.asset_id not in contracts:
|
||||
contracts[c.asset_id] = c
|
||||
|
||||
insurances: dict[int, InsurancePolicy] = {}
|
||||
for ins in (
|
||||
db.query(InsurancePolicy)
|
||||
.filter(InsurancePolicy.asset_id.in_(asset_ids))
|
||||
.order_by(InsurancePolicy.end_date.desc(), InsurancePolicy.id.desc())
|
||||
.all()
|
||||
):
|
||||
if ins.asset_id not in insurances:
|
||||
insurances[ins.asset_id] = ins
|
||||
|
||||
cal_plans: dict[int, CalibrationPlan] = {
|
||||
p.asset_id: p
|
||||
for p in db.query(CalibrationPlan)
|
||||
.filter(CalibrationPlan.asset_id.in_(asset_ids), CalibrationPlan.is_active.is_(True))
|
||||
.all()
|
||||
}
|
||||
|
||||
cal_open_recs: dict[int, CalibrationRecord] = {}
|
||||
cal_last_recs: dict[int, CalibrationRecord] = {}
|
||||
for rec in (
|
||||
db.query(CalibrationRecord)
|
||||
.filter(CalibrationRecord.asset_id.in_(asset_ids))
|
||||
.order_by(CalibrationRecord.due_date.desc(), CalibrationRecord.id.desc())
|
||||
.all()
|
||||
):
|
||||
if rec.asset_id not in cal_last_recs:
|
||||
cal_last_recs[rec.asset_id] = rec
|
||||
if rec.status != "completed" and rec.asset_id not in cal_open_recs:
|
||||
cal_open_recs[rec.asset_id] = rec
|
||||
|
||||
return {
|
||||
"warranty": warranties,
|
||||
"contract": contracts,
|
||||
"insurance": insurances,
|
||||
"cal_plan": cal_plans,
|
||||
"cal_open_rec": cal_open_recs,
|
||||
"cal_last_rec": cal_last_recs,
|
||||
}
|
||||
|
||||
|
||||
def _derive_asset_fields(
|
||||
asset: Asset,
|
||||
rels: dict[str, dict[int, Any]],
|
||||
today: date,
|
||||
leads: dict[str, int],
|
||||
) -> dict[str, Any]:
|
||||
w = rels["warranty"].get(asset.id)
|
||||
if w:
|
||||
w_status, w_sev = coverage_status(w.start_date, w.end_date, today, leads["warranty"], leads["red"])
|
||||
w_end = w.end_date
|
||||
else:
|
||||
w_status, w_sev, w_end = "none", "none", None
|
||||
|
||||
c = rels["contract"].get(asset.id)
|
||||
if c:
|
||||
c_status, c_sev = coverage_status(c.start_date, c.end_date, today, leads["contract"], leads["red"])
|
||||
c_type, c_end = c.contract_type, c.end_date
|
||||
else:
|
||||
c_status, c_sev, c_type, c_end = "none", "none", None, None
|
||||
|
||||
ins = rels["insurance"].get(asset.id)
|
||||
if ins:
|
||||
ins_status, _ = coverage_status(ins.start_date, ins.end_date, today, leads["insurance"], leads["red"])
|
||||
ins_end = ins.end_date
|
||||
else:
|
||||
ins_status, ins_end = "none", None
|
||||
|
||||
plan = rels["cal_plan"].get(asset.id)
|
||||
open_rec = rels["cal_open_rec"].get(asset.id)
|
||||
last_rec = rels["cal_last_rec"].get(asset.id)
|
||||
if open_rec is not None:
|
||||
cal_due = open_rec.due_date
|
||||
cal_status, cal_sev = compute_schedule_status(cal_due, open_rec.status, today, leads["calibration"], leads["red"])
|
||||
elif plan is not None:
|
||||
cal_due = plan.next_due_date
|
||||
cal_status, cal_sev = compute_schedule_status(cal_due, None, today, leads["calibration"], leads["red"])
|
||||
elif last_rec is not None:
|
||||
cal_due = last_rec.due_date
|
||||
cal_status, cal_sev = compute_schedule_status(cal_due, last_rec.status, today, leads["calibration"], leads["red"])
|
||||
else:
|
||||
cal_status, cal_due, cal_sev = "none", None, "none"
|
||||
|
||||
return {
|
||||
"warranty_status": w_status,
|
||||
"warranty_end_date": w_end,
|
||||
"warranty_severity": w_sev,
|
||||
"contract_status": c_status,
|
||||
"contract_type": c_type,
|
||||
"contract_end_date": c_end,
|
||||
"contract_severity": c_sev,
|
||||
"calibration_status": cal_status,
|
||||
"calibration_due_date": cal_due,
|
||||
"calibration_severity": cal_sev,
|
||||
"insurance_status": ins_status,
|
||||
"insurance_end_date": ins_end,
|
||||
"_contract_obj": c,
|
||||
"_insurance_obj": ins,
|
||||
}
|
||||
|
||||
|
||||
def _to_asset_out(
|
||||
asset: Asset,
|
||||
rels: dict[str, dict[int, Any]],
|
||||
today: date,
|
||||
leads: dict[str, int],
|
||||
cov: dict[str, Any] | None = None,
|
||||
) -> AssetOut:
|
||||
d = _derive_asset_fields(asset, rels, today, leads)
|
||||
cov_out = CoverageOut(**cov) if cov is not None else None
|
||||
return AssetOut(
|
||||
id=asset.id,
|
||||
asset_code=asset.asset_code,
|
||||
serial_no=asset.serial_no,
|
||||
name=asset.name,
|
||||
category_id=asset.category_id,
|
||||
category_name=asset.category.name if asset.category else None,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
location_id=asset.location_id,
|
||||
location_name=asset.location.name if asset.location else None,
|
||||
supplier_id=asset.supplier_id,
|
||||
supplier_name=asset.supplier.name if asset.supplier else None,
|
||||
purchase_value=asset.purchase_value,
|
||||
acquisition_mode=asset.acquisition_mode or "purchased",
|
||||
monthly_rent=asset.monthly_rent,
|
||||
useful_life_years=asset.useful_life_years,
|
||||
salvage_pct=asset.salvage_pct,
|
||||
depreciation_method=asset.depreciation_method,
|
||||
purchase_date=asset.purchase_date,
|
||||
installation_date=asset.installation_date,
|
||||
status=asset.status,
|
||||
criticality=asset.criticality,
|
||||
requires_calibration=asset.requires_calibration,
|
||||
insurance_applicable=asset.insurance_applicable,
|
||||
remarks=asset.remarks,
|
||||
warranty_status=d["warranty_status"],
|
||||
warranty_end_date=d["warranty_end_date"],
|
||||
warranty_severity=d["warranty_severity"],
|
||||
contract_status=d["contract_status"],
|
||||
contract_type=d["contract_type"],
|
||||
contract_end_date=d["contract_end_date"],
|
||||
contract_severity=d["contract_severity"],
|
||||
calibration_status=d["calibration_status"],
|
||||
calibration_due_date=d["calibration_due_date"],
|
||||
calibration_severity=d["calibration_severity"],
|
||||
insurance_status=d["insurance_status"],
|
||||
insurance_end_date=d["insurance_end_date"],
|
||||
coverage_tag=cov_out.tag if cov_out else "out_of_contract",
|
||||
coverage=cov_out,
|
||||
created_at=asset.created_at,
|
||||
updated_at=asset.updated_at,
|
||||
)
|
||||
|
||||
|
||||
def _validate_asset_fks(
|
||||
db: Session,
|
||||
category_id: int | None = None,
|
||||
department_id: int | None = None,
|
||||
location_id: int | None = None,
|
||||
supplier_id: int | None = None,
|
||||
) -> None:
|
||||
if category_id is not None and not db.query(Category.id).filter(Category.id == category_id).first():
|
||||
raise HTTPException(status_code=404, detail="Category not found.")
|
||||
if department_id is not None and not db.query(Department.id).filter(Department.id == department_id).first():
|
||||
raise HTTPException(status_code=404, detail="Department not found.")
|
||||
if location_id is not None and not db.query(Location.id).filter(Location.id == location_id).first():
|
||||
raise HTTPException(status_code=404, detail="Location not found.")
|
||||
if supplier_id is not None and not db.query(Vendor.id).filter(Vendor.id == supplier_id).first():
|
||||
raise HTTPException(status_code=404, detail="Supplier vendor not found.")
|
||||
|
||||
|
||||
def _load_asset_with_joins(db: Session, asset_id: int) -> Asset | None:
|
||||
return (
|
||||
db.query(Asset)
|
||||
.options(
|
||||
joinedload(Asset.category),
|
||||
joinedload(Asset.department),
|
||||
joinedload(Asset.location),
|
||||
joinedload(Asset.supplier),
|
||||
)
|
||||
.filter(Asset.id == asset_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
@router.get("/lookup", response_model=AssetLookupListOut)
|
||||
def lookup_assets(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
limit: int = Query(25, ge=1, le=100),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Asset).options(
|
||||
joinedload(Asset.category),
|
||||
joinedload(Asset.department),
|
||||
joinedload(Asset.location),
|
||||
joinedload(Asset.supplier),
|
||||
)
|
||||
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 q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Asset.serial_no.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(Asset.asset_code.asc()).limit(limit).all()
|
||||
asset_ids = [a.id for a in rows]
|
||||
rels = _preload_latest_relations(db, asset_ids)
|
||||
today = effective_today(db)
|
||||
leads = _lead_settings(db)
|
||||
cov_map = get_coverage_map(db, asset_ids, today)
|
||||
|
||||
items: list[AssetLookupOut] = []
|
||||
for a in rows:
|
||||
d = _derive_asset_fields(a, rels, today, leads)
|
||||
cov = cov_map.get(a.id)
|
||||
cov_out = CoverageOut(**cov) if cov is not None else None
|
||||
c_obj = d["_contract_obj"]
|
||||
ins_obj = d["_insurance_obj"]
|
||||
if c_obj is not None:
|
||||
c_summary = f"{c_obj.contract_type} ({d['contract_status']}, till {format_date(c_obj.end_date)})"
|
||||
else:
|
||||
c_summary = "No active contract"
|
||||
if ins_obj is not None:
|
||||
ins_summary = f"Policy {ins_obj.policy_no} ({d['insurance_status']}, till {format_date(ins_obj.end_date)})"
|
||||
else:
|
||||
ins_summary = "No policy"
|
||||
|
||||
items.append(
|
||||
AssetLookupOut(
|
||||
id=a.id,
|
||||
asset_code=a.asset_code,
|
||||
serial_no=a.serial_no,
|
||||
name=a.name,
|
||||
category_id=a.category_id,
|
||||
category_name=a.category.name if a.category else None,
|
||||
department_id=a.department_id,
|
||||
department_name=a.department.name if a.department else None,
|
||||
location_id=a.location_id,
|
||||
location_name=a.location.name if a.location else None,
|
||||
supplier_id=a.supplier_id,
|
||||
supplier_name=a.supplier.name if a.supplier else None,
|
||||
status=a.status,
|
||||
criticality=a.criticality,
|
||||
requires_calibration=a.requires_calibration,
|
||||
insurance_applicable=a.insurance_applicable,
|
||||
warranty_status=d["warranty_status"],
|
||||
warranty_end_date=d["warranty_end_date"],
|
||||
contract_status=d["contract_status"],
|
||||
contract_type=d["contract_type"],
|
||||
contract_end_date=d["contract_end_date"],
|
||||
contract_summary=c_summary,
|
||||
insurance_status=d["insurance_status"],
|
||||
insurance_end_date=d["insurance_end_date"],
|
||||
insurance_summary=ins_summary,
|
||||
coverage_tag=cov_out.tag if cov_out else "out_of_contract",
|
||||
coverage=cov_out,
|
||||
)
|
||||
)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
@router.get("", response_model=AssetListOut)
|
||||
def list_assets(
|
||||
q: Optional[str] = None,
|
||||
department_id: Optional[int] = None,
|
||||
category_id: Optional[int] = None,
|
||||
location_id: Optional[int] = None,
|
||||
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),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
sort: str = "id",
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Asset).options(
|
||||
joinedload(Asset.category),
|
||||
joinedload(Asset.department),
|
||||
joinedload(Asset.location),
|
||||
joinedload(Asset.supplier),
|
||||
)
|
||||
|
||||
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 category_id is not None:
|
||||
query = query.filter(Asset.category_id == category_id)
|
||||
if location_id is not None:
|
||||
query = query.filter(Asset.location_id == location_id)
|
||||
if supplier_id is not None:
|
||||
query = query.filter(Asset.supplier_id == supplier_id)
|
||||
if status_filter:
|
||||
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()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Asset.serial_no.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
sort_desc = sort.startswith("-")
|
||||
sort_key = sort.lstrip("-")
|
||||
sort_col_map = {
|
||||
"id": Asset.id,
|
||||
"asset_code": Asset.asset_code,
|
||||
"name": Asset.name,
|
||||
"serial_no": Asset.serial_no,
|
||||
"status": Asset.status,
|
||||
"criticality": Asset.criticality,
|
||||
"purchase_date": Asset.purchase_date,
|
||||
"purchase_value": Asset.purchase_value,
|
||||
}
|
||||
col = sort_col_map.get(sort_key, Asset.id)
|
||||
query = query.order_by(col.desc() if sort_desc else col.asc())
|
||||
|
||||
rows = query.all()
|
||||
asset_ids = [a.id for a in rows]
|
||||
rels = _preload_latest_relations(db, asset_ids)
|
||||
today = effective_today(db)
|
||||
leads = _lead_settings(db)
|
||||
cov_map = get_coverage_map(db, asset_ids, today)
|
||||
|
||||
out_items = [_to_asset_out(a, rels, today, leads, cov_map.get(a.id)) for a in rows]
|
||||
|
||||
if warranty_status:
|
||||
out_items = [item for item in out_items if item.warranty_status == warranty_status]
|
||||
if contract_status:
|
||||
out_items = [item for item in out_items if item.contract_status == contract_status]
|
||||
|
||||
total = len(out_items)
|
||||
if page_size > 0:
|
||||
start = (page - 1) * page_size
|
||||
out_items = out_items[start : start + page_size]
|
||||
|
||||
return maybe_strip_costs_response({"items": out_items, "total": total}, current_user.role)
|
||||
|
||||
|
||||
@router.post("", response_model=AssetOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_asset(
|
||||
payload: AssetCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
code_clean = payload.asset_code.strip()
|
||||
if db.query(Asset.id).filter(Asset.asset_code == code_clean).first():
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Asset code already exists.",
|
||||
code="DUPLICATE_ASSET_CODE",
|
||||
)
|
||||
|
||||
_validate_asset_fks(
|
||||
db,
|
||||
category_id=payload.category_id,
|
||||
department_id=payload.department_id,
|
||||
location_id=payload.location_id,
|
||||
supplier_id=payload.supplier_id,
|
||||
)
|
||||
|
||||
asset = Asset(
|
||||
asset_code=code_clean,
|
||||
serial_no=payload.serial_no.strip(),
|
||||
name=payload.name.strip(),
|
||||
category_id=payload.category_id,
|
||||
department_id=payload.department_id,
|
||||
location_id=payload.location_id,
|
||||
supplier_id=payload.supplier_id,
|
||||
purchase_value=payload.purchase_value,
|
||||
acquisition_mode=payload.acquisition_mode,
|
||||
monthly_rent=payload.monthly_rent,
|
||||
useful_life_years=payload.useful_life_years,
|
||||
salvage_pct=payload.salvage_pct,
|
||||
depreciation_method=payload.depreciation_method,
|
||||
purchase_date=payload.purchase_date,
|
||||
installation_date=payload.installation_date,
|
||||
status=payload.status,
|
||||
criticality=payload.criticality,
|
||||
requires_calibration=payload.requires_calibration,
|
||||
insurance_applicable=payload.insurance_applicable,
|
||||
remarks=payload.remarks,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(asset)
|
||||
try:
|
||||
db.flush()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Asset code already exists.",
|
||||
code="DUPLICATE_ASSET_CODE",
|
||||
)
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="asset",
|
||||
entity_id=asset.id,
|
||||
action="create",
|
||||
changes={"asset_code": asset.asset_code, "name": asset.name, "department_id": asset.department_id},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_asset_with_joins(db, asset.id)
|
||||
today = effective_today(db)
|
||||
rels = _preload_latest_relations(db, [asset.id])
|
||||
cov = get_coverage(db, asset.id, today)
|
||||
return _to_asset_out(loaded, rels, today, _lead_settings(db), cov)
|
||||
|
||||
|
||||
@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}/coverage", response_model=CoverageOut)
|
||||
def get_asset_coverage(
|
||||
asset_id: int,
|
||||
on_date: Optional[date] = None,
|
||||
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.",
|
||||
)
|
||||
return CoverageOut(**get_coverage(db, asset.id, on_date or effective_today(db)))
|
||||
|
||||
|
||||
@router.get("/{asset_id}", response_model=AssetOut)
|
||||
def get_asset(
|
||||
asset_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
asset = _load_asset_with_joins(db, asset_id)
|
||||
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)
|
||||
rels = _preload_latest_relations(db, [asset.id])
|
||||
cov = get_coverage(db, asset.id, today)
|
||||
return maybe_strip_costs_response(
|
||||
_to_asset_out(asset, rels, today, _lead_settings(db), cov),
|
||||
current_user.role,
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/{asset_id}", response_model=AssetOut)
|
||||
def update_asset(
|
||||
asset_id: int,
|
||||
payload: AssetUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
asset = _load_asset_with_joins(db, asset_id)
|
||||
if asset is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if current_user.role == Role.coordinator.value:
|
||||
disallowed = set(data.keys()) - COORDINATOR_ALLOWED_FIELDS
|
||||
if disallowed:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Coordinators can only edit contract-related asset fields.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
|
||||
if "asset_code" in data and data["asset_code"] is not None:
|
||||
new_code = data["asset_code"].strip()
|
||||
existing = db.query(Asset.id).filter(Asset.asset_code == new_code, Asset.id != asset.id).first()
|
||||
if existing:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Asset code already exists.",
|
||||
code="DUPLICATE_ASSET_CODE",
|
||||
)
|
||||
data["asset_code"] = new_code
|
||||
|
||||
if "serial_no" in data and data["serial_no"] is not None:
|
||||
data["serial_no"] = data["serial_no"].strip()
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
|
||||
_validate_asset_fks(
|
||||
db,
|
||||
category_id=data.get("category_id"),
|
||||
department_id=data.get("department_id"),
|
||||
location_id=data.get("location_id"),
|
||||
supplier_id=data.get("supplier_id"),
|
||||
)
|
||||
|
||||
changes: dict[str, dict[str, Any]] = {}
|
||||
for k, v in data.items():
|
||||
old_val = getattr(asset, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(asset, k, v)
|
||||
asset.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="asset",
|
||||
entity_id=asset.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Asset code already exists.",
|
||||
code="DUPLICATE_ASSET_CODE",
|
||||
)
|
||||
|
||||
loaded = _load_asset_with_joins(db, asset.id)
|
||||
today = effective_today(db)
|
||||
rels = _preload_latest_relations(db, [asset.id])
|
||||
cov = get_coverage(db, asset.id, today)
|
||||
return _to_asset_out(loaded, rels, today, _lead_settings(db), cov)
|
||||
|
||||
|
||||
@router.get("/{asset_id}/overview", response_model=AssetOverviewOut)
|
||||
def get_asset_overview(
|
||||
asset_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
asset = _load_asset_with_joins(db, asset_id)
|
||||
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)
|
||||
leads = _lead_settings(db)
|
||||
rels = _preload_latest_relations(db, [asset.id])
|
||||
cov = get_coverage(db, asset.id, today)
|
||||
asset_out = _to_asset_out(asset, rels, today, leads, cov)
|
||||
|
||||
warranties_rows = (
|
||||
db.query(Warranty)
|
||||
.options(joinedload(Warranty.provider))
|
||||
.filter(Warranty.asset_id == asset.id)
|
||||
.order_by(Warranty.end_date.desc(), Warranty.id.desc())
|
||||
.all()
|
||||
)
|
||||
warranties_out = []
|
||||
for w in warranties_rows:
|
||||
st, sev = coverage_status(w.start_date, w.end_date, today, leads["warranty"], leads["red"])
|
||||
warranties_out.append(
|
||||
WarrantySummaryOut(
|
||||
id=w.id,
|
||||
asset_id=w.asset_id,
|
||||
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,
|
||||
remarks=w.remarks,
|
||||
)
|
||||
)
|
||||
|
||||
contracts_rows = (
|
||||
db.query(Contract)
|
||||
.options(joinedload(Contract.provider))
|
||||
.filter(Contract.asset_id == asset.id)
|
||||
.order_by(Contract.is_superseded.asc(), Contract.end_date.desc(), Contract.id.desc())
|
||||
.all()
|
||||
)
|
||||
contracts_out = []
|
||||
for c in contracts_rows:
|
||||
if c.is_superseded:
|
||||
st, sev = "superseded", "none"
|
||||
else:
|
||||
st, sev = coverage_status(c.start_date, c.end_date, today, leads["contract"], leads["red"])
|
||||
contracts_out.append(
|
||||
ContractSummaryOut(
|
||||
id=c.id,
|
||||
asset_id=c.asset_id,
|
||||
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,
|
||||
contract_value=c.contract_value,
|
||||
coverage_period_text=c.coverage_period_text,
|
||||
renewed_from_id=c.renewed_from_id,
|
||||
is_superseded=c.is_superseded,
|
||||
status=st,
|
||||
severity=sev,
|
||||
remarks=c.remarks,
|
||||
)
|
||||
)
|
||||
|
||||
insurance_rows = (
|
||||
db.query(InsurancePolicy)
|
||||
.options(joinedload(InsurancePolicy.insurer))
|
||||
.filter(InsurancePolicy.asset_id == asset.id)
|
||||
.order_by(InsurancePolicy.end_date.desc(), InsurancePolicy.id.desc())
|
||||
.all()
|
||||
)
|
||||
insurance_out = []
|
||||
for ins in insurance_rows:
|
||||
st, sev = coverage_status(ins.start_date, ins.end_date, today, leads["insurance"], leads["red"])
|
||||
insurance_out.append(
|
||||
InsuranceSummaryOut(
|
||||
id=ins.id,
|
||||
asset_id=ins.asset_id,
|
||||
insurer_id=ins.insurer_id,
|
||||
insurer_name=ins.insurer.name if ins.insurer else None,
|
||||
policy_no=ins.policy_no,
|
||||
start_date=ins.start_date,
|
||||
end_date=ins.end_date,
|
||||
coverage_amount=ins.coverage_amount,
|
||||
status=st,
|
||||
severity=sev,
|
||||
remarks=ins.remarks,
|
||||
)
|
||||
)
|
||||
|
||||
cal_plan_row = (
|
||||
db.query(CalibrationPlan)
|
||||
.options(joinedload(CalibrationPlan.agency))
|
||||
.filter(CalibrationPlan.asset_id == asset.id)
|
||||
.first()
|
||||
)
|
||||
cal_plan_out = (
|
||||
CalibrationPlanSummaryOut(
|
||||
id=cal_plan_row.id,
|
||||
asset_id=cal_plan_row.asset_id,
|
||||
frequency_months=cal_plan_row.frequency_months,
|
||||
calibrations_per_year=cal_plan_row.calibrations_per_year,
|
||||
agency_id=cal_plan_row.agency_id,
|
||||
agency_name=cal_plan_row.agency.name if cal_plan_row.agency else None,
|
||||
approved_by_id=cal_plan_row.approved_by_id,
|
||||
approved_on=cal_plan_row.approved_on,
|
||||
next_due_date=cal_plan_row.next_due_date,
|
||||
is_active=cal_plan_row.is_active,
|
||||
)
|
||||
if cal_plan_row
|
||||
else None
|
||||
)
|
||||
|
||||
cal_records_rows = (
|
||||
db.query(CalibrationRecord)
|
||||
.options(joinedload(CalibrationRecord.agency))
|
||||
.filter(CalibrationRecord.asset_id == asset.id)
|
||||
.order_by(CalibrationRecord.due_date.desc(), CalibrationRecord.id.desc())
|
||||
.all()
|
||||
)
|
||||
cal_records_out = []
|
||||
for rec in cal_records_rows:
|
||||
st, sev = compute_schedule_status(rec.due_date, rec.status, today, leads["calibration"], leads["red"])
|
||||
cal_records_out.append(
|
||||
CalibrationRecordSummaryOut(
|
||||
id=rec.id,
|
||||
asset_id=rec.asset_id,
|
||||
plan_id=rec.plan_id,
|
||||
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=st,
|
||||
severity=sev,
|
||||
)
|
||||
)
|
||||
|
||||
pm_sched_rows = (
|
||||
db.query(PMSchedule)
|
||||
.options(joinedload(PMSchedule.provider))
|
||||
.filter(PMSchedule.asset_id == asset.id)
|
||||
.order_by(PMSchedule.id.desc())
|
||||
.all()
|
||||
)
|
||||
pm_sched_out = [
|
||||
PMScheduleSummaryOut(
|
||||
id=s.id,
|
||||
asset_id=s.asset_id,
|
||||
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,
|
||||
cost_per_visit=s.cost_per_visit,
|
||||
next_planned_date=s.next_planned_date,
|
||||
is_active=s.is_active,
|
||||
)
|
||||
for s in pm_sched_rows
|
||||
]
|
||||
|
||||
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:
|
||||
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,
|
||||
schedule_id=r.schedule_id,
|
||||
asset_id=r.asset_id,
|
||||
planned_date=r.planned_date,
|
||||
completed_date=r.completed_date,
|
||||
status=st,
|
||||
severity=sev,
|
||||
service_details=r.service_details,
|
||||
remarks=r.remarks,
|
||||
rescheduled_to=r.rescheduled_to,
|
||||
)
|
||||
)
|
||||
|
||||
complaint_rows = (
|
||||
db.query(Complaint)
|
||||
.filter(Complaint.asset_id == asset.id)
|
||||
.order_by(Complaint.registered_at.desc(), Complaint.id.desc())
|
||||
.all()
|
||||
)
|
||||
complaints_out = [
|
||||
ComplaintSummaryOut(
|
||||
id=comp.id,
|
||||
complaint_no=comp.complaint_no,
|
||||
asset_id=comp.asset_id,
|
||||
description=comp.description,
|
||||
priority=comp.priority,
|
||||
call_status=comp.call_status,
|
||||
registered_at=comp.registered_at,
|
||||
closed_at=comp.closed_at,
|
||||
)
|
||||
for comp in complaint_rows
|
||||
]
|
||||
|
||||
att_rows = (
|
||||
db.query(Attachment)
|
||||
.filter(Attachment.entity_type == "asset", Attachment.entity_id == asset.id)
|
||||
.order_by(Attachment.uploaded_at.desc(), Attachment.id.desc())
|
||||
.all()
|
||||
)
|
||||
uploader_ids = {a.uploaded_by_id for a in att_rows}
|
||||
uploader_names = {}
|
||||
if uploader_ids:
|
||||
uploader_names = {
|
||||
u.id: u.name
|
||||
for u in db.query(User.id, User.name).filter(User.id.in_(uploader_ids)).all()
|
||||
}
|
||||
attachments_out = [
|
||||
AttachmentSummaryOut(
|
||||
id=a.id,
|
||||
entity_type=a.entity_type,
|
||||
entity_id=a.entity_id,
|
||||
original_name=a.original_name,
|
||||
mime_type=a.mime_type,
|
||||
size_bytes=a.size_bytes,
|
||||
uploaded_by_id=a.uploaded_by_id,
|
||||
uploaded_by_name=uploader_names.get(a.uploaded_by_id),
|
||||
uploaded_at=a.uploaded_at,
|
||||
)
|
||||
for a in att_rows
|
||||
]
|
||||
|
||||
overview = AssetOverviewOut(
|
||||
asset=asset_out,
|
||||
coverage=CoverageOut(**cov),
|
||||
warranties=warranties_out,
|
||||
contracts=contracts_out,
|
||||
insurance_policies=insurance_out,
|
||||
calibration_plan=cal_plan_out,
|
||||
calibration_records=cal_records_out,
|
||||
pm_schedules=pm_sched_out,
|
||||
pm_records=pm_rec_out,
|
||||
complaints=complaints_out,
|
||||
attachments=attachments_out,
|
||||
)
|
||||
return maybe_strip_costs_response(overview, current_user.role)
|
||||
@@ -0,0 +1,104 @@
|
||||
from pathlib import Path
|
||||
from fastapi import APIRouter, Depends, File, Form, Query, Response, UploadFile, status
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.config import settings
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..models import Attachment, User
|
||||
from ..schemas.attachments import AttachmentListOut, AttachmentOut
|
||||
from ..services.attachment_service import (
|
||||
assert_entity_visible,
|
||||
delete_attachment,
|
||||
save_attachment,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/attachments", tags=["attachments"])
|
||||
|
||||
|
||||
def _to_out(att: Attachment, user_names: dict[int, str]) -> AttachmentOut:
|
||||
return AttachmentOut(
|
||||
id=att.id,
|
||||
entity_type=att.entity_type,
|
||||
entity_id=att.entity_id,
|
||||
original_name=att.original_name,
|
||||
mime_type=att.mime_type,
|
||||
size_bytes=att.size_bytes,
|
||||
uploaded_by_id=att.uploaded_by_id,
|
||||
uploaded_by_name=user_names.get(att.uploaded_by_id),
|
||||
uploaded_at=att.uploaded_at,
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=AttachmentOut, status_code=status.HTTP_201_CREATED)
|
||||
def upload_attachment(
|
||||
entity_type: str = Form(...),
|
||||
entity_id: int = Form(...),
|
||||
file: UploadFile = File(...),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
att = save_attachment(db, current_user, entity_type, entity_id, file)
|
||||
return _to_out(att, {current_user.id: current_user.name})
|
||||
|
||||
|
||||
@router.get("", response_model=AttachmentListOut)
|
||||
def list_attachments(
|
||||
entity_type: str = Query(...),
|
||||
entity_id: int = Query(...),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
assert_entity_visible(db, current_user, entity_type, entity_id)
|
||||
rows = (
|
||||
db.query(Attachment)
|
||||
.filter(Attachment.entity_type == entity_type, Attachment.entity_id == entity_id)
|
||||
.order_by(Attachment.uploaded_at.desc(), Attachment.id.desc())
|
||||
.all()
|
||||
)
|
||||
user_ids = {r.uploaded_by_id for r in rows}
|
||||
user_names = {}
|
||||
if user_ids:
|
||||
user_names = {
|
||||
u.id: u.name
|
||||
for u in db.query(User.id, User.name).filter(User.id.in_(user_ids)).all()
|
||||
}
|
||||
return {
|
||||
"items": [_to_out(r, user_names) for r in rows],
|
||||
"total": len(rows),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{attachment_id}/download")
|
||||
def download_attachment(
|
||||
attachment_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
att = db.query(Attachment).filter(Attachment.id == attachment_id).first()
|
||||
if att is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Attachment not found.", code="NOT_FOUND")
|
||||
|
||||
assert_entity_visible(db, current_user, att.entity_type, att.entity_id)
|
||||
|
||||
file_path = Path(settings.UPLOAD_DIR) / att.stored_name
|
||||
if not file_path.is_file():
|
||||
raise CodedHTTPException(status_code=404, detail="Attachment file missing on disk.", code="FILE_NOT_FOUND")
|
||||
|
||||
return FileResponse(
|
||||
path=file_path,
|
||||
media_type=att.mime_type,
|
||||
filename=att.original_name,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/{attachment_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def remove_attachment(
|
||||
attachment_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
delete_attachment(db, current_user, attachment_id)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -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,
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
from collections import defaultdict, deque
|
||||
import threading
|
||||
import time
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.security import create_access_token, 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,
|
||||
name=user.name,
|
||||
email=user.email,
|
||||
role=user.role,
|
||||
department_id=user.department_id,
|
||||
department_name=user.department.name if user.department else None,
|
||||
is_active=user.is_active,
|
||||
demo_as_of_date=get_demo_as_of_date(db),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
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))
|
||||
.filter(User.email == email_norm)
|
||||
.first()
|
||||
)
|
||||
if user is None or not verify_password(payload.password, user.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid email or password.",
|
||||
)
|
||||
if not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="User account is inactive.",
|
||||
)
|
||||
|
||||
token = create_access_token({
|
||||
"sub": str(user.id),
|
||||
"role": user.role,
|
||||
"tv": user.token_version,
|
||||
})
|
||||
return TokenResponse(
|
||||
access_token=token,
|
||||
token_type="bearer",
|
||||
user=_build_user_out(user, db),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
def get_me(
|
||||
current_user: User = Depends(get_current_user),
|
||||
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,950 @@
|
||||
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, effective_today, utc_now
|
||||
from ..models import Asset, Complaint, ComplaintEvent, Contract, User, Vendor
|
||||
from ..schemas.assets import CoverageOut
|
||||
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,
|
||||
coverage_status,
|
||||
)
|
||||
from ..services.coverage import (
|
||||
format_coverage_tag_label,
|
||||
format_vendor_contact,
|
||||
get_coverage,
|
||||
get_coverage_map,
|
||||
)
|
||||
from ..services.numbering import generate_complaint_no
|
||||
from ..services.permissions import RESTRICTED_COMPLAINT_FIELDS, Role, maybe_strip_costs_response
|
||||
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 _preload_coverage_refs(
|
||||
db: Session, complaints: list[Complaint]
|
||||
) -> tuple[dict[int, Vendor], dict[int, Contract], dict[int, dict[str, Any]]]:
|
||||
provider_ids = {c.coverage_provider_id for c in complaints if c.coverage_provider_id is not None}
|
||||
contract_ids = {c.coverage_contract_id for c in complaints if c.coverage_contract_id is not None}
|
||||
asset_ids = [c.asset_id for c in complaints]
|
||||
|
||||
vendors_by_id = (
|
||||
{v.id: v for v in db.query(Vendor).filter(Vendor.id.in_(provider_ids)).all()}
|
||||
if provider_ids
|
||||
else {}
|
||||
)
|
||||
contracts_by_id = (
|
||||
{ct.id: ct for ct in db.query(Contract).filter(Contract.id.in_(contract_ids)).all()}
|
||||
if contract_ids
|
||||
else {}
|
||||
)
|
||||
cov_now_map = get_coverage_map(db, asset_ids, effective_today(db))
|
||||
return vendors_by_id, contracts_by_id, cov_now_map
|
||||
|
||||
|
||||
def _build_snapshot_coverage(
|
||||
db: Session,
|
||||
c: Complaint,
|
||||
vendors_by_id: dict[int, Vendor],
|
||||
contracts_by_id: dict[int, Contract],
|
||||
) -> CoverageOut:
|
||||
reg_date = _norm_utc(c.registered_at).astimezone(KOLKATA).date()
|
||||
if c.coverage_tag:
|
||||
provider = vendors_by_id.get(c.coverage_provider_id) if c.coverage_provider_id else None
|
||||
contract = contracts_by_id.get(c.coverage_contract_id) if c.coverage_contract_id else None
|
||||
valid_from = contract.start_date if contract else None
|
||||
valid_until = contract.end_date if contract else None
|
||||
days_left = (valid_until - reg_date).days if valid_until else None
|
||||
if c.coverage_tag == "out_of_contract":
|
||||
sev = "red"
|
||||
elif valid_until is not None:
|
||||
lead = int(get_setting_value(db, "contract_expiry_alert_days", 30))
|
||||
red = int(get_setting_value(db, "contract_critical_alert_days", 7))
|
||||
_, raw_sev = coverage_status(valid_from, valid_until, reg_date, lead, red)
|
||||
sev = raw_sev if raw_sev in ("ok", "yellow", "red") else "ok"
|
||||
else:
|
||||
sev = "ok"
|
||||
return CoverageOut(
|
||||
tag=c.coverage_tag,
|
||||
contract_id=c.coverage_contract_id,
|
||||
warranty_id=None,
|
||||
provider_id=c.coverage_provider_id,
|
||||
provider_name=provider.name if provider else None,
|
||||
provider_contact=format_vendor_contact(provider),
|
||||
valid_from=valid_from,
|
||||
valid_until=valid_until,
|
||||
days_left=days_left,
|
||||
severity=sev,
|
||||
)
|
||||
return CoverageOut(**get_coverage(db, c.asset_id, reg_date))
|
||||
|
||||
|
||||
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,
|
||||
coverage_at_registration: CoverageOut | None = None,
|
||||
coverage_now: CoverageOut | None = None,
|
||||
) -> 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,
|
||||
repair_cost=c.repair_cost,
|
||||
coverage_tag=c.coverage_tag or (coverage_at_registration.tag if coverage_at_registration else None),
|
||||
coverage_contract_id=c.coverage_contract_id,
|
||||
coverage_provider_id=c.coverage_provider_id,
|
||||
coverage_at_registration=coverage_at_registration,
|
||||
coverage_now=coverage_now,
|
||||
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)
|
||||
vendors_by_id, contracts_by_id, cov_now_map = _preload_coverage_refs(db, [comp])
|
||||
cov_reg = _build_snapshot_coverage(db, comp, vendors_by_id, contracts_by_id)
|
||||
cov_now = CoverageOut(**cov_now_map[comp.asset_id]) if comp.asset_id in cov_now_map else None
|
||||
return _to_complaint_out(
|
||||
comp,
|
||||
user_names,
|
||||
milestone,
|
||||
response_start,
|
||||
now_utc,
|
||||
critical_sla_hours=critical_sla,
|
||||
non_critical_sla_hours=non_critical_sla,
|
||||
coverage_at_registration=cov_reg,
|
||||
coverage_now=cov_now,
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
coverage_tag: 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 coverage_tag:
|
||||
query = query.filter(Complaint.coverage_tag == coverage_tag)
|
||||
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)
|
||||
vendors_by_id, contracts_by_id, cov_now_map = _preload_coverage_refs(db, rows)
|
||||
items = [
|
||||
_to_complaint_out(
|
||||
c,
|
||||
user_names,
|
||||
milestone,
|
||||
response_start,
|
||||
now_utc,
|
||||
critical_sla_hours=critical_sla,
|
||||
non_critical_sla_hours=non_critical_sla,
|
||||
coverage_at_registration=_build_snapshot_coverage(db, c, vendors_by_id, contracts_by_id),
|
||||
coverage_now=CoverageOut(**cov_now_map[c.asset_id]) if c.asset_id in cov_now_map else None,
|
||||
)
|
||||
for c in rows
|
||||
]
|
||||
return maybe_strip_costs_response({"items": items, "total": total}, current_user.role)
|
||||
|
||||
|
||||
@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)
|
||||
cov_snapshot = get_coverage(db, asset.id, effective_today(db))
|
||||
|
||||
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",
|
||||
coverage_tag=cov_snapshot["tag"],
|
||||
coverage_contract_id=cov_snapshot["contract_id"],
|
||||
coverage_provider_id=cov_snapshot["provider_id"],
|
||||
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,
|
||||
)
|
||||
)
|
||||
cov_note = f"Auto-tagged as {format_coverage_tag_label(cov_snapshot['tag'])}"
|
||||
if cov_snapshot.get("provider_name"):
|
||||
cov_note += f" — {cov_snapshot['provider_name']}"
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="coverage_tagged",
|
||||
from_value=None,
|
||||
to_value=cov_snapshot["tag"],
|
||||
by_user_id=current_user.id,
|
||||
at=reg_at,
|
||||
note=cov_note,
|
||||
)
|
||||
)
|
||||
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 maybe_strip_costs_response(
|
||||
_serialize_one(db, loaded),
|
||||
current_user.role,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
|
||||
|
||||
@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 maybe_strip_costs_response(_serialize_one(db, comp), current_user.role)
|
||||
|
||||
|
||||
@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 maybe_strip_costs_response(_serialize_one(db, loaded), current_user.role)
|
||||
|
||||
|
||||
@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,455 @@
|
||||
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, maybe_strip_costs_response
|
||||
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,
|
||||
contract_value=c.contract_value,
|
||||
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 maybe_strip_costs_response(
|
||||
ContractListOut(items=items_all[start : start + page_size], total=total),
|
||||
current_user.role,
|
||||
)
|
||||
|
||||
|
||||
@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 maybe_strip_costs_response(
|
||||
ContractHistoryOut(
|
||||
items=[_to_contract_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
||||
),
|
||||
current_user.role,
|
||||
)
|
||||
|
||||
|
||||
@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,
|
||||
contract_value=payload.contract_value,
|
||||
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,
|
||||
contract_value=payload.contract_value if payload.contract_value is not None else old_contract.contract_value,
|
||||
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,8 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health_check():
|
||||
return {"status": "ok", "service": "Poona Hospital AMS", "version": "0.1.0"}
|
||||
@@ -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,393 @@
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
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 ..models.masters import Category, Department, Location, User, Vendor
|
||||
from ..schemas.masters import (
|
||||
CategoryCreate,
|
||||
CategoryOut,
|
||||
CategoryUpdate,
|
||||
DepartmentCreate,
|
||||
DepartmentOut,
|
||||
DepartmentUpdate,
|
||||
LocationCreate,
|
||||
LocationOut,
|
||||
LocationUpdate,
|
||||
PaginatedOut,
|
||||
VendorCreate,
|
||||
VendorOut,
|
||||
VendorUpdate,
|
||||
)
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(tags=["masters"])
|
||||
|
||||
|
||||
def _paginate(query, page: int, page_size: int):
|
||||
total = query.count()
|
||||
if page_size > 0:
|
||||
query = query.offset((page - 1) * page_size).limit(page_size)
|
||||
return query.all(), total
|
||||
|
||||
|
||||
def _loc_out(loc: Location) -> LocationOut:
|
||||
return LocationOut(
|
||||
id=loc.id,
|
||||
department_id=loc.department_id,
|
||||
department_name=loc.department.name if loc.department else None,
|
||||
name=loc.name,
|
||||
floor_wing=loc.floor_wing,
|
||||
is_active=loc.is_active,
|
||||
)
|
||||
|
||||
|
||||
# ---------------- Departments ----------------
|
||||
@router.get("/departments", response_model=PaginatedOut[DepartmentOut])
|
||||
def list_departments(
|
||||
q: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Department)
|
||||
if not include_inactive:
|
||||
query = query.filter(Department.is_active.is_(True))
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(or_(Department.name.ilike(like), Department.code.ilike(like)))
|
||||
query = query.order_by(Department.name.asc())
|
||||
items, total = _paginate(query, page, page_size)
|
||||
return {"items": items, "total": total}
|
||||
|
||||
|
||||
@router.post("/departments", response_model=DepartmentOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_department(
|
||||
payload: DepartmentCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
dept = Department(
|
||||
name=payload.name.strip(),
|
||||
code=payload.code.strip().upper(),
|
||||
description=payload.description,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
db.add(dept)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Department with this name or code already exists.",
|
||||
)
|
||||
db.refresh(dept)
|
||||
return dept
|
||||
|
||||
|
||||
@router.patch("/departments/{dept_id}", response_model=DepartmentOut)
|
||||
def update_department(
|
||||
dept_id: int,
|
||||
payload: DepartmentUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
dept = db.query(Department).filter(Department.id == dept_id).first()
|
||||
if dept is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
if "code" in data and data["code"] is not None:
|
||||
data["code"] = data["code"].strip().upper()
|
||||
for k, v in data.items():
|
||||
setattr(dept, k, v)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Department with this name or code already exists.",
|
||||
)
|
||||
db.refresh(dept)
|
||||
return dept
|
||||
|
||||
|
||||
@router.delete("/departments/{dept_id}", response_model=DepartmentOut)
|
||||
def delete_department(
|
||||
dept_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
dept = db.query(Department).filter(Department.id == dept_id).first()
|
||||
if dept is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
dept.is_active = False
|
||||
db.commit()
|
||||
db.refresh(dept)
|
||||
return dept
|
||||
|
||||
|
||||
# ---------------- Locations ----------------
|
||||
@router.get("/locations", response_model=PaginatedOut[LocationOut])
|
||||
def list_locations(
|
||||
q: Optional[str] = None,
|
||||
department_id: Optional[int] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Location).options(joinedload(Location.department))
|
||||
if not include_inactive:
|
||||
query = query.filter(Location.is_active.is_(True))
|
||||
if department_id is not None:
|
||||
query = query.filter(Location.department_id == department_id)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(or_(Location.name.ilike(like), Location.floor_wing.ilike(like)))
|
||||
query = query.order_by(Location.name.asc())
|
||||
items, total = _paginate(query, page, page_size)
|
||||
return {"items": [_loc_out(loc) for loc in items], "total": total}
|
||||
|
||||
|
||||
@router.post("/locations", response_model=LocationOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_location(
|
||||
payload: LocationCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
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.")
|
||||
loc = Location(
|
||||
department_id=payload.department_id,
|
||||
name=payload.name.strip(),
|
||||
floor_wing=payload.floor_wing,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
db.add(loc)
|
||||
db.commit()
|
||||
db.refresh(loc)
|
||||
loc.department = dept
|
||||
return _loc_out(loc)
|
||||
|
||||
|
||||
@router.patch("/locations/{location_id}", response_model=LocationOut)
|
||||
def update_location(
|
||||
location_id: int,
|
||||
payload: LocationUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
loc = db.query(Location).options(joinedload(Location.department)).filter(Location.id == location_id).first()
|
||||
if loc is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
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:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
for k, v in data.items():
|
||||
setattr(loc, k, v)
|
||||
db.commit()
|
||||
db.refresh(loc)
|
||||
return _loc_out(loc)
|
||||
|
||||
|
||||
@router.delete("/locations/{location_id}", response_model=LocationOut)
|
||||
def delete_location(
|
||||
location_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
loc = db.query(Location).options(joinedload(Location.department)).filter(Location.id == location_id).first()
|
||||
if loc is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
|
||||
loc.is_active = False
|
||||
db.commit()
|
||||
db.refresh(loc)
|
||||
return _loc_out(loc)
|
||||
|
||||
|
||||
# ---------------- Categories ----------------
|
||||
@router.get("/categories", response_model=PaginatedOut[CategoryOut])
|
||||
def list_categories(
|
||||
q: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Category)
|
||||
if not include_inactive:
|
||||
query = query.filter(Category.is_active.is_(True))
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(Category.name.ilike(like))
|
||||
query = query.order_by(Category.name.asc())
|
||||
items, total = _paginate(query, page, page_size)
|
||||
return {"items": items, "total": total}
|
||||
|
||||
|
||||
@router.post("/categories", response_model=CategoryOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_category(
|
||||
payload: CategoryCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
cat = Category(
|
||||
name=payload.name.strip(),
|
||||
description=payload.description,
|
||||
default_useful_life_years=payload.default_useful_life_years,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
db.add(cat)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Category with this name already exists.",
|
||||
)
|
||||
db.refresh(cat)
|
||||
return cat
|
||||
|
||||
|
||||
@router.patch("/categories/{category_id}", response_model=CategoryOut)
|
||||
def update_category(
|
||||
category_id: int,
|
||||
payload: CategoryUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
cat = db.query(Category).filter(Category.id == category_id).first()
|
||||
if cat is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found.")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
for k, v in data.items():
|
||||
setattr(cat, k, v)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Category with this name already exists.",
|
||||
)
|
||||
db.refresh(cat)
|
||||
return cat
|
||||
|
||||
|
||||
@router.delete("/categories/{category_id}", response_model=CategoryOut)
|
||||
def delete_category(
|
||||
category_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
cat = db.query(Category).filter(Category.id == category_id).first()
|
||||
if cat is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found.")
|
||||
cat.is_active = False
|
||||
db.commit()
|
||||
db.refresh(cat)
|
||||
return cat
|
||||
|
||||
|
||||
# ---------------- Vendors ----------------
|
||||
@router.get("/vendors", response_model=PaginatedOut[VendorOut])
|
||||
def list_vendors(
|
||||
q: Optional[str] = None,
|
||||
vendor_type: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Vendor)
|
||||
if not include_inactive:
|
||||
query = query.filter(Vendor.is_active.is_(True))
|
||||
if vendor_type:
|
||||
query = query.filter(Vendor.vendor_type == vendor_type)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Vendor.name.ilike(like),
|
||||
Vendor.contact_person.ilike(like),
|
||||
Vendor.email.ilike(like),
|
||||
)
|
||||
)
|
||||
query = query.order_by(Vendor.name.asc())
|
||||
items, total = _paginate(query, page, page_size)
|
||||
return {"items": items, "total": total}
|
||||
|
||||
|
||||
@router.post("/vendors", response_model=VendorOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_vendor(
|
||||
payload: VendorCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
vendor = Vendor(
|
||||
name=payload.name.strip(),
|
||||
vendor_type=payload.vendor_type,
|
||||
contact_person=payload.contact_person,
|
||||
phone=payload.phone,
|
||||
email=payload.email,
|
||||
address=payload.address,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
db.add(vendor)
|
||||
db.commit()
|
||||
db.refresh(vendor)
|
||||
return vendor
|
||||
|
||||
|
||||
@router.patch("/vendors/{vendor_id}", response_model=VendorOut)
|
||||
def update_vendor(
|
||||
vendor_id: int,
|
||||
payload: VendorUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
|
||||
if vendor is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Vendor not found.")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
for k, v in data.items():
|
||||
setattr(vendor, k, v)
|
||||
db.commit()
|
||||
db.refresh(vendor)
|
||||
return vendor
|
||||
|
||||
|
||||
@router.delete("/vendors/{vendor_id}", response_model=VendorOut)
|
||||
def delete_vendor(
|
||||
vendor_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
|
||||
if vendor is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Vendor not found.")
|
||||
vendor.is_active = False
|
||||
db.commit()
|
||||
db.refresh(vendor)
|
||||
return vendor
|
||||
@@ -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,680 @@
|
||||
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.assets import CoverageOut
|
||||
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.coverage import get_active_amc_cmc, get_coverage, get_coverage_map
|
||||
from ..services.permissions import Role, maybe_strip_costs_response
|
||||
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,
|
||||
cov: dict | None = None,
|
||||
no_active_contract: bool | None = None,
|
||||
) -> 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)})"
|
||||
cov_out = CoverageOut(**cov) if cov is not None else None
|
||||
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,
|
||||
cost_per_visit=s.cost_per_visit,
|
||||
coverage_tag=cov_out.tag if cov_out else None,
|
||||
coverage=cov_out,
|
||||
no_active_contract=no_active_contract,
|
||||
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],
|
||||
cov: dict | None = None,
|
||||
) -> 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"]
|
||||
)
|
||||
cov_out = CoverageOut(**cov) if cov is not None else None
|
||||
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,
|
||||
coverage_tag=cov_out.tag if cov_out else None,
|
||||
coverage=cov_out,
|
||||
)
|
||||
|
||||
|
||||
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],
|
||||
allow_auto_fill: bool = False,
|
||||
) -> tuple[Optional[str], Optional[int], Optional[int], bool]:
|
||||
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, False
|
||||
|
||||
no_active_contract = False
|
||||
if allow_auto_fill and (provider_id is None or contract_id is None):
|
||||
active_contract = get_active_amc_cmc(db, asset_id, effective_today(db))
|
||||
if active_contract is not None:
|
||||
if contract_id is None:
|
||||
contract_id = active_contract.id
|
||||
if provider_id is None:
|
||||
provider_id = active_contract.provider_id
|
||||
elif provider_id is None and contract_id is None:
|
||||
no_active_contract = True
|
||||
|
||||
if provider_id is not None:
|
||||
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.")
|
||||
elif not allow_auto_fill:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="provider_id is required for outsourced PM schedules.",
|
||||
)
|
||||
|
||||
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, no_active_contract
|
||||
|
||||
|
||||
@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()
|
||||
)
|
||||
cov_map = get_coverage_map(db, [s.asset_id for s in rows], effective_today(db))
|
||||
return maybe_strip_costs_response(
|
||||
PMScheduleListOut(items=[_to_schedule_out(s, cov_map.get(s.asset_id)) for s in rows], total=total),
|
||||
current_user.role,
|
||||
)
|
||||
|
||||
|
||||
@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)),
|
||||
):
|
||||
if current_user.role == Role.coordinator.value and payload.cost_per_visit is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only Biomedical or System Admin can edit PM cost per visit.",
|
||||
)
|
||||
|
||||
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, no_active_contract = _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,
|
||||
allow_auto_fill=True,
|
||||
)
|
||||
|
||||
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,
|
||||
cost_per_visit=payload.cost_per_visit,
|
||||
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)
|
||||
cov = get_coverage(db, asset.id, effective_today(db))
|
||||
return _to_schedule_out(loaded, cov, no_active_contract=True if no_active_contract else None)
|
||||
|
||||
|
||||
@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)
|
||||
if current_user.role == Role.coordinator.value and "cost_per_visit" in data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only Biomedical or System Admin can edit PM cost per visit.",
|
||||
)
|
||||
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,
|
||||
allow_auto_fill=True,
|
||||
)
|
||||
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)
|
||||
cov = get_coverage(db, schedule.asset_id, effective_today(db))
|
||||
return _to_schedule_out(loaded, cov)
|
||||
|
||||
|
||||
@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)
|
||||
cov = get_coverage(db, schedule.asset_id, effective_today(db))
|
||||
return _to_schedule_out(loaded, cov)
|
||||
|
||||
|
||||
@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()
|
||||
cov_map = get_coverage_map(db, [r.asset_id for r in rows], today)
|
||||
computed_all = [_to_record_out(r, today, leads, cov_map.get(r.asset_id)) 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)
|
||||
cov = get_coverage(db, rec.asset_id, today)
|
||||
return PMRecordCompleteOut(
|
||||
completed_record=_to_record_out(loaded_completed, today, leads, cov),
|
||||
next_record=_to_record_out(loaded_next, today, leads, cov),
|
||||
)
|
||||
|
||||
|
||||
@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)
|
||||
cov = get_coverage(db, rec.asset_id, today)
|
||||
return PMRecordRescheduleOut(
|
||||
rescheduled_record=_to_record_out(loaded_rescheduled, today, leads, cov),
|
||||
next_record=_to_record_out(loaded_next, today, leads, cov),
|
||||
)
|
||||
@@ -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
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import require_roles
|
||||
from ..core.time_utils import effective_today
|
||||
from ..models.masters import User
|
||||
from ..schemas.settings import DemoDateIn, DemoDateOut, SettingsListOut, SettingsUpdateIn
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_all_settings, get_demo_as_of_date, update_settings
|
||||
|
||||
router = APIRouter(prefix="/settings", tags=["settings"])
|
||||
|
||||
|
||||
@router.get("", response_model=SettingsListOut)
|
||||
def list_settings(
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
return {"items": get_all_settings(db)}
|
||||
|
||||
|
||||
@router.put("", response_model=SettingsListOut)
|
||||
def save_settings(
|
||||
payload: SettingsUpdateIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
items = update_settings(db, payload.values, user_id=current_user.id)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
@router.post("/demo-date", response_model=DemoDateOut)
|
||||
def set_demo_date(
|
||||
payload: DemoDateIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
val = payload.demo_as_of_date if payload.demo_as_of_date is not None else ""
|
||||
update_settings(db, {"demo_as_of_date": val}, user_id=current_user.id)
|
||||
return {
|
||||
"demo_as_of_date": get_demo_as_of_date(db),
|
||||
"effective_today": effective_today(db).isoformat(),
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
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, validate_password
|
||||
from ..models.masters import Department, User
|
||||
from ..schemas.masters import (
|
||||
PaginatedOut,
|
||||
UserCreate,
|
||||
UserListOut,
|
||||
UserLookupOut,
|
||||
UserUpdate,
|
||||
)
|
||||
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,
|
||||
name=user.name,
|
||||
email=user.email,
|
||||
role=user.role,
|
||||
department_id=user.department_id,
|
||||
department_name=user.department.name if user.department else None,
|
||||
is_active=user.is_active,
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=PaginatedOut[UserListOut])
|
||||
def list_users(
|
||||
q: Optional[str] = None,
|
||||
role: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
query = db.query(User).options(joinedload(User.department))
|
||||
if not include_inactive:
|
||||
query = query.filter(User.is_active.is_(True))
|
||||
if role:
|
||||
query = query.filter(User.role == role)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(or_(User.name.ilike(like), User.email.ilike(like)))
|
||||
query = query.order_by(User.name.asc())
|
||||
total = query.count()
|
||||
if page_size > 0:
|
||||
query = query.offset((page - 1) * page_size).limit(page_size)
|
||||
items = query.all()
|
||||
return {"items": [_user_list_out(u) for u in items], "total": total}
|
||||
|
||||
|
||||
@router.get("/lookup", response_model=PaginatedOut[UserLookupOut])
|
||||
def lookup_users(
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
users = (
|
||||
db.query(User)
|
||||
.filter(User.is_active.is_(True))
|
||||
.order_by(User.name.asc())
|
||||
.all()
|
||||
)
|
||||
return {"items": users, "total": len(users)}
|
||||
|
||||
|
||||
@router.post("", response_model=UserListOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_user(
|
||||
payload: UserCreate,
|
||||
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(),
|
||||
password_hash=hash_password(payload.password),
|
||||
role=payload.role,
|
||||
department_id=payload.department_id,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
db.add(user)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="A user with this email already exists.",
|
||||
)
|
||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user.id).first()
|
||||
return _user_list_out(user)
|
||||
|
||||
|
||||
@router.patch("/{user_id}", response_model=UserListOut)
|
||||
def update_user(
|
||||
user_id: int,
|
||||
payload: UserUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
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:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
if "email" in data and data["email"] is not None:
|
||||
data["email"] = data["email"].strip().lower()
|
||||
|
||||
password = data.pop("password", None)
|
||||
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)
|
||||
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="A user with this email already exists.",
|
||||
)
|
||||
db.refresh(user)
|
||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user.id).first()
|
||||
return _user_list_out(user)
|
||||
|
||||
|
||||
@router.delete("/{user_id}", response_model=UserListOut)
|
||||
def delete_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
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)
|
||||
@@ -0,0 +1,151 @@
|
||||
from .assets import (
|
||||
AssetCreate,
|
||||
AssetListOut,
|
||||
AssetLookupListOut,
|
||||
AssetLookupOut,
|
||||
AssetOut,
|
||||
AssetOverviewOut,
|
||||
AssetUpdate,
|
||||
)
|
||||
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,
|
||||
CategoryUpdate,
|
||||
DepartmentCreate,
|
||||
DepartmentOut,
|
||||
DepartmentUpdate,
|
||||
LocationCreate,
|
||||
LocationOut,
|
||||
LocationUpdate,
|
||||
PaginatedOut,
|
||||
UserCreate,
|
||||
UserListOut,
|
||||
UserLookupOut,
|
||||
UserUpdate,
|
||||
VendorCreate,
|
||||
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",
|
||||
"AssetListOut",
|
||||
"AssetLookupListOut",
|
||||
"AssetLookupOut",
|
||||
"AssetOut",
|
||||
"AssetOverviewOut",
|
||||
"AssetUpdate",
|
||||
"AttachmentListOut",
|
||||
"AttachmentOut",
|
||||
"LoginRequest",
|
||||
"TokenResponse",
|
||||
"UserOut",
|
||||
"PaginatedOut",
|
||||
"DepartmentCreate",
|
||||
"DepartmentUpdate",
|
||||
"DepartmentOut",
|
||||
"LocationCreate",
|
||||
"LocationUpdate",
|
||||
"LocationOut",
|
||||
"CategoryCreate",
|
||||
"CategoryUpdate",
|
||||
"CategoryOut",
|
||||
"VendorCreate",
|
||||
"VendorUpdate",
|
||||
"VendorOut",
|
||||
"UserCreate",
|
||||
"UserUpdate",
|
||||
"UserListOut",
|
||||
"UserLookupOut",
|
||||
"SettingItemOut",
|
||||
"SettingsListOut",
|
||||
"SettingsUpdateIn",
|
||||
"DemoDateIn",
|
||||
"DemoDateOut",
|
||||
]
|
||||
@@ -0,0 +1,288 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Literal, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
AssetStatus = Literal["in_service", "under_repair", "condemned", "out_of_service"]
|
||||
AssetCriticality = Literal["critical", "non_critical"]
|
||||
AcquisitionMode = Literal["purchased", "rented"]
|
||||
DepreciationMethod = Literal["straight_line", "written_down"]
|
||||
CoverageTag = Literal["warranty", "cmc", "amc", "other_contract", "out_of_contract"]
|
||||
|
||||
|
||||
class CoverageOut(BaseModel):
|
||||
tag: CoverageTag
|
||||
contract_id: Optional[int] = None
|
||||
warranty_id: Optional[int] = None
|
||||
provider_id: Optional[int] = None
|
||||
provider_name: Optional[str] = None
|
||||
provider_contact: Optional[str] = None
|
||||
valid_from: Optional[date] = None
|
||||
valid_until: Optional[date] = None
|
||||
days_left: Optional[int] = None
|
||||
severity: Literal["ok", "yellow", "red"]
|
||||
|
||||
|
||||
class AssetCreate(BaseModel):
|
||||
asset_code: str = Field(..., min_length=1, max_length=60)
|
||||
serial_no: str = Field(..., min_length=1, max_length=100)
|
||||
name: str = Field(..., min_length=1, max_length=200)
|
||||
category_id: int
|
||||
department_id: int
|
||||
location_id: int
|
||||
supplier_id: Optional[int] = None
|
||||
purchase_value: Optional[float] = Field(None, ge=0)
|
||||
acquisition_mode: AcquisitionMode = "purchased"
|
||||
monthly_rent: Optional[float] = Field(None, ge=0)
|
||||
useful_life_years: Optional[int] = Field(None, ge=1, le=100)
|
||||
salvage_pct: Optional[float] = Field(None, ge=0, le=50)
|
||||
depreciation_method: Optional[DepreciationMethod] = None
|
||||
purchase_date: Optional[date] = None
|
||||
installation_date: Optional[date] = None
|
||||
status: AssetStatus = "in_service"
|
||||
criticality: AssetCriticality = "non_critical"
|
||||
requires_calibration: bool = False
|
||||
insurance_applicable: bool = False
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class AssetUpdate(BaseModel):
|
||||
asset_code: Optional[str] = Field(None, min_length=1, max_length=60)
|
||||
serial_no: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=200)
|
||||
category_id: Optional[int] = None
|
||||
department_id: Optional[int] = None
|
||||
location_id: Optional[int] = None
|
||||
supplier_id: Optional[int] = None
|
||||
purchase_value: Optional[float] = Field(None, ge=0)
|
||||
acquisition_mode: Optional[AcquisitionMode] = None
|
||||
monthly_rent: Optional[float] = Field(None, ge=0)
|
||||
useful_life_years: Optional[int] = Field(None, ge=1, le=100)
|
||||
salvage_pct: Optional[float] = Field(None, ge=0, le=50)
|
||||
depreciation_method: Optional[DepreciationMethod] = None
|
||||
purchase_date: Optional[date] = None
|
||||
installation_date: Optional[date] = None
|
||||
status: Optional[AssetStatus] = None
|
||||
criticality: Optional[AssetCriticality] = None
|
||||
requires_calibration: Optional[bool] = None
|
||||
insurance_applicable: Optional[bool] = None
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class AssetOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
asset_code: str
|
||||
serial_no: str
|
||||
name: str
|
||||
category_id: int
|
||||
category_name: Optional[str] = None
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
location_id: int
|
||||
location_name: Optional[str] = None
|
||||
supplier_id: Optional[int] = None
|
||||
supplier_name: Optional[str] = None
|
||||
purchase_value: Optional[float] = None
|
||||
acquisition_mode: str = "purchased"
|
||||
monthly_rent: Optional[float] = None
|
||||
useful_life_years: Optional[int] = None
|
||||
salvage_pct: Optional[float] = None
|
||||
depreciation_method: Optional[str] = None
|
||||
purchase_date: Optional[date] = None
|
||||
installation_date: Optional[date] = None
|
||||
status: str
|
||||
criticality: str
|
||||
requires_calibration: bool
|
||||
insurance_applicable: bool
|
||||
remarks: Optional[str] = None
|
||||
warranty_status: str = "none"
|
||||
warranty_end_date: Optional[date] = None
|
||||
warranty_severity: str = "none"
|
||||
contract_status: str = "none"
|
||||
contract_type: Optional[str] = None
|
||||
contract_end_date: Optional[date] = None
|
||||
contract_severity: str = "none"
|
||||
calibration_status: str = "none"
|
||||
calibration_due_date: Optional[date] = None
|
||||
calibration_severity: str = "none"
|
||||
insurance_status: str = "none"
|
||||
insurance_end_date: Optional[date] = None
|
||||
coverage_tag: str = "out_of_contract"
|
||||
coverage: Optional[CoverageOut] = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class AssetListOut(BaseModel):
|
||||
items: list[AssetOut]
|
||||
total: int
|
||||
|
||||
|
||||
class AssetLookupOut(BaseModel):
|
||||
id: int
|
||||
asset_code: str
|
||||
serial_no: str
|
||||
name: str
|
||||
category_id: int
|
||||
category_name: Optional[str] = None
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
location_id: int
|
||||
location_name: Optional[str] = None
|
||||
supplier_id: Optional[int] = None
|
||||
supplier_name: Optional[str] = None
|
||||
status: str
|
||||
criticality: str
|
||||
requires_calibration: bool
|
||||
insurance_applicable: bool
|
||||
warranty_status: str = "none"
|
||||
warranty_end_date: Optional[date] = None
|
||||
contract_status: str = "none"
|
||||
contract_type: Optional[str] = None
|
||||
contract_end_date: Optional[date] = None
|
||||
contract_summary: str = "No active contract"
|
||||
insurance_status: str = "none"
|
||||
insurance_end_date: Optional[date] = None
|
||||
insurance_summary: str = "No policy"
|
||||
coverage_tag: str = "out_of_contract"
|
||||
coverage: Optional[CoverageOut] = None
|
||||
|
||||
|
||||
class AssetLookupListOut(BaseModel):
|
||||
items: list[AssetLookupOut]
|
||||
|
||||
|
||||
class WarrantySummaryOut(BaseModel):
|
||||
id: int
|
||||
asset_id: int
|
||||
duration_months: int
|
||||
start_date: date
|
||||
end_date: date
|
||||
provider_id: Optional[int] = None
|
||||
provider_name: Optional[str] = None
|
||||
status: str
|
||||
severity: str
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class ContractSummaryOut(BaseModel):
|
||||
id: int
|
||||
asset_id: int
|
||||
contract_type: str
|
||||
provider_id: int
|
||||
provider_name: Optional[str] = None
|
||||
start_date: date
|
||||
end_date: date
|
||||
contract_value: Optional[float] = None
|
||||
coverage_period_text: Optional[str] = None
|
||||
renewed_from_id: Optional[int] = None
|
||||
is_superseded: bool
|
||||
status: str
|
||||
severity: str
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class InsuranceSummaryOut(BaseModel):
|
||||
id: int
|
||||
asset_id: int
|
||||
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
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class CalibrationPlanSummaryOut(BaseModel):
|
||||
id: int
|
||||
asset_id: int
|
||||
frequency_months: int
|
||||
calibrations_per_year: int
|
||||
agency_id: Optional[int] = None
|
||||
agency_name: Optional[str] = None
|
||||
approved_by_id: Optional[int] = None
|
||||
approved_on: Optional[date] = None
|
||||
next_due_date: date
|
||||
is_active: bool
|
||||
|
||||
|
||||
class CalibrationRecordSummaryOut(BaseModel):
|
||||
id: int
|
||||
asset_id: int
|
||||
plan_id: int
|
||||
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
|
||||
|
||||
|
||||
class PMScheduleSummaryOut(BaseModel):
|
||||
id: int
|
||||
asset_id: int
|
||||
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
|
||||
cost_per_visit: Optional[float] = None
|
||||
next_planned_date: date
|
||||
is_active: bool
|
||||
|
||||
|
||||
class PMRecordSummaryOut(BaseModel):
|
||||
id: int
|
||||
schedule_id: int
|
||||
asset_id: int
|
||||
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
|
||||
|
||||
|
||||
class ComplaintSummaryOut(BaseModel):
|
||||
id: int
|
||||
complaint_no: str
|
||||
asset_id: int
|
||||
description: str
|
||||
priority: str
|
||||
call_status: str
|
||||
registered_at: datetime
|
||||
closed_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class AttachmentSummaryOut(BaseModel):
|
||||
id: int
|
||||
entity_type: str
|
||||
entity_id: int
|
||||
original_name: str
|
||||
mime_type: str
|
||||
size_bytes: int
|
||||
uploaded_by_id: int
|
||||
uploaded_by_name: Optional[str] = None
|
||||
uploaded_at: datetime
|
||||
|
||||
|
||||
class AssetOverviewOut(BaseModel):
|
||||
asset: AssetOut
|
||||
coverage: CoverageOut
|
||||
warranties: list[WarrantySummaryOut]
|
||||
contracts: list[ContractSummaryOut]
|
||||
insurance_policies: list[InsuranceSummaryOut]
|
||||
calibration_plan: Optional[CalibrationPlanSummaryOut] = None
|
||||
calibration_records: list[CalibrationRecordSummaryOut]
|
||||
pm_schedules: list[PMScheduleSummaryOut]
|
||||
pm_records: list[PMRecordSummaryOut]
|
||||
complaints: list[ComplaintSummaryOut]
|
||||
attachments: list[AttachmentSummaryOut]
|
||||
@@ -0,0 +1,22 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class AttachmentOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
entity_type: str
|
||||
entity_id: int
|
||||
original_name: str
|
||||
mime_type: str
|
||||
size_bytes: int
|
||||
uploaded_by_id: int
|
||||
uploaded_by_name: Optional[str] = None
|
||||
uploaded_at: datetime
|
||||
|
||||
|
||||
class AttachmentListOut(BaseModel):
|
||||
items: list[AttachmentOut]
|
||||
total: int
|
||||
@@ -0,0 +1,26 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: str
|
||||
password: str
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
email: str
|
||||
role: str
|
||||
department_id: Optional[int] = None
|
||||
department_name: Optional[str] = None
|
||||
is_active: bool
|
||||
demo_as_of_date: Optional[str] = None
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
user: UserOut
|
||||
@@ -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,161 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from .assets import CoverageOut
|
||||
|
||||
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)
|
||||
repair_cost: 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
|
||||
repair_cost: Optional[float] = None
|
||||
coverage_tag: Optional[str] = None
|
||||
coverage_contract_id: Optional[int] = None
|
||||
coverage_provider_id: Optional[int] = None
|
||||
coverage_at_registration: Optional[CoverageOut] = None
|
||||
coverage_now: Optional[CoverageOut] = 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,78 @@
|
||||
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
|
||||
contract_value: Optional[float] = Field(None, ge=0)
|
||||
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
|
||||
contract_value: Optional[float] = Field(None, ge=0)
|
||||
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
|
||||
contract_value: Optional[float] = Field(None, ge=0)
|
||||
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
|
||||
contract_value: Optional[float] = None
|
||||
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
|
||||
@@ -0,0 +1,162 @@
|
||||
from typing import Generic, Literal, Optional, TypeVar
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
VendorType = Literal["supplier", "service_provider", "calibration_agency", "insurer", "oem"]
|
||||
UserRole = Literal["system_admin", "biomedical", "department_user", "management", "coordinator"]
|
||||
|
||||
|
||||
class PaginatedOut(BaseModel, Generic[T]):
|
||||
items: list[T]
|
||||
total: int
|
||||
|
||||
|
||||
# --- Departments ---
|
||||
class DepartmentCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=150)
|
||||
code: str = Field(..., min_length=1, max_length=30)
|
||||
description: Optional[str] = None
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class DepartmentUpdate(BaseModel):
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=150)
|
||||
code: Optional[str] = Field(None, min_length=1, max_length=30)
|
||||
description: Optional[str] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class DepartmentOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
code: str
|
||||
description: Optional[str] = None
|
||||
is_active: bool
|
||||
|
||||
|
||||
# --- Locations ---
|
||||
class LocationCreate(BaseModel):
|
||||
department_id: int
|
||||
name: str = Field(..., min_length=1, max_length=150)
|
||||
floor_wing: Optional[str] = Field(None, max_length=100)
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class LocationUpdate(BaseModel):
|
||||
department_id: Optional[int] = None
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=150)
|
||||
floor_wing: Optional[str] = Field(None, max_length=100)
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class LocationOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
name: str
|
||||
floor_wing: Optional[str] = None
|
||||
is_active: bool
|
||||
|
||||
|
||||
# --- Categories ---
|
||||
class CategoryCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=150)
|
||||
description: Optional[str] = None
|
||||
default_useful_life_years: Optional[int] = Field(None, ge=1, le=100)
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class CategoryUpdate(BaseModel):
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=150)
|
||||
description: Optional[str] = None
|
||||
default_useful_life_years: Optional[int] = Field(None, ge=1, le=100)
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class CategoryOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
default_useful_life_years: Optional[int] = None
|
||||
is_active: bool
|
||||
|
||||
|
||||
# --- Vendors ---
|
||||
class VendorCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=200)
|
||||
vendor_type: VendorType
|
||||
contact_person: Optional[str] = Field(None, max_length=150)
|
||||
phone: Optional[str] = Field(None, max_length=50)
|
||||
email: Optional[str] = Field(None, max_length=150)
|
||||
address: Optional[str] = None
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class VendorUpdate(BaseModel):
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=200)
|
||||
vendor_type: Optional[VendorType] = None
|
||||
contact_person: Optional[str] = Field(None, max_length=150)
|
||||
phone: Optional[str] = Field(None, max_length=50)
|
||||
email: Optional[str] = Field(None, max_length=150)
|
||||
address: Optional[str] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class VendorOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
vendor_type: str
|
||||
contact_person: Optional[str] = None
|
||||
phone: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
address: Optional[str] = None
|
||||
is_active: bool
|
||||
|
||||
|
||||
# --- Users ---
|
||||
class UserCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=150)
|
||||
email: str = Field(..., min_length=3, max_length=200)
|
||||
password: str = Field(..., max_length=128)
|
||||
role: UserRole
|
||||
department_id: Optional[int] = None
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=150)
|
||||
email: Optional[str] = Field(None, min_length=3, max_length=200)
|
||||
password: Optional[str] = Field(None, max_length=128)
|
||||
role: Optional[UserRole] = None
|
||||
department_id: Optional[int] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class UserListOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
email: str
|
||||
role: str
|
||||
department_id: Optional[int] = None
|
||||
department_name: Optional[str] = None
|
||||
is_active: bool
|
||||
|
||||
|
||||
class UserLookupOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
role: str
|
||||
department_id: Optional[int] = None
|
||||
@@ -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,122 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Literal, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from .assets import CoverageOut
|
||||
|
||||
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
|
||||
cost_per_visit: Optional[float] = Field(None, ge=0)
|
||||
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
|
||||
cost_per_visit: Optional[float] = Field(None, ge=0)
|
||||
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
|
||||
cost_per_visit: Optional[float] = None
|
||||
coverage_tag: Optional[str] = None
|
||||
coverage: Optional[CoverageOut] = None
|
||||
no_active_contract: Optional[bool] = 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
|
||||
coverage_tag: Optional[str] = None
|
||||
coverage: Optional[CoverageOut] = None
|
||||
|
||||
|
||||
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,31 @@
|
||||
from typing import Any, Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class SettingItemOut(BaseModel):
|
||||
key: str
|
||||
value: Any
|
||||
type: str
|
||||
label: str
|
||||
description: str
|
||||
default: Any
|
||||
min: Optional[float] = None
|
||||
max: Optional[float] = None
|
||||
options: Optional[list[str]] = None
|
||||
|
||||
|
||||
class SettingsListOut(BaseModel):
|
||||
items: list[SettingItemOut]
|
||||
|
||||
|
||||
class SettingsUpdateIn(BaseModel):
|
||||
values: dict[str, Any]
|
||||
|
||||
|
||||
class DemoDateIn(BaseModel):
|
||||
demo_as_of_date: Optional[str] = None
|
||||
|
||||
|
||||
class DemoDateOut(BaseModel):
|
||||
demo_as_of_date: Optional[str] = None
|
||||
effective_today: str
|
||||
@@ -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
|
||||
@@ -0,0 +1,917 @@
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
from pathlib import Path
|
||||
import random
|
||||
import time as pytime
|
||||
from PIL import Image, ImageDraw
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.config import settings
|
||||
from ..core.db import SessionLocal, engine
|
||||
from ..core.security import hash_password
|
||||
from ..core.time_utils import KOLKATA, effective_today
|
||||
from ..models import (
|
||||
Asset,
|
||||
Attachment,
|
||||
Base,
|
||||
CalibrationPlan,
|
||||
CalibrationRecord,
|
||||
Category,
|
||||
Complaint,
|
||||
ComplaintEvent,
|
||||
Contract,
|
||||
DemoEquipment,
|
||||
Department,
|
||||
DepartmentVisit,
|
||||
InsurancePolicy,
|
||||
Location,
|
||||
PMRecord,
|
||||
PMSchedule,
|
||||
User,
|
||||
Vendor,
|
||||
Warranty,
|
||||
)
|
||||
from ..services.alerts import run_alert_check
|
||||
from ..services.coverage import get_coverage
|
||||
from ..services.settings_service import ensure_default_settings, get_demo_as_of_date
|
||||
|
||||
|
||||
def _make_minimal_pdf(title: str) -> bytes:
|
||||
safe_title = title.replace("(", "").replace(")", "")
|
||||
stream = f"BT /F1 14 Tf 50 750 Td ({safe_title}) Tj ET".encode("latin-1", errors="ignore")
|
||||
objects = [
|
||||
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n",
|
||||
b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",
|
||||
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\nendobj\n",
|
||||
f"4 0 obj\n<< /Length {len(stream)} >>\nstream\n".encode("ascii") + stream + b"\nendstream\nendobj\n",
|
||||
b"5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n",
|
||||
]
|
||||
out = bytearray(b"%PDF-1.4\n")
|
||||
offsets = [0]
|
||||
for obj in objects:
|
||||
offsets.append(len(out))
|
||||
out.extend(obj)
|
||||
xref_pos = len(out)
|
||||
out.extend(f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode("ascii"))
|
||||
for off in offsets[1:]:
|
||||
out.extend(f"{off:010d} 00000 n \n".encode("ascii"))
|
||||
out.extend(
|
||||
f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode("ascii")
|
||||
)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _make_placeholder_jpeg(dest: Path, label: str, bg_rgb: tuple[int, int, int]) -> int:
|
||||
img = Image.new("RGB", (640, 480), color=bg_rgb)
|
||||
draw = ImageDraw.Draw(img)
|
||||
draw.rectangle([20, 20, 620, 460], outline=(255, 255, 255), width=3)
|
||||
draw.text((40, 200), "Poona Hospital & Research Centre", fill=(255, 255, 255))
|
||||
draw.text((40, 240), label, fill=(240, 240, 240))
|
||||
img.save(dest, format="JPEG", quality=80)
|
||||
return dest.stat().st_size
|
||||
|
||||
|
||||
def _ist_to_utc(d: date, hour: int = 10, minute: int = 0) -> datetime:
|
||||
local_dt = KOLKATA.localize(datetime.combine(d, time(hour, minute)))
|
||||
return local_dt.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]:
|
||||
rng = random.Random(42)
|
||||
|
||||
# 1. Clear all tables cleanly in reverse dependency order
|
||||
for table in reversed(Base.metadata.sorted_tables):
|
||||
db.execute(table.delete())
|
||||
# Reset SQLite autoincrement counters if sqlite_sequence exists
|
||||
try:
|
||||
db.execute(text("DELETE FROM sqlite_sequence"))
|
||||
except Exception:
|
||||
pass
|
||||
db.flush()
|
||||
db.expunge_all()
|
||||
|
||||
# 2. Settings (all defaults)
|
||||
ensure_default_settings(db)
|
||||
|
||||
today = effective_today(db)
|
||||
now_utc = _ist_to_utc(today, 12, 0) if get_demo_as_of_date(db) else datetime.now(timezone.utc)
|
||||
|
||||
# 3. Departments (8)
|
||||
dept_specs = [
|
||||
("Intensive Care Unit", "ICU", "Medical and surgical intensive care beds"),
|
||||
("Operation Theatre", "OT", "Main and modular surgical suites"),
|
||||
("Radiology & Imaging", "RAD", "CT, MRI, Ultrasound, and X-Ray"),
|
||||
("Cardiology", "CARD", "Cath lab and cardiac diagnostics"),
|
||||
("Emergency & Trauma", "EMER", "24x7 casualty and trauma care"),
|
||||
("Pathology & Lab", "LAB", "Clinical biochemistry and hematology"),
|
||||
("Neonatal ICU", "NICU", "Neonatal intensive care and warmers"),
|
||||
("Dialysis Unit", "DIAL", "Hemodialysis and RO water treatment"),
|
||||
]
|
||||
departments: list[Department] = []
|
||||
for name, code, desc in dept_specs:
|
||||
d = Department(name=name, code=code, description=desc, is_active=True)
|
||||
db.add(d)
|
||||
departments.append(d)
|
||||
db.flush()
|
||||
|
||||
# 4. Locations (20)
|
||||
loc_specs = [
|
||||
(0, "ICU Bay A", "2nd Floor - East Wing"),
|
||||
(0, "ICU Bay B", "2nd Floor - East Wing"),
|
||||
(0, "ICU Isolation Room 1", "2nd Floor - East Wing"),
|
||||
(1, "Modular OT 1", "3rd Floor - Central Block"),
|
||||
(1, "Modular OT 2", "3rd Floor - Central Block"),
|
||||
(1, "OT Recovery Suite", "3rd Floor - Central Block"),
|
||||
(2, "CT Scan Room", "Ground Floor - West Wing"),
|
||||
(2, "Digital X-Ray Suite", "Ground Floor - West Wing"),
|
||||
(2, "Ultrasound Room 2", "Ground Floor - West Wing"),
|
||||
(3, "Cath Lab 1", "4th Floor - Cardiac Block"),
|
||||
(3, "Echo & TMT Room", "4th Floor - Cardiac Block"),
|
||||
(4, "Trauma Resuscitation Bay", "Ground Floor - Main Gate"),
|
||||
(4, "Emergency Observation Ward", "Ground Floor - Main Gate"),
|
||||
(5, "Biochemistry Analyzer Lab", "1st Floor - Diagnostic Wing"),
|
||||
(5, "Hematology & Blood Bank", "1st Floor - Diagnostic Wing"),
|
||||
(6, "NICU Level 3 Bay", "2nd Floor - Maternity Wing"),
|
||||
(6, "NICU Step-Down Unit", "2nd Floor - Maternity Wing"),
|
||||
(7, "Dialysis Station 1-6", "1st Floor - Renal Wing"),
|
||||
(7, "Dialysis Station 7-12", "1st Floor - Renal Wing"),
|
||||
(7, "RO Water Plant Room", "1st Floor - Renal Wing"),
|
||||
]
|
||||
locations: list[Location] = []
|
||||
locs_by_dept: dict[int, list[Location]] = {d.id: [] for d in departments}
|
||||
for dept_idx, lname, floor in loc_specs:
|
||||
dept = departments[dept_idx]
|
||||
loc = Location(department_id=dept.id, name=lname, floor_wing=floor, is_active=True)
|
||||
db.add(loc)
|
||||
locations.append(loc)
|
||||
locs_by_dept[dept.id].append(loc)
|
||||
db.flush()
|
||||
|
||||
# 5. Categories (8) with realistic default_useful_life_years
|
||||
cat_specs = [
|
||||
("Life Support & Ventilators", "ICU ventilators, CPAP/BiPAP, anesthesia systems", 10),
|
||||
("Patient Monitoring", "Multipara monitors, pulse oximeters, central stations", 8),
|
||||
("Diagnostic Imaging", "X-Ray, C-Arm, ultrasound, CT/MRI auxiliaries", 12),
|
||||
("Surgical & OT Equipment", "Electrosurgical cautery, OT tables, OT lights", 10),
|
||||
("Laboratory Analyzers", "Biochemistry, hematology, blood gas analyzers", 8),
|
||||
("Infusion & Dialysis", "Syringe pumps, infusion pumps, hemodialysis machines", 7),
|
||||
("Sterilization & CSSD", "Autoclaves, ETO sterilizers, washer-disinfectors", 12),
|
||||
("Emergency & Resuscitation", "Defibrillators, crash carts, suction apparatus", 8),
|
||||
]
|
||||
categories: list[Category] = []
|
||||
for cname, cdesc, clife in cat_specs:
|
||||
c = Category(
|
||||
name=cname,
|
||||
description=cdesc,
|
||||
default_useful_life_years=clife,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(c)
|
||||
categories.append(c)
|
||||
db.flush()
|
||||
|
||||
# 6. Vendors (12)
|
||||
vendor_specs = [
|
||||
("Philips Healthcare India", "oem", "Arun Mehta", "+91-20-66201100", "service.west@philips-demo.in", "Pune, MH"),
|
||||
("GE HealthCare Medical Systems", "oem", "Sanjay Verma", "+91-20-66202200", "support@gehc-demo.in", "Mumbai, MH"),
|
||||
("Mindray Medical India", "oem", "Rohan Kapoor", "+91-22-40203300", "service@mindray-demo.in", "Mumbai, MH"),
|
||||
("MedTech Pune Distributors", "supplier", "Prashant Joshi", "+91-9822011223", "sales@medtechpune.in", "Deccan Gymkhana, Pune"),
|
||||
("Sahyadri Medical Supplies", "supplier", "Manish Patwardhan", "+91-9823044556", "orders@sahyadrimed.in", "Kothrud, Pune"),
|
||||
("Deccan Bio-Equipments", "supplier", "Kavita Gokhale", "+91-9890077889", "info@deccanbio.in", "Shivajinagar, Pune"),
|
||||
("Apex Biomedical Services", "service_provider", "Nitin Kulkarni", "+91-9765012345", "amc@apexbiomed.in", "Pimpri, Pune"),
|
||||
("Precision MedCare Engineering", "service_provider", "Deepak Rao", "+91-9850098765", "ops@precisionmedcare.in", "Hadapsar, Pune"),
|
||||
("NABL Metrology & CalLabs Pune", "calibration_agency", "Dr. Sunita Deshpande", "+91-20-25441234", "cal@nablcallabs.in", "Bhosari MIDC, Pune"),
|
||||
("Western India Calibration Lab", "calibration_agency", "Mahesh Pawar", "+91-20-24335678", "qa@wical.in", "Satara Road, Pune"),
|
||||
("New India Assurance Co.", "insurer", "Smita Kale", "+91-20-26128899", "corporate@nia-demo.in", "MG Road, Pune"),
|
||||
("Bajaj Allianz General Insurance", "insurer", "Vivek Deshmukh", "+91-20-66026602", "healthassets@bagic-demo.in", "Yerwada, Pune"),
|
||||
]
|
||||
vendors: list[Vendor] = []
|
||||
vendors_by_type: dict[str, list[Vendor]] = {}
|
||||
for vname, vtype, cp, ph, em, addr in vendor_specs:
|
||||
v = Vendor(
|
||||
name=vname,
|
||||
vendor_type=vtype,
|
||||
contact_person=cp,
|
||||
phone=ph,
|
||||
email=em,
|
||||
address=addr,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(v)
|
||||
vendors.append(v)
|
||||
vendors_by_type.setdefault(vtype, []).append(v)
|
||||
db.flush()
|
||||
|
||||
# 7. Users (11: 5 demo + 6 realistic hospital staff)
|
||||
demo_pw_hash = hash_password("Demo@123")
|
||||
user_specs = [
|
||||
("Dr. Rajesh Kulkarni", "admin@poona.demo", "system_admin", None),
|
||||
("Suresh Deshmukh", "bio@poona.demo", "biomedical", None),
|
||||
("Sister Kavita Joshi", "dept@poona.demo", "department_user", departments[0].id), # ICU
|
||||
("Dr. Anjali Gokhale", "mgmt@poona.demo", "management", None),
|
||||
("Priya Patwardhan", "coord@poona.demo", "coordinator", None),
|
||||
("Vikram Shinde", "vikram.shinde@poona.demo", "biomedical", None),
|
||||
("Sneha Kulkarni", "sneha.kulkarni@poona.demo", "biomedical", None),
|
||||
("Dr. Amit Bhosale", "dr.amit.bhosale@poona.demo", "department_user", departments[1].id), # OT
|
||||
("Meera Nair", "meera.nair@poona.demo", "department_user", departments[2].id), # RAD
|
||||
("Rohit Deshpande", "rohit.deshpande@poona.demo", "department_user", departments[3].id), # CARD
|
||||
("Neha Chavan", "neha.chavan@poona.demo", "coordinator", None),
|
||||
]
|
||||
users: list[User] = []
|
||||
for uname, uemail, urole, udept in user_specs:
|
||||
u = User(
|
||||
name=uname,
|
||||
email=uemail,
|
||||
password_hash=demo_pw_hash,
|
||||
role=urole,
|
||||
department_id=udept,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(u)
|
||||
users.append(u)
|
||||
db.flush()
|
||||
|
||||
admin_user = users[0]
|
||||
bio_users = [users[1], users[5], users[6]]
|
||||
dept_users = [users[2], users[7], users[8], users[9]]
|
||||
coord_users = [users[4], users[10]]
|
||||
|
||||
# 8. Assets (60)
|
||||
equipment_catalog = [
|
||||
("ICU Ventilator Servo-i", 0, 0, True, True, 950000.0),
|
||||
("Multipara Patient Monitor MP50", 1, 0, True, True, 380000.0),
|
||||
("Syringe Infusion Pump SP-500", 5, 0, True, False, 65000.0),
|
||||
("Biphasic Defibrillator DFM100", 7, 4, True, True, 320000.0),
|
||||
("Anesthesia Workstation Aespire", 0, 1, True, True, 1150000.0),
|
||||
("Electrosurgical Cautery Unit", 3, 1, True, False, 260000.0),
|
||||
("LED Dual-Dome OT Light", 3, 1, False, False, 480000.0),
|
||||
("64-Slice CT Scanner Optima", 2, 2, True, True, 12500000.0),
|
||||
("C-Arm Fluoroscopy System", 2, 1, True, True, 3400000.0),
|
||||
("Color Doppler Ultrasound", 2, 2, False, True, 2600000.0),
|
||||
("12-Channel Digital ECG Machine", 1, 3, True, False, 140000.0),
|
||||
("1.5T MRI Imaging System", 2, 2, False, True, 18500000.0),
|
||||
("Automated Biochemistry Analyzer", 4, 5, True, True, 1450000.0),
|
||||
("5-Part Hematology Analyzer", 4, 5, True, True, 980000.0),
|
||||
("ABG Blood Gas Analyzer", 4, 0, True, False, 420000.0),
|
||||
("Infant Radiant Warmer", 0, 6, True, False, 210000.0),
|
||||
("Neonatal Phototherapy Unit", 0, 6, False, False, 125000.0),
|
||||
("Hemodialysis Machine 4008S", 5, 7, True, True, 890000.0),
|
||||
("High-Pressure Steam Autoclave", 6, 1, True, True, 450000.0),
|
||||
("Portable Suction Apparatus", 7, 4, False, False, 180000.0),
|
||||
]
|
||||
suppliers_and_oems = vendors_by_type["supplier"] + vendors_by_type["oem"]
|
||||
dept_counters: dict[str, int] = {}
|
||||
assets: list[Asset] = []
|
||||
rented_indices = {45, 46, 47, 48, 49, 50}
|
||||
fully_dep_indices = {40, 41}
|
||||
|
||||
for i in range(60):
|
||||
base_name, cat_idx, default_dept_idx, req_cal, ins_app, base_val = equipment_catalog[i % len(equipment_catalog)]
|
||||
dept_idx = default_dept_idx if i < 20 else rng.randrange(len(departments))
|
||||
dept = departments[dept_idx]
|
||||
dept_counters[dept.code] = dept_counters.get(dept.code, 0) + 1
|
||||
asset_code = f"PHRC-{dept.code}-{dept_counters[dept.code]:04d}"
|
||||
loc = rng.choice(locs_by_dept[dept.id])
|
||||
supplier = rng.choice(suppliers_and_oems)
|
||||
|
||||
if i < 10:
|
||||
# 10 latest equipment purchased in the last 12 months
|
||||
purchase_date = today - timedelta(days=30 + i * 26)
|
||||
install_date = purchase_date + timedelta(days=7)
|
||||
elif i in fully_dep_indices:
|
||||
# Fully depreciated assets (> 10 years old)
|
||||
purchase_date = today - timedelta(days=12 * 365 + (i - 40) * 180)
|
||||
install_date = purchase_date + timedelta(days=15)
|
||||
else:
|
||||
years_ago = rng.randint(2, 8)
|
||||
purchase_date = today - timedelta(days=years_ago * 365 + rng.randint(15, 280))
|
||||
install_date = purchase_date + timedelta(days=rng.randint(7, 30))
|
||||
|
||||
# Status distribution: mostly in_service, a few under_repair / out_of_service / condemned
|
||||
if i in (5, 19, 31, 44):
|
||||
status_val = "under_repair"
|
||||
elif i in (52, 57):
|
||||
status_val = "out_of_service"
|
||||
elif i in (58, 59):
|
||||
status_val = "condemned"
|
||||
else:
|
||||
status_val = "in_service"
|
||||
|
||||
criticality = "critical" if (cat_idx in (0, 2, 3, 7) or i % 3 == 0) else "non_critical"
|
||||
needs_cal = True if i < 22 else req_cal
|
||||
needs_ins = True if i < 26 else ins_app
|
||||
|
||||
is_rented = i in rented_indices
|
||||
pv = None if is_rented else round(base_val * rng.uniform(0.95, 1.08), 0)
|
||||
acq_mode = "rented" if is_rented else "purchased"
|
||||
if is_rented:
|
||||
m_rent = round(base_val * rng.uniform(0.022, 0.03), -2)
|
||||
elif i < 25:
|
||||
# 25 owned assets with monthly_rent quotes for buy-vs-rent comparison
|
||||
m_rent = round((pv or base_val) * rng.uniform(0.022, 0.032), -2)
|
||||
else:
|
||||
m_rent = None
|
||||
|
||||
cat_life = categories[cat_idx].default_useful_life_years or 10
|
||||
u_life = None if is_rented else (10 if i in fully_dep_indices else cat_life)
|
||||
salv_pct = None if is_rented else (5.0 if i % 4 != 0 else 10.0)
|
||||
dep_method = None if is_rented else ("straight_line" if i % 3 != 2 else "written_down")
|
||||
|
||||
a = Asset(
|
||||
asset_code=asset_code,
|
||||
serial_no=f"SN-{2016 + (i % 9)}-{10000 + i * 37}",
|
||||
name=f"{base_name}" if i < 20 else f"{base_name} #{(i // 20) + 1}",
|
||||
category_id=categories[cat_idx].id,
|
||||
department_id=dept.id,
|
||||
location_id=loc.id,
|
||||
supplier_id=supplier.id,
|
||||
purchase_value=pv,
|
||||
acquisition_mode=acq_mode,
|
||||
monthly_rent=m_rent,
|
||||
useful_life_years=u_life,
|
||||
salvage_pct=salv_pct,
|
||||
depreciation_method=dep_method,
|
||||
purchase_date=purchase_date,
|
||||
installation_date=install_date,
|
||||
status=status_val,
|
||||
criticality=criticality,
|
||||
requires_calibration=needs_cal,
|
||||
insurance_applicable=needs_ins,
|
||||
remarks="Procured under Poona Hospital capital equipment budget." if not is_rented else "Leased medical equipment on monthly rental.",
|
||||
created_by_id=admin_user.id,
|
||||
updated_by_id=admin_user.id,
|
||||
)
|
||||
db.add(a)
|
||||
assets.append(a)
|
||||
db.flush()
|
||||
|
||||
# 9. Contracts (35 total: 3 expiring <=30d, 1 <=5d, 1 expired, 1 renewed chain w/ is_superseded=True)
|
||||
service_providers = vendors_by_type["service_provider"] + vendors_by_type["oem"]
|
||||
contracts: list[Contract] = []
|
||||
# Renewed chain: old superseded contract (#0) + active renewed contract (#1)
|
||||
a0_pv = assets[0].purchase_value or 950000.0
|
||||
old_c = Contract(
|
||||
asset_id=assets[0].id,
|
||||
contract_type="CMC",
|
||||
provider_id=service_providers[0].id,
|
||||
start_date=today - timedelta(days=400),
|
||||
end_date=today - timedelta(days=35),
|
||||
contract_value=round(a0_pv * 0.10, -2),
|
||||
coverage_period_text="1 Year",
|
||||
renewed_from_id=None,
|
||||
is_superseded=True,
|
||||
remarks="Previous year CMC superseded on renewal.",
|
||||
created_by_id=coord_users[0].id,
|
||||
updated_by_id=coord_users[0].id,
|
||||
)
|
||||
db.add(old_c)
|
||||
db.flush()
|
||||
contracts.append(old_c)
|
||||
|
||||
new_c = Contract(
|
||||
asset_id=assets[0].id,
|
||||
contract_type="CMC",
|
||||
provider_id=service_providers[0].id,
|
||||
start_date=today - timedelta(days=34),
|
||||
end_date=today + timedelta(days=331),
|
||||
contract_value=round(a0_pv * 0.11, -2),
|
||||
coverage_period_text="1 Year",
|
||||
renewed_from_id=old_c.id,
|
||||
is_superseded=False,
|
||||
remarks="Renewed annual comprehensive maintenance contract.",
|
||||
created_by_id=coord_users[0].id,
|
||||
updated_by_id=coord_users[0].id,
|
||||
)
|
||||
db.add(new_c)
|
||||
contracts.append(new_c)
|
||||
|
||||
# 1 expiring <= 5d (idx 2), 3 expiring <= 30d (idx 3, 4, 5), 1 expired (idx 16), rest active > 45d
|
||||
special_end_offsets = {
|
||||
2: 3, # <= 5 days
|
||||
3: 11, # <= 30 days
|
||||
4: 19, # <= 30 days
|
||||
5: 27, # <= 30 days
|
||||
16: -14, # expired -> out_of_contract
|
||||
}
|
||||
for idx in range(1, 34):
|
||||
asset = assets[idx]
|
||||
offset = special_end_offsets.get(idx, rng.randint(50, 340))
|
||||
end_d = today + timedelta(days=offset)
|
||||
start_d = end_d - timedelta(days=365)
|
||||
ctype = ("AMC" if idx % 2 == 0 else "CMC") if idx < 10 else rng.choice(["AMC", "CMC", "AMC", "OTHER"])
|
||||
pv_base = asset.purchase_value or 500000.0
|
||||
if ctype == "AMC":
|
||||
cval = round(pv_base * rng.uniform(0.055, 0.095), -2)
|
||||
elif ctype == "CMC":
|
||||
cval = round(pv_base * rng.uniform(0.085, 0.135), -2)
|
||||
else:
|
||||
cval = round(pv_base * rng.uniform(0.04, 0.07), -2)
|
||||
c = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type=ctype,
|
||||
provider_id=rng.choice(service_providers).id,
|
||||
start_date=start_d,
|
||||
end_date=end_d,
|
||||
contract_value=cval,
|
||||
coverage_period_text="1 Year",
|
||||
renewed_from_id=None,
|
||||
is_superseded=False,
|
||||
remarks=f"{ctype} maintenance coverage for {asset.asset_code}.",
|
||||
created_by_id=coord_users[idx % 2].id,
|
||||
updated_by_id=coord_users[idx % 2].id,
|
||||
)
|
||||
db.add(c)
|
||||
contracts.append(c)
|
||||
db.flush()
|
||||
|
||||
active_contract_by_asset: dict[int, Contract] = {
|
||||
c.asset_id: c for c in contracts if not c.is_superseded and c.end_date >= today
|
||||
}
|
||||
|
||||
# 10. Warranties (20 total: 4 expiring <= 30d)
|
||||
for idx in range(20):
|
||||
asset = assets[idx]
|
||||
if idx < 4:
|
||||
end_d = today + timedelta(days=[5, 14, 22, 28][idx])
|
||||
dur = 24
|
||||
start_d = end_d - timedelta(days=dur * 30)
|
||||
else:
|
||||
dur = rng.choice([12, 24, 36])
|
||||
end_d = today + timedelta(days=rng.randint(60, 500))
|
||||
start_d = end_d - timedelta(days=dur * 30)
|
||||
w = Warranty(
|
||||
asset_id=asset.id,
|
||||
duration_months=dur,
|
||||
start_date=start_d,
|
||||
end_date=end_d,
|
||||
provider_id=asset.supplier_id,
|
||||
remarks="OEM standard warranty.",
|
||||
created_by_id=coord_users[0].id,
|
||||
updated_by_id=coord_users[0].id,
|
||||
)
|
||||
db.add(w)
|
||||
db.flush()
|
||||
|
||||
# 11. Insurance Policies (25 total: 2 expiring soon)
|
||||
insurers = vendors_by_type["insurer"]
|
||||
insured_assets = [a for a in assets if a.insurance_applicable][:25]
|
||||
for idx, asset in enumerate(insured_assets):
|
||||
if idx == 0:
|
||||
end_d = today + timedelta(days=9)
|
||||
elif idx == 1:
|
||||
end_d = today + timedelta(days=23)
|
||||
else:
|
||||
end_d = today + timedelta(days=rng.randint(45, 330))
|
||||
start_d = end_d - timedelta(days=365)
|
||||
pol = InsurancePolicy(
|
||||
asset_id=asset.id,
|
||||
insurer_id=insurers[idx % len(insurers)].id,
|
||||
policy_no=f"PHRC-INS-{today.year}-{1001 + idx}",
|
||||
start_date=start_d,
|
||||
end_date=end_d,
|
||||
coverage_amount=round((asset.purchase_value or 500000.0) * 0.9, 2),
|
||||
remarks="All-risk biomedical equipment insurance.",
|
||||
created_by_id=coord_users[idx % 2].id,
|
||||
updated_by_id=coord_users[idx % 2].id,
|
||||
)
|
||||
db.add(pol)
|
||||
db.flush()
|
||||
|
||||
# 12. Calibration Plans (20) + historical completed records + open (upcoming/due/overdue) records
|
||||
cal_agencies = vendors_by_type["calibration_agency"]
|
||||
cal_assets = [a for a in assets if a.requires_calibration][:20]
|
||||
for idx, asset in enumerate(cal_assets):
|
||||
freq = 6 if idx % 2 == 0 else 12
|
||||
per_year = 12 // freq
|
||||
agency = cal_agencies[idx % len(cal_agencies)]
|
||||
# Make 3 overdue, 4 due within 15 days, 13 upcoming
|
||||
if idx < 3:
|
||||
next_due = today - timedelta(days=4 + idx * 5)
|
||||
elif idx < 7:
|
||||
next_due = today + timedelta(days=2 + (idx - 3) * 3)
|
||||
else:
|
||||
next_due = today + timedelta(days=25 + idx * 7)
|
||||
|
||||
plan = CalibrationPlan(
|
||||
asset_id=asset.id,
|
||||
frequency_months=freq,
|
||||
calibrations_per_year=per_year,
|
||||
agency_id=agency.id,
|
||||
approved_by_id=bio_users[0].id,
|
||||
approved_on=today - timedelta(days=400),
|
||||
next_due_date=next_due,
|
||||
is_active=True,
|
||||
created_by_id=bio_users[0].id,
|
||||
updated_by_id=bio_users[0].id,
|
||||
)
|
||||
db.add(plan)
|
||||
db.flush()
|
||||
|
||||
# Historical completed record (1-2 cycles back)
|
||||
prev_due = next_due - timedelta(days=freq * 30)
|
||||
if prev_due < today:
|
||||
db.add(
|
||||
CalibrationRecord(
|
||||
asset_id=asset.id,
|
||||
plan_id=plan.id,
|
||||
due_date=prev_due,
|
||||
completed_date=prev_due - timedelta(days=rng.randint(0, 3)),
|
||||
agency_id=agency.id,
|
||||
certificate_no=f"CAL-{today.year - 1}-{400 + idx}",
|
||||
remarks="Calibrated within NABL permissible tolerance.",
|
||||
status="completed",
|
||||
created_by_id=bio_users[idx % len(bio_users)].id,
|
||||
updated_by_id=bio_users[idx % len(bio_users)].id,
|
||||
)
|
||||
)
|
||||
# Current open calibration record (status=None so upcoming/due/overdue is computed dynamically)
|
||||
db.add(
|
||||
CalibrationRecord(
|
||||
asset_id=asset.id,
|
||||
plan_id=plan.id,
|
||||
due_date=next_due,
|
||||
completed_date=None,
|
||||
agency_id=agency.id,
|
||||
certificate_no=None,
|
||||
remarks="Scheduled calibration cycle.",
|
||||
status=None,
|
||||
created_by_id=bio_users[0].id,
|
||||
updated_by_id=bio_users[0].id,
|
||||
)
|
||||
)
|
||||
db.flush()
|
||||
|
||||
# 13. PM Schedules (45: 60% in_house=27, 40% outsourced=18) + 6 months records + 4 due this month + 3 overdue
|
||||
for idx in range(45):
|
||||
asset = assets[idx]
|
||||
mode = "in_house" if idx < 27 else "outsourced"
|
||||
freq = 3 if idx % 3 == 0 else 6
|
||||
contract = active_contract_by_asset.get(asset.id)
|
||||
provider_id = contract.provider_id if (mode == "outsourced" and contract) else (
|
||||
service_providers[idx % len(service_providers)].id if mode == "outsourced" else None
|
||||
)
|
||||
# 3 overdue, 4 due this month (within next 12 days), rest upcoming
|
||||
if idx < 3:
|
||||
next_planned = today - timedelta(days=3 + idx * 5)
|
||||
elif idx < 7:
|
||||
next_planned = today + timedelta(days=1 + (idx - 3) * 3)
|
||||
else:
|
||||
next_planned = today + timedelta(days=22 + (idx % 60))
|
||||
|
||||
inhouse_cost = (
|
||||
round(max(2500.0, min(25000.0, (asset.purchase_value or 350000.0) * 0.008)), -2)
|
||||
if mode == "in_house"
|
||||
else None
|
||||
)
|
||||
|
||||
sched = PMSchedule(
|
||||
asset_id=asset.id,
|
||||
service_mode=mode,
|
||||
frequency_months=freq,
|
||||
responsible_team="In-House Biomedical Team" if mode == "in_house" else None,
|
||||
provider_id=provider_id,
|
||||
contract_id=contract.id if (mode == "outsourced" and contract) else None,
|
||||
cost_per_visit=inhouse_cost,
|
||||
next_planned_date=next_planned,
|
||||
is_active=True,
|
||||
created_by_id=bio_users[0].id,
|
||||
updated_by_id=bio_users[0].id,
|
||||
)
|
||||
db.add(sched)
|
||||
db.flush()
|
||||
|
||||
# Historical completed PM records over past 6 months
|
||||
for cycle in (1, 2):
|
||||
hist_date = today - timedelta(days=cycle * 90 + (idx % 15))
|
||||
db.add(
|
||||
PMRecord(
|
||||
schedule_id=sched.id,
|
||||
asset_id=asset.id,
|
||||
planned_date=hist_date,
|
||||
completed_date=hist_date + timedelta(days=rng.randint(0, 2)),
|
||||
status="completed",
|
||||
service_details="Filter cleaning, electrical safety test, and functional verification.",
|
||||
remarks="Passed all PM checklist points.",
|
||||
created_by_id=bio_users[idx % len(bio_users)].id,
|
||||
updated_by_id=bio_users[idx % len(bio_users)].id,
|
||||
)
|
||||
)
|
||||
# Current open PM record (status=None; upcoming/due/overdue computed dynamically)
|
||||
db.add(
|
||||
PMRecord(
|
||||
schedule_id=sched.id,
|
||||
asset_id=asset.id,
|
||||
planned_date=next_planned,
|
||||
completed_date=None,
|
||||
status=None,
|
||||
service_details=None,
|
||||
remarks="Scheduled preventive maintenance.",
|
||||
created_by_id=bio_users[0].id,
|
||||
updated_by_id=bio_users[0].id,
|
||||
)
|
||||
)
|
||||
db.flush()
|
||||
|
||||
# 14. Complaints (30: 70% non-critical=21, 9 critical; 22 closed, 4 in_progress, 4 open)
|
||||
# Must include: 1 critical open > 24h, 1 spanning month boundary, 6 spares, 5 CE
|
||||
complaints: list[Complaint] = []
|
||||
issue_descriptions = [
|
||||
"Display flickering intermittently during monitoring",
|
||||
"Airway pressure sensor alarm triggering falsely",
|
||||
"Battery backup not holding charge during transport",
|
||||
"Touchscreen unresponsive on main control panel",
|
||||
"Power supply fuse blown after voltage fluctuation",
|
||||
"Flow sensor calibration error on self-test",
|
||||
"Suction vacuum pressure dropping below threshold",
|
||||
"ECG lead wire connector loose at patient cable port",
|
||||
"Temperature probe reading drift observed",
|
||||
"Cautery foot pedal intermittent contact",
|
||||
]
|
||||
# Deterministic asset mapping for 30 complaints:
|
||||
# - assets[12]: 4 closed breakdowns in last 70d (repeat failure, red)
|
||||
# - assets[14]: 3 closed breakdowns in last 60d (repeat failure)
|
||||
# - assets[16]: 3 closed breakdowns in last 60d + expired contract (repeat failure + out-of-contract)
|
||||
# - assets[2]: 1 closed breakdown + contract expiring in 3d (renewal review)
|
||||
# - assets[18]: 2 closed breakdowns w/ high repair+spare cost (>45% of purchase_value)
|
||||
# - assets[20]: 2 closed breakdowns w/ very high repair+spare cost (>100% of purchase_value)
|
||||
# - assets[40]: fully depreciated asset w/ long downtime (efficiency < 80)
|
||||
# - assets[0..9]: latest equipment with realistic breakdowns (including idx=26 critical open > 24h in ICU)
|
||||
complaint_asset_indices = [
|
||||
12, 12, 12, 12, # idx 0..3 (4 breakdowns on assets[12])
|
||||
14, 14, 14, # idx 4..6 (3 breakdowns on assets[14])
|
||||
16, 16, 16, # idx 7..9 (3 breakdowns on assets[16])
|
||||
2, # idx 10 (contract expiring in 3d)
|
||||
18, 18, # idx 11..12 (high maintenance cost > 40%)
|
||||
20, 20, # idx 13..14 (high maintenance cost > 100%)
|
||||
40, # idx 15 (fully depreciated w/ long downtime)
|
||||
0, 1, 3, 4, 5, 7, # idx 16..21 (closed breakdowns on latest equipment)
|
||||
6, 8, 9, 22, # idx 22..25 (in_progress)
|
||||
2, # idx 26 (critical open > 24h in ICU, avoids assets[0])
|
||||
10, 11, 13, # idx 27..29 (open)
|
||||
]
|
||||
repair_cost_indices = {0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 13, 14, 16, 18}
|
||||
for idx in range(30):
|
||||
asset = assets[complaint_asset_indices[idx]]
|
||||
priority = "critical" if idx < 9 else "non_critical"
|
||||
if idx < 22:
|
||||
call_status = "closed"
|
||||
elif idx < 26:
|
||||
call_status = "in_progress"
|
||||
else:
|
||||
call_status = "open"
|
||||
|
||||
reg_user = dept_users[idx % len(dept_users)]
|
||||
recv_user = bio_users[idx % len(bio_users)]
|
||||
assigned_user = bio_users[(idx + 1) % len(bio_users)]
|
||||
|
||||
if idx == 26:
|
||||
# Critical open > 24h (explicit requirement)
|
||||
priority = "critical"
|
||||
call_status = "open"
|
||||
reg_at = now_utc - timedelta(hours=32)
|
||||
closed_at = None
|
||||
elif idx == 0:
|
||||
# Spanning month boundary (registered last month, closed this month)
|
||||
first_of_month = today.replace(day=1)
|
||||
reg_date = first_of_month - timedelta(days=3)
|
||||
close_date = first_of_month + timedelta(days=1) if first_of_month + timedelta(days=1) <= today else today
|
||||
reg_at = _ist_to_utc(reg_date, 18, 30)
|
||||
closed_at = _ist_to_utc(close_date, 11, 15)
|
||||
elif idx == 15:
|
||||
# Fully depreciated asset with extended downtime (to drop efficiency < 80)
|
||||
reg_at = now_utc - timedelta(days=25, hours=4)
|
||||
closed_at = reg_at + timedelta(days=12)
|
||||
else:
|
||||
days_back = rng.randint(5, 70) if call_status == "closed" else rng.randint(0, 3)
|
||||
reg_at = now_utc - timedelta(days=days_back, hours=rng.randint(1, 10))
|
||||
closed_at = reg_at + timedelta(hours=rng.randint(2, 24))
|
||||
|
||||
has_spare = idx in (1, 4, 8, 11, 13, 22)
|
||||
has_ce = idx in (2, 6, 11, 18, 23)
|
||||
|
||||
c_assigned_at = reg_at + timedelta(minutes=25) if call_status in ("in_progress", "closed") else None
|
||||
c_attended_at = (
|
||||
reg_at + timedelta(hours=72) if idx == 15 else (reg_at + timedelta(minutes=65))
|
||||
) if call_status in ("in_progress", "closed") else None
|
||||
c_restored_at = (closed_at - timedelta(minutes=30)) if (call_status == "closed" and closed_at) else None
|
||||
c_closed_at = closed_at if call_status == "closed" else None
|
||||
|
||||
if idx in (11, 12):
|
||||
# assets[18] purchase_value ~ 450,000 -> push maintenance ratio ~55%
|
||||
rep_cost = 115000.0
|
||||
sp_cost = 45000.0 if has_spare else None
|
||||
elif idx in (13, 14):
|
||||
# assets[20] purchase_value ~ 950,000 -> push maintenance ratio > 105%
|
||||
rep_cost = 520000.0
|
||||
sp_cost = 140000.0 if has_spare else None
|
||||
else:
|
||||
rep_cost = float(rng.choice([3500, 6000, 9500, 12500, 18000])) if idx in repair_cost_indices else None
|
||||
sp_cost = float(rng.choice([4500, 8200, 14500, 22000, 31500])) if has_spare else None
|
||||
|
||||
cov_at_reg = get_coverage(db, asset.id, reg_at.astimezone(KOLKATA).date())
|
||||
|
||||
comp = Complaint(
|
||||
complaint_no=f"CMP-{today.year}-{idx + 1:04d}",
|
||||
asset_id=asset.id,
|
||||
description=issue_descriptions[idx % len(issue_descriptions)],
|
||||
breakdown_details=f"Reported by {asset.department.code} nursing/technical staff during routine shift.",
|
||||
priority=priority,
|
||||
notes="Logged via Poona AMS helpdesk.",
|
||||
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,
|
||||
attended_at=c_attended_at,
|
||||
restored_at=c_restored_at,
|
||||
closed_by_id=assigned_user.id if call_status == "closed" else None,
|
||||
closed_at=c_closed_at,
|
||||
call_status=call_status,
|
||||
closure_remarks="Equipment verified functional and handed back to department." if call_status == "closed" else None,
|
||||
action_taken="Diagnosed faulty module, replaced worn harness, and ran safety check." if call_status in ("in_progress", "closed") else None,
|
||||
root_cause="Component aging / power surge wear" if call_status == "closed" else None,
|
||||
corrective_action="Module replacement and preventive recalibration" if call_status == "closed" else None,
|
||||
lessons_learned="Verify UPS line conditioning during monthly rounds" if call_status == "closed" else None,
|
||||
ce_name="Raghavendra Kulkarni (OEM Service)" if has_ce else None,
|
||||
ce_attended_at=(reg_at + timedelta(hours=4)) if has_ce else None,
|
||||
ce_action_taken="OEM service engineer inspected PCB assembly and updated firmware." if has_ce else None,
|
||||
spare_required=has_spare,
|
||||
spare_details="Power supply module / O2 sensor assembly" if has_spare else None,
|
||||
spare_cost_estimate=sp_cost,
|
||||
repair_cost=rep_cost,
|
||||
coverage_tag=cov_at_reg["tag"],
|
||||
coverage_contract_id=cov_at_reg["contract_id"],
|
||||
coverage_provider_id=cov_at_reg["provider_id"],
|
||||
updated_by_id=assigned_user.id,
|
||||
)
|
||||
db.add(comp)
|
||||
db.flush()
|
||||
complaints.append(comp)
|
||||
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="registered",
|
||||
from_value=None,
|
||||
to_value="open",
|
||||
by_user_id=reg_user.id,
|
||||
at=reg_at,
|
||||
note="Complaint registered.",
|
||||
)
|
||||
)
|
||||
if call_status in ("in_progress", "closed"):
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="assigned",
|
||||
from_value="open",
|
||||
to_value="in_progress",
|
||||
by_user_id=recv_user.id,
|
||||
at=c_assigned_at,
|
||||
note=f"Assigned to {assigned_user.name}.",
|
||||
)
|
||||
)
|
||||
if call_status == "closed":
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="closed",
|
||||
from_value="in_progress",
|
||||
to_value="closed",
|
||||
by_user_id=assigned_user.id,
|
||||
at=c_closed_at,
|
||||
note="Restored and closed.",
|
||||
)
|
||||
)
|
||||
db.flush()
|
||||
|
||||
# 15. Placeholder uploads (8 JPEGs + 6 PDFs) + Attachment records
|
||||
target_upload_dir = upload_dir if upload_dir is not None else Path(settings.UPLOAD_DIR)
|
||||
target_upload_dir.mkdir(parents=True, exist_ok=True)
|
||||
# Remove previously seeded placeholder files (keep .gitkeep)
|
||||
for existing_file in target_upload_dir.iterdir():
|
||||
if existing_file.is_file() and existing_file.name != ".gitkeep":
|
||||
existing_file.unlink()
|
||||
|
||||
palette = [
|
||||
(30, 64, 175),
|
||||
(15, 118, 110),
|
||||
(180, 83, 9),
|
||||
(109, 40, 217),
|
||||
]
|
||||
for j in range(8):
|
||||
fname = f"seed_photo_{j + 1:02d}.jpg"
|
||||
fpath = target_upload_dir / fname
|
||||
size_b = _make_placeholder_jpeg(fpath, f"Equipment Fault Photo #{j + 1}", palette[j % len(palette)])
|
||||
db.add(
|
||||
Attachment(
|
||||
entity_type="complaint",
|
||||
entity_id=complaints[j].id,
|
||||
original_name=f"fault_photo_{j + 1}.jpg",
|
||||
stored_name=fname,
|
||||
mime_type="image/jpeg",
|
||||
size_bytes=size_b,
|
||||
uploaded_by_id=bio_users[j % len(bio_users)].id,
|
||||
)
|
||||
)
|
||||
|
||||
for p in range(6):
|
||||
fname = f"seed_doc_{p + 1:02d}.pdf"
|
||||
fpath = target_upload_dir / fname
|
||||
pdf_bytes = _make_minimal_pdf(f"Poona Hospital Service / Calibration Report #{p + 1}")
|
||||
fpath.write_bytes(pdf_bytes)
|
||||
db.add(
|
||||
Attachment(
|
||||
entity_type="asset" if p < 3 else "complaint",
|
||||
entity_id=assets[p].id if p < 3 else complaints[p + 8].id,
|
||||
original_name=f"service_report_{p + 1}.pdf",
|
||||
stored_name=fname,
|
||||
mime_type="application/pdf",
|
||||
size_bytes=len(pdf_bytes),
|
||||
uploaded_by_id=coord_users[p % len(coord_users)].id,
|
||||
)
|
||||
)
|
||||
db.flush()
|
||||
|
||||
# 16. Demo Equipment (3 items)
|
||||
demo_items = [
|
||||
("Portable Video Laryngoscope", "Airway Management", suppliers_and_oems[0].id, departments[0].id, locs_by_dept[departments[0].id][0].id, today - timedelta(days=10), today + timedelta(days=5), None, "Under clinical trial by ICU consultants."),
|
||||
("High-Flow Nasal Cannula Unit", "Respiratory Support", suppliers_and_oems[1].id, departments[4].id, locs_by_dept[departments[4].id][0].id, today - timedelta(days=14), today + timedelta(days=2), None, "Evaluation unit due for vendor pickup shortly."),
|
||||
("Point-of-Care Ultrasound Probe", "Diagnostic Imaging", suppliers_and_oems[2].id, departments[2].id, locs_by_dept[departments[2].id][2].id, today - timedelta(days=30), today - timedelta(days=5), today - timedelta(days=4), "Trial completed and returned to supplier."),
|
||||
]
|
||||
for name, eq_type, sup_id, dep_id, loc_id, s_d, exp_d, act_d, rem in demo_items:
|
||||
db.add(
|
||||
DemoEquipment(
|
||||
name=name,
|
||||
equipment_type=eq_type,
|
||||
supplier_id=sup_id,
|
||||
department_id=dep_id,
|
||||
location_id=loc_id,
|
||||
start_date=s_d,
|
||||
expected_return_date=exp_d,
|
||||
actual_return_date=act_d,
|
||||
remarks=rem,
|
||||
created_by_id=coord_users[0].id,
|
||||
updated_by_id=coord_users[0].id,
|
||||
)
|
||||
)
|
||||
db.flush()
|
||||
|
||||
# 17. Department Visits (12 total: 3 linked to complaints, 1 of which linked to 2 complaints)
|
||||
for v_idx in range(12):
|
||||
dept = departments[v_idx % len(departments)]
|
||||
visit = DepartmentVisit(
|
||||
department_id=dept.id,
|
||||
visited_by_id=bio_users[v_idx % len(bio_users)].id,
|
||||
visit_date=today - timedelta(days=v_idx * 4 + 1),
|
||||
observations=f"Routine biomedical safety & preventive inspection round in {dept.name}.",
|
||||
created_by_id=bio_users[v_idx % len(bio_users)].id,
|
||||
updated_by_id=bio_users[v_idx % len(bio_users)].id,
|
||||
)
|
||||
dept_assets = [a for a in assets if a.department_id == dept.id][:2]
|
||||
visit.assets.extend(dept_assets)
|
||||
if v_idx == 0:
|
||||
# 1 visit linked to 2 complaints
|
||||
visit.complaints.extend([complaints[0], complaints[1]])
|
||||
elif v_idx == 1:
|
||||
visit.complaints.append(complaints[2])
|
||||
elif v_idx == 2:
|
||||
visit.complaints.append(complaints[3])
|
||||
db.add(visit)
|
||||
|
||||
db.flush()
|
||||
alert_res = run_alert_check(db)
|
||||
db.commit()
|
||||
return {
|
||||
"departments": len(departments),
|
||||
"locations": len(locations),
|
||||
"categories": len(categories),
|
||||
"vendors": len(vendors),
|
||||
"users": len(users),
|
||||
"assets": len(assets),
|
||||
"contracts": len(contracts),
|
||||
"warranties": 20,
|
||||
"insurance_policies": len(insured_assets),
|
||||
"calibration_plans": len(cal_assets),
|
||||
"pm_schedules": 45,
|
||||
"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)
|
||||
elapsed = pytime.perf_counter() - t0
|
||||
print(f"Seed completed in {elapsed:.2f}s: {summary}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,719 @@
|
||||
"""
|
||||
AI Narrative generation, strict grounding validation, fallback, and caching.
|
||||
|
||||
All numbers originate exclusively from the deterministic Python metrics engine.
|
||||
Any LLM output is strictly validated for:
|
||||
1. JSON schema shape (headline + up to 6 bullets with metric_ids)
|
||||
2. Every metric_id exists in the evidence list
|
||||
3. Every number in headline/bullets matches a raw or formatted evidence value within 0.5%
|
||||
4. Zero banned words/phrases (approve, approved, guarantee, safe to use, unsafe,
|
||||
purchase immediately, must buy)
|
||||
|
||||
If AI is disabled, unavailable, times out, or fails validation after one retry,
|
||||
a deterministic rule-based narrative is returned cleanly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.time_utils import utc_now
|
||||
from ..models import AISummary
|
||||
from .ai_metrics import _slug, format_inr
|
||||
from .ai_provider import AIProvider, NoneProvider, ProviderUnavailable, get_ai_provider
|
||||
from .audit import log_audit
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
BANNED_PHRASES: tuple[str, ...] = (
|
||||
"approve",
|
||||
"approved",
|
||||
"guarantee",
|
||||
"safe to use",
|
||||
"unsafe",
|
||||
"purchase immediately",
|
||||
"must buy",
|
||||
)
|
||||
|
||||
ALLOWED_METRIC_KEYS = ("id", "label", "value", "unit", "formatted")
|
||||
ALLOWED_SUGGESTION_KEYS = ("id", "rule", "severity", "asset_codes", "evidence_metric_ids", "action_for_human")
|
||||
|
||||
_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
|
||||
_ASSET_CODE_RE = re.compile(r"\b[A-Z]{2,10}-[A-Z0-9]{1,10}-\d{2,6}\b")
|
||||
_METRIC_ID_RE = re.compile(r"\bm_[a-zA-Z0-9_]+\b")
|
||||
_RULE_CODE_RE = re.compile(r"\bS[1-8]\b")
|
||||
_NUMBER_RE = re.compile(r"\d+(?:\.\d+)?")
|
||||
|
||||
SYSTEM_PROMPT_TEMPLATE = (
|
||||
"You are writing a short, factual executive note for hospital managers based strictly on "
|
||||
"pre-calculated biomedical equipment metrics.\n"
|
||||
"Rules you MUST follow:\n"
|
||||
"1. Use ONLY the numbers present in the provided JSON evidence. Never calculate new numbers "
|
||||
"or invent figures.\n"
|
||||
"2. Every bullet MUST list the exact `metric_ids` from the JSON that support its numbers.\n"
|
||||
"3. Do NOT recommend purchases, approvals, or clinical safety decisions. Never use the words "
|
||||
"or phrases: approve, approved, guarantee, safe to use, unsafe, purchase immediately, must buy.\n"
|
||||
"4. Do NOT add suggestions beyond the ones provided in the JSON.\n"
|
||||
"5. Answer strictly as a single JSON object matching:\n"
|
||||
'{"headline": "concise 1-sentence summary", "bullets": [{"text": "factual sentence", "metric_ids": ["m_..."]}]}\n'
|
||||
"6. Include between 1 and 6 bullets."
|
||||
)
|
||||
|
||||
|
||||
def _scrub_emails(text: Any) -> str:
|
||||
return _EMAIL_RE.sub("[redacted]", str(text or ""))
|
||||
|
||||
|
||||
def _sanitize_metrics(metrics: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Whitelist strictly allowed evidence keys so PII/free text can never leak."""
|
||||
clean: list[dict[str, Any]] = []
|
||||
for m in metrics or []:
|
||||
if not isinstance(m, dict) or not m.get("id"):
|
||||
continue
|
||||
clean.append(
|
||||
{
|
||||
"id": str(m["id"]),
|
||||
"label": _scrub_emails(m.get("label", "")),
|
||||
"value": m.get("value"),
|
||||
"unit": str(m.get("unit", "")),
|
||||
"formatted": _scrub_emails(m.get("formatted", "")),
|
||||
}
|
||||
)
|
||||
return clean
|
||||
|
||||
|
||||
def _sanitize_suggestions(suggestions: Optional[list[dict[str, Any]]]) -> list[dict[str, Any]]:
|
||||
"""Whitelist strictly structured fields of suggestions (never free-text user input)."""
|
||||
clean: list[dict[str, Any]] = []
|
||||
for s in suggestions or []:
|
||||
if not isinstance(s, dict) or not s.get("id"):
|
||||
continue
|
||||
codes = [str(c) for c in (s.get("asset_codes") or []) if isinstance(c, str)]
|
||||
ev_ids = [str(eid) for eid in (s.get("evidence_metric_ids") or []) if isinstance(eid, str)]
|
||||
clean.append(
|
||||
{
|
||||
"id": str(s["id"]),
|
||||
"rule": str(s.get("rule", "")),
|
||||
"severity": str(s.get("severity", "info")),
|
||||
"asset_codes": codes,
|
||||
"evidence_metric_ids": ev_ids,
|
||||
"action_for_human": _scrub_emails(s.get("action_for_human", "")),
|
||||
}
|
||||
)
|
||||
return clean
|
||||
|
||||
|
||||
def build_prompt(
|
||||
section: str,
|
||||
metrics: list[dict[str, Any]],
|
||||
suggestions: Optional[list[dict[str, Any]]] = None,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
"""Build (system_prompt, privacy-safe user_json) for an AI provider."""
|
||||
user_payload = {
|
||||
"section": str(section),
|
||||
"metrics": _sanitize_metrics(metrics),
|
||||
"suggestions": _sanitize_suggestions(suggestions),
|
||||
}
|
||||
return SYSTEM_PROMPT_TEMPLATE, user_payload
|
||||
|
||||
|
||||
def _extract_numbers_from_text(text: str, known_asset_codes: Optional[set[str]] = None) -> list[float]:
|
||||
"""Extract numeric values from text after removing asset codes, metric IDs, ₹, and commas."""
|
||||
s = str(text or "")
|
||||
if known_asset_codes:
|
||||
for code in sorted(known_asset_codes, key=len, reverse=True):
|
||||
if code:
|
||||
s = s.replace(code, " ")
|
||||
s = _ASSET_CODE_RE.sub(" ", s)
|
||||
s = _METRIC_ID_RE.sub(" ", s)
|
||||
s = _RULE_CODE_RE.sub(" ", s)
|
||||
s = s.replace("₹", " ").replace("Rs.", " ").replace("INR", " ")
|
||||
s = re.sub(r"(?<=\d),(?=\d)", "", s)
|
||||
numbers: list[float] = []
|
||||
for tok in _NUMBER_RE.findall(s):
|
||||
try:
|
||||
numbers.append(float(tok))
|
||||
except ValueError:
|
||||
continue
|
||||
return numbers
|
||||
|
||||
|
||||
def _collect_known_numbers(
|
||||
metrics: list[dict[str, Any]],
|
||||
section_data: Optional[dict[str, Any]] = None,
|
||||
) -> list[float]:
|
||||
known: list[float] = []
|
||||
for m in metrics or []:
|
||||
val = m.get("value")
|
||||
if isinstance(val, (int, float)) and not isinstance(val, bool):
|
||||
fval = abs(float(val))
|
||||
known.append(fval)
|
||||
if m.get("unit") == "ratio":
|
||||
known.append(abs(fval * 100.0))
|
||||
fmt = m.get("formatted")
|
||||
if isinstance(fmt, str) and fmt:
|
||||
known.extend(_extract_numbers_from_text(fmt))
|
||||
label = m.get("label")
|
||||
if isinstance(label, str) and label:
|
||||
known.extend(_extract_numbers_from_text(label))
|
||||
|
||||
if isinstance(section_data, dict):
|
||||
settings_used = section_data.get("how_calculated", {}).get("settings_used") or {}
|
||||
for sval in settings_used.values():
|
||||
if isinstance(sval, (int, float)) and not isinstance(sval, bool):
|
||||
known.append(abs(float(sval)))
|
||||
|
||||
return known
|
||||
|
||||
|
||||
def _number_matches(val: float, known_numbers: list[float], rel_tol: float = 0.005) -> bool:
|
||||
for ref in known_numbers:
|
||||
if ref == 0.0:
|
||||
if abs(val) < 1e-6:
|
||||
return True
|
||||
else:
|
||||
if abs(val - ref) <= max(abs(ref) * rel_tol, 1e-6):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _find_banned_phrase(text: str) -> Optional[str]:
|
||||
lower = (text or "").lower()
|
||||
for phrase in BANNED_PHRASES:
|
||||
if re.search(rf"\b{re.escape(phrase)}\b", lower):
|
||||
return phrase
|
||||
return None
|
||||
|
||||
|
||||
def validate_narrative(
|
||||
result: Any,
|
||||
metrics: list[dict[str, Any]],
|
||||
known_asset_codes: Optional[set[str]] = None,
|
||||
section_data: Optional[dict[str, Any]] = None,
|
||||
) -> tuple[bool, Optional[str]]:
|
||||
"""Validate an AI model's JSON response against shape, evidence, numbers, and banned words."""
|
||||
if not isinstance(result, dict):
|
||||
return False, "Model response is not a JSON object."
|
||||
|
||||
headline = result.get("headline")
|
||||
if not isinstance(headline, str) or not headline.strip():
|
||||
return False, "Missing or empty 'headline' field."
|
||||
|
||||
bullets = result.get("bullets")
|
||||
if not isinstance(bullets, list) or len(bullets) == 0 or len(bullets) > 6:
|
||||
return False, "Field 'bullets' must be a list of 1 to 6 items."
|
||||
|
||||
valid_metric_ids = {str(m["id"]) for m in (metrics or []) if isinstance(m, dict) and m.get("id")}
|
||||
known_numbers = _collect_known_numbers(metrics, section_data=section_data)
|
||||
|
||||
# Check banned phrases in headline
|
||||
banned = _find_banned_phrase(headline)
|
||||
if banned:
|
||||
return False, f"Banned phrase found in headline: '{banned}'."
|
||||
|
||||
# Check numbers in headline
|
||||
for num in _extract_numbers_from_text(headline, known_asset_codes):
|
||||
if not _number_matches(num, known_numbers):
|
||||
return False, f"Unverified number in headline: {num:g}."
|
||||
|
||||
for idx, item in enumerate(bullets):
|
||||
if not isinstance(item, dict):
|
||||
return False, f"Bullet {idx + 1} is not an object."
|
||||
text = item.get("text")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return False, f"Bullet {idx + 1} has empty 'text'."
|
||||
mids = item.get("metric_ids")
|
||||
if not isinstance(mids, list) or len(mids) == 0 or not all(isinstance(x, str) and x.strip() for x in mids):
|
||||
return False, f"Bullet {idx + 1} must include a non-empty list of 'metric_ids'."
|
||||
|
||||
for mid in mids:
|
||||
if mid not in valid_metric_ids:
|
||||
return False, f"Unknown metric_id referenced: '{mid}'."
|
||||
|
||||
banned = _find_banned_phrase(text)
|
||||
if banned:
|
||||
return False, f"Banned phrase found in bullet {idx + 1}: '{banned}'."
|
||||
|
||||
for num in _extract_numbers_from_text(text, known_asset_codes):
|
||||
if not _number_matches(num, known_numbers):
|
||||
return False, f"Unverified number in bullet {idx + 1}: {num:g}."
|
||||
|
||||
return True, None
|
||||
|
||||
|
||||
def rule_based_narrative(
|
||||
section: str,
|
||||
metrics: list[dict[str, Any]],
|
||||
suggestions: Optional[list[dict[str, Any]]] = None,
|
||||
section_data: Optional[dict[str, Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build deterministic narrative headline and bullets strictly from computed evidence."""
|
||||
by_id = {m["id"]: m for m in (metrics or []) if isinstance(m, dict) and m.get("id")}
|
||||
bullets: list[dict[str, Any]] = []
|
||||
|
||||
def _has(*ids: str) -> bool:
|
||||
return all(i in by_id for i in ids)
|
||||
|
||||
def _fmt(mid: str) -> str:
|
||||
return str(by_id[mid]["formatted"])
|
||||
|
||||
sec = (section or "summary").strip().lower()
|
||||
|
||||
if sec == "comparison":
|
||||
horizon_m = by_id.get("m_cmp_horizon_years")
|
||||
count_m = by_id.get("m_cmp_latest_count")
|
||||
horizon_val = horizon_m["value"] if horizon_m else 5
|
||||
count_val = count_m["value"] if count_m else 0
|
||||
|
||||
headline = (
|
||||
f"Evaluated {count_val} latest equipment items over a {horizon_val}-year horizon "
|
||||
f"across in-house, outsourced, and rent scenarios."
|
||||
)
|
||||
if _has("m_cmp_inhouse_wins", "m_cmp_outsourced_wins", "m_cmp_rent_wins"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Lowest-cost scenario split across evaluated equipment: "
|
||||
f"{_fmt('m_cmp_inhouse_wins')} in-house, "
|
||||
f"{_fmt('m_cmp_outsourced_wins')} outsourced (AMC/CMC), and "
|
||||
f"{_fmt('m_cmp_rent_wins')} rent."
|
||||
),
|
||||
"metric_ids": ["m_cmp_inhouse_wins", "m_cmp_outsourced_wins", "m_cmp_rent_wins"],
|
||||
}
|
||||
)
|
||||
rows = (section_data or {}).get("rows") or []
|
||||
for row in rows:
|
||||
if len(bullets) >= 6:
|
||||
break
|
||||
code = row.get("asset_code")
|
||||
lowest_label = row.get("lowest_scenario_label")
|
||||
lowest_cost = row.get("lowest_cost")
|
||||
diff = row.get("savings_vs_next")
|
||||
if not code or lowest_cost is None:
|
||||
continue
|
||||
slug = _slug(code)
|
||||
low_id = f"m_cmp_lowest_{slug}"
|
||||
diff_id = f"m_cmp_diff_{slug}"
|
||||
if _has(low_id, diff_id) and diff is not None:
|
||||
mids = [low_id, diff_id]
|
||||
if "m_cmp_horizon_years" in by_id:
|
||||
mids.insert(0, "m_cmp_horizon_years")
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Lowest estimated {horizon_val}-year cost for {code} is "
|
||||
f"{lowest_label} at {_fmt(low_id)}, {_fmt(diff_id)} below the next option."
|
||||
),
|
||||
"metric_ids": mids,
|
||||
}
|
||||
)
|
||||
elif _has(low_id):
|
||||
mids = [low_id]
|
||||
if "m_cmp_horizon_years" in by_id:
|
||||
mids.insert(0, "m_cmp_horizon_years")
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Estimated {horizon_val}-year cost for {code} under {lowest_label} is "
|
||||
f"{_fmt(low_id)} (other scenarios lack complete inputs)."
|
||||
),
|
||||
"metric_ids": mids,
|
||||
}
|
||||
)
|
||||
|
||||
elif sec == "depreciation":
|
||||
headline = "Depreciated book value and cumulative maintenance cost summary for assets in scope."
|
||||
if _has("m_dep_total_purchase_value", "m_dep_total_book_value"):
|
||||
headline = (
|
||||
f"Owned assets hold a current book value of {_fmt('m_dep_total_book_value')} "
|
||||
f"against {_fmt('m_dep_total_purchase_value')} in purchase value."
|
||||
)
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Total purchase value is {_fmt('m_dep_total_purchase_value')}, with "
|
||||
f"{_fmt('m_dep_total_book_value')} remaining book value and "
|
||||
f"{_fmt('m_dep_total_accumulated')} accumulated depreciation."
|
||||
if "m_dep_total_accumulated" in by_id
|
||||
else f"Total purchase value is {_fmt('m_dep_total_purchase_value')} with {_fmt('m_dep_total_book_value')} current book value."
|
||||
),
|
||||
"metric_ids": [
|
||||
mid
|
||||
for mid in ("m_dep_total_purchase_value", "m_dep_total_book_value", "m_dep_total_accumulated")
|
||||
if mid in by_id
|
||||
],
|
||||
}
|
||||
)
|
||||
if _has("m_dep_total_maintenance"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"Cumulative maintenance expenditure to date totals {_fmt('m_dep_total_maintenance')}.",
|
||||
"metric_ids": ["m_dep_total_maintenance"],
|
||||
}
|
||||
)
|
||||
if _has("m_dep_review_flag_count", "m_dep_fully_depreciated_count"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"{_fmt('m_dep_review_flag_count')} asset(s) meet or exceed the replacement review "
|
||||
f"maintenance ratio, and {_fmt('m_dep_fully_depreciated_count')} asset(s) are fully depreciated."
|
||||
),
|
||||
"metric_ids": ["m_dep_review_flag_count", "m_dep_fully_depreciated_count"],
|
||||
}
|
||||
)
|
||||
if _has("m_dep_excluded_count") and by_id["m_dep_excluded_count"]["value"]:
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"{_fmt('m_dep_excluded_count')} asset(s) were excluded from depreciation totals "
|
||||
f"(rented equipment or missing valuation/date inputs)."
|
||||
),
|
||||
"metric_ids": ["m_dep_excluded_count"],
|
||||
}
|
||||
)
|
||||
|
||||
elif sec == "efficiency":
|
||||
headline = "Equipment efficiency combines uptime, PM compliance, SLA response, and repeat-free reliability."
|
||||
if _has("m_eff_score_overall", "m_eff_avg_uptime"):
|
||||
headline = (
|
||||
f"Overall efficiency score is {_fmt('m_eff_score_overall')} with "
|
||||
f"{_fmt('m_eff_avg_uptime')} average uptime."
|
||||
)
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Weighted efficiency score is {_fmt('m_eff_score_overall')} across operational assets, "
|
||||
f"driven by {_fmt('m_eff_avg_uptime')} average uptime."
|
||||
),
|
||||
"metric_ids": ["m_eff_score_overall", "m_eff_avg_uptime"],
|
||||
}
|
||||
)
|
||||
if _has("m_eff_pm_compliance"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"On-time preventive maintenance compliance stands at {_fmt('m_eff_pm_compliance')}.",
|
||||
"metric_ids": ["m_eff_pm_compliance"],
|
||||
}
|
||||
)
|
||||
if _has("m_eff_mttr") and by_id["m_eff_mttr"]["value"] is not None:
|
||||
mids = ["m_eff_mttr"]
|
||||
extra = ""
|
||||
if _has("m_eff_mtbf") and by_id["m_eff_mtbf"]["value"] is not None:
|
||||
mids.append("m_eff_mtbf")
|
||||
extra = f" and mean time between failures (MTBF) is {_fmt('m_eff_mtbf')}"
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"Mean time to repair (MTTR) is {_fmt('m_eff_mttr')}{extra}.",
|
||||
"metric_ids": mids,
|
||||
}
|
||||
)
|
||||
elif _has("m_eff_mtbf"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"Mean time between failures (MTBF) status: {_fmt('m_eff_mtbf')}.",
|
||||
"metric_ids": ["m_eff_mtbf"],
|
||||
}
|
||||
)
|
||||
|
||||
elif sec in ("breakdown_frequency", "breakdown-frequency"):
|
||||
headline = "Breakdown frequency and repeat-failure summary across equipment in scope."
|
||||
if _has("m_bf_total_breakdowns", "m_bf_assets_in_scope", "m_bf_avg_per_equipment"):
|
||||
headline = (
|
||||
f"{_fmt('m_bf_total_breakdowns')} breakdowns logged across {_fmt('m_bf_assets_in_scope')} "
|
||||
f"assets (average {_fmt('m_bf_avg_per_equipment')} per equipment)."
|
||||
)
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"A total of {_fmt('m_bf_total_breakdowns')} breakdown complaints were recorded across "
|
||||
f"{_fmt('m_bf_assets_in_scope')} assets, averaging {_fmt('m_bf_avg_per_equipment')} per equipment."
|
||||
),
|
||||
"metric_ids": ["m_bf_total_breakdowns", "m_bf_assets_in_scope", "m_bf_avg_per_equipment"],
|
||||
}
|
||||
)
|
||||
if _has("m_bf_repeat_failure_assets"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"{_fmt('m_bf_repeat_failure_assets')} asset(s) are currently flagged for repeat failures.",
|
||||
"metric_ids": ["m_bf_repeat_failure_assets"],
|
||||
}
|
||||
)
|
||||
rows = (section_data or {}).get("rows") or []
|
||||
if rows and rows[0].get("breakdown_count", 0) > 0:
|
||||
top = rows[0]
|
||||
mid = f"m_bf_count_{_slug(top['asset_code'])}"
|
||||
if mid in by_id:
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Highest breakdown volume in the period was on {top['asset_code']} "
|
||||
f"({top.get('asset_name', '')}) with {_fmt(mid)} complaint(s)."
|
||||
),
|
||||
"metric_ids": [mid],
|
||||
}
|
||||
)
|
||||
|
||||
else:
|
||||
# Whole-report executive summary ("summary")
|
||||
headline = "Executive summary of equipment cost comparison, depreciation, efficiency, and breakdown frequency."
|
||||
if _has("m_cmp_latest_count", "m_cmp_horizon_years"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Cost comparison evaluated {_fmt('m_cmp_latest_count')} latest assets over "
|
||||
f"{_fmt('m_cmp_horizon_years')}."
|
||||
),
|
||||
"metric_ids": ["m_cmp_latest_count", "m_cmp_horizon_years"],
|
||||
}
|
||||
)
|
||||
if _has("m_dep_total_book_value", "m_dep_total_maintenance"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Owned equipment book value is {_fmt('m_dep_total_book_value')} with "
|
||||
f"{_fmt('m_dep_total_maintenance')} in cumulative maintenance costs."
|
||||
),
|
||||
"metric_ids": ["m_dep_total_book_value", "m_dep_total_maintenance"],
|
||||
}
|
||||
)
|
||||
if _has("m_eff_score_overall", "m_eff_avg_uptime"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Overall operational efficiency score is {_fmt('m_eff_score_overall')} "
|
||||
f"with {_fmt('m_eff_avg_uptime')} average uptime."
|
||||
),
|
||||
"metric_ids": ["m_eff_score_overall", "m_eff_avg_uptime"],
|
||||
}
|
||||
)
|
||||
if _has("m_bf_total_breakdowns", "m_bf_repeat_failure_assets"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"{_fmt('m_bf_total_breakdowns')} breakdowns recorded in period, with "
|
||||
f"{_fmt('m_bf_repeat_failure_assets')} repeat-failure asset(s)."
|
||||
),
|
||||
"metric_ids": ["m_bf_total_breakdowns", "m_bf_repeat_failure_assets"],
|
||||
}
|
||||
)
|
||||
if _has("m_sug_total_count"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"{_fmt('m_sug_total_count')} advisory suggestion(s) generated for human review."
|
||||
),
|
||||
"metric_ids": ["m_sug_total_count"],
|
||||
}
|
||||
)
|
||||
|
||||
# Fallback bullet if metrics were minimal or custom
|
||||
if not bullets:
|
||||
for m in (metrics or [])[:4]:
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"{m['label']}: {m['formatted']}.",
|
||||
"metric_ids": [m["id"]],
|
||||
}
|
||||
)
|
||||
if not bullets:
|
||||
bullets.append(
|
||||
{
|
||||
"text": "Add cost and operational details on asset records to generate metrics for this section.",
|
||||
"metric_ids": [],
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"headline": headline,
|
||||
"bullets": bullets[:6],
|
||||
}
|
||||
|
||||
|
||||
def _sha256_canonical(obj: Any) -> str:
|
||||
encoded = json.dumps(obj, sort_keys=True, default=str, ensure_ascii=False).encode("utf-8")
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def get_or_generate_narrative(
|
||||
db: Session,
|
||||
section: str,
|
||||
filters_dict: dict[str, Any],
|
||||
metrics: list[dict[str, Any]],
|
||||
suggestions: Optional[list[dict[str, Any]]] = None,
|
||||
*,
|
||||
section_data: Optional[dict[str, Any]] = None,
|
||||
user_id: Optional[int] = None,
|
||||
force_regenerate: bool = False,
|
||||
provider_override: Optional[AIProvider] = None,
|
||||
ai_enabled_override: Optional[bool] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Return a cached or freshly generated narrative for `section`.
|
||||
Never raises on provider errors; always returns a complete narrative dict.
|
||||
"""
|
||||
provider = provider_override or get_ai_provider()
|
||||
ai_enabled = (
|
||||
bool(ai_enabled_override)
|
||||
if ai_enabled_override is not None
|
||||
else bool(get_setting_value(db, "ai_enabled", True))
|
||||
)
|
||||
use_ai = ai_enabled and not isinstance(provider, NoneProvider)
|
||||
|
||||
clean_metrics = _sanitize_metrics(metrics)
|
||||
clean_suggestions = _sanitize_suggestions(suggestions)
|
||||
|
||||
cache_filters = {
|
||||
**(filters_dict or {}),
|
||||
"_use_ai": use_ai,
|
||||
"_provider": provider.provider_name if use_ai else "none",
|
||||
"_model": provider.model_name if use_ai else "",
|
||||
}
|
||||
filters_hash = _sha256_canonical(cache_filters)
|
||||
data_hash = _sha256_canonical({"metrics": clean_metrics, "suggestions": clean_suggestions})
|
||||
|
||||
if not force_regenerate:
|
||||
cached = (
|
||||
db.query(AISummary)
|
||||
.filter(
|
||||
AISummary.section == section,
|
||||
AISummary.filters_hash == filters_hash,
|
||||
AISummary.data_hash == data_hash,
|
||||
AISummary.validated == True,
|
||||
)
|
||||
.order_by(AISummary.id.desc())
|
||||
.first()
|
||||
)
|
||||
if cached is not None:
|
||||
try:
|
||||
cached_data = json.loads(cached.payload_json)
|
||||
if not cached_data.get("failure_reason"):
|
||||
return cached_data
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
known_codes: set[str] = set()
|
||||
for s in clean_suggestions:
|
||||
known_codes.update(s.get("asset_codes") or [])
|
||||
for r in (section_data or {}).get("rows") or []:
|
||||
if isinstance(r, dict) and r.get("asset_code"):
|
||||
known_codes.add(str(r["asset_code"]))
|
||||
|
||||
source = "rule_based"
|
||||
model_used: Optional[str] = None
|
||||
validated = True
|
||||
failure_reason: Optional[str] = None
|
||||
narrative_body: Optional[dict[str, Any]] = None
|
||||
|
||||
if use_ai:
|
||||
model_used = provider.model_name or provider.provider_name
|
||||
sys_prompt, user_payload = build_prompt(section, clean_metrics, clean_suggestions)
|
||||
last_error: Optional[str] = None
|
||||
for attempt in range(2):
|
||||
prompt_for_attempt = sys_prompt
|
||||
if attempt == 1 and last_error:
|
||||
prompt_for_attempt = (
|
||||
f"{sys_prompt}\n\n"
|
||||
f"Your previous answer was rejected for this reason: {last_error}\n"
|
||||
"Fix this issue and return strictly valid JSON."
|
||||
)
|
||||
try:
|
||||
raw_resp = provider.generate_json(prompt_for_attempt, user_payload)
|
||||
except ProviderUnavailable as exc:
|
||||
last_error = str(exc)
|
||||
break
|
||||
except Exception as exc:
|
||||
last_error = f"Invalid model output: {exc}"
|
||||
if attempt == 0:
|
||||
continue
|
||||
break
|
||||
|
||||
ok, reason = validate_narrative(
|
||||
raw_resp,
|
||||
clean_metrics,
|
||||
known_asset_codes=known_codes,
|
||||
section_data=section_data,
|
||||
)
|
||||
if ok:
|
||||
narrative_body = {
|
||||
"headline": raw_resp["headline"].strip(),
|
||||
"bullets": [
|
||||
{
|
||||
"text": b["text"].strip(),
|
||||
"metric_ids": list(b["metric_ids"]),
|
||||
}
|
||||
for b in raw_resp["bullets"]
|
||||
],
|
||||
}
|
||||
source = "ai"
|
||||
validated = True
|
||||
failure_reason = None
|
||||
break
|
||||
else:
|
||||
last_error = reason or "Narrative failed validation."
|
||||
|
||||
if narrative_body is None:
|
||||
narrative_body = rule_based_narrative(
|
||||
section,
|
||||
clean_metrics,
|
||||
clean_suggestions,
|
||||
section_data=section_data,
|
||||
)
|
||||
source = "rule_based"
|
||||
validated = False
|
||||
failure_reason = last_error or "AI provider fallback triggered."
|
||||
else:
|
||||
narrative_body = rule_based_narrative(
|
||||
section,
|
||||
clean_metrics,
|
||||
clean_suggestions,
|
||||
section_data=section_data,
|
||||
)
|
||||
source = "rule_based"
|
||||
model_used = None
|
||||
validated = True
|
||||
failure_reason = None
|
||||
|
||||
generated_at = utc_now().isoformat()
|
||||
payload = {
|
||||
"source": source,
|
||||
"model": model_used,
|
||||
"validated": validated,
|
||||
"failure_reason": failure_reason,
|
||||
"generated_at": generated_at,
|
||||
"headline": narrative_body["headline"],
|
||||
"bullets": narrative_body["bullets"],
|
||||
}
|
||||
|
||||
row = AISummary(
|
||||
section=section,
|
||||
filters_hash=filters_hash,
|
||||
data_hash=data_hash,
|
||||
source=source,
|
||||
model=model_used,
|
||||
validated=validated,
|
||||
payload_json=json.dumps(payload, ensure_ascii=False),
|
||||
created_at=utc_now(),
|
||||
created_by_id=user_id,
|
||||
)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="ai_summary",
|
||||
entity_id=row.id,
|
||||
action="regenerated" if force_regenerate else "generated",
|
||||
changes={
|
||||
"section": section,
|
||||
"source": source,
|
||||
"model": model_used,
|
||||
"validated": validated,
|
||||
"failure_reason": failure_reason,
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
return payload
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
Pluggable local AI provider layer for AI Reports.
|
||||
|
||||
Supports:
|
||||
- none (default): deterministic rule-based summaries only; raises ProviderUnavailable.
|
||||
- ollama: POST {base}/api/chat with format="json", stream=False, temperature=0.1.
|
||||
- openai_compatible: POST {base}/v1/chat/completions with response_format={"type": "json_object"}, temperature=0.1.
|
||||
|
||||
No hosted cloud provider is configured or required. Prompts and responses are never
|
||||
logged at INFO level.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
import httpx
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.config import Settings, settings as app_settings
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
|
||||
class ProviderUnavailable(Exception):
|
||||
"""Raised when no AI provider is enabled or the provider cannot be reached."""
|
||||
|
||||
|
||||
class AIProvider(ABC):
|
||||
provider_name: str = "none"
|
||||
model_name: str = ""
|
||||
|
||||
@abstractmethod
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Call the model and return a parsed JSON object."""
|
||||
|
||||
@abstractmethod
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
"""Quick reachability check that never blocks longer than `timeout` seconds."""
|
||||
|
||||
|
||||
class NoneProvider(AIProvider):
|
||||
provider_name = "none"
|
||||
model_name = ""
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
raise ProviderUnavailable("AI provider is disabled (AI_PROVIDER=none).")
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class OllamaProvider(AIProvider):
|
||||
provider_name = "ollama"
|
||||
|
||||
def __init__(self, base_url: str, model: str, timeout_seconds: int = 300) -> None:
|
||||
self.base_url = (base_url or "http://localhost:11434").rstrip("/")
|
||||
self.model_name = (model or "").strip()
|
||||
self.timeout_seconds = max(1, int(timeout_seconds or 300))
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
if not self.model_name:
|
||||
raise ProviderUnavailable("AI_MODEL is not configured for Ollama.")
|
||||
url = f"{self.base_url}/api/chat"
|
||||
payload = {
|
||||
"model": self.model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": json.dumps(user_json, ensure_ascii=False)},
|
||||
],
|
||||
"format": "json",
|
||||
"stream": False,
|
||||
"options": {"temperature": 0.1},
|
||||
}
|
||||
try:
|
||||
with httpx.Client(timeout=float(self.timeout_seconds)) as client:
|
||||
resp = client.post(url, json=payload)
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
except httpx.TimeoutException as exc:
|
||||
raise ProviderUnavailable(f"AI engine request timed out after {self.timeout_seconds}s.") from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise ProviderUnavailable(f"AI engine HTTP error: {exc.__class__.__name__}") from exc
|
||||
except ValueError as exc:
|
||||
raise ValueError("AI engine returned invalid JSON envelope.") from exc
|
||||
|
||||
content = (body.get("message") or {}).get("content")
|
||||
if isinstance(content, dict):
|
||||
return content
|
||||
if not isinstance(content, str) or not content.strip():
|
||||
raise ValueError("Ollama returned empty message content.")
|
||||
parsed = json.loads(content)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("Ollama JSON response must be an object.")
|
||||
return parsed
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
cap = min(float(timeout), 3.0)
|
||||
url = f"{self.base_url}/api/tags"
|
||||
try:
|
||||
with httpx.Client(timeout=cap) as client:
|
||||
resp = client.get(url)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class OpenAICompatibleProvider(AIProvider):
|
||||
provider_name = "openai_compatible"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
model: str,
|
||||
api_key: str = "",
|
||||
timeout_seconds: int = 25,
|
||||
) -> None:
|
||||
raw = (base_url or "http://localhost:8001").rstrip("/")
|
||||
self.base_url = raw[:-3] if raw.endswith("/v1") else raw
|
||||
self.model_name = (model or "").strip()
|
||||
self.api_key = (api_key or "").strip()
|
||||
self.timeout_seconds = max(1, int(timeout_seconds or 25))
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.api_key:
|
||||
headers["Authorization"] = f"Bearer {self.api_key}"
|
||||
return headers
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
if not self.model_name:
|
||||
raise ProviderUnavailable("AI_MODEL is not configured for OpenAI-compatible provider.")
|
||||
url = f"{self.base_url}/v1/chat/completions"
|
||||
payload = {
|
||||
"model": self.model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": json.dumps(user_json, ensure_ascii=False)},
|
||||
],
|
||||
"response_format": {"type": "json_object"},
|
||||
"temperature": 0.1,
|
||||
}
|
||||
try:
|
||||
with httpx.Client(timeout=float(self.timeout_seconds)) as client:
|
||||
resp = client.post(url, headers=self._headers(), json=payload)
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
except httpx.TimeoutException as exc:
|
||||
raise ProviderUnavailable(
|
||||
f"OpenAI-compatible request timed out after {self.timeout_seconds}s."
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise ProviderUnavailable(f"OpenAI-compatible HTTP error: {exc.__class__.__name__}") from exc
|
||||
except ValueError as exc:
|
||||
raise ValueError("OpenAI-compatible server returned invalid JSON envelope.") from exc
|
||||
|
||||
choices = body.get("choices") or []
|
||||
if not choices or not isinstance(choices, list):
|
||||
raise ValueError("OpenAI-compatible response contained no choices.")
|
||||
content = (choices[0].get("message") or {}).get("content")
|
||||
if isinstance(content, dict):
|
||||
return content
|
||||
if not isinstance(content, str) or not content.strip():
|
||||
raise ValueError("OpenAI-compatible response contained empty content.")
|
||||
parsed = json.loads(content)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("OpenAI-compatible JSON response must be an object.")
|
||||
return parsed
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
cap = min(float(timeout), 3.0)
|
||||
url = f"{self.base_url}/v1/models"
|
||||
try:
|
||||
with httpx.Client(timeout=cap) as client:
|
||||
resp = client.get(url, headers=self._headers())
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def get_ai_provider(cfg: Optional[Settings] = None) -> AIProvider:
|
||||
conf = cfg or app_settings
|
||||
name = (conf.AI_PROVIDER or "none").strip().lower()
|
||||
if name == "ollama":
|
||||
return OllamaProvider(
|
||||
base_url=conf.AI_BASE_URL,
|
||||
model=conf.AI_MODEL,
|
||||
timeout_seconds=conf.AI_TIMEOUT_SECONDS,
|
||||
)
|
||||
if name == "openai_compatible":
|
||||
return OpenAICompatibleProvider(
|
||||
base_url=conf.AI_BASE_URL,
|
||||
model=conf.AI_MODEL,
|
||||
api_key=conf.AI_API_KEY,
|
||||
timeout_seconds=conf.AI_TIMEOUT_SECONDS,
|
||||
)
|
||||
return NoneProvider()
|
||||
|
||||
|
||||
def get_ai_status(
|
||||
db: Session,
|
||||
cfg: Optional[Settings] = None,
|
||||
provider_override: Optional[AIProvider] = None,
|
||||
) -> dict[str, Any]:
|
||||
conf = cfg or app_settings
|
||||
provider = provider_override or get_ai_provider(conf)
|
||||
ai_enabled_setting = bool(get_setting_value(db, "ai_enabled", False))
|
||||
provider_name = provider.provider_name
|
||||
model_name = provider.model_name or ""
|
||||
reachable = provider.check_reachable(timeout=2.5) if provider_name != "none" else False
|
||||
return {
|
||||
"enabled": ai_enabled_setting and provider_name != "none",
|
||||
"ai_enabled_setting": ai_enabled_setting,
|
||||
"provider": provider_name,
|
||||
"model": model_name,
|
||||
"reachable": reachable,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
"""
|
||||
Rule-based Suggestions Engine (S1-S8) for AI Reports.
|
||||
|
||||
Pure Python deterministic rules with zero LLM involvement. Every suggestion links
|
||||
to concrete evidence metric IDs, uses neutral advisory language (never 'approve',
|
||||
'safe', 'unsafe', 'must buy'), and ends its action text with 'Needs a human decision.'
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import User
|
||||
from .ai_metrics import (
|
||||
_slug,
|
||||
_to_date,
|
||||
compute_breakdown_frequency_from_dataset,
|
||||
compute_comparison_from_dataset,
|
||||
compute_depreciation_from_dataset,
|
||||
compute_efficiency_from_dataset,
|
||||
format_inr,
|
||||
load_ai_dataset,
|
||||
make_metric,
|
||||
scenario_comparison,
|
||||
)
|
||||
|
||||
SEVERITY_RANK: dict[str, int] = {"red": 0, "yellow": 1, "info": 2}
|
||||
|
||||
SCENARIO_DISPLAY_NAMES: dict[str, str] = {
|
||||
"in_house": "Buy + In-House Maintenance",
|
||||
"outsourced": "Buy + Outsourced Contract (AMC/CMC)",
|
||||
"rent": "Rent",
|
||||
}
|
||||
|
||||
|
||||
def generate_suggestions(
|
||||
dataset: dict[str, Any],
|
||||
*,
|
||||
comparison: Optional[dict[str, Any]] = None,
|
||||
depreciation_data: Optional[dict[str, Any]] = None,
|
||||
efficiency_data: Optional[dict[str, Any]] = None,
|
||||
breakdown_data: Optional[dict[str, Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Generate sorted S1-S8 suggestions and their complete referenced evidence list."""
|
||||
cfg = dataset["settings"]
|
||||
today: date = dataset["today"]
|
||||
contract_lead_days = int(cfg.get("contract_expiry_alert_days", 30))
|
||||
horizon = int(cfg.get("comparison_horizon_years", 5))
|
||||
review_threshold = float(cfg.get("replacement_review_ratio", 0.4))
|
||||
|
||||
cmp_data = comparison or compute_comparison_from_dataset(dataset)
|
||||
dep_data = depreciation_data or compute_depreciation_from_dataset(dataset)
|
||||
eff_data = efficiency_data or compute_efficiency_from_dataset(dataset)
|
||||
bf_data = breakdown_data or compute_breakdown_frequency_from_dataset(dataset)
|
||||
|
||||
evidence_by_id: dict[str, dict[str, Any]] = {}
|
||||
for sec in (cmp_data, dep_data, eff_data, bf_data):
|
||||
for m in sec.get("metrics", []):
|
||||
evidence_by_id[m["id"]] = m
|
||||
|
||||
def _add_ev(metric: dict[str, Any]) -> str:
|
||||
evidence_by_id[metric["id"]] = metric
|
||||
return metric["id"]
|
||||
|
||||
dep_by_asset = {int(r["asset_id"]): r for r in dep_data.get("rows", [])}
|
||||
eff_by_asset = {int(r["asset_id"]): r for r in eff_data.get("per_asset", [])}
|
||||
bf_by_asset = {int(r["asset_id"]): r for r in bf_data.get("per_asset", [])}
|
||||
cov_by_asset = dataset.get("coverage_by_asset", {})
|
||||
|
||||
suggestions: list[dict[str, Any]] = []
|
||||
|
||||
for a in dataset.get("assets", []):
|
||||
aid = int(a["id"])
|
||||
code = a["asset_code"]
|
||||
name = a["name"]
|
||||
slug = _slug(code)
|
||||
|
||||
bf_row = bf_by_asset.get(aid, {})
|
||||
dep_row = dep_by_asset.get(aid, {})
|
||||
eff_row = eff_by_asset.get(aid, {})
|
||||
cov = cov_by_asset.get(aid, {})
|
||||
|
||||
period_b = int(bf_row.get("breakdown_count", 0))
|
||||
repeat_cnt_val = int(bf_row.get("repeat_window_count", 0))
|
||||
is_repeat = bool(bf_row.get("repeat_failure", False))
|
||||
|
||||
# --- S1: Repeat failure ---
|
||||
if is_repeat:
|
||||
sev = "red" if repeat_cnt_val >= 4 else "yellow"
|
||||
ev_id = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_repeat_window_{slug}",
|
||||
f"Breakdowns in Last {cfg.get('repeat_failure_days', 90)}d ({code})",
|
||||
repeat_cnt_val,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S1_{slug}",
|
||||
"rule": "S1",
|
||||
"severity": sev,
|
||||
"title": f"Repeat failure on {code} ({name})",
|
||||
"detail": (
|
||||
f"{code} recorded {repeat_cnt_val} breakdowns within the last "
|
||||
f"{cfg.get('repeat_failure_days', 90)} days."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_id],
|
||||
"action_for_human": "Review root cause and escalate to the vendor. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S2: Out-of-contract with >= 2 breakdowns in period ---
|
||||
cov_tag = cov.get("tag", "out_of_contract")
|
||||
if cov_tag == "out_of_contract" and period_b >= 2:
|
||||
ev_b = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_count_{slug}",
|
||||
f"Breakdowns in Period ({code})",
|
||||
period_b,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
ev_cov = _add_ev(
|
||||
make_metric(
|
||||
f"m_cov_tag_{slug}",
|
||||
f"Current Coverage ({code})",
|
||||
"out_of_contract",
|
||||
"status",
|
||||
"Out of Contract",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S2_{slug}",
|
||||
"rule": "S2",
|
||||
"severity": "yellow",
|
||||
"title": f"Out-of-contract equipment with recurring breakdowns: {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has no active warranty or AMC/CMC contract and logged "
|
||||
f"{period_b} breakdowns in the selected period."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_b, ev_cov],
|
||||
"action_for_human": "Consider an AMC/CMC. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S3: Active AMC/CMC contract ends within contract lead days AND >= 1 breakdown in period ---
|
||||
if cov_tag in ("amc", "cmc") and period_b >= 1:
|
||||
days_left = cov.get("days_left")
|
||||
if days_left is not None and 0 <= int(days_left) <= contract_lead_days:
|
||||
ev_days = _add_ev(
|
||||
make_metric(
|
||||
f"m_cov_days_left_{slug}",
|
||||
f"Contract Days Remaining ({code})",
|
||||
int(days_left),
|
||||
"days",
|
||||
f"{int(days_left)} days",
|
||||
)
|
||||
)
|
||||
ev_b = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_count_{slug}",
|
||||
f"Breakdowns in Period ({code})",
|
||||
period_b,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S3_{slug}",
|
||||
"rule": "S3",
|
||||
"severity": "yellow",
|
||||
"title": f"Expiring {cov_tag.upper()} with recent breakdowns: {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has an active {cov_tag.upper()} expiring in {int(days_left)} day(s) "
|
||||
f"and recorded {period_b} breakdown(s) in the selected period."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_days, ev_b],
|
||||
"action_for_human": "Renewal review before expiry. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S4: maintenance_ratio >= replacement_review_ratio ---
|
||||
maint_ratio = dep_row.get("maintenance_ratio")
|
||||
if maint_ratio is not None and float(maint_ratio) >= review_threshold:
|
||||
ratio_f = float(maint_ratio)
|
||||
sev = "red" if ratio_f >= 1.0 else "yellow"
|
||||
ev_ratio = _add_ev(
|
||||
make_metric(
|
||||
f"m_dep_maint_ratio_{slug}",
|
||||
f"Maintenance Ratio ({code})",
|
||||
round(ratio_f * 100.0, 1),
|
||||
"%",
|
||||
)
|
||||
)
|
||||
ev_maint = _add_ev(
|
||||
make_metric(
|
||||
f"m_dep_maint_cost_{slug}",
|
||||
f"Cumulative Maintenance Cost ({code})",
|
||||
dep_row.get("maintenance_cost"),
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S4_{slug}",
|
||||
"rule": "S4",
|
||||
"severity": sev,
|
||||
"title": f"High maintenance-to-purchase ratio on {code} ({ratio_f * 100:.1f}%)",
|
||||
"detail": (
|
||||
f"Cumulative maintenance cost for {code} ({name}) reached "
|
||||
f"{format_inr(dep_row.get('maintenance_cost'))}, which is {ratio_f * 100:.1f}% "
|
||||
f"of purchase value ({format_inr(dep_row.get('purchase_value'))})."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_ratio, ev_maint],
|
||||
"action_for_human": "Replacement review. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S5: scenario_comparison shows another scenario >= 10% cheaper than current set-up ---
|
||||
sc_res = scenario_comparison(
|
||||
a,
|
||||
dataset.get("contracts_by_asset", {}).get(aid, []),
|
||||
dataset.get("complaints_by_asset", {}).get(aid, []),
|
||||
dataset.get("pm_schedules_by_asset", {}).get(aid, []),
|
||||
horizon_years=horizon,
|
||||
as_of=today,
|
||||
settings=cfg,
|
||||
)
|
||||
cur_setup = sc_res.get("current_setup")
|
||||
lowest_key = sc_res.get("lowest_scenario")
|
||||
if cur_setup and lowest_key and lowest_key != cur_setup:
|
||||
cur_scen = sc_res["scenarios"].get(cur_setup, {})
|
||||
low_scen = sc_res["scenarios"].get(lowest_key, {})
|
||||
if cur_scen.get("available") and low_scen.get("available"):
|
||||
cur_cost = float(cur_scen["total_cost"])
|
||||
low_cost = float(low_scen["total_cost"])
|
||||
if cur_cost > 0 and (cur_cost - low_cost) / cur_cost >= 0.10:
|
||||
savings = round(cur_cost - low_cost, 2)
|
||||
pct_save = round((savings / cur_cost) * 100.0, 1)
|
||||
ev_cur = _add_ev(
|
||||
make_metric(
|
||||
f"m_cmp_current_{slug}",
|
||||
f"Current {horizon}-yr Estimate ({code} - {SCENARIO_DISPLAY_NAMES.get(cur_setup, cur_setup)})",
|
||||
cur_cost,
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
ev_low = _add_ev(
|
||||
make_metric(
|
||||
f"m_cmp_lowest_{slug}",
|
||||
f"Lowest {horizon}-yr Estimate ({code} - {SCENARIO_DISPLAY_NAMES.get(lowest_key, lowest_key)})",
|
||||
low_cost,
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
target_label = SCENARIO_DISPLAY_NAMES.get(lowest_key, lowest_key)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S5_{slug}",
|
||||
"rule": "S5",
|
||||
"severity": "info",
|
||||
"title": f"Lower {horizon}-year cost option identified for {code}",
|
||||
"detail": (
|
||||
f"For {code} ({name}), {target_label} ({format_inr(low_cost)}) is "
|
||||
f"{pct_save:.1f}% ({format_inr(savings)}) below current {SCENARIO_DISPLAY_NAMES.get(cur_setup, cur_setup)} "
|
||||
f"({format_inr(cur_cost)}) over {horizon} years."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_cur, ev_low],
|
||||
"action_for_human": f"Evaluate {target_label}. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S6: PM overdue AND >= 1 breakdown in period ---
|
||||
pm_recs = dataset.get("pm_records_by_asset", {}).get(aid, [])
|
||||
overdue_pm_days = 0
|
||||
for rec in pm_recs:
|
||||
if rec.get("status") not in ("completed", "rescheduled"):
|
||||
p_d = _to_date(rec.get("planned_date"))
|
||||
if p_d is not None and p_d < today:
|
||||
overdue_pm_days = max(overdue_pm_days, (today - p_d).days)
|
||||
if overdue_pm_days > 0 and period_b >= 1:
|
||||
ev_pm = _add_ev(
|
||||
make_metric(
|
||||
f"m_pm_overdue_days_{slug}",
|
||||
f"PM Overdue Days ({code})",
|
||||
overdue_pm_days,
|
||||
"days",
|
||||
f"{overdue_pm_days} days overdue",
|
||||
)
|
||||
)
|
||||
ev_b = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_count_{slug}",
|
||||
f"Breakdowns in Period ({code})",
|
||||
period_b,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S6_{slug}",
|
||||
"rule": "S6",
|
||||
"severity": "yellow",
|
||||
"title": f"Overdue PM with active breakdowns on {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has preventive maintenance overdue by {overdue_pm_days} day(s) "
|
||||
f"and recorded {period_b} breakdown(s) in the period."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_pm, ev_b],
|
||||
"action_for_human": "Clear overdue PM. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S7: Calibration overdue ---
|
||||
cal_recs = dataset.get("cal_records_by_asset", {}).get(aid, [])
|
||||
cal_plan = dataset.get("cal_plans_by_asset", {}).get(aid)
|
||||
cal_overdue_days = 0
|
||||
open_cal_found = False
|
||||
for cr in cal_recs:
|
||||
if cr.get("status") != "completed":
|
||||
open_cal_found = True
|
||||
d_d = _to_date(cr.get("due_date"))
|
||||
if d_d is not None and d_d < today:
|
||||
cal_overdue_days = max(cal_overdue_days, (today - d_d).days)
|
||||
if not open_cal_found and cal_plan:
|
||||
d_d = _to_date(cal_plan.get("next_due_date"))
|
||||
if d_d is not None and d_d < today:
|
||||
cal_overdue_days = (today - d_d).days
|
||||
|
||||
if cal_overdue_days > 0:
|
||||
sev = "red" if cal_overdue_days > 30 else "yellow"
|
||||
ev_cal = _add_ev(
|
||||
make_metric(
|
||||
f"m_cal_overdue_days_{slug}",
|
||||
f"Calibration Overdue Days ({code})",
|
||||
cal_overdue_days,
|
||||
"days",
|
||||
f"{cal_overdue_days} days overdue",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S7_{slug}",
|
||||
"rule": "S7",
|
||||
"severity": sev,
|
||||
"title": f"Calibration overdue on {code} ({cal_overdue_days} days)",
|
||||
"detail": (
|
||||
f"Scheduled calibration for {code} ({name}) is overdue by {cal_overdue_days} day(s)."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_cal],
|
||||
"action_for_human": "Complete calibration. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S8: Fully depreciated AND efficiency_score < 80 ---
|
||||
eff_score = eff_row.get("efficiency_score")
|
||||
if dep_row.get("fully_depreciated") and eff_score is not None and float(eff_score) < 80.0:
|
||||
ev_bv = _add_ev(
|
||||
make_metric(
|
||||
f"m_dep_book_value_{slug}",
|
||||
f"Book Value ({code})",
|
||||
dep_row.get("book_value"),
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
ev_eff = _add_ev(
|
||||
make_metric(
|
||||
f"m_eff_score_{slug}",
|
||||
f"Efficiency Score ({code})",
|
||||
float(eff_score),
|
||||
"score",
|
||||
f"{float(eff_score):.1f} / 100",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S8_{slug}",
|
||||
"rule": "S8",
|
||||
"severity": "yellow",
|
||||
"title": f"Fully depreciated asset with low efficiency: {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has reached the end of its depreciable life "
|
||||
f"(book value {format_inr(dep_row.get('book_value'))}) with an efficiency score of "
|
||||
f"{float(eff_score):.1f} / 100."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_bv, ev_eff],
|
||||
"action_for_human": "Replacement planning. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
suggestions.sort(
|
||||
key=lambda s: (
|
||||
SEVERITY_RANK.get(s["severity"], 9),
|
||||
s["asset_codes"][0] if s["asset_codes"] else "",
|
||||
s["rule"],
|
||||
)
|
||||
)
|
||||
|
||||
return {
|
||||
"suggestions": suggestions,
|
||||
"evidence": list(evidence_by_id.values()),
|
||||
}
|
||||
|
||||
|
||||
def get_suggestions_for_scope(
|
||||
db: Session,
|
||||
user: User,
|
||||
period_start: date,
|
||||
period_end: date,
|
||||
department_id: Optional[int] = None,
|
||||
category_id: Optional[int] = None,
|
||||
) -> dict[str, Any]:
|
||||
dataset = load_ai_dataset(
|
||||
db,
|
||||
user,
|
||||
period_start,
|
||||
period_end,
|
||||
department_id=department_id,
|
||||
category_id=category_id,
|
||||
)
|
||||
return generate_suggestions(dataset)
|
||||
|
||||
@@ -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,585 @@
|
||||
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",
|
||||
"acquisition_mode",
|
||||
"monthly_rent",
|
||||
"useful_life_years",
|
||||
"salvage_pct",
|
||||
"depreciation_method",
|
||||
]
|
||||
|
||||
VALID_STATUSES = ("in_service", "under_repair", "out_of_service", "condemned")
|
||||
VALID_CRITICALITIES = ("critical", "non_critical")
|
||||
VALID_ACQUISITION_MODES = ("purchased", "rented")
|
||||
VALID_DEPRECIATION_METHODS = ("straight_line", "written_down")
|
||||
|
||||
_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",
|
||||
"purchased",
|
||||
3500,
|
||||
10,
|
||||
5,
|
||||
"straight_line",
|
||||
]
|
||||
_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"),
|
||||
(15, "Acquisition Modes"),
|
||||
(17, "Depreciation Methods"),
|
||||
]
|
||||
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)
|
||||
|
||||
for idx, mode in enumerate(VALID_ACQUISITION_MODES, start=2):
|
||||
ref.cell(row=idx, column=15, value=mode)
|
||||
|
||||
for idx, dm in enumerate(VALID_DEPRECIATION_METHODS, start=2):
|
||||
ref.cell(row=idx, column=17, value=dm)
|
||||
|
||||
_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)
|
||||
|
||||
acq_raw = _clean_str(row_dict.get("acquisition_mode"))
|
||||
acq_val = acq_raw.lower().replace(" ", "_") if acq_raw else "purchased"
|
||||
if acq_val not in VALID_ACQUISITION_MODES:
|
||||
row_errors.append(
|
||||
f"Invalid acquisition_mode '{acq_raw}' (valid: {', '.join(VALID_ACQUISITION_MODES)})"
|
||||
)
|
||||
|
||||
monthly_rent, rent_err = _parse_optional_float(row_dict.get("monthly_rent"), "monthly_rent")
|
||||
if rent_err:
|
||||
row_errors.append(rent_err)
|
||||
|
||||
useful_life_raw = _clean_str(row_dict.get("useful_life_years"))
|
||||
useful_life_years: int | None = None
|
||||
if useful_life_raw:
|
||||
try:
|
||||
ul_f = float(useful_life_raw)
|
||||
ul_i = int(ul_f)
|
||||
if ul_i < 1 or ul_i > 100 or ul_i != ul_f:
|
||||
row_errors.append(f"Invalid useful_life_years '{useful_life_raw}' (must be an integer 1-100)")
|
||||
else:
|
||||
useful_life_years = ul_i
|
||||
except (TypeError, ValueError):
|
||||
row_errors.append(f"Invalid useful_life_years '{useful_life_raw}' (must be an integer 1-100)")
|
||||
|
||||
salvage_pct, salv_err = _parse_optional_float(row_dict.get("salvage_pct"), "salvage_pct")
|
||||
if salv_err:
|
||||
row_errors.append(salv_err)
|
||||
elif salvage_pct is not None and salvage_pct > 50:
|
||||
row_errors.append("salvage_pct must be between 0 and 50")
|
||||
|
||||
dm_raw = _clean_str(row_dict.get("depreciation_method"))
|
||||
dm_val: str | None = dm_raw.lower().replace(" ", "_") if dm_raw else None
|
||||
if dm_val is not None and dm_val not in VALID_DEPRECIATION_METHODS:
|
||||
row_errors.append(
|
||||
f"Invalid depreciation_method '{dm_raw}' (valid: {', '.join(VALID_DEPRECIATION_METHODS)})"
|
||||
)
|
||||
|
||||
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,
|
||||
acquisition_mode=acq_val,
|
||||
monthly_rent=monthly_rent,
|
||||
useful_life_years=useful_life_years,
|
||||
salvage_pct=salvage_pct,
|
||||
depreciation_method=dm_val,
|
||||
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,
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
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
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.time_utils import utc_now
|
||||
from ..models import (
|
||||
Asset,
|
||||
Attachment,
|
||||
CalibrationRecord,
|
||||
Complaint,
|
||||
Contract,
|
||||
DemoEquipment,
|
||||
InsurancePolicy,
|
||||
PMRecord,
|
||||
PMSchedule,
|
||||
User,
|
||||
Warranty,
|
||||
)
|
||||
from ..services.audit import log_audit
|
||||
from ..services.permissions import Role
|
||||
|
||||
ALLOWED_ENTITY_TYPES: set[str] = {
|
||||
"complaint",
|
||||
"contract",
|
||||
"calibration_record",
|
||||
"insurance",
|
||||
"demo_equipment",
|
||||
"asset",
|
||||
"warranty",
|
||||
"pm_record",
|
||||
}
|
||||
|
||||
EXT_TO_MIME: dict[str, str] = {
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".pdf": "application/pdf",
|
||||
}
|
||||
|
||||
ACCEPTED_CONTENT_TYPES: dict[str, set[str]] = {
|
||||
"image/jpeg": {"image/jpeg", "image/jpg", "image/pjpeg", "application/octet-stream", ""},
|
||||
"image/png": {"image/png", "application/octet-stream", ""},
|
||||
"application/pdf": {"application/pdf", "application/octet-stream", ""},
|
||||
}
|
||||
|
||||
COORDINATOR_UPLOAD_ENTITIES: set[str] = {
|
||||
"contract",
|
||||
"calibration_record",
|
||||
"insurance",
|
||||
"warranty",
|
||||
"demo_equipment",
|
||||
"pm_record",
|
||||
}
|
||||
|
||||
|
||||
def resolve_entity_department_id(db: Session, entity_type: str, entity_id: int) -> int:
|
||||
if entity_type not in ALLOWED_ENTITY_TYPES:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail=f"Unsupported entity_type '{entity_type}'.",
|
||||
code="INVALID_ENTITY_TYPE",
|
||||
)
|
||||
|
||||
if entity_type == "asset":
|
||||
obj = db.query(Asset).filter(Asset.id == entity_id).first()
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Asset not found.", code="NOT_FOUND")
|
||||
return obj.department_id
|
||||
|
||||
if entity_type == "complaint":
|
||||
obj = (
|
||||
db.query(Complaint)
|
||||
.options(joinedload(Complaint.asset))
|
||||
.filter(Complaint.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Complaint not found.", code="NOT_FOUND")
|
||||
return obj.asset.department_id
|
||||
|
||||
if entity_type == "demo_equipment":
|
||||
obj = db.query(DemoEquipment).filter(DemoEquipment.id == entity_id).first()
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Demo equipment not found.", code="NOT_FOUND")
|
||||
return obj.department_id
|
||||
|
||||
if entity_type == "contract":
|
||||
obj = (
|
||||
db.query(Contract)
|
||||
.options(joinedload(Contract.asset))
|
||||
.filter(Contract.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Contract not found.", code="NOT_FOUND")
|
||||
return obj.asset.department_id
|
||||
|
||||
if entity_type == "warranty":
|
||||
obj = (
|
||||
db.query(Warranty)
|
||||
.options(joinedload(Warranty.asset))
|
||||
.filter(Warranty.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Warranty not found.", code="NOT_FOUND")
|
||||
return obj.asset.department_id
|
||||
|
||||
if entity_type == "insurance":
|
||||
obj = (
|
||||
db.query(InsurancePolicy)
|
||||
.options(joinedload(InsurancePolicy.asset))
|
||||
.filter(InsurancePolicy.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Insurance policy not found.", code="NOT_FOUND")
|
||||
return obj.asset.department_id
|
||||
|
||||
if entity_type == "calibration_record":
|
||||
obj = (
|
||||
db.query(CalibrationRecord)
|
||||
.options(joinedload(CalibrationRecord.asset))
|
||||
.filter(CalibrationRecord.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
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")
|
||||
|
||||
|
||||
def assert_entity_visible(db: Session, user: User, entity_type: str, entity_id: int) -> int:
|
||||
dept_id = resolve_entity_department_id(db, entity_type, entity_id)
|
||||
if user.role == Role.department_user.value and dept_id != user.department_id:
|
||||
raise CodedHTTPException(
|
||||
status_code=403,
|
||||
detail="Access denied for another department's record.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
return dept_id
|
||||
|
||||
|
||||
def assert_can_upload(user: User, entity_type: str) -> None:
|
||||
if user.role in (Role.system_admin.value, Role.biomedical.value):
|
||||
return
|
||||
if user.role == Role.department_user.value:
|
||||
if entity_type != "complaint":
|
||||
raise CodedHTTPException(
|
||||
status_code=403,
|
||||
detail="Department users may only upload attachments to complaints.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
return
|
||||
if user.role == Role.coordinator.value:
|
||||
if entity_type not in COORDINATOR_UPLOAD_ENTITIES:
|
||||
raise CodedHTTPException(
|
||||
status_code=403,
|
||||
detail=f"Coordinators cannot upload attachments to '{entity_type}'.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
return
|
||||
raise CodedHTTPException(
|
||||
status_code=403,
|
||||
detail="You do not have permission to upload attachments.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
|
||||
|
||||
def assert_can_delete(user: User, att: Attachment) -> None:
|
||||
if user.role in (Role.system_admin.value, Role.biomedical.value):
|
||||
return
|
||||
if user.role != Role.management.value and att.uploaded_by_id == user.id:
|
||||
return
|
||||
raise CodedHTTPException(
|
||||
status_code=403,
|
||||
detail="You do not have permission to delete this attachment.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
|
||||
|
||||
def validate_and_read_upload(file: UploadFile) -> tuple[str, str, bytes]:
|
||||
original_name = Path(file.filename or "").name
|
||||
ext = Path(original_name).suffix.lower()
|
||||
if ext not in EXT_TO_MIME:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="Only JPG, JPEG, PNG, and PDF files are allowed.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
|
||||
expected_mime = EXT_TO_MIME[ext]
|
||||
claimed_type = (file.content_type or "").lower().strip()
|
||||
if claimed_type not in ACCEPTED_CONTENT_TYPES[expected_mime]:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid content type '{claimed_type}' for {ext} file.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
|
||||
max_bytes = settings.MAX_UPLOAD_SIZE_MB * 1024 * 1024
|
||||
content = file.file.read(max_bytes + 1)
|
||||
if len(content) > max_bytes:
|
||||
raise CodedHTTPException(
|
||||
status_code=413,
|
||||
detail=f"File size exceeds the {settings.MAX_UPLOAD_SIZE_MB} MB limit.",
|
||||
code="FILE_TOO_LARGE",
|
||||
)
|
||||
if len(content) == 0:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="Uploaded file is empty.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
|
||||
# Magic bytes verification
|
||||
if expected_mime == "image/jpeg" and not content.startswith(b"\xff\xd8\xff"):
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="File contents do not match a valid JPEG image.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
if expected_mime == "image/png" and not content.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="File contents do not match a valid PNG image.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
if expected_mime == "application/pdf" and not content.startswith(b"%PDF-"):
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="File contents do not match a valid PDF document.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
|
||||
return original_name, expected_mime, content
|
||||
|
||||
|
||||
def save_attachment(
|
||||
db: Session,
|
||||
user: User,
|
||||
entity_type: str,
|
||||
entity_id: int,
|
||||
file: UploadFile,
|
||||
) -> Attachment:
|
||||
assert_entity_visible(db, user, entity_type, entity_id)
|
||||
assert_can_upload(user, entity_type)
|
||||
|
||||
original_name, mime_type, content = validate_and_read_upload(file)
|
||||
ext = Path(original_name).suffix.lower()
|
||||
stored_name = f"{uuid4().hex}{ext}"
|
||||
|
||||
upload_dir = Path(settings.UPLOAD_DIR)
|
||||
upload_dir.mkdir(parents=True, exist_ok=True)
|
||||
dest_path = upload_dir / stored_name
|
||||
dest_path.write_bytes(content)
|
||||
|
||||
att = Attachment(
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
original_name=original_name,
|
||||
stored_name=stored_name,
|
||||
mime_type=mime_type,
|
||||
size_bytes=len(content),
|
||||
uploaded_by_id=user.id,
|
||||
uploaded_at=utc_now(),
|
||||
)
|
||||
db.add(att)
|
||||
db.flush()
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="attachment",
|
||||
entity_id=att.id,
|
||||
action="upload",
|
||||
changes={"parent_type": entity_type, "parent_id": entity_id, "original_name": original_name},
|
||||
user_id=user.id,
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(att)
|
||||
return att
|
||||
|
||||
|
||||
def delete_attachment(db: Session, user: User, attachment_id: int) -> None:
|
||||
att = db.query(Attachment).filter(Attachment.id == attachment_id).first()
|
||||
if att is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Attachment not found.", code="NOT_FOUND")
|
||||
|
||||
assert_entity_visible(db, user, att.entity_type, att.entity_id)
|
||||
assert_can_delete(user, att)
|
||||
|
||||
file_path = Path(settings.UPLOAD_DIR) / att.stored_name
|
||||
if file_path.is_file():
|
||||
file_path.unlink()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="attachment",
|
||||
entity_id=att.id,
|
||||
action="delete",
|
||||
changes={"parent_type": att.entity_type, "parent_id": att.entity_id, "original_name": att.original_name},
|
||||
user_id=user.id,
|
||||
)
|
||||
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,25 @@
|
||||
import json
|
||||
from typing import Any
|
||||
from sqlalchemy.orm import Session
|
||||
from ..core.time_utils import utc_now
|
||||
from ..models.system import AuditLog
|
||||
|
||||
|
||||
def log_audit(
|
||||
db: Session,
|
||||
entity_type: str,
|
||||
entity_id: int,
|
||||
action: str,
|
||||
changes: dict[str, Any],
|
||||
user_id: int | None,
|
||||
) -> AuditLog:
|
||||
entry = AuditLog(
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
action=action,
|
||||
changes_json=json.dumps(changes, default=str),
|
||||
by_user_id=user_id,
|
||||
at=utc_now(),
|
||||
)
|
||||
db.add(entry)
|
||||
return entry
|
||||
@@ -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",
|
||||
"contract_value",
|
||||
"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("contract_value")
|
||||
if cost_val is None or (isinstance(cost_val, str) and not cost_val.strip()):
|
||||
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, "contract_value")
|
||||
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:
|
||||
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,
|
||||
"contract_value": cost,
|
||||
"coverage_period_text": coverage_details or f"{start_date} to {end_date}",
|
||||
"remarks": 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 ""),
|
||||
"contract_value": cost,
|
||||
"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"],
|
||||
contract_value=item["contract_value"],
|
||||
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,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
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(
|
||||
due_date: date | None,
|
||||
today: date,
|
||||
lead_days: int,
|
||||
red_days: int,
|
||||
) -> Literal["ok", "yellow", "red"]:
|
||||
"""Classify a due date into ok/yellow/red alert severity relative to today."""
|
||||
if due_date is None:
|
||||
return "ok"
|
||||
days_left = (due_date - today).days
|
||||
if days_left <= red_days:
|
||||
return "red"
|
||||
if days_left <= lead_days:
|
||||
return "yellow"
|
||||
return "ok"
|
||||
|
||||
|
||||
def coverage_status(
|
||||
start_date: date | None,
|
||||
end_date: date | None,
|
||||
today: date,
|
||||
lead_days: int,
|
||||
red_days: int,
|
||||
) -> tuple[str, str]:
|
||||
"""Compute (status, severity) for a warranty, contract, or insurance policy."""
|
||||
if end_date is None:
|
||||
return ("none", "none")
|
||||
if end_date < today:
|
||||
return ("expired", "red")
|
||||
state = alert_state(end_date, today, lead_days, red_days)
|
||||
if state in ("yellow", "red"):
|
||||
return ("expiring", state)
|
||||
return ("active", "ok")
|
||||
|
||||
|
||||
def compute_schedule_status(
|
||||
due_date: date | None,
|
||||
persisted_status: str | None,
|
||||
today: date,
|
||||
due_window_days: int,
|
||||
red_days: int,
|
||||
) -> tuple[str, str]:
|
||||
"""Compute (status, severity) for calibration or PM records.
|
||||
|
||||
Only 'completed' or 'rescheduled' are stored in DB; upcoming/due/overdue are
|
||||
always derived dynamically against effective_today().
|
||||
"""
|
||||
if persisted_status in ("completed", "rescheduled"):
|
||||
return (persisted_status, "ok")
|
||||
if due_date is None:
|
||||
return ("none", "none")
|
||||
days_left = (due_date - today).days
|
||||
if days_left < 0:
|
||||
return ("overdue", "red")
|
||||
if days_left <= due_window_days:
|
||||
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,257 @@
|
||||
from datetime import date
|
||||
from typing import Any, Optional
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.time_utils import effective_today
|
||||
from ..models import Asset, Contract, Vendor, Warranty
|
||||
from .calculations import coverage_status
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
COVERAGE_TAG_LABELS: dict[str, str] = {
|
||||
"warranty": "Warranty",
|
||||
"cmc": "CMC",
|
||||
"amc": "AMC",
|
||||
"other_contract": "Other Contract",
|
||||
"out_of_contract": "Out of Contract",
|
||||
}
|
||||
|
||||
_CONTRACT_TYPE_PRIORITY = {
|
||||
"CMC": 1,
|
||||
"AMC": 2,
|
||||
"OTHER": 3,
|
||||
}
|
||||
|
||||
_CONTRACT_TYPE_TO_TAG = {
|
||||
"CMC": "cmc",
|
||||
"AMC": "amc",
|
||||
"OTHER": "other_contract",
|
||||
}
|
||||
|
||||
|
||||
def format_coverage_tag_label(tag: Optional[str]) -> str:
|
||||
if not tag:
|
||||
return "Out of Contract"
|
||||
return COVERAGE_TAG_LABELS.get(tag, tag.replace("_", " ").title())
|
||||
|
||||
|
||||
def format_vendor_contact(vendor: Optional[Vendor]) -> Optional[str]:
|
||||
if vendor is None:
|
||||
return None
|
||||
parts: list[str] = []
|
||||
if vendor.phone and vendor.phone.strip():
|
||||
parts.append(vendor.phone.strip())
|
||||
elif vendor.email and vendor.email.strip():
|
||||
parts.append(vendor.email.strip())
|
||||
if vendor.contact_person and vendor.contact_person.strip():
|
||||
if parts:
|
||||
return f"{vendor.contact_person.strip()} ({parts[0]})"
|
||||
return vendor.contact_person.strip()
|
||||
return parts[0] if parts else None
|
||||
|
||||
|
||||
def _lead_and_red_settings(db: Session) -> dict[str, int]:
|
||||
return {
|
||||
"warranty_lead": int(get_setting_value(db, "warranty_expiry_alert_days", 30)),
|
||||
"contract_lead": int(get_setting_value(db, "contract_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)),
|
||||
}
|
||||
|
||||
|
||||
def _compute_from_records(
|
||||
warranties: list[Warranty],
|
||||
contracts: list[Contract],
|
||||
supplier: Optional[Vendor],
|
||||
on_date: date,
|
||||
leads: dict[str, int],
|
||||
) -> dict[str, Any]:
|
||||
# 1. Active warranties: start_date <= on_date <= end_date
|
||||
active_warranties = [
|
||||
w for w in warranties if w.start_date <= on_date <= w.end_date
|
||||
]
|
||||
if active_warranties:
|
||||
active_warranties.sort(key=lambda w: (w.end_date, w.id), reverse=True)
|
||||
w = active_warranties[0]
|
||||
provider = w.provider or supplier
|
||||
_, sev = coverage_status(
|
||||
w.start_date, w.end_date, on_date, leads["warranty_lead"], leads["red"]
|
||||
)
|
||||
sev_norm = sev if sev in ("ok", "yellow", "red") else "ok"
|
||||
return {
|
||||
"tag": "warranty",
|
||||
"contract_id": None,
|
||||
"warranty_id": w.id,
|
||||
"provider_id": provider.id if provider else w.provider_id,
|
||||
"provider_name": provider.name if provider else None,
|
||||
"provider_contact": format_vendor_contact(provider),
|
||||
"valid_from": w.start_date,
|
||||
"valid_until": w.end_date,
|
||||
"days_left": (w.end_date - on_date).days,
|
||||
"severity": sev_norm,
|
||||
}
|
||||
|
||||
# 2. Active non-superseded contracts: priority CMC > AMC > OTHER
|
||||
active_contracts = [
|
||||
c
|
||||
for c in contracts
|
||||
if not c.is_superseded and c.start_date <= on_date <= c.end_date
|
||||
]
|
||||
if active_contracts:
|
||||
active_contracts.sort(
|
||||
key=lambda c: (
|
||||
_CONTRACT_TYPE_PRIORITY.get((c.contract_type or "").upper(), 99),
|
||||
-c.end_date.toordinal(),
|
||||
-c.id,
|
||||
)
|
||||
)
|
||||
c = active_contracts[0]
|
||||
ctype = (c.contract_type or "OTHER").upper()
|
||||
tag = _CONTRACT_TYPE_TO_TAG.get(ctype, "other_contract")
|
||||
provider = c.provider
|
||||
_, sev = coverage_status(
|
||||
c.start_date, c.end_date, on_date, leads["contract_lead"], leads["contract_red"]
|
||||
)
|
||||
sev_norm = sev if sev in ("ok", "yellow", "red") else "ok"
|
||||
return {
|
||||
"tag": tag,
|
||||
"contract_id": c.id,
|
||||
"warranty_id": None,
|
||||
"provider_id": c.provider_id,
|
||||
"provider_name": provider.name if provider else None,
|
||||
"provider_contact": format_vendor_contact(provider),
|
||||
"valid_from": c.start_date,
|
||||
"valid_until": c.end_date,
|
||||
"days_left": (c.end_date - on_date).days,
|
||||
"severity": sev_norm,
|
||||
}
|
||||
|
||||
# 3. Out of contract
|
||||
return {
|
||||
"tag": "out_of_contract",
|
||||
"contract_id": None,
|
||||
"warranty_id": None,
|
||||
"provider_id": None,
|
||||
"provider_name": None,
|
||||
"provider_contact": None,
|
||||
"valid_from": None,
|
||||
"valid_until": None,
|
||||
"days_left": None,
|
||||
"severity": "red",
|
||||
}
|
||||
|
||||
|
||||
def get_coverage(
|
||||
db: Session,
|
||||
asset_id: int,
|
||||
on_date: Optional[date] = None,
|
||||
) -> dict[str, Any]:
|
||||
target_date = on_date or effective_today(db)
|
||||
leads = _lead_and_red_settings(db)
|
||||
|
||||
asset = (
|
||||
db.query(Asset)
|
||||
.options(joinedload(Asset.supplier))
|
||||
.filter(Asset.id == asset_id)
|
||||
.first()
|
||||
)
|
||||
supplier = asset.supplier if asset else None
|
||||
|
||||
warranties = (
|
||||
db.query(Warranty)
|
||||
.options(joinedload(Warranty.provider))
|
||||
.filter(Warranty.asset_id == asset_id)
|
||||
.all()
|
||||
)
|
||||
contracts = (
|
||||
db.query(Contract)
|
||||
.options(joinedload(Contract.provider))
|
||||
.filter(Contract.asset_id == asset_id, Contract.is_superseded.is_(False))
|
||||
.all()
|
||||
)
|
||||
return _compute_from_records(warranties, contracts, supplier, target_date, leads)
|
||||
|
||||
|
||||
def get_coverage_map(
|
||||
db: Session,
|
||||
asset_ids: list[int],
|
||||
on_date: Optional[date] = None,
|
||||
) -> dict[int, dict[str, Any]]:
|
||||
if not asset_ids:
|
||||
return {}
|
||||
unique_ids = list(set(asset_ids))
|
||||
target_date = on_date or effective_today(db)
|
||||
leads = _lead_and_red_settings(db)
|
||||
|
||||
assets = (
|
||||
db.query(Asset)
|
||||
.options(joinedload(Asset.supplier))
|
||||
.filter(Asset.id.in_(unique_ids))
|
||||
.all()
|
||||
)
|
||||
supplier_by_asset: dict[int, Optional[Vendor]] = {a.id: a.supplier for a in assets}
|
||||
|
||||
warranties_by_asset: dict[int, list[Warranty]] = {aid: [] for aid in unique_ids}
|
||||
for w in (
|
||||
db.query(Warranty)
|
||||
.options(joinedload(Warranty.provider))
|
||||
.filter(Warranty.asset_id.in_(unique_ids))
|
||||
.all()
|
||||
):
|
||||
warranties_by_asset.setdefault(w.asset_id, []).append(w)
|
||||
|
||||
contracts_by_asset: dict[int, list[Contract]] = {aid: [] for aid in unique_ids}
|
||||
for c in (
|
||||
db.query(Contract)
|
||||
.options(joinedload(Contract.provider))
|
||||
.filter(Contract.asset_id.in_(unique_ids), Contract.is_superseded.is_(False))
|
||||
.all()
|
||||
):
|
||||
contracts_by_asset.setdefault(c.asset_id, []).append(c)
|
||||
|
||||
return {
|
||||
aid: _compute_from_records(
|
||||
warranties_by_asset.get(aid, []),
|
||||
contracts_by_asset.get(aid, []),
|
||||
supplier_by_asset.get(aid),
|
||||
target_date,
|
||||
leads,
|
||||
)
|
||||
for aid in unique_ids
|
||||
}
|
||||
|
||||
|
||||
def get_active_amc_cmc(
|
||||
db: Session,
|
||||
asset_id: int,
|
||||
on_date: Optional[date] = None,
|
||||
) -> Optional[Contract]:
|
||||
"""Return the highest-priority active non-superseded AMC/CMC contract (CMC > AMC)."""
|
||||
target_date = on_date or effective_today(db)
|
||||
contracts = (
|
||||
db.query(Contract)
|
||||
.filter(
|
||||
Contract.asset_id == asset_id,
|
||||
Contract.is_superseded.is_(False),
|
||||
Contract.contract_type.in_(["CMC", "AMC"]),
|
||||
Contract.start_date <= target_date,
|
||||
Contract.end_date >= target_date,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
if not contracts:
|
||||
return None
|
||||
contracts.sort(
|
||||
key=lambda c: (
|
||||
_CONTRACT_TYPE_PRIORITY.get((c.contract_type or "").upper(), 99),
|
||||
-c.end_date.toordinal(),
|
||||
-c.id,
|
||||
)
|
||||
)
|
||||
return contracts[0]
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
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 _write_styled_sheet(ws, report_payload: dict[str, Any]) -> None:
|
||||
# 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
|
||||
|
||||
|
||||
def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = _sanitize_sheet_title(report_payload.get("title", "Report"))
|
||||
_write_styled_sheet(ws, report_payload)
|
||||
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def build_ai_xlsx(
|
||||
report_payload: dict[str, Any],
|
||||
evidence: list[dict[str, Any]],
|
||||
how_calculated: dict[str, Any],
|
||||
) -> BytesIO:
|
||||
"""Build a styled 3-sheet AI report workbook: main report, Evidence, and How calculated."""
|
||||
wb = Workbook()
|
||||
|
||||
# Sheet 1: Main report
|
||||
ws_main = wb.active
|
||||
ws_main.title = _sanitize_sheet_title(report_payload.get("title", "AI Report"))
|
||||
_write_styled_sheet(ws_main, report_payload)
|
||||
|
||||
# Sheet 2: Evidence
|
||||
ws_ev = wb.create_sheet(title=_sanitize_sheet_title("Evidence"))
|
||||
ev_payload = {
|
||||
"title": f"{report_payload.get('title', 'AI Report')} — Evidence",
|
||||
"filters_applied": report_payload.get("filters_applied", {}),
|
||||
"summary": {"evidence_metrics": len(evidence)},
|
||||
"columns": [
|
||||
{"key": "id", "label": "Metric ID"},
|
||||
{"key": "label", "label": "Label"},
|
||||
{"key": "value", "label": "Raw Value"},
|
||||
{"key": "unit", "label": "Unit"},
|
||||
{"key": "formatted", "label": "Formatted"},
|
||||
],
|
||||
"rows": [
|
||||
{
|
||||
"id": m.get("id", ""),
|
||||
"label": m.get("label", ""),
|
||||
"value": m.get("value"),
|
||||
"unit": m.get("unit", ""),
|
||||
"formatted": m.get("formatted", ""),
|
||||
}
|
||||
for m in (evidence or [])
|
||||
],
|
||||
}
|
||||
_write_styled_sheet(ws_ev, ev_payload)
|
||||
|
||||
# Sheet 3: How calculated
|
||||
ws_how = wb.create_sheet(title=_sanitize_sheet_title("How calculated"))
|
||||
how_rows: list[dict[str, Any]] = []
|
||||
for idx, formula in enumerate((how_calculated or {}).get("formulas", []), start=1):
|
||||
how_rows.append({"item": f"Formula {idx}", "details": str(formula)})
|
||||
if (how_calculated or {}).get("latest_equipment_rule"):
|
||||
how_rows.append({"item": "Latest Equipment Rule", "details": str(how_calculated["latest_equipment_rule"])})
|
||||
if (how_calculated or {}).get("missing_data_rule"):
|
||||
how_rows.append({"item": "Missing Data Rule", "details": str(how_calculated["missing_data_rule"])})
|
||||
for k, v in ((how_calculated or {}).get("weights") or {}).items():
|
||||
how_rows.append({"item": f"Weight: {k}", "details": str(v)})
|
||||
for k, v in ((how_calculated or {}).get("settings_used") or {}).items():
|
||||
how_rows.append({"item": f"Setting: {k}", "details": str(v)})
|
||||
if not how_rows:
|
||||
how_rows.append({"item": "Method", "details": "Deterministic Python calculations on hospital AMS data."})
|
||||
|
||||
how_payload = {
|
||||
"title": f"{report_payload.get('title', 'AI Report')} — How Calculated",
|
||||
"filters_applied": report_payload.get("filters_applied", {}),
|
||||
"summary": {"items": len(how_rows)},
|
||||
"columns": [
|
||||
{"key": "item", "label": "Item"},
|
||||
{"key": "details", "label": "Formula / Parameter Details"},
|
||||
],
|
||||
"rows": how_rows,
|
||||
}
|
||||
_write_styled_sheet(ws_how, how_payload)
|
||||
|
||||
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}"
|
||||
@@ -0,0 +1,141 @@
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
class Role(str, Enum):
|
||||
system_admin = "system_admin"
|
||||
biomedical = "biomedical"
|
||||
department_user = "department_user"
|
||||
management = "management"
|
||||
coordinator = "coordinator"
|
||||
|
||||
|
||||
ALL_ROLES: set[str] = {r.value for r in Role}
|
||||
|
||||
RESTRICTED_COMPLAINT_FIELDS: set[str] = {
|
||||
"action_taken",
|
||||
"root_cause",
|
||||
"corrective_action",
|
||||
"lessons_learned",
|
||||
"ce_name",
|
||||
"ce_attended_at",
|
||||
"ce_action_taken",
|
||||
"spare_required",
|
||||
"spare_details",
|
||||
"spare_cost_estimate",
|
||||
"repair_cost",
|
||||
}
|
||||
|
||||
COST_FIELDS: set[str] = {
|
||||
"purchase_value",
|
||||
"monthly_rent",
|
||||
"contract_value",
|
||||
"cost_per_visit",
|
||||
"repair_cost",
|
||||
"spare_cost_estimate",
|
||||
}
|
||||
|
||||
CAPABILITIES: dict[Role, set[str]] = {
|
||||
Role.system_admin: {
|
||||
"manage_admin",
|
||||
"create_edit_assets",
|
||||
"edit_asset_contracts_only",
|
||||
"view_assets",
|
||||
"raise_complaint",
|
||||
"handle_complaint",
|
||||
"edit_technical_fields",
|
||||
"manage_pm",
|
||||
"view_pm",
|
||||
"manage_calibration_contracts",
|
||||
"view_calibration_contracts",
|
||||
"manage_demo_equipment",
|
||||
"view_demo_equipment",
|
||||
"manage_visits",
|
||||
"view_visits",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
},
|
||||
Role.biomedical: {
|
||||
"create_edit_assets",
|
||||
"view_assets",
|
||||
"raise_complaint",
|
||||
"handle_complaint",
|
||||
"edit_technical_fields",
|
||||
"manage_pm",
|
||||
"view_pm",
|
||||
"manage_calibration_contracts",
|
||||
"view_calibration_contracts",
|
||||
"manage_demo_equipment",
|
||||
"view_demo_equipment",
|
||||
"manage_visits",
|
||||
"view_visits",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
},
|
||||
Role.department_user: {
|
||||
"view_assets",
|
||||
"raise_complaint",
|
||||
"view_pm",
|
||||
"view_calibration_contracts",
|
||||
"view_demo_equipment",
|
||||
"view_dept_reports",
|
||||
},
|
||||
Role.management: {
|
||||
"view_assets",
|
||||
"view_pm",
|
||||
"view_calibration_contracts",
|
||||
"view_demo_equipment",
|
||||
"view_visits",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
},
|
||||
Role.coordinator: {
|
||||
"edit_asset_contracts_only",
|
||||
"view_assets",
|
||||
"handle_complaint",
|
||||
"view_pm",
|
||||
"manage_calibration_contracts",
|
||||
"view_calibration_contracts",
|
||||
"manage_demo_equipment",
|
||||
"view_demo_equipment",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def has_capability(role: Role | str | None, capability: str) -> bool:
|
||||
if role is None:
|
||||
return False
|
||||
try:
|
||||
role_enum = role if isinstance(role, Role) else Role(role)
|
||||
except ValueError:
|
||||
return False
|
||||
return capability in CAPABILITIES.get(role_enum, set())
|
||||
|
||||
|
||||
def strip_cost_fields(data: Any) -> Any:
|
||||
"""Recursively remove cost keys from serialized JSON payloads for restricted roles."""
|
||||
if isinstance(data, dict):
|
||||
return {k: strip_cost_fields(v) for k, v in data.items() if k not in COST_FIELDS}
|
||||
if isinstance(data, list):
|
||||
return [strip_cost_fields(item) for item in data]
|
||||
return data
|
||||
|
||||
|
||||
def maybe_strip_costs_response(payload: Any, role: Role | str | None, status_code: int = 200) -> Any:
|
||||
"""Return payload unchanged if role can view costs; otherwise return JSONResponse with cost fields stripped."""
|
||||
if has_capability(role, "view_costs"):
|
||||
return payload
|
||||
encoded = jsonable_encoder(payload)
|
||||
return JSONResponse(content=strip_cost_fields(encoded), status_code=status_code)
|
||||
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,
|
||||
)
|
||||
@@ -0,0 +1,566 @@
|
||||
import json
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from ..core.time_utils import utc_now
|
||||
from ..models.masters import Setting
|
||||
|
||||
SETTINGS_SCHEMA: list[dict[str, Any]] = [
|
||||
{
|
||||
"key": "demo_as_of_date",
|
||||
"type": "date_or_empty",
|
||||
"default": "",
|
||||
"label": "Demo As-Of Date",
|
||||
"description": "Optional YYYY-MM-DD override for the system clock (used for testing/demos). Leave empty for real Asia/Kolkata date.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "contract_expiry_alert_days",
|
||||
"type": "int",
|
||||
"default": 30,
|
||||
"label": "Contract Expiry Alert Lead Days",
|
||||
"description": "Days prior to AMC/CMC/OTHER contract end date to generate expiry alerts.",
|
||||
"min": 1,
|
||||
"max": 180,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "contract_critical_alert_days",
|
||||
"type": "int",
|
||||
"default": 7,
|
||||
"label": "Contract Critical Expiry Alert Days",
|
||||
"description": "Days prior to contract expiry to escalate alert severity to critical (red).",
|
||||
"min": 1,
|
||||
"max": 60,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "warranty_expiry_alert_days",
|
||||
"type": "int",
|
||||
"default": 30,
|
||||
"label": "Warranty Expiry Alert Lead Days",
|
||||
"description": "Days prior to warranty end date to trigger expiry alerts.",
|
||||
"min": 1,
|
||||
"max": 180,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "insurance_expiry_alert_days",
|
||||
"type": "int",
|
||||
"default": 30,
|
||||
"label": "Insurance Expiry Alert Lead Days",
|
||||
"description": "Days prior to insurance policy end date to trigger renewal alerts.",
|
||||
"min": 1,
|
||||
"max": 180,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "calibration_due_window_days",
|
||||
"type": "int",
|
||||
"default": 15,
|
||||
"label": "Calibration Due Window (Days)",
|
||||
"description": "Days before calibration due date when status transitions from upcoming to due.",
|
||||
"min": 1,
|
||||
"max": 90,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "pm_due_window_days",
|
||||
"type": "int",
|
||||
"default": 15,
|
||||
"label": "PM Due Window (Days)",
|
||||
"description": "Days before planned PM date when status transitions from upcoming to due.",
|
||||
"min": 1,
|
||||
"max": 90,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "critical_complaint_sla_hours",
|
||||
"type": "int",
|
||||
"default": 4,
|
||||
"label": "Critical Complaint Response SLA (Hours)",
|
||||
"description": "Target hours to attend and restore a critical priority breakdown complaint.",
|
||||
"min": 1,
|
||||
"max": 72,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "non_critical_complaint_sla_hours",
|
||||
"type": "int",
|
||||
"default": 24,
|
||||
"label": "Non-Critical Complaint Response SLA (Hours)",
|
||||
"description": "Target hours to attend and restore a non-critical priority complaint.",
|
||||
"min": 1,
|
||||
"max": 168,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "escalation_open_complaint_hours",
|
||||
"type": "int",
|
||||
"default": 24,
|
||||
"label": "Open Critical Complaint Escalation (Hours)",
|
||||
"description": "Hours after registration before an unclosed critical complaint triggers escalation.",
|
||||
"min": 1,
|
||||
"max": 168,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "demo_return_alert_days",
|
||||
"type": "int",
|
||||
"default": 3,
|
||||
"label": "Demo Equipment Return Lead Days",
|
||||
"description": "Days before expected return date to alert on demo equipment return.",
|
||||
"min": 0,
|
||||
"max": 30,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "require_closure_remarks",
|
||||
"type": "bool",
|
||||
"default": True,
|
||||
"label": "Require Complaint Closure Remarks",
|
||||
"description": "Require closure remarks before marking a breakdown complaint as closed.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "asset_code_prefix",
|
||||
"type": "str",
|
||||
"default": "PHRC",
|
||||
"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,
|
||||
},
|
||||
{
|
||||
"key": "default_pm_mode",
|
||||
"type": "enum",
|
||||
"default": "in_house",
|
||||
"label": "Default PM Service Mode",
|
||||
"description": "Default preventive maintenance execution mode when creating new schedules.",
|
||||
"min": None,
|
||||
"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,
|
||||
},
|
||||
{
|
||||
"key": "comparison_horizon_years",
|
||||
"type": "int",
|
||||
"default": 5,
|
||||
"label": "Cost Comparison Horizon (Years)",
|
||||
"description": "Projection horizon in years for In-House vs Outsourced vs Rent cost comparisons.",
|
||||
"min": 1,
|
||||
"max": 15,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "latest_equipment_count",
|
||||
"type": "int",
|
||||
"default": 10,
|
||||
"label": "Latest Equipment Comparison Count",
|
||||
"description": "Number of most recently installed/purchased assets shown in the AI cost comparison table.",
|
||||
"min": 3,
|
||||
"max": 50,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "default_useful_life_years",
|
||||
"type": "int",
|
||||
"default": 10,
|
||||
"label": "Default Useful Life (Years)",
|
||||
"description": "Fallback useful life in years for depreciation when neither asset nor category specifies one.",
|
||||
"min": 1,
|
||||
"max": 50,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "default_salvage_pct",
|
||||
"type": "float",
|
||||
"default": 5.0,
|
||||
"label": "Default Salvage Value (%)",
|
||||
"description": "Default residual salvage value percentage (0-50%) used in depreciation calculations.",
|
||||
"min": 0,
|
||||
"max": 50,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "default_depreciation_method",
|
||||
"type": "enum",
|
||||
"default": "straight_line",
|
||||
"label": "Default Depreciation Method",
|
||||
"description": "Default asset depreciation formula when an asset does not override it.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": ["straight_line", "written_down"],
|
||||
},
|
||||
{
|
||||
"key": "repeat_failure_count",
|
||||
"type": "int",
|
||||
"default": 3,
|
||||
"label": "Repeat Failure Threshold (Count)",
|
||||
"description": "Minimum breakdown count within the repeat failure window to flag an asset as a repeat failure.",
|
||||
"min": 2,
|
||||
"max": 20,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "repeat_failure_days",
|
||||
"type": "int",
|
||||
"default": 90,
|
||||
"label": "Repeat Failure Window (Days)",
|
||||
"description": "Rolling lookback window in days (from effective today) for counting repeat breakdowns.",
|
||||
"min": 7,
|
||||
"max": 365,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "replacement_review_ratio",
|
||||
"type": "float",
|
||||
"default": 0.4,
|
||||
"label": "Replacement Review Maintenance Ratio",
|
||||
"description": "Cumulative maintenance cost to purchase value ratio (e.g. 0.4 = 40%) that triggers a replacement review flag.",
|
||||
"min": 0.05,
|
||||
"max": 2.0,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "ai_enabled",
|
||||
"type": "bool",
|
||||
"default": True,
|
||||
"label": "Enable Local AI Narrative Summaries",
|
||||
"description": "Allow the configured local AI provider to generate narrative text for AI report metrics (falls back to rule-based text if disabled or unreachable).",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
]
|
||||
|
||||
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
|
||||
|
||||
|
||||
def validate_setting_value(key: str, value: Any) -> Any:
|
||||
if key not in SETTINGS_BY_KEY:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Unknown setting key: '{key}'",
|
||||
)
|
||||
spec = SETTINGS_BY_KEY[key]
|
||||
stype = spec["type"]
|
||||
|
||||
if stype == "int":
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be an integer.",
|
||||
)
|
||||
if spec["min"] is not None and value < spec["min"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be >= {spec['min']}.",
|
||||
)
|
||||
if spec["max"] is not None and value > spec["max"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be <= {spec['max']}.",
|
||||
)
|
||||
return value
|
||||
|
||||
if stype == "float":
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be a number.",
|
||||
)
|
||||
fval = float(value)
|
||||
if spec["min"] is not None and fval < spec["min"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be >= {spec['min']}.",
|
||||
)
|
||||
if spec["max"] is not None and fval > spec["max"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be <= {spec['max']}.",
|
||||
)
|
||||
return fval
|
||||
|
||||
if stype == "bool":
|
||||
if not isinstance(value, bool):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be a boolean.",
|
||||
)
|
||||
return value
|
||||
|
||||
if stype == "enum":
|
||||
if not isinstance(value, str) or value not in (spec["options"] or []):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be one of {spec['options']}.",
|
||||
)
|
||||
return value
|
||||
|
||||
if stype == "str":
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be a non-empty string.",
|
||||
)
|
||||
return value.strip()
|
||||
|
||||
if stype == "date_or_empty":
|
||||
if value is None or value == "":
|
||||
return ""
|
||||
if not isinstance(value, str):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be a YYYY-MM-DD date string or empty.",
|
||||
)
|
||||
cleaned = value.strip()
|
||||
if cleaned == "":
|
||||
return ""
|
||||
try:
|
||||
date.fromisoformat(cleaned)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be a valid YYYY-MM-DD date.",
|
||||
)
|
||||
return cleaned
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Unsupported setting type for '{key}'.",
|
||||
)
|
||||
|
||||
|
||||
def ensure_default_settings(db: Session) -> None:
|
||||
existing_rows = {row.key: row for row in db.query(Setting).all()}
|
||||
for spec in SETTINGS_SCHEMA:
|
||||
if spec["key"] not in existing_rows:
|
||||
db.add(
|
||||
Setting(
|
||||
key=spec["key"],
|
||||
value_json=json.dumps(spec["default"]),
|
||||
updated_at=utc_now(),
|
||||
)
|
||||
)
|
||||
elif spec["key"] == "ai_enabled":
|
||||
# AI is always on; update legacy false values
|
||||
row = existing_rows["ai_enabled"]
|
||||
if row.value_json in ("false", "False", "0"):
|
||||
row.value_json = json.dumps(True)
|
||||
row.updated_at = utc_now()
|
||||
db.flush()
|
||||
|
||||
|
||||
def get_setting_value(db: Session, key: str, default: Any = None) -> Any:
|
||||
if key == "ai_enabled":
|
||||
return True
|
||||
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 default
|
||||
try:
|
||||
return json.loads(row.value_json)
|
||||
except (ValueError, TypeError):
|
||||
return spec["default"] if spec else default
|
||||
|
||||
|
||||
def get_demo_as_of_date(db: Session) -> str | None:
|
||||
val = get_setting_value(db, "demo_as_of_date")
|
||||
if isinstance(val, str) and val.strip():
|
||||
return val.strip()
|
||||
return None
|
||||
|
||||
|
||||
def get_all_settings(db: Session) -> list[dict[str, Any]]:
|
||||
rows = {row.key: row for row in db.query(Setting).all()}
|
||||
items: list[dict[str, Any]] = []
|
||||
for spec in SETTINGS_SCHEMA:
|
||||
row = rows.get(spec["key"])
|
||||
value = spec["default"]
|
||||
if row is not None:
|
||||
try:
|
||||
value = json.loads(row.value_json)
|
||||
except (ValueError, TypeError):
|
||||
value = spec["default"]
|
||||
items.append(
|
||||
{
|
||||
"key": spec["key"],
|
||||
"value": value,
|
||||
"type": spec["type"],
|
||||
"label": spec["label"],
|
||||
"description": spec["description"],
|
||||
"default": spec["default"],
|
||||
"min": spec["min"],
|
||||
"max": spec["max"],
|
||||
"options": spec["options"],
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def update_settings(db: Session, values: dict[str, Any], user_id: int | None = None) -> list[dict[str, Any]]:
|
||||
for key, raw_val in values.items():
|
||||
clean_val = validate_setting_value(key, raw_val)
|
||||
serialized = json.dumps(clean_val)
|
||||
row = db.query(Setting).filter(Setting.key == key).first()
|
||||
if row is None:
|
||||
row = Setting(
|
||||
key=key,
|
||||
value_json=serialized,
|
||||
updated_at=utc_now(),
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(row)
|
||||
else:
|
||||
row.value_json = serialized
|
||||
row.updated_at = utc_now()
|
||||
row.updated_by_id = user_id
|
||||
db.commit()
|
||||
return get_all_settings(db)
|
||||
@@ -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,15 @@
|
||||
fastapi==0.115.5
|
||||
uvicorn[standard]==0.32.1
|
||||
sqlalchemy==2.0.36
|
||||
pydantic==2.10.1
|
||||
pydantic-settings==2.6.1
|
||||
python-jose[cryptography]==3.3.0
|
||||
bcrypt==5.0.0
|
||||
python-multipart==0.0.12
|
||||
apscheduler==3.10.4
|
||||
openpyxl==3.1.5
|
||||
pillow==11.0.0
|
||||
pytest==8.3.3
|
||||
pytest-asyncio==0.24.0
|
||||
httpx==0.28.0
|
||||
pytz==2024.2
|
||||
@@ -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())
|
||||
@@ -0,0 +1,121 @@
|
||||
import asyncio
|
||||
import threading
|
||||
import httpx
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
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
|
||||
session.close()
|
||||
Base.metadata.drop_all(bind=engine_test)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client(db):
|
||||
def override_get_db():
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
pass
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
c = SyncASGITestClient(app)
|
||||
try:
|
||||
yield c
|
||||
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,448 @@
|
||||
from datetime import timedelta
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from app.core.migrations import run_sqlite_migrations
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import Asset, Category, Complaint, Contract, PMSchedule, Vendor
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.permissions import COST_FIELDS
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_ai1_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("ai1_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 _collect_keys(obj) -> set[str]:
|
||||
keys: set[str] = set()
|
||||
if isinstance(obj, dict):
|
||||
for k, v in obj.items():
|
||||
keys.add(k)
|
||||
keys.update(_collect_keys(v))
|
||||
elif isinstance(obj, list):
|
||||
for item in obj:
|
||||
keys.update(_collect_keys(item))
|
||||
return keys
|
||||
|
||||
|
||||
def test_sqlite_migration_adds_cost_columns_to_old_db(tmp_path):
|
||||
db_file = tmp_path / "legacy.db"
|
||||
eng = create_engine(f"sqlite:///{db_file}")
|
||||
with eng.begin() as conn:
|
||||
conn.exec_driver_sql(
|
||||
"""
|
||||
CREATE TABLE categories (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name VARCHAR(150) NOT NULL,
|
||||
description TEXT,
|
||||
is_active BOOLEAN NOT NULL DEFAULT 1,
|
||||
created_at DATETIME NOT NULL,
|
||||
updated_at DATETIME NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.exec_driver_sql(
|
||||
"""
|
||||
CREATE TABLE assets (
|
||||
id INTEGER PRIMARY KEY,
|
||||
asset_code VARCHAR(60) NOT NULL,
|
||||
serial_no VARCHAR(100) NOT NULL,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
category_id INTEGER NOT NULL,
|
||||
department_id INTEGER NOT NULL,
|
||||
location_id INTEGER NOT NULL,
|
||||
supplier_id INTEGER,
|
||||
purchase_value FLOAT,
|
||||
purchase_date DATE,
|
||||
installation_date DATE,
|
||||
status VARCHAR(40) NOT NULL,
|
||||
criticality VARCHAR(30) NOT NULL,
|
||||
requires_calibration BOOLEAN NOT NULL DEFAULT 0,
|
||||
insurance_applicable BOOLEAN NOT NULL DEFAULT 0,
|
||||
remarks TEXT,
|
||||
created_at DATETIME NOT NULL,
|
||||
created_by_id INTEGER,
|
||||
updated_at DATETIME NOT NULL,
|
||||
updated_by_id INTEGER
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.exec_driver_sql(
|
||||
"""
|
||||
CREATE TABLE contracts (
|
||||
id INTEGER PRIMARY KEY,
|
||||
asset_id INTEGER NOT NULL,
|
||||
contract_type VARCHAR(20) NOT NULL,
|
||||
provider_id INTEGER NOT NULL,
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE NOT NULL,
|
||||
coverage_period_text VARCHAR(100),
|
||||
renewed_from_id INTEGER,
|
||||
is_superseded BOOLEAN NOT NULL DEFAULT 0,
|
||||
remarks TEXT,
|
||||
created_at DATETIME NOT NULL,
|
||||
created_by_id INTEGER,
|
||||
updated_at DATETIME NOT NULL,
|
||||
updated_by_id INTEGER
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.exec_driver_sql(
|
||||
"""
|
||||
CREATE TABLE pm_schedules (
|
||||
id INTEGER PRIMARY KEY,
|
||||
asset_id INTEGER NOT NULL,
|
||||
service_mode VARCHAR(30) NOT NULL,
|
||||
frequency_months INTEGER NOT NULL,
|
||||
responsible_team VARCHAR(150),
|
||||
provider_id INTEGER,
|
||||
contract_id INTEGER,
|
||||
next_planned_date DATE NOT NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT 1,
|
||||
created_at DATETIME NOT NULL,
|
||||
created_by_id INTEGER,
|
||||
updated_at DATETIME NOT NULL,
|
||||
updated_by_id INTEGER
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.exec_driver_sql(
|
||||
"""
|
||||
CREATE TABLE complaints (
|
||||
id INTEGER PRIMARY KEY,
|
||||
complaint_no VARCHAR(60) NOT NULL,
|
||||
asset_id INTEGER NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
priority VARCHAR(30) NOT NULL,
|
||||
registered_at DATETIME NOT NULL,
|
||||
registered_by_id INTEGER NOT NULL,
|
||||
received_by_id INTEGER NOT NULL,
|
||||
call_status VARCHAR(30) NOT NULL,
|
||||
spare_required BOOLEAN NOT NULL DEFAULT 0,
|
||||
updated_at DATETIME NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.exec_driver_sql(
|
||||
"""
|
||||
INSERT INTO assets (
|
||||
id, asset_code, serial_no, name, category_id, department_id, location_id,
|
||||
status, criticality, requires_calibration, insurance_applicable, created_at, updated_at
|
||||
) VALUES (
|
||||
1, 'OLD-001', 'SN-1', 'Legacy Monitor', 1, 1, 1,
|
||||
'in_service', 'critical', 0, 0, '2025-01-01', '2025-01-01'
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
run_sqlite_migrations(eng)
|
||||
|
||||
with eng.connect() as conn:
|
||||
asset_cols = {r[1] for r in conn.execute(text("PRAGMA table_info(assets)")).fetchall()}
|
||||
cat_cols = {r[1] for r in conn.execute(text("PRAGMA table_info(categories)")).fetchall()}
|
||||
con_cols = {r[1] for r in conn.execute(text("PRAGMA table_info(contracts)")).fetchall()}
|
||||
pm_cols = {r[1] for r in conn.execute(text("PRAGMA table_info(pm_schedules)")).fetchall()}
|
||||
cmp_cols = {r[1] for r in conn.execute(text("PRAGMA table_info(complaints)")).fetchall()}
|
||||
|
||||
assert {"acquisition_mode", "monthly_rent", "useful_life_years", "salvage_pct", "depreciation_method"}.issubset(asset_cols)
|
||||
assert "default_useful_life_years" in cat_cols
|
||||
assert "contract_value" in con_cols
|
||||
assert "cost_per_visit" in pm_cols
|
||||
assert "repair_cost" in cmp_cols
|
||||
|
||||
mode = conn.execute(text("SELECT acquisition_mode FROM assets WHERE id = 1")).scalar()
|
||||
assert mode == "purchased"
|
||||
|
||||
eng.dispose()
|
||||
|
||||
|
||||
def test_department_user_never_receives_cost_fields(client):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
# 1. /api/assets
|
||||
res_assets = client.get("/api/assets?page_size=20", headers=dept_headers)
|
||||
assert res_assets.status_code == 200
|
||||
assert len(res_assets.json()["items"]) > 0
|
||||
assert not (COST_FIELDS & _collect_keys(res_assets.json()))
|
||||
|
||||
first_asset_id = res_assets.json()["items"][0]["id"]
|
||||
res_asset_one = client.get(f"/api/assets/{first_asset_id}", headers=dept_headers)
|
||||
assert res_asset_one.status_code == 200
|
||||
assert not (COST_FIELDS & _collect_keys(res_asset_one.json()))
|
||||
|
||||
res_overview = client.get(f"/api/assets/{first_asset_id}/overview", headers=dept_headers)
|
||||
assert res_overview.status_code == 200
|
||||
assert not (COST_FIELDS & _collect_keys(res_overview.json()))
|
||||
|
||||
# 2. /api/contracts
|
||||
res_contracts = client.get("/api/contracts?page_size=20", headers=dept_headers)
|
||||
assert res_contracts.status_code == 200
|
||||
assert not (COST_FIELDS & _collect_keys(res_contracts.json()))
|
||||
|
||||
# 3. /api/complaints
|
||||
res_complaints = client.get("/api/complaints?page_size=20", headers=dept_headers)
|
||||
assert res_complaints.status_code == 200
|
||||
assert len(res_complaints.json()["items"]) > 0
|
||||
assert not (COST_FIELDS & _collect_keys(res_complaints.json()))
|
||||
|
||||
first_comp_id = res_complaints.json()["items"][0]["id"]
|
||||
res_comp_one = client.get(f"/api/complaints/{first_comp_id}", headers=dept_headers)
|
||||
assert res_comp_one.status_code == 200
|
||||
assert not (COST_FIELDS & _collect_keys(res_comp_one.json()))
|
||||
|
||||
# 4. /api/pm/schedules
|
||||
res_pm = client.get("/api/pm/schedules?page_size=20", headers=dept_headers)
|
||||
assert res_pm.status_code == 200
|
||||
assert not (COST_FIELDS & _collect_keys(res_pm.json()))
|
||||
|
||||
# Admin DOES see cost fields
|
||||
admin_assets = client.get("/api/assets?page_size=5", headers=admin_headers)
|
||||
assert "purchase_value" in admin_assets.json()["items"][0]
|
||||
admin_contracts = client.get("/api/contracts?page_size=5", headers=admin_headers)
|
||||
assert "contract_value" in admin_contracts.json()["items"][0]
|
||||
admin_complaints = client.get("/api/complaints?page_size=5", headers=admin_headers)
|
||||
assert "repair_cost" in admin_complaints.json()["items"][0]
|
||||
|
||||
|
||||
def test_repair_cost_and_cost_editing_role_permissions(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
|
||||
# Find an ICU complaint visible to dept@poona.demo
|
||||
comp = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.filter(Asset.department_id == 1)
|
||||
.first()
|
||||
)
|
||||
assert comp is not None
|
||||
|
||||
# Denied (403) for coordinator, department_user, management
|
||||
for headers in (coord_headers, dept_headers, mgmt_headers):
|
||||
res = client.patch(
|
||||
f"/api/complaints/{comp.id}",
|
||||
headers=headers,
|
||||
json={"repair_cost": 9999.0},
|
||||
)
|
||||
assert res.status_code == 403, f"Expected 403, got {res.status_code}: {res.text}"
|
||||
|
||||
# Allowed for biomedical
|
||||
res_ok = client.patch(
|
||||
f"/api/complaints/{comp.id}",
|
||||
headers=bio_headers,
|
||||
json={"repair_cost": 14500.0},
|
||||
)
|
||||
assert res_ok.status_code == 200, res_ok.text
|
||||
assert res_ok.json()["repair_cost"] == 14500.0
|
||||
|
||||
# Coordinator CAN edit contract_value
|
||||
contract = db.query(Contract).first()
|
||||
assert contract is not None
|
||||
res_con = client.patch(
|
||||
f"/api/contracts/{contract.id}",
|
||||
headers=coord_headers,
|
||||
json={"contract_value": 88000.0},
|
||||
)
|
||||
assert res_con.status_code == 200, res_con.text
|
||||
assert res_con.json()["contract_value"] == 88000.0
|
||||
|
||||
# Coordinator CANNOT edit PM cost_per_visit or asset purchase_value
|
||||
pm_sched = db.query(PMSchedule).filter(PMSchedule.service_mode == "in_house").first()
|
||||
assert pm_sched is not None
|
||||
res_pm_deny = client.patch(
|
||||
f"/api/pm/schedules/{pm_sched.id}",
|
||||
headers=coord_headers,
|
||||
json={"cost_per_visit": 9000.0},
|
||||
)
|
||||
assert res_pm_deny.status_code == 403
|
||||
|
||||
res_asset_deny = client.patch(
|
||||
f"/api/assets/{comp.asset_id}",
|
||||
headers=coord_headers,
|
||||
json={"monthly_rent": 15000.0},
|
||||
)
|
||||
assert res_asset_deny.status_code == 403
|
||||
|
||||
|
||||
def test_new_ai_cost_settings_present_and_validated(client):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
res = client.get("/api/settings", headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
by_key = {item["key"]: item for item in res.json()["items"]}
|
||||
|
||||
expected_defaults = {
|
||||
"comparison_horizon_years": 5,
|
||||
"latest_equipment_count": 10,
|
||||
"default_useful_life_years": 10,
|
||||
"default_salvage_pct": 5.0,
|
||||
"default_depreciation_method": "straight_line",
|
||||
"repeat_failure_count": 3,
|
||||
"repeat_failure_days": 90,
|
||||
"replacement_review_ratio": 0.4,
|
||||
"ai_enabled": True,
|
||||
}
|
||||
for key, val in expected_defaults.items():
|
||||
assert key in by_key, f"Missing setting {key}"
|
||||
assert by_key[key]["value"] == val
|
||||
|
||||
# Invalid range rejected with 422
|
||||
bad = client.put(
|
||||
"/api/settings",
|
||||
headers=admin_headers,
|
||||
json={"values": {"comparison_horizon_years": 25}},
|
||||
)
|
||||
assert bad.status_code == 422
|
||||
|
||||
bad_ratio = client.put(
|
||||
"/api/settings",
|
||||
headers=admin_headers,
|
||||
json={"values": {"replacement_review_ratio": 5.0}},
|
||||
)
|
||||
assert bad_ratio.status_code == 422
|
||||
|
||||
# Valid update succeeds
|
||||
good = client.put(
|
||||
"/api/settings",
|
||||
headers=admin_headers,
|
||||
json={"values": {"comparison_horizon_years": 7, "replacement_review_ratio": 0.45}},
|
||||
)
|
||||
assert good.status_code == 200
|
||||
# Restore defaults
|
||||
client.put(
|
||||
"/api/settings",
|
||||
headers=admin_headers,
|
||||
json={"values": {"comparison_horizon_years": 5, "replacement_review_ratio": 0.4}},
|
||||
)
|
||||
|
||||
|
||||
def test_seed_data_meets_cost_and_ai_prerequisites(db):
|
||||
today = effective_today(db)
|
||||
assets = db.query(Asset).all()
|
||||
contracts = db.query(Contract).all()
|
||||
inhouse_pms = db.query(PMSchedule).filter(PMSchedule.service_mode == "in_house").all()
|
||||
closed_complaints = db.query(Complaint).filter(Complaint.call_status == "closed").all()
|
||||
|
||||
rented = [a for a in assets if a.acquisition_mode == "rented" and a.monthly_rent is not None]
|
||||
assert len(rented) == 6
|
||||
|
||||
owned_with_rent_quote = [
|
||||
a for a in assets if a.acquisition_mode == "purchased" and a.monthly_rent is not None
|
||||
]
|
||||
assert len(owned_with_rent_quote) >= 25
|
||||
|
||||
assert all(c.contract_value is not None and c.contract_value > 0 for c in contracts)
|
||||
assert all(p.cost_per_visit is not None and p.cost_per_visit > 0 for p in inhouse_pms)
|
||||
|
||||
closed_with_repair = [c for c in closed_complaints if c.repair_cost is not None]
|
||||
assert len(closed_with_repair) >= 12 # ~60% of 22 closed
|
||||
|
||||
latest_12m = [
|
||||
a for a in assets if a.purchase_date is not None and (today - a.purchase_date).days <= 365
|
||||
]
|
||||
assert len(latest_12m) >= 10
|
||||
|
||||
fully_dep = [
|
||||
a
|
||||
for a in assets
|
||||
if a.acquisition_mode == "purchased"
|
||||
and (a.installation_date or a.purchase_date) is not None
|
||||
and ((today - (a.installation_date or a.purchase_date)).days / 365.25)
|
||||
>= (a.useful_life_years or 10)
|
||||
]
|
||||
assert len(fully_dep) >= 1
|
||||
|
||||
# At least 3 assets with >= 3 breakdowns in last 90 days
|
||||
cutoff = today - timedelta(days=90)
|
||||
counts_by_asset: dict[int, int] = {}
|
||||
for c in db.query(Complaint).all():
|
||||
if c.registered_at.date() >= cutoff:
|
||||
counts_by_asset[c.asset_id] = counts_by_asset.get(c.asset_id, 0) + 1
|
||||
repeat_assets = [aid for aid, cnt in counts_by_asset.items() if cnt >= 3]
|
||||
assert len(repeat_assets) >= 3
|
||||
|
||||
# At least 2 assets with repair+spare+contract cost > 40% of purchase value
|
||||
high_maint = 0
|
||||
for a in assets:
|
||||
if not a.purchase_value:
|
||||
continue
|
||||
comp_cost = sum(
|
||||
(c.repair_cost or 0.0) + (c.spare_cost_estimate or 0.0)
|
||||
for c in db.query(Complaint).filter(Complaint.asset_id == a.id).all()
|
||||
)
|
||||
if comp_cost / a.purchase_value >= 0.4:
|
||||
high_maint += 1
|
||||
assert high_maint >= 2
|
||||
|
||||
|
||||
def test_asset_and_contract_bulk_import_cost_columns(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
cat = db.query(Category).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
|
||||
# Import an asset with new cost/depreciation columns
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Assets"
|
||||
ws.append([
|
||||
"asset_code", "serial_no", "name", "category", "department", "location",
|
||||
"purchase_value", "acquisition_mode", "monthly_rent", "useful_life_years",
|
||||
"salvage_pct", "depreciation_method",
|
||||
])
|
||||
ws.append([
|
||||
"PHRC-AI1-0001", "SN-AI1-01", "Test Cost Monitor", cat.name, "ICU", "ICU Bay A",
|
||||
500000, "purchased", 14000, 8, 10, "written_down",
|
||||
])
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
|
||||
res = client.post(
|
||||
"/api/assets/bulk-import?dry_run=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("assets_cost.xlsx", buf.getvalue(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
assert res.json()["created_count"] == 1
|
||||
|
||||
created = db.query(Asset).filter(Asset.asset_code == "PHRC-AI1-0001").first()
|
||||
assert created is not None
|
||||
assert created.acquisition_mode == "purchased"
|
||||
assert created.monthly_rent == 14000.0
|
||||
assert created.useful_life_years == 8
|
||||
assert created.salvage_pct == 10.0
|
||||
assert created.depreciation_method == "written_down"
|
||||
|
||||
# Import contract with contract_value
|
||||
wb2 = openpyxl.Workbook()
|
||||
ws2 = wb2.active
|
||||
ws2.title = "Contracts"
|
||||
ws2.append(["asset_code", "provider_name", "contract_type", "start_date", "end_date", "contract_value"])
|
||||
ws2.append(["PHRC-AI1-0001", vendor.name, "AMC", "2026-01-01", "2026-12-31", 42500])
|
||||
buf2 = BytesIO()
|
||||
wb2.save(buf2)
|
||||
|
||||
res2 = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("contracts_cost.xlsx", buf2.getvalue(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res2.status_code == 200, res2.text
|
||||
assert res2.json()["created_count"] == 1
|
||||
|
||||
con = db.query(Contract).filter(Contract.asset_id == created.id).first()
|
||||
assert con is not None
|
||||
assert con.contract_value == 42500.0
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
from datetime import date, timedelta
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import Asset, Category, ComplaintEvent, Contract, Department, Location, Vendor, Warranty
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.coverage import get_coverage
|
||||
from app.services.permissions import COST_FIELDS
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_ai2_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("ai2_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_isolated_asset(db, code: str, dept_code: str = "ICU") -> Asset:
|
||||
dept = db.query(Department).filter(Department.code == dept_code).first()
|
||||
loc = db.query(Location).filter(Location.department_id == dept.id).first()
|
||||
cat = db.query(Category).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
asset = Asset(
|
||||
asset_code=code,
|
||||
serial_no=f"SN-{code}",
|
||||
name=f"Coverage Test Asset {code}",
|
||||
category_id=cat.id,
|
||||
department_id=dept.id,
|
||||
location_id=loc.id,
|
||||
supplier_id=vendor.id,
|
||||
purchase_value=500000.0,
|
||||
status="in_service",
|
||||
criticality="critical",
|
||||
)
|
||||
db.add(asset)
|
||||
db.commit()
|
||||
db.refresh(asset)
|
||||
return asset
|
||||
|
||||
|
||||
def test_coverage_priority_and_expiry_boundaries_and_superseded(db):
|
||||
asset = _create_isolated_asset(db, "PHRC-COV-0001")
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).limit(4).all()
|
||||
on_d = date(2026, 6, 15)
|
||||
|
||||
# 1. No coverage -> out_of_contract (severity red)
|
||||
cov0 = get_coverage(db, asset.id, on_d)
|
||||
assert cov0["tag"] == "out_of_contract"
|
||||
assert cov0["severity"] == "red"
|
||||
assert cov0["provider_id"] is None
|
||||
|
||||
# 2. Add superseded CMC covering on_d -> must be ignored!
|
||||
sup_cmc = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type="CMC",
|
||||
provider_id=vendors[0].id,
|
||||
start_date=date(2026, 1, 1),
|
||||
end_date=date(2026, 12, 31),
|
||||
is_superseded=True,
|
||||
)
|
||||
db.add(sup_cmc)
|
||||
db.commit()
|
||||
assert get_coverage(db, asset.id, on_d)["tag"] == "out_of_contract"
|
||||
|
||||
# 3. Add active OTHER contract -> tag = other_contract
|
||||
other_c = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type="OTHER",
|
||||
provider_id=vendors[0].id,
|
||||
start_date=date(2026, 6, 1),
|
||||
end_date=date(2026, 6, 30),
|
||||
is_superseded=False,
|
||||
)
|
||||
db.add(other_c)
|
||||
db.commit()
|
||||
cov_other = get_coverage(db, asset.id, on_d)
|
||||
assert cov_other["tag"] == "other_contract"
|
||||
assert cov_other["contract_id"] == other_c.id
|
||||
assert cov_other["days_left"] == 15
|
||||
assert cov_other["severity"] == "yellow" # within 30d lead, > 7d red
|
||||
|
||||
# Boundary dates: start_date and end_date are inclusive; day before/after are out_of_contract
|
||||
assert get_coverage(db, asset.id, date(2026, 5, 31))["tag"] == "out_of_contract"
|
||||
assert get_coverage(db, asset.id, date(2026, 6, 1))["tag"] == "other_contract"
|
||||
assert get_coverage(db, asset.id, date(2026, 6, 30))["tag"] == "other_contract"
|
||||
assert get_coverage(db, asset.id, date(2026, 6, 30))["days_left"] == 0
|
||||
assert get_coverage(db, asset.id, date(2026, 6, 30))["severity"] == "red"
|
||||
assert get_coverage(db, asset.id, date(2026, 7, 1))["tag"] == "out_of_contract"
|
||||
|
||||
# 4. Add active AMC -> beats OTHER
|
||||
amc_c = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type="AMC",
|
||||
provider_id=vendors[1].id,
|
||||
start_date=date(2026, 1, 1),
|
||||
end_date=date(2026, 12, 31),
|
||||
is_superseded=False,
|
||||
)
|
||||
db.add(amc_c)
|
||||
db.commit()
|
||||
cov_amc = get_coverage(db, asset.id, on_d)
|
||||
assert cov_amc["tag"] == "amc"
|
||||
assert cov_amc["contract_id"] == amc_c.id
|
||||
assert cov_amc["severity"] == "ok"
|
||||
|
||||
# 5. Add active CMC -> beats AMC
|
||||
cmc_c = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type="CMC",
|
||||
provider_id=vendors[2].id,
|
||||
start_date=date(2026, 1, 1),
|
||||
end_date=date(2026, 12, 31),
|
||||
is_superseded=False,
|
||||
)
|
||||
db.add(cmc_c)
|
||||
db.commit()
|
||||
cov_cmc = get_coverage(db, asset.id, on_d)
|
||||
assert cov_cmc["tag"] == "cmc"
|
||||
assert cov_cmc["contract_id"] == cmc_c.id
|
||||
|
||||
# 6. Add active Warranty -> beats CMC
|
||||
warr = Warranty(
|
||||
asset_id=asset.id,
|
||||
duration_months=12,
|
||||
start_date=date(2026, 1, 1),
|
||||
end_date=date(2026, 12, 31),
|
||||
provider_id=vendors[3].id,
|
||||
)
|
||||
db.add(warr)
|
||||
db.commit()
|
||||
cov_warr = get_coverage(db, asset.id, on_d)
|
||||
assert cov_warr["tag"] == "warranty"
|
||||
assert cov_warr["warranty_id"] == warr.id
|
||||
assert cov_warr["provider_name"] == vendors[3].name
|
||||
assert cov_warr["provider_contact"] is not None
|
||||
|
||||
|
||||
def test_complaint_coverage_snapshot_persists_after_contract_expires(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
asset = _create_isolated_asset(db, "PHRC-COV-0002")
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
today = effective_today(db)
|
||||
|
||||
# Create active AMC ending in 10 days
|
||||
amc = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type="AMC",
|
||||
provider_id=vendor.id,
|
||||
start_date=today - timedelta(days=30),
|
||||
end_date=today + timedelta(days=10),
|
||||
contract_value=50000.0,
|
||||
is_superseded=False,
|
||||
)
|
||||
db.add(amc)
|
||||
db.commit()
|
||||
|
||||
# Raise complaint while AMC is active
|
||||
create_res = client.post(
|
||||
"/api/complaints",
|
||||
headers=admin_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"description": "Power supply intermittent",
|
||||
"priority": "critical",
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
comp = create_res.json()
|
||||
cid = comp["id"]
|
||||
assert comp["coverage_tag"] == "amc"
|
||||
assert comp["coverage_at_registration"]["tag"] == "amc"
|
||||
assert comp["coverage_now"]["tag"] == "amc"
|
||||
|
||||
# Verify 'coverage_tagged' event was created
|
||||
events = db.query(ComplaintEvent).filter(ComplaintEvent.complaint_id == cid).all()
|
||||
assert any(ev.event_type == "coverage_tagged" and ev.to_value == "amc" for ev in events)
|
||||
|
||||
# Filter GET /api/complaints?coverage_tag=amc includes this complaint
|
||||
filt_res = client.get(f"/api/complaints?coverage_tag=amc&asset_id={asset.id}", headers=admin_headers)
|
||||
assert filt_res.status_code == 200
|
||||
assert any(item["id"] == cid for item in filt_res.json()["items"])
|
||||
|
||||
# Advance demo clock past contract end_date (+20 days)
|
||||
future = today + timedelta(days=20)
|
||||
try:
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": str(future)},
|
||||
)
|
||||
after_res = client.get(f"/api/complaints/{cid}", headers=admin_headers)
|
||||
assert after_res.status_code == 200
|
||||
after_data = after_res.json()
|
||||
# Snapshot at registration remains 'amc', while coverage_now flips to 'out_of_contract'
|
||||
assert after_data["coverage_at_registration"]["tag"] == "amc"
|
||||
assert after_data["coverage_now"]["tag"] == "out_of_contract"
|
||||
finally:
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": None},
|
||||
)
|
||||
|
||||
# Verify Breakdown/Complaint report and Excel export include Coverage column
|
||||
rep_res = client.get("/api/reports/breakdown-complaints", headers=admin_headers)
|
||||
assert rep_res.status_code == 200
|
||||
col_labels = [c["label"] for c in rep_res.json()["columns"]]
|
||||
assert "Coverage" in col_labels
|
||||
|
||||
exp_res = client.get("/api/reports/breakdown-complaints/export?format=xlsx", headers=admin_headers)
|
||||
assert exp_res.status_code == 200
|
||||
wb = openpyxl.load_workbook(BytesIO(exp_res.content))
|
||||
ws = wb.active
|
||||
all_cells = [cell.value for row in ws.iter_rows(min_row=1, max_row=15) for cell in row]
|
||||
assert "Coverage" in all_cells
|
||||
|
||||
|
||||
def test_pm_outsourced_auto_fill_and_no_active_contract_warning(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
today = effective_today(db)
|
||||
|
||||
# Case 1: Asset with active CMC -> auto-fills contract_id and provider_id
|
||||
asset_with_cmc = _create_isolated_asset(db, "PHRC-COV-PM1")
|
||||
cmc = Contract(
|
||||
asset_id=asset_with_cmc.id,
|
||||
contract_type="CMC",
|
||||
provider_id=vendor.id,
|
||||
start_date=today - timedelta(days=10),
|
||||
end_date=today + timedelta(days=300),
|
||||
is_superseded=False,
|
||||
)
|
||||
db.add(cmc)
|
||||
db.commit()
|
||||
|
||||
res_auto = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset_with_cmc.id,
|
||||
"service_mode": "outsourced",
|
||||
"frequency_months": 6,
|
||||
"next_planned_date": str(today + timedelta(days=30)),
|
||||
},
|
||||
)
|
||||
assert res_auto.status_code == 201, res_auto.text
|
||||
auto_data = res_auto.json()
|
||||
assert auto_data["contract_id"] == cmc.id
|
||||
assert auto_data["provider_id"] == vendor.id
|
||||
assert auto_data["coverage_tag"] == "cmc"
|
||||
assert not auto_data.get("no_active_contract")
|
||||
|
||||
# Case 2: Asset with NO active AMC/CMC -> leaves empty & returns no_active_contract=True
|
||||
asset_no_con = _create_isolated_asset(db, "PHRC-COV-PM2")
|
||||
res_warn = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset_no_con.id,
|
||||
"service_mode": "outsourced",
|
||||
"frequency_months": 6,
|
||||
"next_planned_date": str(today + timedelta(days=30)),
|
||||
},
|
||||
)
|
||||
assert res_warn.status_code == 201, res_warn.text
|
||||
warn_data = res_warn.json()
|
||||
assert warn_data["contract_id"] is None
|
||||
assert warn_data["provider_id"] is None
|
||||
assert warn_data["no_active_contract"] is True
|
||||
assert warn_data["coverage_tag"] == "out_of_contract"
|
||||
|
||||
|
||||
def test_department_user_reads_coverage_tag_without_cost_fields(client, db):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
icu_asset = db.query(Asset).filter(Asset.department_id == 1).first()
|
||||
assert icu_asset is not None
|
||||
|
||||
# GET /api/assets/{id}/coverage succeeds for department_user's own department
|
||||
cov_res = client.get(f"/api/assets/{icu_asset.id}/coverage", headers=dept_headers)
|
||||
assert cov_res.status_code == 200
|
||||
cov_data = cov_res.json()
|
||||
assert cov_data["tag"] in ("warranty", "cmc", "amc", "other_contract", "out_of_contract")
|
||||
assert not (COST_FIELDS & set(cov_data.keys()))
|
||||
|
||||
# GET /api/assets/{id}/overview includes coverage tag but zero cost fields
|
||||
ov_res = client.get(f"/api/assets/{icu_asset.id}/overview", headers=dept_headers)
|
||||
assert ov_res.status_code == 200
|
||||
ov_data = ov_res.json()
|
||||
assert ov_data["coverage"]["tag"] == cov_data["tag"]
|
||||
assert "purchase_value" not in ov_data["asset"]
|
||||
assert "monthly_rent" not in ov_data["asset"]
|
||||
|
||||
# Another department's asset coverage is 403 for department_user
|
||||
other_asset = db.query(Asset).filter(Asset.department_id != 1).first()
|
||||
assert other_asset is not None
|
||||
forbid = client.get(f"/api/assets/{other_asset.id}/coverage", headers=dept_headers)
|
||||
assert forbid.status_code == 403
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import Asset, User
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.ai_metrics import (
|
||||
EFFICIENCY_WEIGHTS,
|
||||
_book_value_at_years,
|
||||
_compute_response_score,
|
||||
breakdown_frequency,
|
||||
compute_comparison_from_dataset,
|
||||
compute_depreciation_from_dataset,
|
||||
cost_analysis,
|
||||
depreciation,
|
||||
efficiency,
|
||||
format_inr,
|
||||
load_ai_dataset,
|
||||
scenario_comparison,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_ai3_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("ai3_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def test_depreciation_worked_examples_and_edge_cases():
|
||||
# Exact formula worked examples at years_elapsed = 3.0 and 10.0
|
||||
bv_sl_3, acc_sl_3, chg_sl_3 = _book_value_at_years(1_000_000.0, 10, 5.0, "straight_line", 3.0)
|
||||
assert bv_sl_3 == pytest.approx(715_000.0, abs=1.0)
|
||||
assert acc_sl_3 == pytest.approx(285_000.0, abs=1.0)
|
||||
assert chg_sl_3 == pytest.approx(95_000.0, abs=1.0)
|
||||
|
||||
# Written-down value: rate = 1 - (0.05)^(1/10) ≈ 0.25886555 -> book_value(3y) = 1_000_000 * 0.05^0.3 ≈ 407,090.53
|
||||
bv_wd_3, acc_wd_3, _ = _book_value_at_years(1_000_000.0, 10, 5.0, "written_down", 3.0)
|
||||
expected_wd_3 = 1_000_000.0 * (0.05 ** 0.3)
|
||||
assert bv_wd_3 == pytest.approx(expected_wd_3, abs=1.0)
|
||||
assert acc_wd_3 == pytest.approx(1_000_000.0 - expected_wd_3, abs=1.0)
|
||||
|
||||
# After 10 years, both straight_line and written_down equal salvage value (50,000)
|
||||
bv_sl_10, _, chg_sl_10 = _book_value_at_years(1_000_000.0, 10, 5.0, "straight_line", 10.0)
|
||||
bv_wd_10, _, chg_wd_10 = _book_value_at_years(1_000_000.0, 10, 5.0, "written_down", 10.0)
|
||||
assert bv_sl_10 == pytest.approx(50_000.0, abs=1.0)
|
||||
assert bv_wd_10 == pytest.approx(50_000.0, abs=1.0)
|
||||
assert chg_sl_10 == 0.0
|
||||
assert chg_wd_10 == 0.0
|
||||
|
||||
# Asset dict using purchase_date fallback when installation_date is missing
|
||||
asset_sl = {
|
||||
"asset_code": "T-SL-1",
|
||||
"purchase_value": 1_000_000.0,
|
||||
"useful_life_years": 10,
|
||||
"salvage_pct": 5.0,
|
||||
"depreciation_method": "straight_line",
|
||||
"installation_date": None,
|
||||
"purchase_date": date(2020, 1, 1),
|
||||
}
|
||||
res_10y = depreciation(asset_sl, date(2030, 1, 5))
|
||||
assert res_10y["applicable"] is True
|
||||
assert res_10y["fully_depreciated"] is True
|
||||
assert res_10y["book_value"] == pytest.approx(50_000.0, abs=1.0)
|
||||
|
||||
# Rented asset returns applicable=False, book_value=None, reason='rented'
|
||||
rented = {
|
||||
"asset_code": "T-RENT-1",
|
||||
"acquisition_mode": "rented",
|
||||
"monthly_rent": 20_000.0,
|
||||
}
|
||||
res_rent = depreciation(rented, date(2026, 1, 1))
|
||||
assert res_rent["applicable"] is False
|
||||
assert res_rent["reason"] == "rented"
|
||||
assert res_rent["book_value"] is None
|
||||
|
||||
# Missing dates -> Insufficient data
|
||||
no_dates = {
|
||||
"asset_code": "T-NODATE",
|
||||
"purchase_value": 500_000.0,
|
||||
"installation_date": None,
|
||||
"purchase_date": None,
|
||||
}
|
||||
res_nodate = depreciation(no_dates, date(2026, 1, 1))
|
||||
assert res_nodate["applicable"] is False
|
||||
assert "Insufficient data" in res_nodate["reason"]
|
||||
|
||||
# Future installation date -> years_elapsed never negative
|
||||
future_asset = {
|
||||
"asset_code": "T-FUT",
|
||||
"purchase_value": 1_000_000.0,
|
||||
"installation_date": date(2028, 1, 1),
|
||||
}
|
||||
res_fut = depreciation(future_asset, date(2026, 1, 1))
|
||||
assert res_fut["years_elapsed"] == 0.0
|
||||
assert res_fut["book_value"] == 1_000_000.0
|
||||
|
||||
|
||||
def test_scenario_comparison_worked_example_and_cmc_spare_exclusion():
|
||||
as_of = date(2026, 6, 1)
|
||||
asset = {
|
||||
"id": 1,
|
||||
"asset_code": "PHRC-WORK-1",
|
||||
"name": "Worked Example Monitor",
|
||||
"purchase_value": 1_000_000.0,
|
||||
"acquisition_mode": "purchased",
|
||||
"monthly_rent": 15_000.0,
|
||||
"useful_life_years": 10,
|
||||
"salvage_pct": 5.0,
|
||||
"depreciation_method": "straight_line",
|
||||
"installation_date": date(2025, 6, 1),
|
||||
}
|
||||
contracts = [
|
||||
{
|
||||
"id": 10,
|
||||
"contract_type": "AMC",
|
||||
"start_date": date(2025, 6, 1),
|
||||
"end_date": date(2026, 5, 31),
|
||||
"contract_value": 80_000.0,
|
||||
"is_superseded": False,
|
||||
}
|
||||
]
|
||||
complaints = [
|
||||
{
|
||||
"id": 100,
|
||||
"asset_id": 1,
|
||||
"registered_at": datetime(2026, 1, 15, 10, 0, tzinfo=timezone.utc),
|
||||
"repair_cost": 12_000.0,
|
||||
"spare_cost_estimate": 8_000.0,
|
||||
}
|
||||
]
|
||||
pm_schedules = [
|
||||
{
|
||||
"id": 50,
|
||||
"service_mode": "in_house",
|
||||
"frequency_months": 3, # 4 visits/yr * 10,000 = 40,000/yr
|
||||
"cost_per_visit": 10_000.0,
|
||||
"is_active": True,
|
||||
}
|
||||
]
|
||||
|
||||
res = scenario_comparison(asset, contracts, complaints, pm_schedules, horizon_years=5, as_of=as_of)
|
||||
assert res["inputs_used"]["book_value_at_horizon"] == pytest.approx(525_000.0, abs=1.0)
|
||||
assert res["scenarios"]["in_house"]["total_cost"] == pytest.approx(775_000.0, abs=1.0)
|
||||
assert res["scenarios"]["outsourced"]["total_cost"] == pytest.approx(975_000.0, abs=1.0)
|
||||
assert res["scenarios"]["rent"]["total_cost"] == pytest.approx(900_000.0, abs=1.0)
|
||||
assert res["lowest_scenario"] == "in_house"
|
||||
assert res["next_scenario"] == "rent"
|
||||
assert res["savings_vs_next"] == pytest.approx(125_000.0, abs=1.0)
|
||||
|
||||
# Switch contract to CMC -> spare_cost_estimate (8,000/yr * 5 = 40,000) excluded from B
|
||||
contracts[0]["contract_type"] = "CMC"
|
||||
res_cmc = scenario_comparison(asset, contracts, complaints, pm_schedules, horizon_years=5, as_of=as_of)
|
||||
assert res_cmc["scenarios"]["outsourced"]["total_cost"] == pytest.approx(935_000.0, abs=1.0)
|
||||
assert res_cmc["scenarios"]["outsourced"]["breakdown"]["cmc_spares_excluded"] is True
|
||||
|
||||
# Missing inputs return 'Insufficient data: ...' instead of zero
|
||||
missing_asset = {"id": 2, "asset_code": "T-MISS", "name": "Missing", "purchase_value": 500_000.0, "monthly_rent": None}
|
||||
res_miss = scenario_comparison(missing_asset, [], [], [], horizon_years=5, as_of=as_of)
|
||||
assert res_miss["scenarios"]["in_house"]["available"] is False
|
||||
assert "Insufficient data" in res_miss["scenarios"]["in_house"]["insufficient_reason"]
|
||||
assert res_miss["scenarios"]["outsourced"]["available"] is False
|
||||
assert "Insufficient data" in res_miss["scenarios"]["outsourced"]["insufficient_reason"]
|
||||
assert res_miss["scenarios"]["rent"]["available"] is False
|
||||
assert "Insufficient data" in res_miss["scenarios"]["rent"]["insufficient_reason"]
|
||||
|
||||
|
||||
def test_cost_analysis_proration_and_review_flag():
|
||||
as_of = date(2026, 6, 30)
|
||||
asset = {
|
||||
"id": 1,
|
||||
"purchase_value": 200_000.0,
|
||||
"acquisition_mode": "purchased",
|
||||
"installation_date": date(2024, 6, 30),
|
||||
}
|
||||
contracts = [
|
||||
{
|
||||
"id": 1,
|
||||
"start_date": date(2026, 1, 1),
|
||||
"end_date": date(2026, 12, 31),
|
||||
"contract_value": 36_500.0,
|
||||
}
|
||||
]
|
||||
complaints = [
|
||||
{"registered_at": datetime(2026, 3, 1, tzinfo=timezone.utc), "repair_cost": 50_000.0, "spare_cost_estimate": 20_000.0},
|
||||
]
|
||||
pm_schedules = [{"id": 10, "service_mode": "in_house", "cost_per_visit": 5_000.0}]
|
||||
pm_records = [
|
||||
{"schedule_id": 10, "status": "completed", "completed_date": date(2026, 2, 1)},
|
||||
{"schedule_id": 10, "status": "completed", "completed_date": date(2026, 5, 1)},
|
||||
{"schedule_id": 10, "status": None, "planned_date": date(2026, 8, 1)},
|
||||
]
|
||||
res = cost_analysis(asset, contracts, complaints, pm_schedules, pm_records, as_of)
|
||||
# Contract prorated 181 / 365 days ≈ 18,100
|
||||
assert res["contract_cost_to_date"] == pytest.approx(36_500.0 * (181 / 365.0), abs=1.0)
|
||||
assert res["repair_and_spare_cost_to_date"] == 70_000.0
|
||||
assert res["inhouse_pm_cost_to_date"] == 10_000.0
|
||||
assert res["maintenance_cost"] > 98_000.0
|
||||
assert res["maintenance_ratio"] > 0.49
|
||||
assert res["review_flag"] is True
|
||||
|
||||
|
||||
def test_breakdown_frequency_and_efficiency_pure_math_and_zero_division():
|
||||
# Empty assets -> no zero division
|
||||
bf_empty = breakdown_frequency([], [], date(2026, 1, 1), date(2026, 3, 31), date(2026, 3, 31))
|
||||
assert bf_empty["summary"]["avg_breakdowns_per_equipment"] == 0.0
|
||||
eff_empty = efficiency([], [], [], date(2026, 1, 1), date(2026, 3, 31), date(2026, 3, 31))
|
||||
assert eff_empty["summary"]["avg_efficiency_score"] == 0.0
|
||||
|
||||
# Two assets in ICU: asset 1 has 3 breakdowns, asset 2 has 0 -> avg = 1.5 (zero-breakdown asset counts!)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-1", "name": "Vent 1", "department_name": "ICU", "category_name": "Life Support", "status": "in_service"},
|
||||
{"id": 2, "asset_code": "A-2", "name": "Vent 2", "department_name": "ICU", "category_name": "Life Support", "status": "in_service"},
|
||||
]
|
||||
t0 = datetime(2026, 3, 1, 10, 0, tzinfo=timezone.utc)
|
||||
complaints = [
|
||||
{
|
||||
"id": 1,
|
||||
"asset_id": 1,
|
||||
"priority": "critical",
|
||||
"registered_at": t0,
|
||||
"attended_at": t0 + timedelta(hours=2), # <= 4h SLA -> response_score = 100
|
||||
"restored_at": t0 + timedelta(hours=10),
|
||||
"closed_at": t0 + timedelta(hours=11),
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"asset_id": 1,
|
||||
"priority": "critical",
|
||||
"registered_at": t0 + timedelta(days=5),
|
||||
"attended_at": t0 + timedelta(days=5, hours=4), # == 4h SLA -> 100
|
||||
"restored_at": t0 + timedelta(days=5, hours=10),
|
||||
"closed_at": t0 + timedelta(days=5, hours=11),
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"asset_id": 1,
|
||||
"priority": "critical",
|
||||
"registered_at": t0 + timedelta(days=10),
|
||||
"attended_at": t0 + timedelta(days=10, hours=16), # == 4x SLA -> 0
|
||||
"restored_at": t0 + timedelta(days=10, hours=20),
|
||||
"closed_at": t0 + timedelta(days=10, hours=21),
|
||||
},
|
||||
]
|
||||
pm_records = [
|
||||
{"asset_id": 1, "planned_date": date(2026, 3, 15), "completed_date": date(2026, 3, 15), "status": "completed"},
|
||||
{"asset_id": 1, "planned_date": date(2026, 3, 25), "completed_date": None, "status": None}, # 1/2 = 50%
|
||||
]
|
||||
|
||||
bf = breakdown_frequency(assets, complaints, date(2026, 3, 1), date(2026, 3, 31), date(2026, 3, 31))
|
||||
assert bf["summary"]["total_breakdowns"] == 3
|
||||
assert bf["summary"]["avg_breakdowns_per_equipment"] == 1.5
|
||||
assert bf["summary"]["repeat_failure_count"] == 1
|
||||
assert bf["by_department"][0]["avg_breakdowns_per_equipment"] == 1.5
|
||||
|
||||
eff = efficiency(assets, complaints, pm_records, date(2026, 3, 1), date(2026, 3, 31), date(2026, 3, 31))
|
||||
assert sum(EFFICIENCY_WEIGHTS.values()) == pytest.approx(1.0)
|
||||
a2 = next(r for r in eff["per_asset"] if r["asset_code"] == "A-2")
|
||||
assert a2["mtbf_hours"] is None
|
||||
assert a2["mtbf_formatted"] == "No failures"
|
||||
assert a2["efficiency_score"] == 100.0
|
||||
|
||||
a1 = next(r for r in eff["per_asset"] if r["asset_code"] == "A-1")
|
||||
assert a1["pm_compliance_pct"] == 50.0
|
||||
assert a1["repeat_free_score"] == 0.0
|
||||
assert a1["response_score"] == pytest.approx((100.0 + 100.0 + 0.0) / 3.0, abs=0.1)
|
||||
assert _compute_response_score(10.0, 4.0) == pytest.approx(50.0, abs=0.1)
|
||||
assert format_inr(1250000) == "₹12,50,000"
|
||||
|
||||
|
||||
def test_db_loader_department_scoping_and_demo_clock(client, db):
|
||||
admin = db.query(User).filter(User.email == "admin@poona.demo").first()
|
||||
dept_user = db.query(User).filter(User.email == "dept@poona.demo").first()
|
||||
|
||||
today = effective_today(db)
|
||||
ds_all = load_ai_dataset(db, admin, today - timedelta(days=365), today)
|
||||
ds_icu = load_ai_dataset(db, dept_user, today - timedelta(days=365), today)
|
||||
|
||||
assert len(ds_all["assets"]) == 60
|
||||
assert len(ds_icu["assets"]) > 0
|
||||
assert len(ds_icu["assets"]) < len(ds_all["assets"])
|
||||
assert all(a["department_id"] == dept_user.department_id for a in ds_icu["assets"])
|
||||
|
||||
# Unassigned department_user -> 0 assets
|
||||
unassigned = User(
|
||||
name="Unassigned Dept",
|
||||
email="unassigned.ai3@poona.demo",
|
||||
password_hash="x",
|
||||
role="department_user",
|
||||
department_id=None,
|
||||
is_active=True,
|
||||
)
|
||||
ds_empty = load_ai_dataset(db, unassigned, today - timedelta(days=365), today)
|
||||
assert ds_empty["assets"] == []
|
||||
|
||||
# Demo clock moves depreciation book values downward as time advances
|
||||
dep_now = compute_depreciation_from_dataset(ds_all)
|
||||
cmp_now = compute_comparison_from_dataset(ds_all)
|
||||
assert len(cmp_now["rows"]) == 10
|
||||
|
||||
admin_res = client.post("/api/auth/login", json={"email": "admin@poona.demo", "password": "Demo@123"})
|
||||
headers = {"Authorization": f"Bearer {admin_res.json()['access_token']}"}
|
||||
try:
|
||||
future_date = today + timedelta(days=365 * 2)
|
||||
client.post("/api/settings/demo-date", headers=headers, json={"demo_as_of_date": str(future_date)})
|
||||
ds_future = load_ai_dataset(db, admin, future_date - timedelta(days=365), future_date)
|
||||
dep_future = compute_depreciation_from_dataset(ds_future)
|
||||
assert dep_future["summary"]["total_book_value"] < dep_now["summary"]["total_book_value"]
|
||||
finally:
|
||||
client.post("/api/settings/demo-date", headers=headers, json={"demo_as_of_date": None})
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import re
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import User
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.ai_metrics import DEFAULT_AI_SETTINGS, load_ai_dataset
|
||||
from app.services.ai_suggestions import SEVERITY_RANK, generate_suggestions
|
||||
|
||||
BANNED_WORDS_RE = re.compile(
|
||||
r"\b(approve|approved|guarantee|safe to use|safe|unsafe|purchase immediately|must buy)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _base_dataset(today: date, assets: list[dict], **overrides) -> dict:
|
||||
ds = {
|
||||
"today": today,
|
||||
"now_utc": datetime(today.year, today.month, today.day, 12, 0, tzinfo=timezone.utc),
|
||||
"period_start": today - timedelta(days=90),
|
||||
"period_end": today,
|
||||
"settings": dict(DEFAULT_AI_SETTINGS),
|
||||
"assets": assets,
|
||||
"contracts_by_asset": {},
|
||||
"complaints": [],
|
||||
"complaints_by_asset": {},
|
||||
"pm_schedules_by_asset": {},
|
||||
"pm_records": [],
|
||||
"pm_records_by_asset": {},
|
||||
"coverage_by_asset": {},
|
||||
"cal_plans_by_asset": {},
|
||||
"cal_records_by_asset": {},
|
||||
}
|
||||
ds.update(overrides)
|
||||
return ds
|
||||
|
||||
|
||||
def _assert_suggestion_invariants(res: dict):
|
||||
ev_ids = {m["id"] for m in res["evidence"]}
|
||||
suggestions = res["suggestions"]
|
||||
# Every referenced evidence_metric_id must exist
|
||||
for s in suggestions:
|
||||
assert s["action_for_human"].endswith("Needs a human decision.")
|
||||
assert len(s["evidence_metric_ids"]) > 0
|
||||
for mid in s["evidence_metric_ids"]:
|
||||
assert mid in ev_ids, f"Missing evidence metric id {mid} for suggestion {s['id']}"
|
||||
for field in (s["title"], s["detail"], s["action_for_human"]):
|
||||
assert not BANNED_WORDS_RE.search(field), f"Banned word found in {field!r}"
|
||||
|
||||
# Verify strict ordering: red -> yellow -> info, then asset_code, then rule
|
||||
keys = [
|
||||
(SEVERITY_RANK[s["severity"]], s["asset_codes"][0] if s["asset_codes"] else "", s["rule"])
|
||||
for s in suggestions
|
||||
]
|
||||
assert keys == sorted(keys)
|
||||
|
||||
|
||||
def test_rule_s1_repeat_failure_yellow_and_red():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-YEL", "name": "Vent Yellow", "department_name": "ICU", "category_name": "Life Support", "status": "in_service"},
|
||||
{"id": 2, "asset_code": "A-RED", "name": "Vent Red", "department_name": "ICU", "category_name": "Life Support", "status": "in_service"},
|
||||
]
|
||||
cmps_1 = [
|
||||
{"id": i, "asset_id": 1, "priority": "non_critical", "registered_at": datetime(2026, 5, i + 1, 10, 0, tzinfo=timezone.utc)}
|
||||
for i in range(3)
|
||||
]
|
||||
cmps_2 = [
|
||||
{"id": 10 + i, "asset_id": 2, "priority": "critical", "registered_at": datetime(2026, 5, i + 1, 10, 0, tzinfo=timezone.utc)}
|
||||
for i in range(4)
|
||||
]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps_1 + cmps_2,
|
||||
complaints_by_asset={1: cmps_1, 2: cmps_2},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 100}, 2: {"tag": "cmc", "days_left": 100}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s1_map = {s["asset_codes"][0]: s for s in res["suggestions"] if s["rule"] == "S1"}
|
||||
assert s1_map["A-YEL"]["severity"] == "yellow"
|
||||
assert s1_map["A-RED"]["severity"] == "red"
|
||||
assert "Review root cause and escalate to the vendor" in s1_map["A-RED"]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s2_out_of_contract_with_two_breakdowns():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-OOC", "name": "Monitor", "department_name": "ICU", "category_name": "Monitors", "status": "in_service"},
|
||||
]
|
||||
cmps = [
|
||||
{"id": 1, "asset_id": 1, "priority": "non_critical", "registered_at": datetime(2026, 5, 5, 10, 0, tzinfo=timezone.utc)},
|
||||
{"id": 2, "asset_id": 1, "priority": "non_critical", "registered_at": datetime(2026, 5, 20, 10, 0, tzinfo=timezone.utc)},
|
||||
]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps,
|
||||
complaints_by_asset={1: cmps},
|
||||
coverage_by_asset={1: {"tag": "out_of_contract", "days_left": None}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s2 = [s for s in res["suggestions"] if s["rule"] == "S2"]
|
||||
assert len(s2) == 1
|
||||
assert s2[0]["severity"] == "yellow"
|
||||
assert "Consider an AMC/CMC" in s2[0]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s3_expiring_contract_with_breakdown():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-EXP", "name": "Pump", "department_name": "ICU", "category_name": "Infusion", "status": "in_service"},
|
||||
]
|
||||
cmps = [
|
||||
{"id": 1, "asset_id": 1, "priority": "non_critical", "registered_at": datetime(2026, 6, 1, 10, 0, tzinfo=timezone.utc)},
|
||||
]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps,
|
||||
complaints_by_asset={1: cmps},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 12}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s3 = [s for s in res["suggestions"] if s["rule"] == "S3"]
|
||||
assert len(s3) == 1
|
||||
assert s3[0]["severity"] == "yellow"
|
||||
assert "Renewal review before expiry" in s3[0]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s4_high_maintenance_ratio_yellow_and_red():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-M50", "name": "Pump 50%", "department_name": "ICU", "category_name": "Infusion", "status": "in_service", "purchase_value": 100_000.0, "installation_date": date(2023, 1, 1)},
|
||||
{"id": 2, "asset_code": "A-M120", "name": "Pump 120%", "department_name": "ICU", "category_name": "Infusion", "status": "in_service", "purchase_value": 100_000.0, "installation_date": date(2023, 1, 1)},
|
||||
]
|
||||
cmps_1 = [{"id": 1, "asset_id": 1, "registered_at": datetime(2026, 4, 1, tzinfo=timezone.utc), "repair_cost": 55_000.0, "spare_cost_estimate": 0.0}]
|
||||
cmps_2 = [{"id": 2, "asset_id": 2, "registered_at": datetime(2026, 4, 1, tzinfo=timezone.utc), "repair_cost": 120_000.0, "spare_cost_estimate": 0.0}]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps_1 + cmps_2,
|
||||
complaints_by_asset={1: cmps_1, 2: cmps_2},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 100}, 2: {"tag": "amc", "days_left": 100}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s4_map = {s["asset_codes"][0]: s for s in res["suggestions"] if s["rule"] == "S4"}
|
||||
assert s4_map["A-M50"]["severity"] == "yellow"
|
||||
assert s4_map["A-M120"]["severity"] == "red"
|
||||
assert "Replacement review" in s4_map["A-M120"]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s5_cheaper_scenario_by_10_percent_info():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{
|
||||
"id": 1,
|
||||
"asset_code": "A-S5",
|
||||
"name": "Monitor S5",
|
||||
"department_name": "ICU",
|
||||
"category_name": "Monitors",
|
||||
"status": "in_service",
|
||||
"acquisition_mode": "purchased",
|
||||
"purchase_value": 1_000_000.0,
|
||||
"monthly_rent": 5_000.0, # 5y rent = 300,000 vs in-house >= 475,000 -> >10% cheaper!
|
||||
"useful_life_years": 10,
|
||||
"salvage_pct": 5.0,
|
||||
"depreciation_method": "straight_line",
|
||||
"installation_date": date(2025, 6, 1),
|
||||
}
|
||||
]
|
||||
pm_scheds = {1: [{"id": 1, "asset_id": 1, "service_mode": "in_house", "frequency_months": 6, "cost_per_visit": 10_000.0, "is_active": True}]}
|
||||
ds = _base_dataset(today, assets, pm_schedules_by_asset=pm_scheds, coverage_by_asset={1: {"tag": "warranty", "days_left": 100}})
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s5 = [s for s in res["suggestions"] if s["rule"] == "S5"]
|
||||
assert len(s5) == 1
|
||||
assert s5[0]["severity"] == "info"
|
||||
assert "Evaluate Rent" in s5[0]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s6_pm_overdue_with_breakdown():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [{"id": 1, "asset_code": "A-PMO", "name": "Autoclave", "department_name": "OT", "category_name": "CSSD", "status": "in_service"}]
|
||||
cmps = [{"id": 1, "asset_id": 1, "registered_at": datetime(2026, 6, 1, tzinfo=timezone.utc)}]
|
||||
pm_recs = [{"id": 1, "asset_id": 1, "schedule_id": 1, "planned_date": date(2026, 6, 1), "completed_date": None, "status": None}]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps,
|
||||
complaints_by_asset={1: cmps},
|
||||
pm_records=pm_recs,
|
||||
pm_records_by_asset={1: pm_recs},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 100}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s6 = [s for s in res["suggestions"] if s["rule"] == "S6"]
|
||||
assert len(s6) == 1
|
||||
assert s6[0]["severity"] == "yellow"
|
||||
assert "Clear overdue PM" in s6[0]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s7_calibration_overdue_yellow_and_red():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-CAL-Y", "name": "Cal 10d", "department_name": "LAB", "category_name": "Lab", "status": "in_service"},
|
||||
{"id": 2, "asset_code": "A-CAL-R", "name": "Cal 45d", "department_name": "LAB", "category_name": "Lab", "status": "in_service"},
|
||||
]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
cal_records_by_asset={
|
||||
1: [{"id": 1, "asset_id": 1, "due_date": today - timedelta(days=10), "status": None}],
|
||||
2: [{"id": 2, "asset_id": 2, "due_date": today - timedelta(days=45), "status": None}],
|
||||
},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 100}, 2: {"tag": "amc", "days_left": 100}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s7_map = {s["asset_codes"][0]: s for s in res["suggestions"] if s["rule"] == "S7"}
|
||||
assert s7_map["A-CAL-Y"]["severity"] == "yellow"
|
||||
assert s7_map["A-CAL-R"]["severity"] == "red"
|
||||
assert "Complete calibration" in s7_map["A-CAL-R"]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s8_fully_depreciated_and_low_efficiency():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{
|
||||
"id": 1,
|
||||
"asset_code": "A-OLD",
|
||||
"name": "Old Analyzer",
|
||||
"department_name": "LAB",
|
||||
"category_name": "Lab",
|
||||
"status": "in_service",
|
||||
"purchase_value": 500_000.0,
|
||||
"useful_life_years": 10,
|
||||
"salvage_pct": 5.0,
|
||||
"installation_date": date(2014, 1, 1),
|
||||
}
|
||||
]
|
||||
# 30 days of downtime in 90-day period + 1 overdue PM + slow response -> efficiency well below 80
|
||||
reg = datetime(2026, 5, 1, 10, 0, tzinfo=timezone.utc)
|
||||
cmps = [
|
||||
{
|
||||
"id": 1,
|
||||
"asset_id": 1,
|
||||
"priority": "critical",
|
||||
"registered_at": reg,
|
||||
"attended_at": reg + timedelta(hours=20),
|
||||
"restored_at": reg + timedelta(days=30),
|
||||
"closed_at": reg + timedelta(days=30),
|
||||
}
|
||||
]
|
||||
pm_recs = [{"id": 1, "asset_id": 1, "schedule_id": 1, "planned_date": date(2026, 5, 10), "completed_date": None, "status": None}]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps,
|
||||
complaints_by_asset={1: cmps},
|
||||
pm_records=pm_recs,
|
||||
pm_records_by_asset={1: pm_recs},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 100}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s8 = [s for s in res["suggestions"] if s["rule"] == "S8"]
|
||||
assert len(s8) == 1
|
||||
assert s8[0]["severity"] == "yellow"
|
||||
assert "Replacement planning" in s8[0]["action_for_human"]
|
||||
|
||||
|
||||
def test_seeded_db_produces_expected_suggestions(db, tmp_path):
|
||||
seed_database(db, upload_dir=tmp_path)
|
||||
admin = db.query(User).filter(User.email == "admin@poona.demo").first()
|
||||
today = effective_today(db)
|
||||
ds = load_ai_dataset(db, admin, today - timedelta(days=365), today)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
|
||||
s1_list = [s for s in res["suggestions"] if s["rule"] == "S1"]
|
||||
s4_list = [s for s in res["suggestions"] if s["rule"] == "S4"]
|
||||
assert len(s1_list) >= 3
|
||||
assert len(s4_list) >= 2
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
import json
|
||||
import httpx
|
||||
|
||||
from app.models import AISummary, AuditLog
|
||||
from app.services.ai_metrics import make_metric
|
||||
from app.services.ai_narrative import (
|
||||
build_prompt,
|
||||
get_or_generate_narrative,
|
||||
rule_based_narrative,
|
||||
validate_narrative,
|
||||
)
|
||||
from app.services.ai_provider import AIProvider, NoneProvider, ProviderUnavailable
|
||||
|
||||
|
||||
class FakeProvider(AIProvider):
|
||||
provider_name = "ollama"
|
||||
model_name = "fake-llama3"
|
||||
|
||||
def __init__(self, responses):
|
||||
# responses: list of dicts or Exceptions or callables
|
||||
self._responses = list(responses)
|
||||
self.calls: list[tuple[str, dict]] = []
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict) -> dict:
|
||||
self.calls.append((system_prompt, user_json))
|
||||
idx = min(len(self.calls) - 1, len(self._responses) - 1)
|
||||
item = self._responses[idx]
|
||||
if isinstance(item, Exception):
|
||||
raise item
|
||||
if callable(item):
|
||||
return item(system_prompt, user_json)
|
||||
return item
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _sample_metrics():
|
||||
return [
|
||||
make_metric("m_cmp_horizon_years", "Comparison Horizon", 5, "years", "5 years"),
|
||||
make_metric("m_cmp_latest_count", "Latest Equipment Evaluated", 10, "count"),
|
||||
make_metric("m_cmp_lowest_PHRC_ICU_0001", "Lowest 5-yr Cost (PHRC-ICU-0001)", 775000.0, "INR"),
|
||||
make_metric("m_cmp_diff_PHRC_ICU_0001", "Savings vs Next Option (PHRC-ICU-0001)", 125000.0, "INR"),
|
||||
make_metric("m_cmp_inhouse_wins", "Equipment Where In-House Is Lowest", 6, "count"),
|
||||
make_metric("m_cmp_outsourced_wins", "Equipment Where Outsourced Is Lowest", 3, "count"),
|
||||
make_metric("m_cmp_rent_wins", "Equipment Where Rent Is Lowest", 1, "count"),
|
||||
]
|
||||
|
||||
|
||||
def test_ai5_valid_provider_response_is_accepted(db):
|
||||
metrics = _sample_metrics()
|
||||
provider = FakeProvider(
|
||||
[
|
||||
{
|
||||
"headline": "Across 10 latest equipment items over 5 years, in-house maintenance is lowest for 6 assets.",
|
||||
"bullets": [
|
||||
{
|
||||
"text": "Lowest estimated 5-year cost for PHRC-ICU-0001 is ₹7,75,000, saving ₹1,25,000 against the next option.",
|
||||
"metric_ids": [
|
||||
"m_cmp_horizon_years",
|
||||
"m_cmp_lowest_PHRC_ICU_0001",
|
||||
"m_cmp_diff_PHRC_ICU_0001",
|
||||
],
|
||||
},
|
||||
{
|
||||
"text": "Across the 10 items, 6 favour in-house, 3 favour outsourced, and 1 favours rent.",
|
||||
"metric_ids": [
|
||||
"m_cmp_latest_count",
|
||||
"m_cmp_inhouse_wins",
|
||||
"m_cmp_outsourced_wins",
|
||||
"m_cmp_rent_wins",
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
res = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m"},
|
||||
metrics,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res["source"] == "ai"
|
||||
assert res["model"] == "fake-llama3"
|
||||
assert res["validated"] is True
|
||||
assert res["failure_reason"] is None
|
||||
assert len(res["bullets"]) == 2
|
||||
assert len(provider.calls) == 1
|
||||
|
||||
|
||||
def test_ai5_invented_number_retries_once_and_falls_back(db):
|
||||
metrics = _sample_metrics()
|
||||
bad_response = {
|
||||
"headline": "Evaluation of 10 assets over 5 years.",
|
||||
"bullets": [
|
||||
{
|
||||
# 999999 is NOT in metrics!
|
||||
"text": "Lowest cost for PHRC-ICU-0001 is ₹9,99,999.",
|
||||
"metric_ids": ["m_cmp_lowest_PHRC_ICU_0001"],
|
||||
}
|
||||
],
|
||||
}
|
||||
provider = FakeProvider([bad_response, bad_response])
|
||||
|
||||
res = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "case": "invented"},
|
||||
metrics,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert len(provider.calls) == 2
|
||||
assert "Unverified number" in provider.calls[1][0]
|
||||
assert res["source"] == "rule_based"
|
||||
assert res["validated"] is False
|
||||
assert res["failure_reason"] and "Unverified number" in res["failure_reason"]
|
||||
assert res["headline"]
|
||||
assert len(res["bullets"]) >= 1
|
||||
|
||||
|
||||
def test_ai5_unknown_metric_id_falls_back(db):
|
||||
metrics = _sample_metrics()
|
||||
bad_response = {
|
||||
"headline": "Summary of 10 items.",
|
||||
"bullets": [
|
||||
{
|
||||
"text": "In-house is lowest for 6 assets.",
|
||||
"metric_ids": ["m_does_not_exist"],
|
||||
}
|
||||
],
|
||||
}
|
||||
provider = FakeProvider([bad_response, bad_response])
|
||||
|
||||
res = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "case": "missing_id"},
|
||||
metrics,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert len(provider.calls) == 2
|
||||
assert res["source"] == "rule_based"
|
||||
assert res["validated"] is False
|
||||
assert res["failure_reason"] and "Unknown metric_id" in res["failure_reason"]
|
||||
|
||||
|
||||
def test_ai5_broken_json_and_timeout_fall_back(db):
|
||||
metrics = _sample_metrics()
|
||||
|
||||
broken_provider = FakeProvider(
|
||||
[
|
||||
json.JSONDecodeError("Expecting value", "{bad", 1),
|
||||
json.JSONDecodeError("Expecting value", "{bad", 1),
|
||||
]
|
||||
)
|
||||
res_broken = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "case": "broken_json"},
|
||||
metrics,
|
||||
provider_override=broken_provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res_broken["source"] == "rule_based"
|
||||
assert res_broken["validated"] is False
|
||||
assert res_broken["failure_reason"]
|
||||
|
||||
timeout_provider = FakeProvider(
|
||||
[ProviderUnavailable("Ollama request timed out after 25s.")]
|
||||
)
|
||||
res_timeout = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "case": "timeout"},
|
||||
metrics,
|
||||
provider_override=timeout_provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert len(timeout_provider.calls) == 1
|
||||
assert res_timeout["source"] == "rule_based"
|
||||
assert res_timeout["validated"] is False
|
||||
assert res_timeout["failure_reason"] and "timed out" in res_timeout["failure_reason"]
|
||||
|
||||
# Also verify raw httpx.TimeoutException never crashes
|
||||
raw_timeout_provider = FakeProvider([httpx.TimeoutException("read timeout")])
|
||||
res_raw_to = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "case": "raw_timeout"},
|
||||
metrics,
|
||||
provider_override=raw_timeout_provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res_raw_to["source"] == "rule_based"
|
||||
assert res_raw_to["failure_reason"]
|
||||
|
||||
|
||||
def test_ai5_banned_words_rejected():
|
||||
metrics = _sample_metrics()
|
||||
for phrase in ("approve", "approved", "guarantee", "safe to use", "unsafe", "purchase immediately", "must buy"):
|
||||
ok, reason = validate_narrative(
|
||||
{
|
||||
"headline": f"We {phrase} this equipment after reviewing 10 items.",
|
||||
"bullets": [{"text": "Total 6 in-house.", "metric_ids": ["m_cmp_inhouse_wins"]}],
|
||||
},
|
||||
metrics,
|
||||
)
|
||||
assert not ok, f"Expected banned phrase '{phrase}' to fail validation"
|
||||
assert reason and "Banned phrase" in reason
|
||||
|
||||
|
||||
def test_ai5_cache_hit_invalidation_and_audit_log(db):
|
||||
metrics_v1 = _sample_metrics()
|
||||
valid_v1 = {
|
||||
"headline": "Evaluated 10 items over 5 years.",
|
||||
"bullets": [{"text": "In-house is lowest for 6 assets.", "metric_ids": ["m_cmp_inhouse_wins"]}],
|
||||
}
|
||||
valid_v2 = {
|
||||
"headline": "Evaluated 10 items over 5 years.",
|
||||
"bullets": [{"text": "In-house is lowest for 7 assets.", "metric_ids": ["m_cmp_inhouse_wins"]}],
|
||||
}
|
||||
provider = FakeProvider([valid_v1, valid_v2, valid_v2])
|
||||
|
||||
before_summaries = db.query(AISummary).filter(AISummary.section == "comparison").count()
|
||||
before_audits = db.query(AuditLog).filter(AuditLog.entity_type == "ai_summary").count()
|
||||
|
||||
# First call: generates and caches
|
||||
res1 = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "dept": None, "case": "cache_test"},
|
||||
metrics_v1,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res1["source"] == "ai"
|
||||
assert len(provider.calls) == 1
|
||||
assert db.query(AISummary).filter(AISummary.section == "comparison").count() == before_summaries + 1
|
||||
assert db.query(AuditLog).filter(AuditLog.entity_type == "ai_summary").count() == before_audits + 1
|
||||
|
||||
# Second call with same filters & metrics: cache hit!
|
||||
res2 = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "dept": None, "case": "cache_test"},
|
||||
metrics_v1,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res2 == res1
|
||||
assert len(provider.calls) == 1
|
||||
|
||||
# Third call with changed metric value: cache invalidated!
|
||||
metrics_v2 = [
|
||||
make_metric("m_cmp_inhouse_wins", "Equipment Where In-House Is Lowest", 7, "count")
|
||||
if m["id"] == "m_cmp_inhouse_wins"
|
||||
else m
|
||||
for m in metrics_v1
|
||||
]
|
||||
res3 = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "dept": None, "case": "cache_test"},
|
||||
metrics_v2,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res3["source"] == "ai"
|
||||
assert len(provider.calls) == 2
|
||||
assert "7 assets" in res3["bullets"][0]["text"]
|
||||
|
||||
# Fourth call with force_regenerate=True: bypasses cache!
|
||||
res4 = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "dept": None, "case": "cache_test"},
|
||||
metrics_v2,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
force_regenerate=True,
|
||||
)
|
||||
assert res4["source"] == "ai"
|
||||
assert len(provider.calls) == 3
|
||||
|
||||
|
||||
def test_ai5_privacy_no_pii_or_free_text_in_prompt(db):
|
||||
secret_user = "Dr. Rajesh Deshmukh"
|
||||
secret_email = "rajesh.deshmukh@poonahospital.org"
|
||||
secret_desc = "Patient monitor alarm speaker cracked during ICU night shift"
|
||||
secret_remark = "Confidential nurse note about ward staff conflict"
|
||||
|
||||
dirty_metrics = [
|
||||
{
|
||||
**make_metric("m_bf_total_breakdowns", f"Breakdowns ({secret_email})", 12, "count"),
|
||||
"user_name": secret_user,
|
||||
"email": secret_email,
|
||||
"description": secret_desc,
|
||||
"remarks": secret_remark,
|
||||
}
|
||||
]
|
||||
dirty_suggestions = [
|
||||
{
|
||||
"id": "S1_PHRC_ICU_0001",
|
||||
"rule": "S1",
|
||||
"severity": "red",
|
||||
"title": f"Repeat failure reported by {secret_user}",
|
||||
"detail": f"Complaint description: {secret_desc}; remarks: {secret_remark}",
|
||||
"asset_codes": ["PHRC-ICU-0001"],
|
||||
"evidence_metric_ids": ["m_bf_total_breakdowns"],
|
||||
"action_for_human": "Review root cause and escalate to the vendor. Needs a human decision.",
|
||||
"reported_by": secret_user,
|
||||
"email": secret_email,
|
||||
}
|
||||
]
|
||||
|
||||
sys_prompt, user_payload = build_prompt("breakdown_frequency", dirty_metrics, dirty_suggestions)
|
||||
serialized = sys_prompt + "\n" + json.dumps(user_payload, ensure_ascii=False)
|
||||
|
||||
assert secret_user not in serialized
|
||||
assert secret_email not in serialized
|
||||
assert secret_desc not in serialized
|
||||
assert secret_remark not in serialized
|
||||
# Allowed structured fields MUST remain present
|
||||
assert "m_bf_total_breakdowns" in serialized
|
||||
assert "PHRC-ICU-0001" in serialized
|
||||
|
||||
|
||||
def test_ai5_none_provider_and_disabled_setting_use_rule_based(db):
|
||||
metrics = _sample_metrics()
|
||||
res = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m"},
|
||||
metrics,
|
||||
provider_override=NoneProvider(),
|
||||
ai_enabled_override=False,
|
||||
)
|
||||
assert res["source"] == "rule_based"
|
||||
assert res["model"] is None
|
||||
assert res["validated"] is True
|
||||
assert res["failure_reason"] is None
|
||||
assert res["headline"]
|
||||
assert len(res["bullets"]) >= 1
|
||||
|
||||
# Also verify direct rule_based_narrative works for every section
|
||||
for sec in ("summary", "comparison", "depreciation", "efficiency", "breakdown_frequency"):
|
||||
out = rule_based_narrative(sec, metrics)
|
||||
assert out["headline"]
|
||||
assert isinstance(out["bullets"], list) and len(out["bullets"]) >= 1
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.models import Category, Department
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_ai6_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("ai6_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']}"}
|
||||
|
||||
|
||||
AI_GET_ENDPOINTS = [
|
||||
"/api/ai/status",
|
||||
"/api/ai/summary",
|
||||
"/api/ai/comparison",
|
||||
"/api/ai/depreciation",
|
||||
"/api/ai/efficiency",
|
||||
"/api/ai/breakdown-frequency",
|
||||
"/api/ai/suggestions",
|
||||
]
|
||||
|
||||
AI_EXPORT_SECTIONS = [
|
||||
"summary",
|
||||
"comparison",
|
||||
"depreciation",
|
||||
"efficiency",
|
||||
"breakdown-frequency",
|
||||
]
|
||||
|
||||
|
||||
def test_ai6_role_matrix_department_user_403_and_viewers_200(client):
|
||||
dept_hdr = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
# department_user must get 403 on EVERY /api/ai/* route
|
||||
for url in AI_GET_ENDPOINTS:
|
||||
r = client.get(url, headers=dept_hdr)
|
||||
assert r.status_code == 403, f"Expected 403 for department_user on {url}, got {r.status_code}"
|
||||
|
||||
for sec in AI_EXPORT_SECTIONS:
|
||||
r = client.get(f"/api/ai/{sec}/export?format=xlsx", headers=dept_hdr)
|
||||
assert r.status_code == 403
|
||||
r_csv = client.get(f"/api/ai/{sec}/export?format=csv", headers=dept_hdr)
|
||||
assert r_csv.status_code == 403
|
||||
|
||||
r_regen_dept = client.post(
|
||||
"/api/ai/narrative/regenerate",
|
||||
json={"section": "summary", "filters": {"period": "12m"}},
|
||||
headers=dept_hdr,
|
||||
)
|
||||
assert r_regen_dept.status_code == 403
|
||||
|
||||
# management, coordinator, biomedical get 200 on all GETs, 403 on regenerate
|
||||
for email in (
|
||||
"mgmt@poona.demo",
|
||||
"coord@poona.demo",
|
||||
"bio@poona.demo",
|
||||
):
|
||||
hdr = _auth_headers(client, email)
|
||||
for url in AI_GET_ENDPOINTS:
|
||||
r = client.get(url, headers=hdr)
|
||||
assert r.status_code == 200, f"Expected 200 for {email} on {url}, got {r.status_code}: {r.text}"
|
||||
r_regen = client.post(
|
||||
"/api/ai/narrative/regenerate",
|
||||
json={"section": "comparison", "filters": {"period": "12m"}},
|
||||
headers=hdr,
|
||||
)
|
||||
assert r_regen.status_code == 403, f"Expected 403 for {email} on regenerate"
|
||||
|
||||
# system_admin gets 200 on all GETs AND 200 on regenerate
|
||||
admin_hdr = _auth_headers(client, "admin@poona.demo")
|
||||
for url in AI_GET_ENDPOINTS:
|
||||
r = client.get(url, headers=admin_hdr)
|
||||
assert r.status_code == 200, f"Expected 200 for admin on {url}: {r.text}"
|
||||
|
||||
r_regen_admin = client.post(
|
||||
"/api/ai/narrative/regenerate",
|
||||
json={"section": "comparison", "filters": {"period": "12m"}},
|
||||
headers=admin_hdr,
|
||||
)
|
||||
assert r_regen_admin.status_code == 200, r_regen_admin.text
|
||||
regen_body = r_regen_admin.json()
|
||||
assert regen_body["section"] == "comparison"
|
||||
assert regen_body["narrative"]["source"] == "rule_based"
|
||||
assert regen_body["narrative"]["headline"]
|
||||
|
||||
|
||||
def test_ai6_scoping_department_category_and_custom_period(client, db):
|
||||
mgmt_hdr = _auth_headers(client, "mgmt@poona.demo")
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
cat = db.query(Category).first()
|
||||
assert icu is not None and cat is not None
|
||||
|
||||
r_dept = client.get(f"/api/ai/depreciation?period=6m&department_id={icu.id}", headers=mgmt_hdr)
|
||||
assert r_dept.status_code == 200, r_dept.text
|
||||
dep_body = r_dept.json()
|
||||
assert len(dep_body["rows"]) > 0
|
||||
assert all(row["department_name"] == icu.name for row in dep_body["rows"])
|
||||
|
||||
r_cat = client.get(f"/api/ai/breakdown-frequency?period=3m&category_id={cat.id}", headers=mgmt_hdr)
|
||||
assert r_cat.status_code == 200, r_cat.text
|
||||
bf_body = r_cat.json()
|
||||
assert all(row["category_name"] == cat.name for row in bf_body["rows"])
|
||||
|
||||
# Valid custom period
|
||||
r_custom = client.get(
|
||||
"/api/ai/efficiency?period=custom&date_from=2025-01-01&date_to=2025-12-31",
|
||||
headers=mgmt_hdr,
|
||||
)
|
||||
assert r_custom.status_code == 200, r_custom.text
|
||||
assert r_custom.json()["period_start"] == "2025-01-01"
|
||||
assert r_custom.json()["period_end"] == "2025-12-31"
|
||||
|
||||
# Inverted custom period -> 422
|
||||
r_bad = client.get(
|
||||
"/api/ai/efficiency?period=custom&date_from=2026-06-01&date_to=2026-01-01",
|
||||
headers=mgmt_hdr,
|
||||
)
|
||||
assert r_bad.status_code == 422
|
||||
|
||||
|
||||
def test_ai6_default_none_provider_shapes_and_real_seeded_data(client, monkeypatch):
|
||||
from app.core.config import settings
|
||||
monkeypatch.setattr(settings, "AI_PROVIDER", "none")
|
||||
admin_hdr = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
status_res = client.get("/api/ai/status", headers=admin_hdr)
|
||||
assert status_res.status_code == 200
|
||||
st = status_res.json()
|
||||
assert st["provider"] == "none"
|
||||
assert st["enabled"] is False
|
||||
assert st["reachable"] is False
|
||||
|
||||
summary = client.get("/api/ai/summary?period=12m", headers=admin_hdr).json()
|
||||
assert set(summary["sections"].keys()) == {
|
||||
"comparison",
|
||||
"depreciation",
|
||||
"efficiency",
|
||||
"breakdown_frequency",
|
||||
}
|
||||
assert summary["narrative"]["source"] == "rule_based"
|
||||
assert len(summary["suggestions"]) > 0
|
||||
|
||||
for ep in ("comparison", "depreciation", "efficiency", "breakdown-frequency"):
|
||||
body = client.get(f"/api/ai/{ep}?period=12m", headers=admin_hdr).json()
|
||||
for key in ("metrics", "rows", "chart_data", "narrative", "how_calculated"):
|
||||
assert key in body, f"Missing '{key}' in /api/ai/{ep}"
|
||||
assert body["narrative"]["source"] == "rule_based"
|
||||
assert len(body["metrics"]) > 0
|
||||
assert len(body["rows"]) > 0
|
||||
|
||||
cmp_body = client.get("/api/ai/comparison?period=12m", headers=admin_hdr).json()
|
||||
assert len(cmp_body["rows"]) == 10
|
||||
|
||||
sugs = client.get("/api/ai/suggestions?period=12m", headers=admin_hdr).json()["suggestions"]
|
||||
s1 = [s for s in sugs if s["rule"] == "S1"]
|
||||
s4 = [s for s in sugs if s["rule"] == "S4"]
|
||||
assert len(s1) >= 3
|
||||
assert len(s4) >= 2
|
||||
|
||||
|
||||
def test_ai6_exports_xlsx_three_sheets_and_csv(client):
|
||||
biomed_hdr = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
for sec in AI_EXPORT_SECTIONS:
|
||||
r_xlsx = client.get(f"/api/ai/{sec}/export?format=xlsx&period=12m", headers=biomed_hdr)
|
||||
assert r_xlsx.status_code == 200, f"XLSX export failed for {sec}: {r_xlsx.text}"
|
||||
assert "spreadsheetml" in r_xlsx.headers["content-type"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(r_xlsx.content))
|
||||
assert len(wb.sheetnames) == 3, f"Expected 3 sheets for {sec}, got {wb.sheetnames}"
|
||||
assert wb.sheetnames[1] == "Evidence"
|
||||
assert wb.sheetnames[2] == "How calculated"
|
||||
assert len(wb.sheetnames[0]) <= 31
|
||||
|
||||
# Verify each sheet has header row (row 5) and at least one data row (row 6)
|
||||
for ws_name in wb.sheetnames:
|
||||
ws = wb[ws_name]
|
||||
assert ws.cell(row=5, column=1).value is not None, f"Missing header on {sec}/{ws_name}"
|
||||
assert ws.cell(row=6, column=1).value is not None, f"Missing data row on {sec}/{ws_name}"
|
||||
|
||||
r_csv = client.get(f"/api/ai/{sec}/export?format=csv&period=12m", headers=biomed_hdr)
|
||||
assert r_csv.status_code == 200, f"CSV export failed for {sec}: {r_csv.text}"
|
||||
assert "text/csv" in r_csv.headers["content-type"]
|
||||
assert len(r_csv.text.splitlines()) >= 5
|
||||
|
||||
# Unknown export section -> 404
|
||||
r_404 = client.get("/api/ai/nonexistent/export?format=xlsx", headers=biomed_hdr)
|
||||
assert r_404.status_code == 404
|
||||
|
||||
@@ -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"
|
||||
@@ -0,0 +1,336 @@
|
||||
from datetime import date, timedelta
|
||||
import io
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
import pytest
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models import Asset, AuditLog, Category, Complaint, Department, Location
|
||||
from app.seed.seed import _make_minimal_pdf, seed_database
|
||||
from app.services.calculations import alert_state, compute_schedule_status, coverage_status
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_assets_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("asset_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", (32, 32), color=(10, 120, 200)).save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _make_jpeg_bytes() -> bytes:
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (32, 32), color=(200, 50, 50)).save(buf, format="JPEG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_alert_state_and_coverage_status():
|
||||
today = date(2026, 5, 1)
|
||||
|
||||
assert alert_state(None, today, lead_days=30, red_days=7) == "ok"
|
||||
assert alert_state(today - timedelta(days=1), today, 30, 7) == "red"
|
||||
assert alert_state(today, today, 30, 7) == "red"
|
||||
assert alert_state(today + timedelta(days=7), today, 30, 7) == "red"
|
||||
assert alert_state(today + timedelta(days=8), today, 30, 7) == "yellow"
|
||||
assert alert_state(today + timedelta(days=30), today, 30, 7) == "yellow"
|
||||
assert alert_state(today + timedelta(days=31), today, 30, 7) == "ok"
|
||||
|
||||
assert coverage_status(None, None, today, 30, 7) == ("none", "none")
|
||||
assert coverage_status(today - timedelta(days=100), today - timedelta(days=1), today, 30, 7) == ("expired", "red")
|
||||
assert coverage_status(today - timedelta(days=100), today + timedelta(days=5), today, 30, 7) == ("expiring", "red")
|
||||
assert coverage_status(today - timedelta(days=100), today + timedelta(days=20), today, 30, 7) == ("expiring", "yellow")
|
||||
assert coverage_status(today - timedelta(days=100), today + timedelta(days=45), today, 30, 7) == ("active", "ok")
|
||||
|
||||
assert compute_schedule_status(today - timedelta(days=1), "completed", today, 15, 7) == ("completed", "ok")
|
||||
assert compute_schedule_status(today - timedelta(days=1), None, today, 15, 7) == ("overdue", "red")
|
||||
assert compute_schedule_status(today + timedelta(days=10), None, today, 15, 7) == ("due", "yellow")
|
||||
assert compute_schedule_status(today + timedelta(days=30), None, today, 15, 7) == ("upcoming", "ok")
|
||||
|
||||
|
||||
def test_asset_crud_and_duplicate_code(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
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()
|
||||
|
||||
# department_user cannot create assets
|
||||
forbidden_create = client.post(
|
||||
"/api/assets",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_code": "PHRC-ICU-9998",
|
||||
"serial_no": "SN-9998",
|
||||
"name": "Unauthorized Asset",
|
||||
"category_id": cat.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": loc.id,
|
||||
},
|
||||
)
|
||||
assert forbidden_create.status_code == 403
|
||||
|
||||
# biomedical creates asset
|
||||
create_res = client.post(
|
||||
"/api/assets",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_code": "PHRC-ICU-9999",
|
||||
"serial_no": "SN-TEST-9999",
|
||||
"name": "Test Cardiac Monitor",
|
||||
"category_id": cat.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": loc.id,
|
||||
"purchase_value": 250000.0,
|
||||
"status": "in_service",
|
||||
"criticality": "critical",
|
||||
"requires_calibration": True,
|
||||
"insurance_applicable": True,
|
||||
"remarks": "Phase 2 test asset",
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
created = create_res.json()
|
||||
assert created["asset_code"] == "PHRC-ICU-9999"
|
||||
assert created["department_name"] == icu.name
|
||||
|
||||
# Duplicate asset_code -> 409 DUPLICATE_ASSET_CODE
|
||||
dup_res = client.post(
|
||||
"/api/assets",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_code": "PHRC-ICU-9999",
|
||||
"serial_no": "SN-DUP",
|
||||
"name": "Duplicate Asset",
|
||||
"category_id": cat.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": loc.id,
|
||||
},
|
||||
)
|
||||
assert dup_res.status_code == 409
|
||||
assert dup_res.json()["code"] == "DUPLICATE_ASSET_CODE"
|
||||
|
||||
# Audit log written on create
|
||||
audit = (
|
||||
db.query(AuditLog)
|
||||
.filter(AuditLog.entity_type == "asset", AuditLog.entity_id == created["id"], AuditLog.action == "create")
|
||||
.first()
|
||||
)
|
||||
assert audit is not None
|
||||
|
||||
# Overview returns structured data
|
||||
ov_res = client.get(f"/api/assets/{created['id']}/overview", headers=bio_headers)
|
||||
assert ov_res.status_code == 200
|
||||
ov = ov_res.json()
|
||||
assert ov["asset"]["id"] == created["id"]
|
||||
assert "warranties" in ov
|
||||
assert "contracts" in ov
|
||||
assert "attachments" in ov
|
||||
|
||||
|
||||
def test_department_user_scoping_on_assets(client, db):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
ot = db.query(Department).filter(Department.code == "OT").first()
|
||||
other_asset = db.query(Asset).filter(Asset.department_id == ot.id).first()
|
||||
assert other_asset is not None
|
||||
|
||||
# List returns only ICU assets even if another department_id is requested
|
||||
list_res = client.get(f"/api/assets?department_id={ot.id}&page_size=200", headers=dept_headers)
|
||||
assert list_res.status_code == 200
|
||||
items = list_res.json()["items"]
|
||||
assert len(items) > 0
|
||||
assert all(item["department_id"] == icu.id for item in items)
|
||||
|
||||
# Lookup returns only ICU assets
|
||||
lookup_res = client.get(f"/api/assets/lookup?department_id={ot.id}", headers=dept_headers)
|
||||
assert lookup_res.status_code == 200
|
||||
lookup_items = lookup_res.json()["items"]
|
||||
assert all(item["department_id"] == icu.id for item in lookup_items)
|
||||
|
||||
# Direct access to another department's asset & overview -> 403
|
||||
assert client.get(f"/api/assets/{other_asset.id}", headers=dept_headers).status_code == 403
|
||||
assert client.get(f"/api/assets/{other_asset.id}/overview", headers=dept_headers).status_code == 403
|
||||
|
||||
|
||||
def test_coordinator_field_level_patch_restrictions(client, db):
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
asset = db.query(Asset).first()
|
||||
|
||||
ok_patch = client.patch(
|
||||
f"/api/assets/{asset.id}",
|
||||
headers=coord_headers,
|
||||
json={"insurance_applicable": not asset.insurance_applicable, "remarks": "Updated by coordinator"},
|
||||
)
|
||||
assert ok_patch.status_code == 200
|
||||
assert ok_patch.json()["remarks"] == "Updated by coordinator"
|
||||
|
||||
bad_name = client.patch(
|
||||
f"/api/assets/{asset.id}",
|
||||
headers=coord_headers,
|
||||
json={"name": "Unauthorized Rename"},
|
||||
)
|
||||
assert bad_name.status_code == 403
|
||||
assert bad_name.json()["code"] == "FORBIDDEN"
|
||||
|
||||
bad_status = client.patch(
|
||||
f"/api/assets/{asset.id}",
|
||||
headers=coord_headers,
|
||||
json={"status": "condemned"},
|
||||
)
|
||||
assert bad_status.status_code == 403
|
||||
assert bad_status.json()["code"] == "FORBIDDEN"
|
||||
|
||||
|
||||
def test_attachments_upload_download_delete_and_security(client, db, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(settings, "UPLOAD_DIR", str(tmp_path))
|
||||
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
ot = db.query(Department).filter(Department.code == "OT").first()
|
||||
icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first()
|
||||
ot_asset = db.query(Asset).filter(Asset.department_id == ot.id).first()
|
||||
icu_complaint = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.filter(Asset.department_id == icu.id)
|
||||
.first()
|
||||
)
|
||||
assert icu_complaint is not None
|
||||
|
||||
# 1. Valid PNG upload & download exact bytes
|
||||
png_bytes = _make_png_bytes()
|
||||
up_png = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("panel.png", png_bytes, "image/png")},
|
||||
)
|
||||
assert up_png.status_code == 201, up_png.text
|
||||
att_id = up_png.json()["id"]
|
||||
assert up_png.json()["mime_type"] == "image/png"
|
||||
|
||||
dl_res = client.get(f"/api/attachments/{att_id}/download", headers=bio_headers)
|
||||
assert dl_res.status_code == 200
|
||||
assert dl_res.content == png_bytes
|
||||
|
||||
# 2. Valid JPG and PDF uploads
|
||||
jpg_bytes = _make_jpeg_bytes()
|
||||
up_jpg = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("photo.jpg", jpg_bytes, "image/jpeg")},
|
||||
)
|
||||
assert up_jpg.status_code == 201
|
||||
|
||||
pdf_bytes = _make_minimal_pdf("Asset Service Manual")
|
||||
up_pdf = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("manual.pdf", pdf_bytes, "application/pdf")},
|
||||
)
|
||||
assert up_pdf.status_code == 201
|
||||
|
||||
# 3. Reject .exe / .txt and spoofed magic bytes -> 400 INVALID_FILE_TYPE
|
||||
bad_exe = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("malware.exe", b"MZ\x90\x00", "application/octet-stream")},
|
||||
)
|
||||
assert bad_exe.status_code == 400
|
||||
assert bad_exe.json()["code"] == "INVALID_FILE_TYPE"
|
||||
|
||||
bad_spoof = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("fake.jpg", b"not really a jpeg", "image/jpeg")},
|
||||
)
|
||||
assert bad_spoof.status_code == 400
|
||||
assert bad_spoof.json()["code"] == "INVALID_FILE_TYPE"
|
||||
|
||||
# 4. Reject >10 MB -> 413 FILE_TOO_LARGE
|
||||
oversized = b"%PDF-" + (b"0" * (10 * 1024 * 1024 + 100))
|
||||
too_big = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("huge.pdf", oversized, "application/pdf")},
|
||||
)
|
||||
assert too_big.status_code == 413
|
||||
assert too_big.json()["code"] == "FILE_TOO_LARGE"
|
||||
|
||||
# 5. department_user cannot upload to or download from another department's asset
|
||||
ot_up = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(ot_asset.id)},
|
||||
files={"file": ("ot.png", png_bytes, "image/png")},
|
||||
)
|
||||
assert ot_up.status_code == 201
|
||||
ot_att_id = ot_up.json()["id"]
|
||||
|
||||
assert client.get(f"/api/attachments/{ot_att_id}/download", headers=dept_headers).status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/attachments",
|
||||
headers=dept_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(ot_asset.id)},
|
||||
files={"file": ("unauth.png", png_bytes, "image/png")},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# department_user cannot upload to own-dept asset (only complaint), CAN upload to own-dept complaint
|
||||
assert (
|
||||
client.post(
|
||||
"/api/attachments",
|
||||
headers=dept_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("icu.png", png_bytes, "image/png")},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
dept_cmp_up = client.post(
|
||||
"/api/attachments",
|
||||
headers=dept_headers,
|
||||
data={"entity_type": "complaint", "entity_id": str(icu_complaint.id)},
|
||||
files={"file": ("fault.jpg", jpg_bytes, "image/jpeg")},
|
||||
)
|
||||
assert dept_cmp_up.status_code == 201
|
||||
|
||||
# management cannot upload or delete
|
||||
assert (
|
||||
client.post(
|
||||
"/api/attachments",
|
||||
headers=mgmt_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("mgmt.png", png_bytes, "image/png")},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert client.delete(f"/api/attachments/{att_id}", headers=mgmt_headers).status_code == 403
|
||||
|
||||
# Delete removes DB row and disk file
|
||||
stored_files_before = list(Path(tmp_path).iterdir())
|
||||
del_res = client.delete(f"/api/attachments/{att_id}", headers=bio_headers)
|
||||
assert del_res.status_code == 204
|
||||
stored_files_after = list(Path(tmp_path).iterdir())
|
||||
assert len(stored_files_after) == len(stored_files_before) - 1
|
||||
assert client.get(f"/api/attachments/{att_id}/download", headers=bio_headers).status_code == 404
|
||||
@@ -0,0 +1,390 @@
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import KOLKATA, effective_today
|
||||
from app.models import (
|
||||
Asset,
|
||||
Attachment,
|
||||
CalibrationPlan,
|
||||
Category,
|
||||
Complaint,
|
||||
Contract,
|
||||
DemoEquipment,
|
||||
Department,
|
||||
DepartmentVisit,
|
||||
InsurancePolicy,
|
||||
Location,
|
||||
PMSchedule,
|
||||
User,
|
||||
Vendor,
|
||||
Warranty,
|
||||
)
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.permissions import RESTRICTED_COMPLAINT_FIELDS, Role, has_capability
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_test_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str, password: str = "Demo@123") -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": password})
|
||||
assert res.status_code == 200, res.text
|
||||
token = res.json()["access_token"]
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def test_login_valid_and_invalid(client, db):
|
||||
res = client.post("/api/auth/login", json={"email": "admin@poona.demo", "password": "Demo@123"})
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["token_type"] == "bearer"
|
||||
assert body["access_token"]
|
||||
assert body["user"]["email"] == "admin@poona.demo"
|
||||
assert body["user"]["role"] == "system_admin"
|
||||
assert body["user"]["demo_as_of_date"] is None
|
||||
|
||||
bad_pw = client.post("/api/auth/login", json={"email": "admin@poona.demo", "password": "wrong"})
|
||||
assert bad_pw.status_code == 401
|
||||
|
||||
bad_email = client.post("/api/auth/login", json={"email": "nobody@poona.demo", "password": "Demo@123"})
|
||||
assert bad_email.status_code == 401
|
||||
|
||||
# Inactive user rejected
|
||||
user = db.query(User).filter(User.email == "neha.chavan@poona.demo").first()
|
||||
assert user is not None
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
try:
|
||||
res_inactive = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "neha.chavan@poona.demo", "password": "Demo@123"},
|
||||
)
|
||||
assert res_inactive.status_code in (401, 403)
|
||||
finally:
|
||||
user.is_active = True
|
||||
db.commit()
|
||||
|
||||
|
||||
def test_auth_me(client):
|
||||
unauth = client.get("/api/auth/me")
|
||||
assert unauth.status_code == 401
|
||||
|
||||
bad_tok = client.get("/api/auth/me", headers={"Authorization": "Bearer invalid.token.here"})
|
||||
assert bad_tok.status_code == 401
|
||||
|
||||
headers = _auth_headers(client, "dept@poona.demo")
|
||||
me = client.get("/api/auth/me", headers=headers)
|
||||
assert me.status_code == 200
|
||||
data = me.json()
|
||||
assert data["email"] == "dept@poona.demo"
|
||||
assert data["role"] == "department_user"
|
||||
assert data["department_name"] == "Intensive Care Unit"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"email",
|
||||
[
|
||||
"bio@poona.demo",
|
||||
"dept@poona.demo",
|
||||
"mgmt@poona.demo",
|
||||
"coord@poona.demo",
|
||||
],
|
||||
)
|
||||
def test_non_admin_forbidden_on_admin_endpoints(client, db, email):
|
||||
headers = _auth_headers(client, email)
|
||||
dept = db.query(Department).first()
|
||||
target_user = db.query(User).filter(User.email == "dept@poona.demo").first()
|
||||
|
||||
# Masters GET is allowed for authenticated users
|
||||
assert client.get("/api/departments", headers=headers).status_code == 200
|
||||
assert client.get("/api/locations", headers=headers).status_code == 200
|
||||
assert client.get("/api/categories", headers=headers).status_code == 200
|
||||
assert client.get("/api/vendors", headers=headers).status_code == 200
|
||||
assert client.get("/api/users/lookup", headers=headers).status_code == 200
|
||||
|
||||
# Masters write -> 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/departments",
|
||||
headers=headers,
|
||||
json={"name": "Test Dept", "code": "TST"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/departments/{dept.id}",
|
||||
headers=headers,
|
||||
json={"description": "hacked"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert client.delete(f"/api/departments/{dept.id}", headers=headers).status_code == 403
|
||||
|
||||
# Users admin endpoints -> 403
|
||||
assert client.get("/api/users", headers=headers).status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Hack",
|
||||
"email": "hack@poona.demo",
|
||||
"password": "Password1",
|
||||
"role": "biomedical",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/users/{target_user.id}",
|
||||
headers=headers,
|
||||
json={"name": "Hacked"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert client.delete(f"/api/users/{target_user.id}", headers=headers).status_code == 403
|
||||
|
||||
# Settings endpoints -> 403
|
||||
assert client.get("/api/settings", headers=headers).status_code == 403
|
||||
assert (
|
||||
client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"contract_expiry_alert_days": 45}},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=headers,
|
||||
json={"demo_as_of_date": "2026-06-01"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
|
||||
def test_admin_masters_and_users_crud(client):
|
||||
headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
# Department create, patch, soft-delete
|
||||
r = client.post(
|
||||
"/api/departments",
|
||||
headers=headers,
|
||||
json={"name": "Physiotherapy", "code": "PHYS", "description": "Rehab unit"},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
dept_id = r.json()["id"]
|
||||
|
||||
r_patch = client.patch(
|
||||
f"/api/departments/{dept_id}",
|
||||
headers=headers,
|
||||
json={"description": "Physiotherapy & Rehab"},
|
||||
)
|
||||
assert r_patch.status_code == 200
|
||||
assert r_patch.json()["description"] == "Physiotherapy & Rehab"
|
||||
|
||||
r_del = client.delete(f"/api/departments/{dept_id}", headers=headers)
|
||||
assert r_del.status_code == 200
|
||||
assert r_del.json()["is_active"] is False
|
||||
|
||||
# User create, password update, soft-delete
|
||||
u_res = client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Temp Staff",
|
||||
"email": "temp.staff@poona.demo",
|
||||
"password": "InitPassword1",
|
||||
"role": "biomedical",
|
||||
},
|
||||
)
|
||||
assert u_res.status_code == 201
|
||||
uid = u_res.json()["id"]
|
||||
|
||||
# Update password
|
||||
u_patch = client.patch(
|
||||
f"/api/users/{uid}",
|
||||
headers=headers,
|
||||
json={"password": "NewPassword2"},
|
||||
)
|
||||
assert u_patch.status_code == 200
|
||||
login_new = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "temp.staff@poona.demo", "password": "NewPassword2"},
|
||||
)
|
||||
assert login_new.status_code == 200
|
||||
|
||||
# Soft delete user
|
||||
u_del = client.delete(f"/api/users/{uid}", headers=headers)
|
||||
assert u_del.status_code == 200
|
||||
assert u_del.json()["is_active"] is False
|
||||
|
||||
|
||||
def test_permissions_matrix_all_roles():
|
||||
assert "action_taken" in RESTRICTED_COMPLAINT_FIELDS
|
||||
assert "spare_cost_estimate" in RESTRICTED_COMPLAINT_FIELDS
|
||||
|
||||
# system_admin
|
||||
assert has_capability(Role.system_admin, "manage_admin") is True
|
||||
assert has_capability(Role.system_admin, "edit_technical_fields") is True
|
||||
assert has_capability(Role.system_admin, "view_visits") is True
|
||||
|
||||
# biomedical
|
||||
assert has_capability(Role.biomedical, "manage_admin") is False
|
||||
assert has_capability(Role.biomedical, "create_edit_assets") is True
|
||||
assert has_capability(Role.biomedical, "edit_technical_fields") is True
|
||||
assert has_capability(Role.biomedical, "manage_pm") is True
|
||||
assert has_capability(Role.biomedical, "manage_visits") is True
|
||||
assert has_capability(Role.biomedical, "view_all_reports") is True
|
||||
|
||||
# department_user
|
||||
assert has_capability(Role.department_user, "manage_admin") is False
|
||||
assert has_capability(Role.department_user, "view_assets") is True
|
||||
assert has_capability(Role.department_user, "raise_complaint") is True
|
||||
assert has_capability(Role.department_user, "handle_complaint") is False
|
||||
assert has_capability(Role.department_user, "edit_technical_fields") is False
|
||||
assert has_capability(Role.department_user, "view_visits") is False
|
||||
assert has_capability(Role.department_user, "view_dept_reports") is True
|
||||
assert has_capability(Role.department_user, "view_all_reports") is False
|
||||
|
||||
# management
|
||||
assert has_capability(Role.management, "manage_admin") is False
|
||||
assert has_capability(Role.management, "view_assets") is True
|
||||
assert has_capability(Role.management, "view_visits") is True
|
||||
assert has_capability(Role.management, "view_all_reports") is True
|
||||
assert has_capability(Role.management, "create_edit_assets") is False
|
||||
assert has_capability(Role.management, "raise_complaint") is False
|
||||
assert has_capability(Role.management, "edit_technical_fields") is False
|
||||
|
||||
# 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
|
||||
assert has_capability(Role.coordinator, "manage_calibration_contracts") is True
|
||||
assert has_capability(Role.coordinator, "manage_demo_equipment") is True
|
||||
assert has_capability(Role.coordinator, "view_visits") is False
|
||||
|
||||
# invalid / None
|
||||
assert has_capability(None, "view_assets") is False
|
||||
assert has_capability("unknown_role", "view_assets") is False
|
||||
|
||||
|
||||
def test_settings_validation_and_demo_date(client, db):
|
||||
headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
res = client.get("/api/settings", headers=headers)
|
||||
assert res.status_code == 200
|
||||
items = res.json()["items"]
|
||||
assert len(items) >= 14
|
||||
|
||||
# Out of range int
|
||||
bad_range = client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"contract_expiry_alert_days": 999}},
|
||||
)
|
||||
assert bad_range.status_code == 422
|
||||
|
||||
# Bool passed to int
|
||||
bad_type = client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"contract_expiry_alert_days": True}},
|
||||
)
|
||||
assert bad_type.status_code == 422
|
||||
|
||||
# Invalid enum
|
||||
bad_enum = client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"default_pm_mode": "third_party"}},
|
||||
)
|
||||
assert bad_enum.status_code == 422
|
||||
|
||||
# Unknown key
|
||||
bad_key = client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"nonexistent_key": 123}},
|
||||
)
|
||||
assert bad_key.status_code == 422
|
||||
|
||||
# Valid update
|
||||
ok_put = client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"contract_expiry_alert_days": 45, "require_closure_remarks": False}},
|
||||
)
|
||||
assert ok_put.status_code == 200
|
||||
updated_map = {item["key"]: item["value"] for item in ok_put.json()["items"]}
|
||||
assert updated_map["contract_expiry_alert_days"] == 45
|
||||
assert updated_map["require_closure_remarks"] is False
|
||||
|
||||
# Demo date set & reset
|
||||
set_demo = client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=headers,
|
||||
json={"demo_as_of_date": "2026-06-15"},
|
||||
)
|
||||
assert set_demo.status_code == 200
|
||||
assert set_demo.json()["demo_as_of_date"] == "2026-06-15"
|
||||
assert set_demo.json()["effective_today"] == "2026-06-15"
|
||||
assert effective_today(db) == date(2026, 6, 15)
|
||||
|
||||
me_res = client.get("/api/auth/me", headers=headers)
|
||||
assert me_res.json()["demo_as_of_date"] == "2026-06-15"
|
||||
|
||||
# Reset demo date
|
||||
reset_demo = client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=headers,
|
||||
json={"demo_as_of_date": None},
|
||||
)
|
||||
assert reset_demo.status_code == 200
|
||||
assert reset_demo.json()["demo_as_of_date"] is None
|
||||
assert effective_today(db) == datetime.now(KOLKATA).date()
|
||||
|
||||
|
||||
def test_seed_idempotency_and_counts(db, tmp_path):
|
||||
summary1 = seed_database(db, upload_dir=tmp_path)
|
||||
summary2 = seed_database(db, upload_dir=tmp_path)
|
||||
assert summary1 == summary2
|
||||
|
||||
assert db.query(Department).count() == 8
|
||||
assert db.query(Location).count() == 20
|
||||
assert db.query(Category).count() == 8
|
||||
assert db.query(Vendor).count() == 12
|
||||
assert db.query(User).count() == 11
|
||||
assert db.query(Asset).count() == 60
|
||||
assert db.query(Contract).count() == 35
|
||||
assert db.query(Contract).filter(Contract.is_superseded.is_(True)).count() == 1
|
||||
assert db.query(Warranty).count() == 20
|
||||
assert db.query(InsurancePolicy).count() == 25
|
||||
assert db.query(CalibrationPlan).count() == 20
|
||||
assert db.query(PMSchedule).count() == 45
|
||||
assert db.query(PMSchedule).filter(PMSchedule.service_mode == "in_house").count() == 27
|
||||
assert db.query(PMSchedule).filter(PMSchedule.service_mode == "outsourced").count() == 18
|
||||
assert db.query(Complaint).count() == 30
|
||||
assert db.query(Complaint).filter(Complaint.call_status == "closed").count() == 22
|
||||
assert db.query(Complaint).filter(Complaint.call_status == "in_progress").count() == 4
|
||||
assert db.query(Complaint).filter(Complaint.call_status == "open").count() == 4
|
||||
assert db.query(Complaint).filter(Complaint.spare_required.is_(True)).count() == 6
|
||||
assert db.query(Complaint).filter(Complaint.ce_name.is_not(None)).count() == 5
|
||||
assert db.query(DemoEquipment).count() == 3
|
||||
assert db.query(DepartmentVisit).count() == 12
|
||||
assert db.query(Attachment).count() == 14
|
||||
|
||||
jpegs = list(Path(tmp_path).glob("*.jpg"))
|
||||
pdfs = list(Path(tmp_path).glob("*.pdf"))
|
||||
assert len(jpegs) == 8
|
||||
assert len(pdfs) == 6
|
||||
@@ -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)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user