commit 13556aa42377705738f8a3d23c1d776e9bc1d32d Author: Antigravity Date: Wed Nov 18 18:06:22 2026 +0530 initial commit diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..71023f0 --- /dev/null +++ b/.env.example @@ -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 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a0c6ebc --- /dev/null +++ b/.gitignore @@ -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 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..7f26262 --- /dev/null +++ b/AGENTS.md @@ -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: `. +- 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. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..6e5c369 --- /dev/null +++ b/Makefile @@ -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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..f30b67d --- /dev/null +++ b/README.md @@ -0,0 +1,168 @@ +# Poona Hospital Asset Management System + +![Poona Hospital and Research Centre](frontend/public/logo.jpg) + +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_.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 ``, 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 diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..280e2e1 --- /dev/null +++ b/backend/Dockerfile @@ -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"] diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/core/__init__.py b/backend/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/core/config.py b/backend/app/core/config.py new file mode 100644 index 0000000..2921803 --- /dev/null +++ b/backend/app/core/config.py @@ -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() diff --git a/backend/app/core/db.py b/backend/app/core/db.py new file mode 100644 index 0000000..2cfc000 --- /dev/null +++ b/backend/app/core/db.py @@ -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() diff --git a/backend/app/core/deps.py b/backend/app/core/deps.py new file mode 100644 index 0000000..6c6893b --- /dev/null +++ b/backend/app/core/deps.py @@ -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 diff --git a/backend/app/core/exceptions.py b/backend/app/core/exceptions.py new file mode 100644 index 0000000..9e2d104 --- /dev/null +++ b/backend/app/core/exceptions.py @@ -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, + ) diff --git a/backend/app/core/migrations.py b/backend/app/core/migrations.py new file mode 100644 index 0000000..0797c1b --- /dev/null +++ b/backend/app/core/migrations.py @@ -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 diff --git a/backend/app/core/security.py b/backend/app/core/security.py new file mode 100644 index 0000000..f7878e3 --- /dev/null +++ b/backend/app/core/security.py @@ -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]) diff --git a/backend/app/core/time_utils.py b/backend/app/core/time_utils.py new file mode 100644 index 0000000..b19e1c8 --- /dev/null +++ b/backend/app/core/time_utils.py @@ -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) diff --git a/backend/app/main.py b/backend/app/main.py new file mode 100644 index 0000000..3a5635e --- /dev/null +++ b/backend/app/main.py @@ -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") diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py new file mode 100644 index 0000000..7ea5ffb --- /dev/null +++ b/backend/app/models/__init__.py @@ -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", +] diff --git a/backend/app/models/assets.py b/backend/app/models/assets.py new file mode 100644 index 0000000..7af3ba2 --- /dev/null +++ b/backend/app/models/assets.py @@ -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") diff --git a/backend/app/models/base.py b/backend/app/models/base.py new file mode 100644 index 0000000..fa2b68a --- /dev/null +++ b/backend/app/models/base.py @@ -0,0 +1,5 @@ +from sqlalchemy.orm import DeclarativeBase + + +class Base(DeclarativeBase): + pass diff --git a/backend/app/models/complaints.py b/backend/app/models/complaints.py new file mode 100644 index 0000000..1634f12 --- /dev/null +++ b/backend/app/models/complaints.py @@ -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") diff --git a/backend/app/models/maintenance.py b/backend/app/models/maintenance.py new file mode 100644 index 0000000..3737310 --- /dev/null +++ b/backend/app/models/maintenance.py @@ -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") diff --git a/backend/app/models/masters.py b/backend/app/models/masters.py new file mode 100644 index 0000000..9bdbf7d --- /dev/null +++ b/backend/app/models/masters.py @@ -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) diff --git a/backend/app/models/operations.py b/backend/app/models/operations.py new file mode 100644 index 0000000..1a7e043 --- /dev/null +++ b/backend/app/models/operations.py @@ -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) diff --git a/backend/app/models/system.py b/backend/app/models/system.py new file mode 100644 index 0000000..ab9f55f --- /dev/null +++ b/backend/app/models/system.py @@ -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) diff --git a/backend/app/routers/__init__.py b/backend/app/routers/__init__.py new file mode 100644 index 0000000..8225d12 --- /dev/null +++ b/backend/app/routers/__init__.py @@ -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", +] diff --git a/backend/app/routers/ai_reports.py b/backend/app/routers/ai_reports.py new file mode 100644 index 0000000..d478398 --- /dev/null +++ b/backend/app/routers/ai_reports.py @@ -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}"', + }, + ) + diff --git a/backend/app/routers/assets.py b/backend/app/routers/assets.py new file mode 100644 index 0000000..9eab9b8 --- /dev/null +++ b/backend/app/routers/assets.py @@ -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) diff --git a/backend/app/routers/attachments.py b/backend/app/routers/attachments.py new file mode 100644 index 0000000..59d590c --- /dev/null +++ b/backend/app/routers/attachments.py @@ -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) diff --git a/backend/app/routers/audit.py b/backend/app/routers/audit.py new file mode 100644 index 0000000..daf9811 --- /dev/null +++ b/backend/app/routers/audit.py @@ -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, + } diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py new file mode 100644 index 0000000..0e16e47 --- /dev/null +++ b/backend/app/routers/auth.py @@ -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", + } diff --git a/backend/app/routers/calibration.py b/backend/app/routers/calibration.py new file mode 100644 index 0000000..c6dd555 --- /dev/null +++ b/backend/app/routers/calibration.py @@ -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), + ) diff --git a/backend/app/routers/complaints.py b/backend/app/routers/complaints.py new file mode 100644 index 0000000..95a81d9 --- /dev/null +++ b/backend/app/routers/complaints.py @@ -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)) diff --git a/backend/app/routers/contracts.py b/backend/app/routers/contracts.py new file mode 100644 index 0000000..80c8303 --- /dev/null +++ b/backend/app/routers/contracts.py @@ -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), + ) diff --git a/backend/app/routers/dashboard.py b/backend/app/routers/dashboard.py new file mode 100644 index 0000000..d6eb6fa --- /dev/null +++ b/backend/app/routers/dashboard.py @@ -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, + ) diff --git a/backend/app/routers/demo_equipment.py b/backend/app/routers/demo_equipment.py new file mode 100644 index 0000000..9ca5a76 --- /dev/null +++ b/backend/app/routers/demo_equipment.py @@ -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) diff --git a/backend/app/routers/health.py b/backend/app/routers/health.py new file mode 100644 index 0000000..a9e6ff5 --- /dev/null +++ b/backend/app/routers/health.py @@ -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"} diff --git a/backend/app/routers/insurance.py b/backend/app/routers/insurance.py new file mode 100644 index 0000000..bc88615 --- /dev/null +++ b/backend/app/routers/insurance.py @@ -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) diff --git a/backend/app/routers/masters.py b/backend/app/routers/masters.py new file mode 100644 index 0000000..4462be7 --- /dev/null +++ b/backend/app/routers/masters.py @@ -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 diff --git a/backend/app/routers/notifications.py b/backend/app/routers/notifications.py new file mode 100644 index 0000000..0867e68 --- /dev/null +++ b/backend/app/routers/notifications.py @@ -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) diff --git a/backend/app/routers/pm.py b/backend/app/routers/pm.py new file mode 100644 index 0000000..9b399df --- /dev/null +++ b/backend/app/routers/pm.py @@ -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), + ) diff --git a/backend/app/routers/reports.py b/backend/app/routers/reports.py new file mode 100644 index 0000000..2e402e0 --- /dev/null +++ b/backend/app/routers/reports.py @@ -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}"', + }, + ) diff --git a/backend/app/routers/search.py b/backend/app/routers/search.py new file mode 100644 index 0000000..47e6ce7 --- /dev/null +++ b/backend/app/routers/search.py @@ -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 + ], + } diff --git a/backend/app/routers/settings.py b/backend/app/routers/settings.py new file mode 100644 index 0000000..09a4581 --- /dev/null +++ b/backend/app/routers/settings.py @@ -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(), + } diff --git a/backend/app/routers/users.py b/backend/app/routers/users.py new file mode 100644 index 0000000..bc40f47 --- /dev/null +++ b/backend/app/routers/users.py @@ -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."} diff --git a/backend/app/routers/visits.py b/backend/app/routers/visits.py new file mode 100644 index 0000000..e5384a7 --- /dev/null +++ b/backend/app/routers/visits.py @@ -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) diff --git a/backend/app/routers/warranties.py b/backend/app/routers/warranties.py new file mode 100644 index 0000000..7ef20b0 --- /dev/null +++ b/backend/app/routers/warranties.py @@ -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) diff --git a/backend/app/schemas/__init__.py b/backend/app/schemas/__init__.py new file mode 100644 index 0000000..9993c7b --- /dev/null +++ b/backend/app/schemas/__init__.py @@ -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", +] diff --git a/backend/app/schemas/assets.py b/backend/app/schemas/assets.py new file mode 100644 index 0000000..1cabb27 --- /dev/null +++ b/backend/app/schemas/assets.py @@ -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] diff --git a/backend/app/schemas/attachments.py b/backend/app/schemas/attachments.py new file mode 100644 index 0000000..963e77d --- /dev/null +++ b/backend/app/schemas/attachments.py @@ -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 diff --git a/backend/app/schemas/auth.py b/backend/app/schemas/auth.py new file mode 100644 index 0000000..d82f296 --- /dev/null +++ b/backend/app/schemas/auth.py @@ -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 diff --git a/backend/app/schemas/calibration.py b/backend/app/schemas/calibration.py new file mode 100644 index 0000000..264677c --- /dev/null +++ b/backend/app/schemas/calibration.py @@ -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 diff --git a/backend/app/schemas/complaints.py b/backend/app/schemas/complaints.py new file mode 100644 index 0000000..38fc648 --- /dev/null +++ b/backend/app/schemas/complaints.py @@ -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 diff --git a/backend/app/schemas/contracts.py b/backend/app/schemas/contracts.py new file mode 100644 index 0000000..4c527ae --- /dev/null +++ b/backend/app/schemas/contracts.py @@ -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] diff --git a/backend/app/schemas/dashboard.py b/backend/app/schemas/dashboard.py new file mode 100644 index 0000000..1e4a344 --- /dev/null +++ b/backend/app/schemas/dashboard.py @@ -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] diff --git a/backend/app/schemas/demo_equipment.py b/backend/app/schemas/demo_equipment.py new file mode 100644 index 0000000..3a834c5 --- /dev/null +++ b/backend/app/schemas/demo_equipment.py @@ -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 diff --git a/backend/app/schemas/insurance.py b/backend/app/schemas/insurance.py new file mode 100644 index 0000000..f1ac643 --- /dev/null +++ b/backend/app/schemas/insurance.py @@ -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 diff --git a/backend/app/schemas/masters.py b/backend/app/schemas/masters.py new file mode 100644 index 0000000..4a059f6 --- /dev/null +++ b/backend/app/schemas/masters.py @@ -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 diff --git a/backend/app/schemas/notifications.py b/backend/app/schemas/notifications.py new file mode 100644 index 0000000..789a7d7 --- /dev/null +++ b/backend/app/schemas/notifications.py @@ -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 diff --git a/backend/app/schemas/pm.py b/backend/app/schemas/pm.py new file mode 100644 index 0000000..2daddff --- /dev/null +++ b/backend/app/schemas/pm.py @@ -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 diff --git a/backend/app/schemas/settings.py b/backend/app/schemas/settings.py new file mode 100644 index 0000000..1b26ed4 --- /dev/null +++ b/backend/app/schemas/settings.py @@ -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 diff --git a/backend/app/schemas/visits.py b/backend/app/schemas/visits.py new file mode 100644 index 0000000..de18f72 --- /dev/null +++ b/backend/app/schemas/visits.py @@ -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 diff --git a/backend/app/schemas/warranties.py b/backend/app/schemas/warranties.py new file mode 100644 index 0000000..61ac09a --- /dev/null +++ b/backend/app/schemas/warranties.py @@ -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 diff --git a/backend/app/seed/__init__.py b/backend/app/seed/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/seed/seed.py b/backend/app/seed/seed.py new file mode 100644 index 0000000..79bd0ec --- /dev/null +++ b/backend/app/seed/seed.py @@ -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() diff --git a/backend/app/services/__init__.py b/backend/app/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/services/ai_metrics.py b/backend/app/services/ai_metrics.py new file mode 100644 index 0000000..0cbb7e9 --- /dev/null +++ b/backend/app/services/ai_metrics.py @@ -0,0 +1,1765 @@ +""" +Pure-Python deterministic metrics engine for AI Reports & Cost Analysis. + +All numerical calculations happen here without any language model involvement. +Core functions accept plain dicts/dates and return plain dicts/lists so they can +be unit-tested without a database. Thin loader wrappers fetch SQLAlchemy records +using the same department scoping rules as reports_service.py. +""" + +from __future__ import annotations + +from datetime import date, datetime, time, timedelta, timezone +import re +from typing import Any, Optional +from sqlalchemy.orm import Session, joinedload + +from ..core.time_utils import KOLKATA, add_months, effective_now_utc, effective_today +from ..models import ( + Asset, + CalibrationPlan, + CalibrationRecord, + Category, + Complaint, + Contract, + Department, + PMRecord, + PMSchedule, + User, + Warranty, +) +from .calculations import ( + compute_response_time_minutes, + compute_schedule_status, +) +from .coverage import get_coverage_map +from .scoping import resolve_department_scope +from .settings_service import get_setting_value + +EFFICIENCY_WEIGHTS: dict[str, float] = { + "uptime": 0.50, + "pm_compliance": 0.20, + "response": 0.15, + "repeat_free": 0.15, +} + +DEFAULT_AI_SETTINGS: dict[str, Any] = { + "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, + "scheduled_hours_per_day": 24, + "downtime_end_milestone": "restored_at", + "response_start": "registered_at", + "critical_complaint_sla_hours": 4, + "non_critical_complaint_sla_hours": 24, + "pm_inhouse_lead_days": 15, + "pm_outsourced_lead_days": 15, + "calibration_lead_days": 15, + "contract_expiry_alert_days": 30, + "red_threshold_days": 7, +} + + +def _slug(text: str) -> str: + return re.sub(r"[^A-Za-z0-9]+", "_", (text or "").strip()).strip("_") or "NA" + + +def format_inr(amount: Optional[float]) -> str: + """Format a number in Indian Rupees with Indian digit grouping (e.g. ₹12,50,000).""" + if amount is None: + return "—" + neg = amount < 0 + rounded = int(round(abs(amount))) + s = str(rounded) + if len(s) <= 3: + grouped = s + else: + last3 = s[-3:] + rest = s[:-3] + parts: list[str] = [] + while len(rest) > 2: + parts.insert(0, rest[-2:]) + rest = rest[:-2] + if rest: + parts.insert(0, rest) + grouped = ",".join(parts) + "," + last3 + return f"-₹{grouped}" if neg else f"₹{grouped}" + + +def make_metric( + metric_id: str, + label: str, + value: Any, + unit: str = "", + formatted: Optional[str] = None, +) -> dict[str, Any]: + if formatted is None: + if value is None: + formatted = "—" + elif unit == "INR": + formatted = format_inr(float(value)) + elif unit == "%": + formatted = f"{float(value):.1f}%" + elif unit == "hours": + formatted = f"{float(value):.1f} hrs" + elif unit == "minutes": + formatted = f"{float(value):.1f} mins" + elif unit == "ratio": + formatted = f"{float(value) * 100:.1f}%" + elif isinstance(value, float): + formatted = f"{value:,.2f}" + else: + formatted = str(value) + return { + "id": metric_id, + "label": label, + "value": value, + "unit": unit, + "formatted": formatted, + } + + +def _ensure_utc(dt: datetime) -> datetime: + if dt.tzinfo is None: + return dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc) + + +def _to_date(val: Any) -> Optional[date]: + if val is None: + return None + if isinstance(val, datetime): + return _ensure_utc(val).astimezone(KOLKATA).date() + if isinstance(val, date): + return val + if isinstance(val, str) and val.strip(): + return date.fromisoformat(val.strip()[:10]) + return None + + +def _clip_interval_to_period( + start_utc: datetime, + end_utc: datetime, + period_start: date, + period_end: date, +) -> int: + """Clip a UTC interval to [period_start 00:00 IST, period_end+1 00:00 IST) in whole minutes.""" + win_start = KOLKATA.localize(datetime.combine(period_start, time(0, 0, 0))) + win_end = KOLKATA.localize(datetime.combine(period_end + timedelta(days=1), time(0, 0, 0))) + s_loc = _ensure_utc(start_utc).astimezone(KOLKATA) + e_loc = _ensure_utc(end_utc).astimezone(KOLKATA) + clipped_s = max(s_loc, win_start) + clipped_e = min(e_loc, win_end) + if clipped_e <= clipped_s: + return 0 + return int((clipped_e - clipped_s).total_seconds() // 60) + + +def _merged_settings(settings: Optional[dict[str, Any]]) -> dict[str, Any]: + merged = dict(DEFAULT_AI_SETTINGS) + if settings: + merged.update({k: v for k, v in settings.items() if v is not None}) + return merged + + +def _book_value_at_years( + cost: float, + life: int, + salvage_pct: float, + method: str, + years_elapsed: float, +) -> tuple[float, float, float]: + """Return (book_value, accumulated_depreciation, annual_charge).""" + salvage = cost * (salvage_pct / 100.0) + yrs = max(0.0, years_elapsed) + if method == "written_down": + if cost <= 0: + return (0.0, 0.0, 0.0) + eff_salvage_ratio = (salvage / cost) if salvage > 0 else 0.01 + rate = 1.0 - (eff_salvage_ratio ** (1.0 / float(life))) + raw_bv = cost * ((1.0 - rate) ** yrs) + bv = max(salvage, raw_bv) + accum = max(0.0, cost - bv) + annual_charge = 0.0 if yrs >= life else bv * rate + return (bv, accum, annual_charge) + + # Default: straight_line + annual = (cost - salvage) / float(life) + raw_bv = cost - annual * yrs + bv = max(salvage, raw_bv) + accum = max(0.0, cost - bv) + annual_charge = 0.0 if yrs >= life else annual + return (bv, accum, annual_charge) + + +# --------------------------------------------------------------------------- +# (a) Depreciation +# --------------------------------------------------------------------------- + +def depreciation( + asset: dict[str, Any], + as_of: date, + settings: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + cfg = _merged_settings(settings) + acq_mode = (asset.get("acquisition_mode") or "purchased").lower() + if acq_mode == "rented": + return { + "applicable": False, + "reason": "rented", + "book_value": None, + "accumulated_depreciation": None, + "annual_charge": None, + "fully_depreciated": False, + "method": None, + "life": None, + "years_elapsed": None, + "salvage_value": None, + "inputs_used": {"acquisition_mode": "rented"}, + } + + cost = asset.get("purchase_value") + if cost is None or float(cost) <= 0: + return { + "applicable": False, + "reason": "Insufficient data: purchase_value", + "book_value": None, + "accumulated_depreciation": None, + "annual_charge": None, + "fully_depreciated": False, + "method": None, + "life": None, + "years_elapsed": None, + "salvage_value": None, + "inputs_used": {"purchase_value": cost}, + } + cost_f = float(cost) + + base_date = _to_date(asset.get("installation_date")) or _to_date(asset.get("purchase_date")) + if base_date is None: + return { + "applicable": False, + "reason": "Insufficient data: installation_date or purchase_date", + "book_value": None, + "accumulated_depreciation": None, + "annual_charge": None, + "fully_depreciated": False, + "method": None, + "life": None, + "years_elapsed": None, + "salvage_value": None, + "inputs_used": {"purchase_value": cost_f, "installation_date": None, "purchase_date": None}, + } + + life = ( + asset.get("useful_life_years") + or asset.get("category_default_useful_life_years") + or int(cfg["default_useful_life_years"]) + ) + life = max(1, int(life)) + + salv_pct = ( + float(asset["salvage_pct"]) + if asset.get("salvage_pct") is not None + else float(cfg["default_salvage_pct"]) + ) + salv_pct = max(0.0, min(50.0, salv_pct)) + + method = asset.get("depreciation_method") or str(cfg["default_depreciation_method"]) + if method not in ("straight_line", "written_down"): + method = "straight_line" + + days_elapsed = max(0, (as_of - base_date).days) + years_elapsed = days_elapsed / 365.25 + + bv, accum, annual_charge = _book_value_at_years(cost_f, life, salv_pct, method, years_elapsed) + salvage_value = cost_f * (salv_pct / 100.0) + fully_dep = years_elapsed >= life + + return { + "applicable": True, + "reason": None, + "book_value": round(bv, 2), + "accumulated_depreciation": round(accum, 2), + "annual_charge": round(annual_charge, 2), + "fully_depreciated": fully_dep, + "method": method, + "life": life, + "years_elapsed": round(years_elapsed, 4), + "salvage_pct": salv_pct, + "salvage_value": round(salvage_value, 2), + "inputs_used": { + "purchase_value": cost_f, + "base_date": str(base_date), + "as_of": str(as_of), + "useful_life_years": life, + "salvage_pct": salv_pct, + "depreciation_method": method, + }, + } + + +def depreciation_curve( + asset: dict[str, Any], + as_of: date, + settings: Optional[dict[str, Any]] = None, +) -> list[dict[str, Any]]: + dep = depreciation(asset, as_of, settings) + if not dep["applicable"]: + return [] + cost = float(asset["purchase_value"]) + life = int(dep["life"]) + salv_pct = float(dep["salvage_pct"]) + method = str(dep["method"]) + base_date = _to_date(asset.get("installation_date")) or _to_date(asset.get("purchase_date")) + base_year = base_date.year if base_date else as_of.year + + points: list[dict[str, Any]] = [] + for yr in range(0, life + 1): + bv, accum, _ = _book_value_at_years(cost, life, salv_pct, method, float(yr)) + points.append( + { + "year_index": yr, + "calendar_year": base_year + yr, + "label": f"Yr {yr} ({base_year + yr})", + "book_value": round(bv, 2), + "accumulated_depreciation": round(accum, 2), + } + ) + return points + + +# --------------------------------------------------------------------------- +# (b) Cost Analysis +# --------------------------------------------------------------------------- + +def cost_analysis( + asset: dict[str, Any], + contracts: list[dict[str, Any]], + complaints: list[dict[str, Any]], + pm_schedules: list[dict[str, Any]], + pm_records: list[dict[str, Any]], + as_of: date, + settings: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + cfg = _merged_settings(settings) + review_threshold = float(cfg["replacement_review_ratio"]) + acq_mode = (asset.get("acquisition_mode") or "purchased").lower() + pv = float(asset["purchase_value"]) if asset.get("purchase_value") is not None else None + + # 1. Contract cost to date (prorated across overlapping contracts up to as_of) + contract_cost = 0.0 + for c in contracts: + cval = c.get("contract_value") + s_d = _to_date(c.get("start_date")) + e_d = _to_date(c.get("end_date")) + if cval is None or s_d is None or e_d is None or as_of < s_d: + continue + total_days = max(1, (e_d - s_d).days + 1) + eff_end = min(as_of, e_d) + elapsed_days = max(0, (eff_end - s_d).days + 1) + contract_cost += float(cval) * (elapsed_days / float(total_days)) + + # 2. Repair and spare cost to date (complaints registered on or before as_of) + repair_and_spare_cost = 0.0 + for comp in complaints: + reg_d = _to_date(comp.get("registered_at")) + if reg_d is not None and reg_d > as_of: + continue + repair_and_spare_cost += float(comp.get("repair_cost") or 0.0) + float( + comp.get("spare_cost_estimate") or 0.0 + ) + + # 3. In-house PM cost to date (completed visits * schedule.cost_per_visit) + sched_cost_map: dict[int, float] = {} + for s in pm_schedules: + if s.get("service_mode") == "in_house" and s.get("cost_per_visit") is not None: + sched_cost_map[int(s["id"])] = float(s["cost_per_visit"]) + + inhouse_pm_cost = 0.0 + inhouse_visits_completed = 0 + for rec in pm_records: + if rec.get("status") != "completed": + continue + comp_d = _to_date(rec.get("completed_date")) or _to_date(rec.get("planned_date")) + if comp_d is not None and comp_d > as_of: + continue + sid = rec.get("schedule_id") + if sid is not None and int(sid) in sched_cost_map: + inhouse_pm_cost += sched_cost_map[int(sid)] + inhouse_visits_completed += 1 + + maintenance_cost = contract_cost + repair_and_spare_cost + inhouse_pm_cost + base_date = _to_date(asset.get("installation_date")) or _to_date(asset.get("purchase_date")) + years_used: Optional[float] = None + if base_date is not None: + days_used = max(0, (as_of - base_date).days) + years_used = days_used / 365.25 + + if acq_mode == "rented": + m_rent = float(asset["monthly_rent"]) if asset.get("monthly_rent") is not None else None + rent_to_date = (m_rent * (years_used * 12.0)) if (m_rent is not None and years_used is not None) else None + lifetime_cost = (rent_to_date + maintenance_cost) if rent_to_date is not None else None + maint_ratio = None + review_flag = False + else: + lifetime_cost = (pv + maintenance_cost) if pv is not None else None + maint_ratio = (maintenance_cost / pv) if (pv is not None and pv > 0) else None + review_flag = bool(maint_ratio is not None and maint_ratio >= review_threshold) + + cost_per_year = ( + round(lifetime_cost / max(years_used, 1.0 / 12.0), 2) + if (lifetime_cost is not None and years_used is not None and years_used > 0) + else None + ) + + return { + "purchase_value": round(pv, 2) if pv is not None else None, + "contract_cost_to_date": round(contract_cost, 2), + "repair_and_spare_cost_to_date": round(repair_and_spare_cost, 2), + "inhouse_pm_cost_to_date": round(inhouse_pm_cost, 2), + "inhouse_visits_completed": inhouse_visits_completed, + "maintenance_cost": round(maintenance_cost, 2), + "lifetime_cost": round(lifetime_cost, 2) if lifetime_cost is not None else None, + "maintenance_ratio": round(maint_ratio, 4) if maint_ratio is not None else None, + "cost_per_year_of_use": cost_per_year, + "review_flag": review_flag, + "review_threshold": review_threshold, + } + + +# --------------------------------------------------------------------------- +# (c) Scenario Comparison (In-House vs Outsourced vs Rent) +# --------------------------------------------------------------------------- + +def _latest_contract_for_comparison(contracts: list[dict[str, Any]]) -> Optional[dict[str, Any]]: + non_sup = [c for c in contracts if not c.get("is_superseded")] + pool = non_sup if non_sup else list(contracts) + if not pool: + return None + pool.sort( + key=lambda c: ( + _to_date(c.get("end_date")) or date.min, + int(c.get("id") or 0), + ), + reverse=True, + ) + return pool[0] + + +def scenario_comparison( + asset: dict[str, Any], + contracts: list[dict[str, Any]], + complaints: list[dict[str, Any]], + pm_schedules: list[dict[str, Any]], + horizon_years: Optional[int] = None, + as_of: Optional[date] = None, + settings: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + cfg = _merged_settings(settings) + horizon = int(horizon_years if horizon_years is not None else cfg["comparison_horizon_years"]) + ref_date = as_of or date.today() + acq_mode = (asset.get("acquisition_mode") or "purchased").lower() + + pv = float(asset["purchase_value"]) if asset.get("purchase_value") is not None else None + monthly_rent = float(asset["monthly_rent"]) if asset.get("monthly_rent") is not None else None + + life = ( + asset.get("useful_life_years") + or asset.get("category_default_useful_life_years") + or int(cfg["default_useful_life_years"]) + ) + life = max(1, int(life)) + salv_pct = ( + float(asset["salvage_pct"]) + if asset.get("salvage_pct") is not None + else float(cfg["default_salvage_pct"]) + ) + method = asset.get("depreciation_method") or str(cfg["default_depreciation_method"]) + if method not in ("straight_line", "written_down"): + method = "straight_line" + + book_value_at_horizon: Optional[float] = None + dep_loss_over_horizon: Optional[float] = None + if pv is not None and pv > 0: + bv_h, _, _ = _book_value_at_years(pv, life, salv_pct, method, float(horizon)) + book_value_at_horizon = round(bv_h, 2) + dep_loss_over_horizon = round(pv - bv_h, 2) + + # Annual breakdown cost over last 12 months relative to ref_date + cutoff_12m = ref_date - timedelta(days=365) + annual_repair_only = 0.0 + annual_spare_only = 0.0 + for comp in complaints: + reg_d = _to_date(comp.get("registered_at")) + if reg_d is not None and (reg_d < cutoff_12m or reg_d > ref_date): + continue + annual_repair_only += float(comp.get("repair_cost") or 0.0) + annual_spare_only += float(comp.get("spare_cost_estimate") or 0.0) + annual_breakdown_full = annual_repair_only + annual_spare_only + + # Active in-house PM schedule + inhouse_scheds = [ + s for s in pm_schedules if s.get("service_mode") == "in_house" and s.get("is_active", True) + ] + outsourced_scheds = [ + s for s in pm_schedules if s.get("service_mode") == "outsourced" and s.get("is_active", True) + ] + inhouse_sched = inhouse_scheds[0] if inhouse_scheds else None + + annual_inhouse_cost: Optional[float] = None + if inhouse_sched and inhouse_sched.get("cost_per_visit") is not None: + freq_m = max(1, int(inhouse_sched.get("frequency_months") or 6)) + visits_per_year = 12.0 / float(freq_m) + annual_inhouse_cost = float(inhouse_sched["cost_per_visit"]) * visits_per_year + + # Latest contract + latest_contract = _latest_contract_for_comparison(contracts) + annual_contract_cost: Optional[float] = None + contract_type: Optional[str] = None + if latest_contract and latest_contract.get("contract_value") is not None: + contract_type = (latest_contract.get("contract_type") or "").upper() + s_d = _to_date(latest_contract.get("start_date")) + e_d = _to_date(latest_contract.get("end_date")) + if s_d is not None and e_d is not None and e_d >= s_d: + days = (e_d - s_d).days + 1 + contract_years = 1.0 if 364 <= days <= 366 else max(days / 365.25, 1.0 / 365.25) + annual_contract_cost = float(latest_contract["contract_value"]) / contract_years + + # Scenario A: Buy + in-house maintenance + if pv is None or pv <= 0: + scen_a = { + "key": "in_house", + "label": "Buy + In-House Maintenance", + "available": False, + "total_cost": None, + "insufficient_reason": "Insufficient data: purchase_value", + "breakdown": None, + } + elif annual_inhouse_cost is None: + scen_a = { + "key": "in_house", + "label": "Buy + In-House Maintenance", + "available": False, + "total_cost": None, + "insufficient_reason": "Insufficient data: in-house PM cost_per_visit", + "breakdown": None, + } + else: + total_a = dep_loss_over_horizon + horizon * annual_inhouse_cost + horizon * annual_breakdown_full + scen_a = { + "key": "in_house", + "label": "Buy + In-House Maintenance", + "available": True, + "total_cost": round(total_a, 2), + "insufficient_reason": None, + "breakdown": { + "depreciation_loss": round(dep_loss_over_horizon, 2), + "pm_total": round(horizon * annual_inhouse_cost, 2), + "breakdown_total": round(horizon * annual_breakdown_full, 2), + }, + } + + # Scenario B: Buy + outsourced contract (AMC/CMC) + # CMC excludes spare_cost_estimate because CMC covers parts; repair_cost is kept. + if pv is None or pv <= 0: + scen_b = { + "key": "outsourced", + "label": "Buy + Outsourced Contract (AMC/CMC)", + "available": False, + "total_cost": None, + "insufficient_reason": "Insufficient data: purchase_value", + "breakdown": None, + } + elif annual_contract_cost is None: + scen_b = { + "key": "outsourced", + "label": "Buy + Outsourced Contract (AMC/CMC)", + "available": False, + "total_cost": None, + "insufficient_reason": "Insufficient data: contract_value", + "breakdown": None, + } + else: + b_annual_breakdown = ( + annual_repair_only if contract_type == "CMC" else annual_breakdown_full + ) + total_b = dep_loss_over_horizon + horizon * annual_contract_cost + horizon * b_annual_breakdown + scen_b = { + "key": "outsourced", + "label": f"Buy + Outsourced ({contract_type or 'AMC/CMC'})", + "available": True, + "total_cost": round(total_b, 2), + "insufficient_reason": None, + "breakdown": { + "depreciation_loss": round(dep_loss_over_horizon, 2), + "contract_total": round(horizon * annual_contract_cost, 2), + "breakdown_total": round(horizon * b_annual_breakdown, 2), + "cmc_spares_excluded": contract_type == "CMC", + }, + } + + # Scenario C: Rent + if monthly_rent is None or monthly_rent <= 0: + scen_c = { + "key": "rent", + "label": "Rent", + "available": False, + "total_cost": None, + "insufficient_reason": "Insufficient data: monthly_rent", + "breakdown": None, + } + else: + total_c = monthly_rent * 12.0 * horizon + scen_c = { + "key": "rent", + "label": "Rent", + "available": True, + "total_cost": round(total_c, 2), + "insufficient_reason": None, + "breakdown": { + "monthly_rent": round(monthly_rent, 2), + "months": 12 * horizon, + }, + } + + scenarios = {"in_house": scen_a, "outsourced": scen_b, "rent": scen_c} + available = [s for s in (scen_a, scen_b, scen_c) if s["available"] and s["total_cost"] is not None] + available.sort(key=lambda s: s["total_cost"]) + + lowest = available[0] if len(available) >= 1 else None + second_lowest = available[1] if len(available) >= 2 else None + diff_to_next = ( + round(second_lowest["total_cost"] - lowest["total_cost"], 2) + if (lowest and second_lowest) + else None + ) + + if acq_mode == "rented": + current_setup: Optional[str] = "rent" + elif inhouse_sched is not None: + current_setup = "in_house" + elif outsourced_scheds or latest_contract is not None: + current_setup = "outsourced" + else: + current_setup = None + + return { + "horizon_years": horizon, + "scenarios": scenarios, + "lowest_scenario": lowest["key"] if lowest else None, + "lowest_scenario_label": lowest["label"] if lowest else None, + "lowest_cost": lowest["total_cost"] if lowest else None, + "next_scenario": second_lowest["key"] if second_lowest else None, + "savings_vs_next": diff_to_next, + "current_setup": current_setup, + "inputs_used": { + "purchase_value": pv, + "book_value_at_horizon": book_value_at_horizon, + "annual_inhouse_cost": round(annual_inhouse_cost, 2) if annual_inhouse_cost is not None else None, + "annual_contract_cost": round(annual_contract_cost, 2) if annual_contract_cost is not None else None, + "contract_type": contract_type, + "annual_breakdown_cost": round(annual_breakdown_full, 2), + "annual_repair_cost": round(annual_repair_only, 2), + "annual_spare_cost": round(annual_spare_only, 2), + "monthly_rent": monthly_rent, + "useful_life_years": life, + "salvage_pct": salv_pct, + "depreciation_method": method, + }, + } + + +# --------------------------------------------------------------------------- +# (d) Breakdown Frequency +# --------------------------------------------------------------------------- + +def breakdown_frequency( + assets: list[dict[str, Any]], + complaints: list[dict[str, Any]], + period_start: date, + period_end: date, + effective_today_date: date, + settings: Optional[dict[str, Any]] = None, + now_utc: Optional[datetime] = None, +) -> dict[str, Any]: + cfg = _merged_settings(settings) + repeat_cnt = int(cfg["repeat_failure_count"]) + repeat_days = int(cfg["repeat_failure_days"]) + sched_hours_day = int(cfg["scheduled_hours_per_day"]) + milestone = str(cfg["downtime_end_milestone"]) + eff_now = now_utc or KOLKATA.localize(datetime.combine(effective_today_date, time(23, 59, 59))).astimezone(timezone.utc) + + period_days = max(1, (period_end - period_start).days + 1) + sched_hours_per_asset = period_days * sched_hours_day + + asset_by_id = {int(a["id"]): a for a in assets} + repeat_cutoff = effective_today_date - timedelta(days=repeat_days) + + period_complaints_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_by_id} + repeat_window_by_asset: dict[int, int] = {aid: 0 for aid in asset_by_id} + monthly_counts: dict[str, int] = {} + + # Seed every month in [period_start, period_end] with 0 so chart has continuous timeline + cur_m = date(period_start.year, period_start.month, 1) + end_m = date(period_end.year, period_end.month, 1) + while cur_m <= end_m: + monthly_counts[cur_m.strftime("%Y-%m")] = 0 + cur_m = add_months(cur_m, 1) + + for comp in complaints: + aid = int(comp["asset_id"]) + if aid not in asset_by_id: + continue + reg_d = _to_date(comp.get("registered_at")) + if reg_d is None: + continue + if repeat_cutoff <= reg_d <= effective_today_date: + repeat_window_by_asset[aid] = repeat_window_by_asset.get(aid, 0) + 1 + if period_start <= reg_d <= period_end: + period_complaints_by_asset[aid].append(comp) + ym = reg_d.strftime("%Y-%m") + monthly_counts[ym] = monthly_counts.get(ym, 0) + 1 + + per_asset: list[dict[str, Any]] = [] + dept_agg: dict[str, dict[str, Any]] = {} + cat_agg: dict[str, dict[str, Any]] = {} + + for aid, a in asset_by_id.items(): + cmps = period_complaints_by_asset.get(aid, []) + dt_list: list[int] = [] + for comp in cmps: + reg_dt = comp.get("registered_at") + if isinstance(reg_dt, str): + reg_dt = datetime.fromisoformat(reg_dt) + end_dt = comp.get(milestone) or eff_now + if isinstance(end_dt, str): + end_dt = datetime.fromisoformat(end_dt) + if isinstance(reg_dt, datetime) and isinstance(end_dt, datetime): + mins = max(0, int((_ensure_utc(end_dt) - _ensure_utc(reg_dt)).total_seconds() // 60)) + dt_list.append(mins) + + avg_dt_mins = round(sum(dt_list) / len(dt_list), 1) if dt_list else 0.0 + rw_count = repeat_window_by_asset.get(aid, 0) + is_repeat = rw_count >= repeat_cnt + + dept_name = a.get("department_name") or "Unassigned" + cat_name = a.get("category_name") or "Uncategorized" + + per_asset.append( + { + "asset_id": aid, + "asset_code": a["asset_code"], + "asset_name": a["name"], + "department_name": dept_name, + "category_name": cat_name, + "breakdown_count": len(cmps), + "avg_downtime_minutes": avg_dt_mins, + "avg_downtime_hours": round(avg_dt_mins / 60.0, 2), + "repeat_window_count": rw_count, + "repeat_failure": is_repeat, + } + ) + + d_bucket = dept_agg.setdefault( + dept_name, + {"group": dept_name, "group_type": "department", "breakdowns": 0, "assets_in_scope": 0}, + ) + d_bucket["assets_in_scope"] += 1 + d_bucket["breakdowns"] += len(cmps) + + c_bucket = cat_agg.setdefault( + cat_name, + {"group": cat_name, "group_type": "category", "breakdowns": 0, "assets_in_scope": 0}, + ) + c_bucket["assets_in_scope"] += 1 + c_bucket["breakdowns"] += len(cmps) + + def _finalize_group(bucket: dict[str, Any]) -> dict[str, Any]: + n_assets = bucket["assets_in_scope"] + total_b = bucket["breakdowns"] + total_sched_h = n_assets * sched_hours_per_asset + avg_per_eq = round(total_b / n_assets, 2) if n_assets > 0 else 0.0 + per_1000 = round((total_b / total_sched_h) * 1000.0, 3) if total_sched_h > 0 else 0.0 + return { + **bucket, + "avg_breakdowns_per_equipment": avg_per_eq, + "breakdowns_per_1000_hours": per_1000, + } + + by_department = sorted( + [_finalize_group(b) for b in dept_agg.values()], + key=lambda r: (-r["breakdowns"], r["group"]), + ) + by_category = sorted( + [_finalize_group(b) for b in cat_agg.values()], + key=lambda r: (-r["breakdowns"], r["group"]), + ) + top_10_assets = sorted( + per_asset, + key=lambda r: (-r["breakdown_count"], -r["repeat_window_count"], r["asset_code"]), + )[:10] + + monthly_trend = [ + { + "month": ym, + "label": datetime.strptime(ym, "%Y-%m").strftime("%b %Y"), + "breakdowns": cnt, + } + for ym, cnt in sorted(monthly_counts.items()) + ] + + total_breakdowns = sum(r["breakdown_count"] for r in per_asset) + assets_count = len(per_asset) + overall_avg_per_eq = round(total_breakdowns / assets_count, 2) if assets_count > 0 else 0.0 + repeat_failure_assets = [r for r in per_asset if r["repeat_failure"]] + + evidence: list[dict[str, Any]] = [ + make_metric("m_bf_total_breakdowns", "Total Breakdowns in Period", total_breakdowns, "count"), + make_metric("m_bf_assets_in_scope", "Assets in Scope", assets_count, "count"), + make_metric( + "m_bf_avg_per_equipment", + "Average Breakdowns per Equipment", + overall_avg_per_eq, + "breakdowns/asset", + f"{overall_avg_per_eq:.2f}", + ), + make_metric( + "m_bf_repeat_failure_assets", + f"Repeat-Failure Assets (>={repeat_cnt} in {repeat_days}d)", + len(repeat_failure_assets), + "count", + ), + ] + for row in top_10_assets: + if row["breakdown_count"] > 0 or row["repeat_failure"]: + slug = _slug(row["asset_code"]) + evidence.append( + make_metric( + f"m_bf_count_{slug}", + f"Breakdowns ({row['asset_code']})", + row["breakdown_count"], + "count", + ) + ) + evidence.append( + make_metric( + f"m_bf_repeat_window_{slug}", + f"Breakdowns in Last {repeat_days}d ({row['asset_code']})", + row["repeat_window_count"], + "count", + ) + ) + + return { + "summary": { + "total_breakdowns": total_breakdowns, + "assets_in_scope": assets_count, + "avg_breakdowns_per_equipment": overall_avg_per_eq, + "repeat_failure_count": len(repeat_failure_assets), + "repeat_threshold": repeat_cnt, + "repeat_window_days": repeat_days, + }, + "per_asset": per_asset, + "by_department": by_department, + "by_category": by_category, + "top_10_assets": top_10_assets, + "monthly_trend": monthly_trend, + "evidence": evidence, + } + + +# --------------------------------------------------------------------------- +# (e) Efficiency +# --------------------------------------------------------------------------- + +def _compute_response_score(response_hours: float, target_sla_hours: float) -> float: + if target_sla_hours <= 0: + return 100.0 + if response_hours <= target_sla_hours: + return 100.0 + if response_hours >= 4.0 * target_sla_hours: + return 0.0 + return 100.0 * (4.0 * target_sla_hours - response_hours) / (3.0 * target_sla_hours) + + +def efficiency( + assets: list[dict[str, Any]], + complaints: list[dict[str, Any]], + pm_records: list[dict[str, Any]], + period_start: date, + period_end: date, + effective_today_date: date, + settings: Optional[dict[str, Any]] = None, + now_utc: Optional[datetime] = None, +) -> dict[str, Any]: + cfg = _merged_settings(settings) + sched_hours_day = int(cfg["scheduled_hours_per_day"]) + milestone = str(cfg["downtime_end_milestone"]) + response_start = str(cfg["response_start"]) + crit_sla = float(cfg["critical_complaint_sla_hours"]) + non_crit_sla = float(cfg["non_critical_complaint_sla_hours"]) + repeat_cnt = int(cfg["repeat_failure_count"]) + repeat_days = int(cfg["repeat_failure_days"]) + eff_now = now_utc or KOLKATA.localize(datetime.combine(effective_today_date, time(23, 59, 59))).astimezone(timezone.utc) + + period_days = max(1, (period_end - period_start).days + 1) + sched_mins_per_asset = period_days * sched_hours_day * 60 + sched_hours_per_asset = period_days * sched_hours_day + + # Exclude condemned assets from operational efficiency (matching Monthly Maintenance report) + active_assets = [a for a in assets if a.get("status") != "condemned"] + asset_ids = {int(a["id"]) for a in active_assets} + repeat_cutoff = effective_today_date - timedelta(days=repeat_days) + + complaints_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids} + repeat_window_by_asset: dict[int, int] = {aid: 0 for aid in asset_ids} + for comp in complaints: + aid = int(comp["asset_id"]) + if aid not in asset_ids: + continue + complaints_by_asset[aid].append(comp) + reg_d = _to_date(comp.get("registered_at")) + if reg_d is not None and repeat_cutoff <= reg_d <= effective_today_date: + repeat_window_by_asset[aid] = repeat_window_by_asset.get(aid, 0) + 1 + + pm_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids} + for rec in pm_records: + aid = int(rec["asset_id"]) + if aid not in asset_ids: + continue + p_d = _to_date(rec.get("planned_date")) + if p_d is not None and period_start <= p_d <= period_end: + pm_by_asset[aid].append(rec) + + per_asset: list[dict[str, Any]] = [] + all_mttr: list[float] = [] + all_resp_mins: list[int] = [] + total_pm_due = 0 + total_pm_on_time = 0 + + for a in active_assets: + aid = int(a["id"]) + cmps = complaints_by_asset.get(aid, []) + downtime_mins = 0 + period_breakdown_count = 0 + mttr_vals: list[float] = [] + resp_mins_vals: list[int] = [] + resp_scores: list[float] = [] + + for comp in cmps: + reg_dt = comp.get("registered_at") + if isinstance(reg_dt, str): + reg_dt = datetime.fromisoformat(reg_dt) + if not isinstance(reg_dt, datetime): + continue + + end_raw = comp.get(milestone) + if isinstance(end_raw, str): + end_raw = datetime.fromisoformat(end_raw) + end_dt = end_raw if isinstance(end_raw, datetime) else eff_now + + clipped = _clip_interval_to_period(reg_dt, end_dt, period_start, period_end) + downtime_mins += clipped + + reg_d = _to_date(reg_dt) + if reg_d is not None and period_start <= reg_d <= period_end: + period_breakdown_count += 1 + + # MTTR: restored_at or closed_at minus registered_at + res_raw = comp.get("restored_at") or comp.get("closed_at") + if isinstance(res_raw, str): + res_raw = datetime.fromisoformat(res_raw) + if isinstance(res_raw, datetime): + mttr_h = max(0.0, (_ensure_utc(res_raw) - _ensure_utc(reg_dt)).total_seconds() / 3600.0) + mttr_vals.append(mttr_h) + all_mttr.append(mttr_h) + + # Response time & SLA score + recv_raw = comp.get("received_at") + att_raw = comp.get("attended_at") + if isinstance(recv_raw, str): + recv_raw = datetime.fromisoformat(recv_raw) + if isinstance(att_raw, str): + att_raw = datetime.fromisoformat(att_raw) + rt_min = compute_response_time_minutes(reg_dt, recv_raw, att_raw, response_start=response_start) + if rt_min is not None: + resp_mins_vals.append(rt_min) + all_resp_mins.append(rt_min) + sla_target = crit_sla if comp.get("priority") == "critical" else non_crit_sla + resp_scores.append(_compute_response_score(rt_min / 60.0, sla_target)) + + uptime_mins = max(0, sched_mins_per_asset - downtime_mins) + uptime_pct = (uptime_mins / float(sched_mins_per_asset)) * 100.0 if sched_mins_per_asset > 0 else 100.0 + mttr_hours = round(sum(mttr_vals) / len(mttr_vals), 2) if mttr_vals else None + mtbf_hours = ( + round((sched_hours_per_asset - (downtime_mins / 60.0)) / float(period_breakdown_count), 2) + if period_breakdown_count > 0 + else None + ) + avg_resp_mins = round(sum(resp_mins_vals) / len(resp_mins_vals), 1) if resp_mins_vals else None + + # PM compliance in period: completed on time (completed_date <= planned_date) / due in period + pm_recs = pm_by_asset.get(aid, []) + due_in_period = len(pm_recs) + on_time_in_period = 0 + for rec in pm_recs: + if rec.get("status") == "completed": + p_d = _to_date(rec.get("planned_date")) + c_d = _to_date(rec.get("completed_date")) + if p_d is not None and c_d is not None and c_d <= p_d: + on_time_in_period += 1 + total_pm_due += due_in_period + total_pm_on_time += on_time_in_period + pm_compliance_pct = ( + (on_time_in_period / float(due_in_period)) * 100.0 if due_in_period > 0 else 100.0 + ) + + response_score = sum(resp_scores) / len(resp_scores) if resp_scores else 100.0 + is_repeat = repeat_window_by_asset.get(aid, 0) >= repeat_cnt + repeat_free_score = 0.0 if is_repeat else 100.0 + + w = EFFICIENCY_WEIGHTS + uptime_part = w["uptime"] * uptime_pct + pm_part = w["pm_compliance"] * pm_compliance_pct + resp_part = w["response"] * response_score + repeat_part = w["repeat_free"] * repeat_free_score + score = uptime_part + pm_part + resp_part + repeat_part + + per_asset.append( + { + "asset_id": aid, + "asset_code": a["asset_code"], + "asset_name": a["name"], + "department_name": a.get("department_name") or "Unassigned", + "category_name": a.get("category_name") or "Uncategorized", + "scheduled_minutes": sched_mins_per_asset, + "downtime_minutes": downtime_mins, + "uptime_pct": round(uptime_pct, 2), + "mttr_hours": mttr_hours, + "mtbf_hours": mtbf_hours, + "mtbf_formatted": f"{mtbf_hours:.1f} hrs" if mtbf_hours is not None else "No failures", + "avg_response_minutes": avg_resp_mins, + "pm_compliance_pct": round(pm_compliance_pct, 2), + "pm_due_count": due_in_period, + "pm_on_time_count": on_time_in_period, + "response_score": round(response_score, 2), + "repeat_free_score": round(repeat_free_score, 2), + "efficiency_score": round(score, 2), + "parts": { + "uptime": round(uptime_part, 2), + "pm_compliance": round(pm_part, 2), + "response": round(resp_part, 2), + "repeat_free": round(repeat_part, 2), + }, + } + ) + + def _aggregate_group(rows: list[dict[str, Any]], key_field: str, group_type: str) -> list[dict[str, Any]]: + buckets: dict[str, list[dict[str, Any]]] = {} + for r in rows: + buckets.setdefault(r[key_field], []).append(r) + out: list[dict[str, Any]] = [] + for gname, items in sorted(buckets.items()): + tot_w = sum(i["scheduled_minutes"] for i in items) + if tot_w <= 0: + continue + w_avg = lambda f: round(sum(i[f] * i["scheduled_minutes"] for i in items) / tot_w, 2) + w_part = lambda p: round(sum(i["parts"][p] * i["scheduled_minutes"] for i in items) / tot_w, 2) + g_mttr = [i["mttr_hours"] for i in items if i["mttr_hours"] is not None] + g_mtbf = [i["mtbf_hours"] for i in items if i["mtbf_hours"] is not None] + out.append( + { + "group": gname, + "group_type": group_type, + "asset_count": len(items), + "uptime_pct": w_avg("uptime_pct"), + "pm_compliance_pct": w_avg("pm_compliance_pct"), + "response_score": w_avg("response_score"), + "repeat_free_score": w_avg("repeat_free_score"), + "mttr_hours": round(sum(g_mttr) / len(g_mttr), 2) if g_mttr else None, + "mtbf_hours": round(sum(g_mtbf) / len(g_mtbf), 2) if g_mtbf else None, + "mtbf_formatted": ( + f"{(sum(g_mtbf) / len(g_mtbf)):.1f} hrs" if g_mtbf else "No failures" + ), + "efficiency_score": w_avg("efficiency_score"), + "parts": { + "uptime": w_part("uptime"), + "pm_compliance": w_part("pm_compliance"), + "response": w_part("response"), + "repeat_free": w_part("repeat_free"), + }, + } + ) + out.sort(key=lambda r: (r["efficiency_score"], r["group"])) + return out + + by_department = _aggregate_group(per_asset, "department_name", "department") + by_category = _aggregate_group(per_asset, "category_name", "category") + + tot_sched = sum(r["scheduled_minutes"] for r in per_asset) + if tot_sched > 0: + avg_uptime = round(sum(r["uptime_pct"] * r["scheduled_minutes"] for r in per_asset) / tot_sched, 2) + avg_score = round(sum(r["efficiency_score"] * r["scheduled_minutes"] for r in per_asset) / tot_sched, 2) + overall_pm_pct = ( + round((total_pm_on_time / float(total_pm_due)) * 100.0, 2) + if total_pm_due > 0 + else 100.0 + ) + else: + avg_uptime = 0.0 + avg_score = 0.0 + overall_pm_pct = 0.0 + + overall_mttr = round(sum(all_mttr) / len(all_mttr), 2) if all_mttr else None + total_breakdowns = sum( + 1 + for a in active_assets + for c in complaints_by_asset.get(int(a["id"]), []) + if _to_date(c.get("registered_at")) is not None + and period_start <= _to_date(c.get("registered_at")) <= period_end + ) + total_dt_hours = sum(r["downtime_minutes"] for r in per_asset) / 60.0 + total_sched_hours = tot_sched / 60.0 + overall_mtbf = ( + round((total_sched_hours - total_dt_hours) / float(total_breakdowns), 2) + if total_breakdowns > 0 + else None + ) + overall_resp = round(sum(all_resp_mins) / len(all_resp_mins), 1) if all_resp_mins else None + + evidence: list[dict[str, Any]] = [ + make_metric("m_eff_avg_score", "Average Efficiency Score", avg_score, "score", f"{avg_score:.1f} / 100"), + make_metric("m_eff_avg_uptime", "Average Uptime", avg_uptime, "%"), + make_metric("m_eff_pm_compliance", "PM On-Time Compliance", overall_pm_pct, "%"), + make_metric( + "m_eff_mttr_hours", + "Mean Time To Repair (MTTR)", + overall_mttr, + "hours", + f"{overall_mttr:.1f} hrs" if overall_mttr is not None else "No repairs", + ), + make_metric( + "m_eff_mtbf_hours", + "Mean Time Between Failures (MTBF)", + overall_mtbf, + "hours", + f"{overall_mtbf:.1f} hrs" if overall_mtbf is not None else "No failures", + ), + make_metric( + "m_eff_avg_response_min", + "Average Response Time", + overall_resp, + "minutes", + f"{overall_resp:.1f} mins" if overall_resp is not None else "—", + ), + ] + for g in by_department: + evidence.append( + make_metric( + f"m_eff_dept_{_slug(g['group'])}", + f"Efficiency Score ({g['group']})", + g["efficiency_score"], + "score", + f"{g['efficiency_score']:.1f}", + ) + ) + + return { + "weights": dict(EFFICIENCY_WEIGHTS), + "summary": { + "avg_uptime_pct": avg_uptime, + "mttr_hours": overall_mttr, + "mtbf_hours": overall_mtbf, + "mtbf_formatted": f"{overall_mtbf:.1f} hrs" if overall_mtbf is not None else "No failures", + "avg_response_minutes": overall_resp, + "pm_compliance_pct": overall_pm_pct, + "avg_efficiency_score": avg_score, + "assets_evaluated": len(per_asset), + }, + "per_asset": per_asset, + "by_department": by_department, + "by_category": by_category, + "evidence": evidence, + } + + +# --------------------------------------------------------------------------- +# Thin DB Loaders & Section Builders +# --------------------------------------------------------------------------- + +def load_ai_settings(db: Session) -> dict[str, Any]: + out: dict[str, Any] = {} + for key, default in DEFAULT_AI_SETTINGS.items(): + val = get_setting_value(db, key, default) + out[key] = default if val is None else val + return out + + +def resolve_period( + db: Session, + period: str = "12m", + date_from: Optional[date] = None, + date_to: Optional[date] = None, +) -> tuple[date, date]: + today = effective_today(db) + if period == "custom" and date_from is not None and date_to is not None: + return (min(date_from, date_to), max(date_from, date_to)) + months_map = {"3m": 3, "6m": 6, "12m": 12} + months = months_map.get(period, 12) + start = add_months(today, -months) + return (start, today) + + +def load_ai_dataset( + db: Session, + user: User, + period_start: date, + period_end: date, + department_id: Optional[int] = None, + category_id: Optional[int] = None, +) -> dict[str, Any]: + today = effective_today(db) + eff_now = effective_now_utc(db) + cfg = load_ai_settings(db) + scope = resolve_department_scope(user, department_id) + + if scope.is_empty: + return { + "today": today, + "now_utc": eff_now, + "period_start": period_start, + "period_end": period_end, + "settings": cfg, + "assets": [], + "contracts_by_asset": {}, + "complaints": [], + "complaints_by_asset": {}, + "pm_schedules_by_asset": {}, + "pm_records": [], + "pm_records_by_asset": {}, + "coverage_by_asset": {}, + "cal_records_by_asset": {}, + "cal_plans_by_asset": {}, + "warranties_by_asset": {}, + } + + asset_q = db.query(Asset).options( + joinedload(Asset.category), + joinedload(Asset.department), + joinedload(Asset.location), + ) + if scope.department_id is not None: + asset_q = asset_q.filter(Asset.department_id == scope.department_id) + if category_id is not None: + asset_q = asset_q.filter(Asset.category_id == category_id) + asset_objs = asset_q.order_by(Asset.asset_code.asc()).all() + asset_ids = [a.id for a in asset_objs] + + assets_plain: list[dict[str, Any]] = [ + { + "id": a.id, + "asset_code": a.asset_code, + "name": a.name, + "category_id": a.category_id, + "category_name": a.category.name if a.category else "Uncategorized", + "category_default_useful_life_years": ( + a.category.default_useful_life_years if a.category else None + ), + "department_id": a.department_id, + "department_name": a.department.name if a.department else "Unassigned", + "purchase_value": a.purchase_value, + "acquisition_mode": a.acquisition_mode or "purchased", + "monthly_rent": a.monthly_rent, + "useful_life_years": a.useful_life_years, + "salvage_pct": a.salvage_pct, + "depreciation_method": a.depreciation_method, + "purchase_date": a.purchase_date, + "installation_date": a.installation_date, + "status": a.status, + "criticality": a.criticality, + "requires_calibration": a.requires_calibration, + } + for a in asset_objs + ] + + contracts_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids} + if asset_ids: + for c in db.query(Contract).filter(Contract.asset_id.in_(asset_ids)).all(): + contracts_by_asset[c.asset_id].append( + { + "id": c.id, + "asset_id": c.asset_id, + "contract_type": c.contract_type, + "provider_id": c.provider_id, + "start_date": c.start_date, + "end_date": c.end_date, + "contract_value": c.contract_value, + "is_superseded": c.is_superseded, + } + ) + + complaints_plain: list[dict[str, Any]] = [] + complaints_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids} + if asset_ids: + for comp in db.query(Complaint).filter(Complaint.asset_id.in_(asset_ids)).all(): + item = { + "id": comp.id, + "complaint_no": comp.complaint_no, + "asset_id": comp.asset_id, + "priority": comp.priority, + "call_status": comp.call_status, + "registered_at": comp.registered_at, + "received_at": comp.received_at, + "attended_at": comp.attended_at, + "restored_at": comp.restored_at, + "closed_at": comp.closed_at, + "repair_cost": comp.repair_cost, + "spare_cost_estimate": comp.spare_cost_estimate, + "coverage_tag": comp.coverage_tag, + } + complaints_plain.append(item) + complaints_by_asset[comp.asset_id].append(item) + + pm_schedules_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids} + if asset_ids: + for s in db.query(PMSchedule).filter(PMSchedule.asset_id.in_(asset_ids)).all(): + pm_schedules_by_asset[s.asset_id].append( + { + "id": s.id, + "asset_id": s.asset_id, + "service_mode": s.service_mode, + "frequency_months": s.frequency_months, + "cost_per_visit": s.cost_per_visit, + "next_planned_date": s.next_planned_date, + "is_active": s.is_active, + } + ) + + pm_records_plain: list[dict[str, Any]] = [] + pm_records_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids} + if asset_ids: + for r in db.query(PMRecord).filter(PMRecord.asset_id.in_(asset_ids)).all(): + item = { + "id": r.id, + "schedule_id": r.schedule_id, + "asset_id": r.asset_id, + "planned_date": r.planned_date, + "completed_date": r.completed_date, + "status": r.status, + } + pm_records_plain.append(item) + pm_records_by_asset[r.asset_id].append(item) + + cal_plans_by_asset: dict[int, dict[str, Any]] = {} + cal_records_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids} + if asset_ids: + for p in db.query(CalibrationPlan).filter(CalibrationPlan.asset_id.in_(asset_ids), CalibrationPlan.is_active.is_(True)).all(): + cal_plans_by_asset[p.asset_id] = { + "id": p.id, + "asset_id": p.asset_id, + "next_due_date": p.next_due_date, + } + for cr in db.query(CalibrationRecord).filter(CalibrationRecord.asset_id.in_(asset_ids)).all(): + cal_records_by_asset[cr.asset_id].append( + { + "id": cr.id, + "asset_id": cr.asset_id, + "due_date": cr.due_date, + "completed_date": cr.completed_date, + "status": cr.status, + } + ) + + coverage_by_asset = get_coverage_map(db, asset_ids, today) if asset_ids else {} + + return { + "today": today, + "now_utc": eff_now, + "period_start": period_start, + "period_end": period_end, + "settings": cfg, + "assets": assets_plain, + "contracts_by_asset": contracts_by_asset, + "complaints": complaints_plain, + "complaints_by_asset": complaints_by_asset, + "pm_schedules_by_asset": pm_schedules_by_asset, + "pm_records": pm_records_plain, + "pm_records_by_asset": pm_records_by_asset, + "coverage_by_asset": coverage_by_asset, + "cal_plans_by_asset": cal_plans_by_asset, + "cal_records_by_asset": cal_records_by_asset, + } + + +def compute_comparison_from_dataset(dataset: dict[str, Any]) -> dict[str, Any]: + cfg = dataset["settings"] + today = dataset["today"] + horizon = int(cfg["comparison_horizon_years"]) + latest_n = int(cfg["latest_equipment_count"]) + + # Latest equipment = most recent installation_date (fallback purchase_date) + def _recency_key(a: dict[str, Any]) -> tuple[date, str]: + d = _to_date(a.get("installation_date")) or _to_date(a.get("purchase_date")) or date.min + return (d, a["asset_code"]) + + dated_assets = [ + a + for a in dataset["assets"] + if (_to_date(a.get("installation_date")) or _to_date(a.get("purchase_date"))) is not None + ] + dated_assets.sort(key=lambda a: (_recency_key(a)[0], a["asset_code"]), reverse=True) + latest_assets = dated_assets[:latest_n] + + rows: list[dict[str, Any]] = [] + chart_data: list[dict[str, Any]] = [] + evidence: list[dict[str, Any]] = [ + make_metric("m_cmp_horizon_years", "Comparison Horizon", horizon, "years", f"{horizon} years"), + make_metric("m_cmp_latest_count", "Latest Equipment Evaluated", len(latest_assets), "count"), + ] + + lowest_counts: dict[str, int] = {"in_house": 0, "outsourced": 0, "rent": 0} + total_potential_savings = 0.0 + + for a in latest_assets: + aid = int(a["id"]) + comp = scenario_comparison( + a, + dataset["contracts_by_asset"].get(aid, []), + dataset["complaints_by_asset"].get(aid, []), + dataset["pm_schedules_by_asset"].get(aid, []), + horizon_years=horizon, + as_of=today, + settings=cfg, + ) + sc = comp["scenarios"] + if comp["lowest_scenario"] in lowest_counts: + lowest_counts[comp["lowest_scenario"]] += 1 + if comp["savings_vs_next"] is not None: + total_potential_savings += float(comp["savings_vs_next"]) + + slug = _slug(a["asset_code"]) + if comp["lowest_cost"] is not None: + evidence.append( + make_metric( + f"m_cmp_lowest_{slug}", + f"Lowest {horizon}-yr Cost ({a['asset_code']} - {comp['lowest_scenario_label']})", + comp["lowest_cost"], + "INR", + ) + ) + if comp["savings_vs_next"] is not None: + evidence.append( + make_metric( + f"m_cmp_diff_{slug}", + f"Savings vs Next Option ({a['asset_code']})", + comp["savings_vs_next"], + "INR", + ) + ) + + rows.append( + { + "asset_id": aid, + "asset_code": a["asset_code"], + "asset_name": a["name"], + "department_name": a["department_name"], + "category_name": a["category_name"], + "installation_date": str(a["installation_date"]) if a.get("installation_date") else None, + "purchase_date": str(a["purchase_date"]) if a.get("purchase_date") else None, + "purchase_value": a.get("purchase_value"), + "in_house_cost": sc["in_house"]["total_cost"], + "in_house_reason": sc["in_house"]["insufficient_reason"], + "outsourced_cost": sc["outsourced"]["total_cost"], + "outsourced_reason": sc["outsourced"]["insufficient_reason"], + "rent_cost": sc["rent"]["total_cost"], + "rent_reason": sc["rent"]["insufficient_reason"], + "lowest_scenario": comp["lowest_scenario"], + "lowest_scenario_label": comp["lowest_scenario_label"], + "lowest_cost": comp["lowest_cost"], + "savings_vs_next": comp["savings_vs_next"], + "current_setup": comp["current_setup"], + "inputs_used": comp["inputs_used"], + } + ) + chart_data.append( + { + "asset_code": a["asset_code"], + "asset_name": a["name"], + "in_house": sc["in_house"]["total_cost"], + "outsourced": sc["outsourced"]["total_cost"], + "rent": sc["rent"]["total_cost"], + } + ) + + evidence.append( + make_metric("m_cmp_inhouse_wins", "Equipment Where In-House Is Lowest", lowest_counts["in_house"], "count") + ) + evidence.append( + make_metric("m_cmp_outsourced_wins", "Equipment Where Outsourced Is Lowest", lowest_counts["outsourced"], "count") + ) + evidence.append( + make_metric("m_cmp_rent_wins", "Equipment Where Rent Is Lowest", lowest_counts["rent"], "count") + ) + + return { + "section": "comparison", + "title": "Comparison: In-House vs Outsourced vs Rent", + "horizon_years": horizon, + "summary": { + "latest_count": len(latest_assets), + "horizon_years": horizon, + "in_house_lowest_count": lowest_counts["in_house"], + "outsourced_lowest_count": lowest_counts["outsourced"], + "rent_lowest_count": lowest_counts["rent"], + }, + "rows": rows, + "chart_data": chart_data, + "metrics": evidence, + "how_calculated": { + "formulas": [ + "Buy + In-House = (Purchase Value - Book Value at Horizon) + Horizon × Annual In-House PM Cost + Horizon × Annual Breakdown Cost", + "Buy + Outsourced (AMC/CMC) = (Purchase Value - Book Value at Horizon) + Horizon × Annual Contract Cost + Horizon × Annual Breakdown Cost (CMC excludes spare cost estimate)", + "Rent = Monthly Rent × 12 × Horizon", + ], + "latest_equipment_rule": f"Top {latest_n} assets ordered by most recent installation_date (falling back to purchase_date).", + "missing_data_rule": "Any missing required input marks that scenario 'Insufficient data: ' and excludes it from totals.", + "settings_used": { + "comparison_horizon_years": horizon, + "latest_equipment_count": latest_n, + }, + }, + } + + +def compute_depreciation_from_dataset(dataset: dict[str, Any]) -> dict[str, Any]: + cfg = dataset["settings"] + today = dataset["today"] + threshold = float(cfg["replacement_review_ratio"]) + + rows: list[dict[str, Any]] = [] + curves_by_asset: dict[str, list[dict[str, Any]]] = {} + total_purchase = 0.0 + total_book = 0.0 + total_accum = 0.0 + total_maint = 0.0 + fully_dep_count = 0 + review_flag_count = 0 + excluded_count = 0 + + for a in dataset["assets"]: + aid = int(a["id"]) + dep = depreciation(a, today, cfg) + ca = cost_analysis( + a, + dataset["contracts_by_asset"].get(aid, []), + dataset["complaints_by_asset"].get(aid, []), + dataset["pm_schedules_by_asset"].get(aid, []), + dataset["pm_records_by_asset"].get(aid, []), + today, + cfg, + ) + if dep["applicable"]: + total_purchase += float(a["purchase_value"]) + total_book += float(dep["book_value"]) + total_accum += float(dep["accumulated_depreciation"]) + total_maint += float(ca["maintenance_cost"]) + if dep["fully_depreciated"]: + fully_dep_count += 1 + curves_by_asset[a["asset_code"]] = depreciation_curve(a, today, cfg) + else: + excluded_count += 1 + + if ca["review_flag"]: + review_flag_count += 1 + + rows.append( + { + "asset_id": aid, + "asset_code": a["asset_code"], + "asset_name": a["name"], + "department_name": a["department_name"], + "category_name": a["category_name"], + "acquisition_mode": a.get("acquisition_mode") or "purchased", + "purchase_value": ca["purchase_value"], + "depreciation_applicable": dep["applicable"], + "depreciation_reason": dep["reason"], + "method": dep["method"], + "useful_life_years": dep["life"], + "book_value": dep["book_value"], + "accumulated_depreciation": dep["accumulated_depreciation"], + "annual_charge": dep["annual_charge"], + "fully_depreciated": dep["fully_depreciated"], + "contract_cost_to_date": ca["contract_cost_to_date"], + "repair_and_spare_cost_to_date": ca["repair_and_spare_cost_to_date"], + "inhouse_pm_cost_to_date": ca["inhouse_pm_cost_to_date"], + "maintenance_cost": ca["maintenance_cost"], + "maintenance_ratio": ca["maintenance_ratio"], + "lifetime_cost": ca["lifetime_cost"], + "cost_per_year_of_use": ca["cost_per_year_of_use"], + "review_flag": ca["review_flag"], + "curve": curves_by_asset.get(a["asset_code"], []), + } + ) + + evidence: list[dict[str, Any]] = [ + make_metric("m_dep_total_purchase_value", "Total Purchase Value (Owned Assets)", round(total_purchase, 2), "INR"), + make_metric("m_dep_total_book_value", "Total Current Book Value", round(total_book, 2), "INR"), + make_metric("m_dep_total_accumulated", "Total Accumulated Depreciation", round(total_accum, 2), "INR"), + make_metric("m_dep_total_maintenance", "Total Maintenance Cost to Date", round(total_maint, 2), "INR"), + make_metric("m_dep_fully_depreciated_count", "Fully Depreciated Assets", fully_dep_count, "count"), + make_metric("m_dep_review_flag_count", f"Assets Above {int(threshold * 100)}% Maintenance Ratio", review_flag_count, "count"), + make_metric("m_dep_excluded_count", "Assets Excluded (Rented / Missing Inputs)", excluded_count, "count"), + ] + for r in rows: + if r["review_flag"] or r["fully_depreciated"]: + slug = _slug(r["asset_code"]) + if r["book_value"] is not None: + evidence.append( + make_metric( + f"m_dep_book_value_{slug}", + f"Book Value ({r['asset_code']})", + r["book_value"], + "INR", + ) + ) + if r["maintenance_ratio"] is not None: + evidence.append( + make_metric( + f"m_dep_maint_ratio_{slug}", + f"Maintenance Ratio ({r['asset_code']})", + round(r["maintenance_ratio"] * 100.0, 1), + "%", + ) + ) + + default_curve = next((r["curve"] for r in rows if r["curve"]), []) + return { + "section": "depreciation", + "title": "Depreciated Price & Cost Analysis", + "summary": { + "total_purchase_value": round(total_purchase, 2), + "total_book_value": round(total_book, 2), + "total_accumulated_depreciation": round(total_accum, 2), + "total_maintenance_cost": round(total_maint, 2), + "fully_depreciated_count": fully_dep_count, + "review_flag_count": review_flag_count, + "replacement_review_ratio": threshold, + "excluded_count": excluded_count, + }, + "rows": rows, + "chart_data": default_curve, + "metrics": evidence, + "how_calculated": { + "formulas": [ + "Straight Line: Annual Charge = (Cost - Salvage) / Life; Book Value = max(Salvage, Cost - Annual Charge × Years Elapsed)", + "Written Down Value: Rate = 1 - (Salvage / Cost)^(1 / Life); Book Value = max(Salvage, Cost × (1 - Rate)^Years Elapsed)", + "Maintenance Cost = Prorated Contract Cost + Repair & Spare Cost + Completed In-House PM Cost", + f"Replacement Review Flag = Maintenance Cost / Purchase Value >= {threshold:.2f}", + ], + "settings_used": { + "default_useful_life_years": cfg["default_useful_life_years"], + "default_salvage_pct": cfg["default_salvage_pct"], + "default_depreciation_method": cfg["default_depreciation_method"], + "replacement_review_ratio": threshold, + }, + }, + } + + +def compute_efficiency_from_dataset(dataset: dict[str, Any]) -> dict[str, Any]: + res = efficiency( + dataset["assets"], + dataset["complaints"], + dataset["pm_records"], + dataset["period_start"], + dataset["period_end"], + dataset["today"], + settings=dataset["settings"], + now_utc=dataset["now_utc"], + ) + rows = res["by_department"] + res["by_category"] + chart_data = [ + { + "group": g["group"], + "uptime": g["parts"]["uptime"], + "pm_compliance": g["parts"]["pm_compliance"], + "response": g["parts"]["response"], + "repeat_free": g["parts"]["repeat_free"], + "efficiency_score": g["efficiency_score"], + } + for g in res["by_department"] + ] + return { + "section": "efficiency", + "title": "Equipment Efficiency", + "weights": res["weights"], + "summary": res["summary"], + "rows": rows, + "per_asset": res["per_asset"], + "by_department": res["by_department"], + "by_category": res["by_category"], + "chart_data": chart_data, + "metrics": res["evidence"], + "how_calculated": { + "formulas": [ + "Efficiency Score = 0.50 × Uptime% + 0.20 × PM Compliance% + 0.15 × Response Score + 0.15 × Repeat-Free Score", + "Uptime% = (Scheduled Minutes - Downtime Minutes) / Scheduled Minutes × 100", + "MTTR = Mean(Restored or Closed At - Registered At); MTBF = (Scheduled Hours - Downtime Hours) / Breakdown Count", + "Response Score = 100 if Avg Response <= SLA Target, falling linearly to 0 at 4 × SLA Target", + "Department & Category scores are weighted averages of their assets weighted by scheduled operating minutes.", + ], + "weights": dict(EFFICIENCY_WEIGHTS), + "settings_used": { + "scheduled_hours_per_day": dataset["settings"]["scheduled_hours_per_day"], + "downtime_end_milestone": dataset["settings"]["downtime_end_milestone"], + "critical_complaint_sla_hours": dataset["settings"]["critical_complaint_sla_hours"], + "non_critical_complaint_sla_hours": dataset["settings"]["non_critical_complaint_sla_hours"], + }, + }, + } + + +def compute_breakdown_frequency_from_dataset(dataset: dict[str, Any]) -> dict[str, Any]: + res = breakdown_frequency( + dataset["assets"], + dataset["complaints"], + dataset["period_start"], + dataset["period_end"], + dataset["today"], + settings=dataset["settings"], + now_utc=dataset["now_utc"], + ) + return { + "section": "breakdown_frequency", + "title": "Breakdown Frequency & Average Breakdowns", + "summary": res["summary"], + "rows": res["top_10_assets"], + "per_asset": res["per_asset"], + "by_department": res["by_department"], + "by_category": res["by_category"], + "chart_data": { + "monthly_trend": res["monthly_trend"], + "by_department": res["by_department"], + "by_category": res["by_category"], + }, + "metrics": res["evidence"], + "how_calculated": { + "formulas": [ + "Average Breakdowns per Equipment = Total Breakdowns in Period / Total Assets in Scope (including zero-breakdown assets)", + "Breakdowns per 1,000 Operating Hours = Total Breakdowns / (Assets × Period Days × Scheduled Hours/Day / 1000)", + f"Repeat Failure = Asset has >= {dataset['settings']['repeat_failure_count']} breakdowns within the last {dataset['settings']['repeat_failure_days']} days (from effective today).", + ], + "settings_used": { + "repeat_failure_count": dataset["settings"]["repeat_failure_count"], + "repeat_failure_days": dataset["settings"]["repeat_failure_days"], + "scheduled_hours_per_day": dataset["settings"]["scheduled_hours_per_day"], + }, + }, + } + diff --git a/backend/app/services/ai_narrative.py b/backend/app/services/ai_narrative.py new file mode 100644 index 0000000..7e20860 --- /dev/null +++ b/backend/app/services/ai_narrative.py @@ -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 + diff --git a/backend/app/services/ai_provider.py b/backend/app/services/ai_provider.py new file mode 100644 index 0000000..d83e51a --- /dev/null +++ b/backend/app/services/ai_provider.py @@ -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, + } + diff --git a/backend/app/services/ai_suggestions.py b/backend/app/services/ai_suggestions.py new file mode 100644 index 0000000..24e4743 --- /dev/null +++ b/backend/app/services/ai_suggestions.py @@ -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) + diff --git a/backend/app/services/alerts.py b/backend/app/services/alerts.py new file mode 100644 index 0000000..e862e93 --- /dev/null +++ b/backend/app/services/alerts.py @@ -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 diff --git a/backend/app/services/asset_import.py b/backend/app/services/asset_import.py new file mode 100644 index 0000000..5c3f5a9 --- /dev/null +++ b/backend/app/services/asset_import.py @@ -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, + } diff --git a/backend/app/services/attachment_service.py b/backend/app/services/attachment_service.py new file mode 100644 index 0000000..d34c556 --- /dev/null +++ b/backend/app/services/attachment_service.py @@ -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} diff --git a/backend/app/services/audit.py b/backend/app/services/audit.py new file mode 100644 index 0000000..38cd004 --- /dev/null +++ b/backend/app/services/audit.py @@ -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 diff --git a/backend/app/services/bulk_templates.py b/backend/app/services/bulk_templates.py new file mode 100644 index 0000000..186200e --- /dev/null +++ b/backend/app/services/bulk_templates.py @@ -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, + } + diff --git a/backend/app/services/calculations.py b/backend/app/services/calculations.py new file mode 100644 index 0000000..bb8dbbf --- /dev/null +++ b/backend/app/services/calculations.py @@ -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) diff --git a/backend/app/services/coverage.py b/backend/app/services/coverage.py new file mode 100644 index 0000000..d7f8e4f --- /dev/null +++ b/backend/app/services/coverage.py @@ -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] + diff --git a/backend/app/services/exports.py b/backend/app/services/exports.py new file mode 100644 index 0000000..11af5dd --- /dev/null +++ b/backend/app/services/exports.py @@ -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 diff --git a/backend/app/services/numbering.py b/backend/app/services/numbering.py new file mode 100644 index 0000000..e741765 --- /dev/null +++ b/backend/app/services/numbering.py @@ -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}" diff --git a/backend/app/services/permissions.py b/backend/app/services/permissions.py new file mode 100644 index 0000000..0126a8d --- /dev/null +++ b/backend/app/services/permissions.py @@ -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) diff --git a/backend/app/services/reports_service.py b/backend/app/services/reports_service.py new file mode 100644 index 0000000..7277dcf --- /dev/null +++ b/backend/app/services/reports_service.py @@ -0,0 +1,1407 @@ +import calendar +from datetime import date, datetime, time, timedelta, timezone +import re +from typing import Any, Callable, Optional +from fastapi import HTTPException, status +from sqlalchemy.orm import Session, joinedload + +from ..core.time_utils import ( + KOLKATA, + add_months, + effective_now_utc, + effective_today, + format_date, + format_datetime, + format_duration, +) +from ..models import ( + Asset, + CalibrationPlan, + CalibrationRecord, + Complaint, + Contract, + DemoEquipment, + Department, + DepartmentVisit, + PMRecord, + PMSchedule, + User, + Warranty, +) +from .attachment_service import get_attachment_counts +from .calculations import ( + clip_downtime_to_month, + compute_downtime_minutes, + compute_response_time_minutes, + compute_schedule_status, + coverage_status, +) +from .coverage import format_coverage_tag_label, get_coverage_map +from .permissions import Role +from .scoping import resolve_department_scope +from .settings_service import get_setting_value + +_MONTH_RE = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$") + + +def _parse_month(month_str: Optional[str], fallback_today: date) -> tuple[str, int, int]: + clean = month_str.strip() if month_str and month_str.strip() else fallback_today.strftime("%Y-%m") + match = _MONTH_RE.fullmatch(clean) + if not match: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="month must be in YYYY-MM format.", + ) + return clean, int(match.group(1)), int(match.group(2)) + + +def _scoped_dept_id(user: User, requested_dept_id: Optional[int]) -> Optional[int]: + scope = resolve_department_scope(user, requested_dept_id) + return scope.department_id + + +def _clean_filters(**kwargs: Any) -> dict[str, Any]: + out: dict[str, Any] = {} + for k, v in kwargs.items(): + if v is None or v == "": + continue + out[k] = str(v) if isinstance(v, date) else v + return out + + +def _build_monthly_maintenance( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + eff_now = effective_now_utc(db) + month_str, year, month = _parse_month(params.get("month"), today) + scope = resolve_department_scope(user, params.get("department_id")) + dept_id = scope.department_id + asset_id = params.get("asset_id") + + days_in_month = calendar.monthrange(year, month)[1] + sched_hours = int(get_setting_value(db, "scheduled_hours_per_day", 24)) + milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at")) + sched_mins_per_asset = days_in_month * sched_hours * 60 + + if scope.is_empty: + return { + "report_key": "monthly-maintenance", + "title": "Monthly Maintenance Summary", + "filters_applied": _clean_filters(month=month_str, department_id=None, asset_id=asset_id), + "formula_info": { + "scheduled_hours_per_day": sched_hours, + "downtime_end_milestone": milestone, + "days_in_month": days_in_month, + "uptime_formula": "total_scheduled_minutes - total_downtime_minutes", + "downtime_formula": "clip_downtime_to_month(registered_at, milestone, month)", + "explanation": ( + f"Scheduled operating hours are {sched_hours}h/day across {days_in_month} days in " + f"{month_str} (Asia/Kolkata); downtime_days_count is distinct calendar days with any breakdown." + ), + }, + "summary": { + "total_assets": 0, + "total_complaints": 0, + "total_downtime_minutes": 0, + "downtime_formatted": format_duration(0), + "downtime_days_count": 0, + "total_scheduled_minutes": 0, + "total_uptime_minutes": 0, + "uptime_formatted": format_duration(0), + "downtime_pct": 0.0, + "downtime_vs_uptime_pct": 0.0, + "scheduled_hours_per_day": sched_hours, + "downtime_end_milestone": milestone, + }, + "columns": [ + {"key": "department_name", "label": "Department"}, + {"key": "asset_count", "label": "Assets"}, + {"key": "complaint_count", "label": "Breakdowns"}, + {"key": "downtime_formatted", "label": "Downtime"}, + {"key": "downtime_days_count", "label": "Downtime Days"}, + {"key": "uptime_formatted", "label": "Uptime"}, + {"key": "downtime_pct", "label": "Downtime %"}, + ], + "rows": [], + "chart_data": [], + } + + dept_q = db.query(Department).filter(Department.is_active.is_(True)) + if dept_id is not None: + dept_q = dept_q.filter(Department.id == dept_id) + departments = dept_q.order_by(Department.name.asc()).all() + dept_by_id = {d.id: d for d in departments} + + asset_q = db.query(Asset).filter(Asset.status != "condemned") + if dept_id is not None: + asset_q = asset_q.filter(Asset.department_id == dept_id) + if asset_id is not None: + asset_q = asset_q.filter(Asset.id == asset_id) + assets = asset_q.all() + + asset_count_by_dept: dict[int, int] = {} + for a in assets: + asset_count_by_dept[a.department_id] = asset_count_by_dept.get(a.department_id, 0) + 1 + if a.department_id not in dept_by_id: + dept_obj = db.query(Department).filter(Department.id == a.department_id).first() + if dept_obj: + dept_by_id[dept_obj.id] = dept_obj + + cmp_q = db.query(Complaint).join(Asset, Complaint.asset_id == Asset.id).options(joinedload(Complaint.asset)) + if dept_id is not None: + cmp_q = cmp_q.filter(Asset.department_id == dept_id) + if asset_id is not None: + cmp_q = cmp_q.filter(Complaint.asset_id == asset_id) + complaints = cmp_q.all() + + dt_mins_by_dept: dict[int, int] = {} + cmp_count_by_dept: dict[int, int] = {} + dates_by_dept: dict[int, set[date]] = {} + overall_dates: set[date] = set() + overall_complaints = 0 + + for c in complaints: + end_map = { + "attended_at": c.attended_at, + "restored_at": c.restored_at, + "closed_at": c.closed_at, + } + end_dt = end_map.get(milestone) or eff_now + mins, dates = clip_downtime_to_month(c.registered_at, end_dt, year, month) + if mins > 0 or len(dates) > 0: + did = c.asset.department_id + dt_mins_by_dept[did] = dt_mins_by_dept.get(did, 0) + mins + cmp_count_by_dept[did] = cmp_count_by_dept.get(did, 0) + 1 + dates_by_dept.setdefault(did, set()).update(dates) + overall_dates.update(dates) + overall_complaints += 1 + + rows: list[dict[str, Any]] = [] + chart_data: list[dict[str, Any]] = [] + ordered_dept_ids = sorted(dept_by_id.keys(), key=lambda did: dept_by_id[did].name) + + for did in ordered_dept_ids: + dept = dept_by_id[did] + a_cnt = asset_count_by_dept.get(did, 0) + if asset_id is not None and a_cnt == 0 and cmp_count_by_dept.get(did, 0) == 0: + continue + c_cnt = cmp_count_by_dept.get(did, 0) + dt_mins = dt_mins_by_dept.get(did, 0) + dt_days = len(dates_by_dept.get(did, set())) + sched_mins = a_cnt * sched_mins_per_asset + up_mins = max(0, sched_mins - dt_mins) + dt_pct = round(dt_mins / sched_mins * 100, 2) if sched_mins > 0 else 0.0 + rows.append( + { + "department_id": did, + "department_name": dept.name, + "asset_count": a_cnt, + "complaint_count": c_cnt, + "total_downtime_minutes": dt_mins, + "downtime_formatted": format_duration(dt_mins), + "downtime_days_count": dt_days, + "scheduled_minutes": sched_mins, + "total_uptime_minutes": up_mins, + "uptime_formatted": format_duration(up_mins), + "downtime_pct": dt_pct, + } + ) + chart_data.append( + { + "department": dept.name, + "downtime_hours": round(dt_mins / 60.0, 2), + "uptime_hours": round(up_mins / 60.0, 2), + } + ) + + total_assets = sum(r["asset_count"] for r in rows) + total_dt_mins = sum(r["total_downtime_minutes"] for r in rows) + total_sched_mins = sum(r["scheduled_minutes"] for r in rows) + total_up_mins = max(0, total_sched_mins - total_dt_mins) + total_dt_pct = round(total_dt_mins / total_sched_mins * 100, 2) if total_sched_mins > 0 else 0.0 + dt_vs_up_pct = round(total_dt_mins / total_up_mins * 100, 2) if total_up_mins > 0 else 0.0 + + return { + "report_key": "monthly-maintenance", + "title": "Monthly Maintenance Summary", + "filters_applied": _clean_filters(month=month_str, department_id=dept_id, asset_id=asset_id), + "formula_info": { + "scheduled_hours_per_day": sched_hours, + "downtime_end_milestone": milestone, + "days_in_month": days_in_month, + "uptime_formula": ( + f"max(0, (non_condemned_assets * {days_in_month} * {sched_hours} * 60) - total_downtime_minutes)" + ), + "downtime_formula": ( + f"Sum of breakdown intervals [registered_at -> {milestone} or effective_now] clipped to " + f"{month_str} (Asia/Kolkata); downtime_days_count is distinct calendar days with any breakdown." + ), + }, + "summary": { + "total_assets": total_assets, + "total_complaints": overall_complaints, + "total_downtime_minutes": total_dt_mins, + "downtime_formatted": format_duration(total_dt_mins), + "downtime_days_count": len(overall_dates), + "total_scheduled_minutes": total_sched_mins, + "total_uptime_minutes": total_up_mins, + "uptime_formatted": format_duration(total_up_mins), + "downtime_pct": total_dt_pct, + "downtime_vs_uptime_pct": dt_vs_up_pct, + "scheduled_hours_per_day": sched_hours, + "downtime_end_milestone": milestone, + }, + "columns": [ + {"key": "department_name", "label": "Department"}, + {"key": "asset_count", "label": "Assets"}, + {"key": "complaint_count", "label": "Breakdowns"}, + {"key": "downtime_formatted", "label": "Downtime"}, + {"key": "downtime_days_count", "label": "Downtime Days"}, + {"key": "uptime_formatted", "label": "Uptime"}, + {"key": "downtime_pct", "label": "Downtime %"}, + ], + "rows": rows, + "chart_data": chart_data, + } + + +def _build_monthly_department( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + month_str, year, month = _parse_month(params.get("month"), today) + scope = resolve_department_scope(user, params.get("department_id")) + dept_id = scope.department_id + + if scope.is_empty: + return { + "report_key": "monthly-department", + "title": "Monthly Department Report", + "filters_applied": _clean_filters(month=month_str, department_id=None), + "summary": { + "departments_count": 0, + "total_under_repair": 0, + "total_outstanding_complaints": 0, + "total_visits": 0, + }, + "columns": [ + {"key": "department_name", "label": "Department"}, + {"key": "total_assets", "label": "Total Assets"}, + {"key": "under_repair_count", "label": "Under Repair"}, + {"key": "out_of_service_count", "label": "Out of Service"}, + {"key": "outstanding_complaints_count", "label": "Open Complaints"}, + {"key": "critical_open_count", "label": "Critical Open"}, + {"key": "visits_this_month", "label": "Visits"}, + {"key": "new_equipment_requirements", "label": "New Equipment Requirements"}, + {"key": "latest_requirements_notes", "label": "Visit Observations"}, + ], + "rows": [], + } + + month_start = date(year, month, 1) + next_month_start = add_months(month_start, 1) + + dept_q = db.query(Department).filter(Department.is_active.is_(True)) + if dept_id is not None: + dept_q = dept_q.filter(Department.id == dept_id) + departments = dept_q.order_by(Department.name.asc()).all() + + assets = db.query(Asset).all() + open_complaints = ( + db.query(Complaint) + .join(Asset, Complaint.asset_id == Asset.id) + .options(joinedload(Complaint.asset)) + .filter(Complaint.call_status != "closed") + .all() + ) + visits = ( + db.query(DepartmentVisit) + .filter( + DepartmentVisit.visit_date >= month_start, + DepartmentVisit.visit_date < next_month_start, + ) + .order_by(DepartmentVisit.visit_date.desc(), DepartmentVisit.id.desc()) + .all() + ) + + rows: list[dict[str, Any]] = [] + for d in departments: + d_assets = [a for a in assets if a.department_id == d.id] + d_cmps = [c for c in open_complaints if c.asset.department_id == d.id] + d_visits = [v for v in visits if v.department_id == d.id] + obs_notes = "; ".join( + f"[{format_date(v.visit_date)}] {v.observations.strip()}" + for v in d_visits + if v.observations and v.observations.strip() + ) + reqs_notes = "; ".join( + f"[{format_date(v.visit_date)}] {v.new_requirements.strip()}" + for v in d_visits + if v.new_requirements and v.new_requirements.strip() + ) + rows.append( + { + "department_id": d.id, + "department_name": d.name, + "total_assets": len(d_assets), + "under_repair_count": sum(1 for a in d_assets if a.status == "under_repair"), + "out_of_service_count": sum(1 for a in d_assets if a.status == "out_of_service"), + "outstanding_complaints_count": len(d_cmps), + "critical_open_count": sum(1 for c in d_cmps if c.priority == "critical"), + "visits_this_month": len(d_visits), + "new_equipment_requirements": reqs_notes or "\u2014", + "latest_requirements_notes": obs_notes or "\u2014", + } + ) + + return { + "report_key": "monthly-department", + "title": "Monthly Department Report", + "filters_applied": _clean_filters(month=month_str, department_id=dept_id), + "summary": { + "departments_count": len(rows), + "total_under_repair": sum(r["under_repair_count"] for r in rows), + "total_outstanding_complaints": sum(r["outstanding_complaints_count"] for r in rows), + "total_visits": sum(r["visits_this_month"] for r in rows), + }, + "columns": [ + {"key": "department_name", "label": "Department"}, + {"key": "total_assets", "label": "Total Assets"}, + {"key": "under_repair_count", "label": "Under Repair"}, + {"key": "out_of_service_count", "label": "Out of Service"}, + {"key": "outstanding_complaints_count", "label": "Open Complaints"}, + {"key": "critical_open_count", "label": "Critical Open"}, + {"key": "visits_this_month", "label": "Visits"}, + {"key": "new_equipment_requirements", "label": "New Equipment Requirements"}, + {"key": "latest_requirements_notes", "label": "Visit Observations"}, + ], + "rows": rows, + } + + +def _build_daily_visit( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + if user.role in (Role.department_user.value, Role.coordinator.value): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Insufficient permissions to access Daily Department Visit Report.", + ) + + date_from = params.get("date_from") + date_to = params.get("date_to") + scope = resolve_department_scope(user, params.get("department_id")) + dept_id = scope.department_id + + if scope.is_empty: + return { + "report_key": "daily-visit", + "title": "Daily Department Visit Report", + "filters_applied": _clean_filters(date_from=date_from, date_to=date_to, department_id=None), + "summary": { + "total_visits": 0, + "departments_visited": 0, + "equipment_checked": 0, + "breakdowns_logged": 0, + }, + "columns": [ + {"key": "visit_date", "label": "Visit Date"}, + {"key": "department_name", "label": "Department"}, + {"key": "visited_by_name", "label": "Biomedical Engineer"}, + {"key": "assets_count", "label": "Equipment Checked"}, + {"key": "complaints_count", "label": "Breakdowns Logged"}, + {"key": "new_requirements", "label": "New Equipment Requirements"}, + {"key": "observations", "label": "Observations"}, + ], + "rows": [], + } + + query = db.query(DepartmentVisit).options( + joinedload(DepartmentVisit.department), + joinedload(DepartmentVisit.visited_by), + joinedload(DepartmentVisit.assets), + joinedload(DepartmentVisit.complaints), + ) + if dept_id is not None: + query = query.filter(DepartmentVisit.department_id == dept_id) + if date_from is not None: + query = query.filter(DepartmentVisit.visit_date >= date_from) + if date_to is not None: + query = query.filter(DepartmentVisit.visit_date <= date_to) + + visits = query.order_by(DepartmentVisit.visit_date.desc(), DepartmentVisit.id.desc()).all() + rows: list[dict[str, Any]] = [] + depts_visited: set[int] = set() + total_eq_checked = 0 + total_linked = 0 + + for v in visits: + depts_visited.add(v.department_id) + eq_list = ", ".join(f"{a.asset_code} ({a.name})" for a in v.assets) + cmp_list = ", ".join(c.complaint_no for c in v.complaints) + total_eq_checked += len(v.assets) + total_linked += len(v.complaints) + rows.append( + { + "id": v.id, + "visit_date": format_date(v.visit_date), + "department_name": v.department.name if v.department else "\u2014", + "visited_by_name": v.visited_by.name if v.visited_by else "\u2014", + "equipment_checked_count": len(v.assets), + "equipment_checked": eq_list or "\u2014", + "observations": v.observations or "\u2014", + "linked_complaints_count": len(v.complaints), + "linked_complaints": cmp_list or "\u2014", + } + ) + + return { + "report_key": "daily-visit", + "title": "Daily Department Visit Report", + "filters_applied": _clean_filters(date_from=date_from, date_to=date_to, department_id=dept_id), + "summary": { + "total_visits": len(rows), + "departments_visited": len(depts_visited), + "total_equipment_checked": total_eq_checked, + "linked_complaints_count": total_linked, + }, + "columns": [ + {"key": "visit_date", "label": "Visit Date"}, + {"key": "department_name", "label": "Department"}, + {"key": "visited_by_name", "label": "Visited By"}, + {"key": "equipment_checked_count", "label": "Assets Checked"}, + {"key": "equipment_checked", "label": "Equipment Checked"}, + {"key": "observations", "label": "Observations"}, + {"key": "linked_complaints_count", "label": "Linked Count"}, + {"key": "linked_complaints", "label": "Linked Complaints"}, + ], + "rows": rows, + } + + +def _build_breakdown_complaints( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + scope = resolve_department_scope(user, params.get("department_id")) + dept_id = scope.department_id + date_from = params.get("date_from") + date_to = params.get("date_to") + asset_id = params.get("asset_id") + priority = params.get("priority") + call_status = params.get("call_status") + assigned_to_id = params.get("assigned_to_id") + + if scope.is_empty: + return { + "report_key": "breakdown-complaints", + "title": "Breakdown / Complaint Report", + "filters_applied": _clean_filters( + date_from=date_from, + date_to=date_to, + department_id=None, + asset_id=asset_id, + priority=priority, + call_status=call_status, + assigned_to_id=assigned_to_id, + ), + "summary": { + "total_complaints": 0, + "open_count": 0, + "in_progress_count": 0, + "closed_count": 0, + "critical_count": 0, + "avg_response_minutes": 0.0, + "total_downtime_minutes": 0, + }, + "columns": [ + {"key": "complaint_no", "label": "Complaint No"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "coverage_tag_label", "label": "Coverage"}, + {"key": "priority", "label": "Priority"}, + {"key": "call_status", "label": "Status"}, + {"key": "registered_at", "label": "Registered At"}, + {"key": "assigned_to_name", "label": "Assigned To"}, + {"key": "response_time_formatted", "label": "Response Time"}, + {"key": "downtime_formatted", "label": "Downtime"}, + {"key": "action_taken", "label": "Action Taken"}, + {"key": "closed_at", "label": "Closed At"}, + {"key": "closure_remarks", "label": "Closure Remarks"}, + ], + "rows": [], + } + + response_start = str(get_setting_value(db, "response_start", "registered_at")) + milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at")) + eff_now = effective_now_utc(db) + + query = ( + db.query(Complaint) + .join(Asset, Complaint.asset_id == Asset.id) + .options( + joinedload(Complaint.asset).joinedload(Asset.department), + ) + ) + if dept_id is not None: + query = query.filter(Asset.department_id == dept_id) + if asset_id is not None: + query = query.filter(Complaint.asset_id == asset_id) + if priority: + query = query.filter(Complaint.priority == priority) + if call_status: + query = query.filter(Complaint.call_status == call_status) + if assigned_to_id is not None: + query = query.filter(Complaint.assigned_to_id == assigned_to_id) + if date_from is not None: + dt_from_utc = KOLKATA.localize(datetime.combine(date_from, time(0, 0, 0))).astimezone(timezone.utc) + query = query.filter(Complaint.registered_at >= dt_from_utc) + if date_to is not None: + dt_to_utc = KOLKATA.localize( + datetime.combine(date_to + timedelta(days=1), time(0, 0, 0)) + ).astimezone(timezone.utc) + query = query.filter(Complaint.registered_at < dt_to_utc) + + complaints = query.order_by(Complaint.registered_at.desc(), Complaint.id.desc()).all() + assigned_ids = {c.assigned_to_id for c in complaints if c.assigned_to_id is not None} + user_name_by_id: dict[int, str] = {} + if assigned_ids: + user_name_by_id = { + u.id: u.name for u in db.query(User).filter(User.id.in_(assigned_ids)).all() + } + cov_map = get_coverage_map(db, [c.asset_id for c in complaints], effective_today(db)) + + rows: list[dict[str, Any]] = [] + rt_values: list[int] = [] + total_dt = 0 + + for c in complaints: + rt = compute_response_time_minutes(c.registered_at, c.received_at, c.attended_at, response_start) + if rt is not None: + rt_values.append(rt) + dt_mins, ongoing = compute_downtime_minutes( + c.registered_at, + c.attended_at, + c.restored_at, + c.closed_at, + milestone=milestone, + now_utc=eff_now, + ) + total_dt += dt_mins + tag_val = c.coverage_tag or cov_map.get(c.asset_id, {}).get("tag") + rows.append( + { + "complaint_no": c.complaint_no, + "asset_code": c.asset.asset_code, + "asset_name": c.asset.name, + "department_name": c.asset.department.name if c.asset.department else "\u2014", + "coverage_tag": tag_val or "out_of_contract", + "coverage_tag_label": format_coverage_tag_label(tag_val), + "priority": c.priority, + "call_status": c.call_status, + "registered_at": format_datetime(c.registered_at), + "assigned_to_name": user_name_by_id.get(c.assigned_to_id, "\u2014") if c.assigned_to_id else "\u2014", + "response_time_minutes": rt, + "response_time_formatted": format_duration(rt), + "downtime_minutes": dt_mins, + "downtime_formatted": format_duration(dt_mins), + "downtime_is_ongoing": ongoing, + "action_taken": c.action_taken or "\u2014", + "closed_at": format_datetime(c.closed_at) or "\u2014", + "closure_remarks": c.closure_remarks or "\u2014", + } + ) + + avg_rt = round(sum(rt_values) / len(rt_values), 1) if rt_values else 0.0 + return { + "report_key": "breakdown-complaints", + "title": "Breakdown / Complaint Report", + "filters_applied": _clean_filters( + date_from=date_from, + date_to=date_to, + department_id=dept_id, + asset_id=asset_id, + priority=priority, + call_status=call_status, + assigned_to_id=assigned_to_id, + ), + "summary": { + "total_complaints": len(rows), + "open_count": sum(1 for c in complaints if c.call_status == "open"), + "in_progress_count": sum(1 for c in complaints if c.call_status == "in_progress"), + "closed_count": sum(1 for c in complaints if c.call_status == "closed"), + "critical_count": sum(1 for c in complaints if c.priority == "critical"), + "avg_response_minutes": avg_rt, + "total_downtime_minutes": total_dt, + }, + "columns": [ + {"key": "complaint_no", "label": "Complaint No"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "coverage_tag_label", "label": "Coverage"}, + {"key": "priority", "label": "Priority"}, + {"key": "call_status", "label": "Status"}, + {"key": "registered_at", "label": "Registered At"}, + {"key": "assigned_to_name", "label": "Assigned To"}, + {"key": "response_time_formatted", "label": "Response Time"}, + {"key": "downtime_formatted", "label": "Downtime"}, + {"key": "action_taken", "label": "Action Taken"}, + {"key": "closed_at", "label": "Closed At"}, + {"key": "closure_remarks", "label": "Closure Remarks"}, + ], + "rows": rows, + } + + +def _build_pm_compliance( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + scope = resolve_department_scope(user, params.get("department_id")) + dept_id = scope.department_id + month_param = params.get("month") + date_from = params.get("date_from") + date_to = params.get("date_to") + asset_id = params.get("asset_id") + service_mode = params.get("service_mode") + + clean_month: str | None = None + if month_param and str(month_param).strip(): + clean_month, y, m = _parse_month(month_param, today) + + if scope.is_empty: + return { + "report_key": "pm-compliance", + "title": "PM Compliance Report", + "filters_applied": _clean_filters( + month=clean_month, + date_from=date_from, + date_to=date_to, + department_id=None, + asset_id=asset_id, + service_mode=service_mode, + ), + "summary": { + "planned_count": 0, + "completed_count": 0, + "upcoming_count": 0, + "due_count": 0, + "overdue_count": 0, + "rescheduled_count": 0, + "compliance_pct": 0.0, + }, + "columns": [ + {"key": "planned_date", "label": "Planned Date"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "service_mode", "label": "Service Mode"}, + {"key": "team_or_provider", "label": "Team / Provider"}, + {"key": "status", "label": "Status"}, + {"key": "completed_date", "label": "Completed Date"}, + {"key": "service_details", "label": "Service Details"}, + {"key": "remarks", "label": "Remarks"}, + ], + "rows": [], + } + + inhouse_lead = int(get_setting_value(db, "pm_inhouse_lead_days", 15)) + outsourced_lead = int(get_setting_value(db, "pm_outsourced_lead_days", 15)) + red_days = int(get_setting_value(db, "red_threshold_days", 7)) + + query = ( + db.query(PMRecord) + .join(PMSchedule, PMRecord.schedule_id == PMSchedule.id) + .join(Asset, PMRecord.asset_id == Asset.id) + .options( + joinedload(PMRecord.asset).joinedload(Asset.department), + joinedload(PMRecord.schedule).joinedload(PMSchedule.provider), + ) + ) + if dept_id is not None: + query = query.filter(Asset.department_id == dept_id) + if asset_id is not None: + query = query.filter(PMRecord.asset_id == asset_id) + if service_mode: + query = query.filter(PMSchedule.service_mode == service_mode) + + clean_month: str | None = None + if month_param and str(month_param).strip(): + clean_month, y, m = _parse_month(month_param, today) + m_start = date(y, m, 1) + m_end = add_months(m_start, 1) + query = query.filter(PMRecord.planned_date >= m_start, PMRecord.planned_date < m_end) + else: + if date_from is not None: + query = query.filter(PMRecord.planned_date >= date_from) + if date_to is not None: + query = query.filter(PMRecord.planned_date <= date_to) + + records = query.order_by(PMRecord.planned_date.asc(), PMRecord.id.asc()).all() + rows: list[dict[str, Any]] = [] + counts = {"completed": 0, "upcoming": 0, "due": 0, "overdue": 0, "rescheduled": 0} + + for rec in records: + sched = rec.schedule + mode = sched.service_mode + lead = inhouse_lead if mode == "in_house" else outsourced_lead + if rec.status in ("completed", "rescheduled"): + st = rec.status + else: + st, _ = compute_schedule_status(rec.planned_date, None, today, lead, red_days) + counts[st] = counts.get(st, 0) + 1 + team_or_provider = ( + sched.responsible_team + if mode == "in_house" + else (sched.provider.name if sched.provider else "\u2014") + ) + rows.append( + { + "planned_date": format_date(rec.planned_date), + "asset_code": rec.asset.asset_code, + "asset_name": rec.asset.name, + "department_name": rec.asset.department.name if rec.asset.department else "\u2014", + "service_mode": mode, + "team_or_provider": team_or_provider or "\u2014", + "status": st, + "completed_date": format_date(rec.completed_date) or "\u2014", + "service_details": rec.service_details or "\u2014", + "remarks": rec.remarks or "\u2014", + } + ) + + planned_count = len(rows) + compliance_pct = round(counts["completed"] / planned_count * 100, 2) if planned_count > 0 else 0.0 + return { + "report_key": "pm-compliance", + "title": "PM Compliance Report", + "filters_applied": _clean_filters( + month=clean_month, + date_from=date_from, + date_to=date_to, + department_id=dept_id, + asset_id=asset_id, + service_mode=service_mode, + ), + "summary": { + "planned_count": planned_count, + "completed_count": counts["completed"], + "upcoming_count": counts["upcoming"], + "due_count": counts["due"], + "overdue_count": counts["overdue"], + "rescheduled_count": counts["rescheduled"], + "compliance_pct": compliance_pct, + }, + "columns": [ + {"key": "planned_date", "label": "Planned Date"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "service_mode", "label": "Service Mode"}, + {"key": "team_or_provider", "label": "Team / Provider"}, + {"key": "status", "label": "Status"}, + {"key": "completed_date", "label": "Completed Date"}, + {"key": "service_details", "label": "Service Details"}, + {"key": "remarks", "label": "Remarks"}, + ], + "rows": rows, + } + + +def _build_calibration_due( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + scope = resolve_department_scope(user, params.get("department_id")) + dept_id = scope.department_id + due_from = params.get("due_from") + due_to = params.get("due_to") + asset_id = params.get("asset_id") + agency_id = params.get("agency_id") + status_filter = params.get("status") + + if scope.is_empty: + return { + "report_key": "calibration-due", + "title": "Calibration Due Report", + "filters_applied": _clean_filters( + due_from=due_from, + due_to=due_to, + department_id=None, + asset_id=asset_id, + agency_id=agency_id, + status=status_filter, + ), + "summary": { + "total_records": 0, + "upcoming_count": 0, + "due_count": 0, + "overdue_count": 0, + "completed_count": 0, + }, + "columns": [ + {"key": "due_date", "label": "Due Date"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "agency_name", "label": "Agency"}, + {"key": "frequency_months", "label": "Freq (Mo)"}, + {"key": "status", "label": "Status"}, + {"key": "completed_date", "label": "Completed Date"}, + {"key": "certificate_no", "label": "Certificate No"}, + {"key": "remarks", "label": "Remarks"}, + ], + "rows": [], + } + + cal_lead = int( + get_setting_value( + db, + "calibration_due_window_days", + get_setting_value(db, "calibration_lead_days", 15), + ) + ) + red_days = int(get_setting_value(db, "red_threshold_days", 7)) + + query = ( + db.query(CalibrationRecord) + .join(CalibrationPlan, CalibrationRecord.plan_id == CalibrationPlan.id) + .join(Asset, CalibrationRecord.asset_id == Asset.id) + .options( + joinedload(CalibrationRecord.asset).joinedload(Asset.department), + joinedload(CalibrationRecord.agency), + joinedload(CalibrationRecord.plan), + ) + ) + if dept_id is not None: + query = query.filter(Asset.department_id == dept_id) + if asset_id is not None: + query = query.filter(CalibrationRecord.asset_id == asset_id) + if agency_id is not None: + query = query.filter(CalibrationRecord.agency_id == agency_id) + if due_from is not None: + query = query.filter(CalibrationRecord.due_date >= due_from) + if due_to is not None: + query = query.filter(CalibrationRecord.due_date <= due_to) + + records = query.order_by(CalibrationRecord.due_date.asc(), CalibrationRecord.id.asc()).all() + rows: list[dict[str, Any]] = [] + counts = {"upcoming": 0, "due": 0, "overdue": 0, "completed": 0} + + for rec in records: + if rec.status == "completed": + st = "completed" + else: + st, _ = compute_schedule_status(rec.due_date, None, today, cal_lead, red_days) + if status_filter and st != status_filter: + continue + counts[st] = counts.get(st, 0) + 1 + rows.append( + { + "due_date": format_date(rec.due_date), + "asset_code": rec.asset.asset_code, + "asset_name": rec.asset.name, + "department_name": rec.asset.department.name if rec.asset.department else "\u2014", + "agency_name": rec.agency.name if rec.agency else "\u2014", + "frequency_months": rec.plan.frequency_months if rec.plan else 0, + "status": st, + "completed_date": format_date(rec.completed_date) or "\u2014", + "certificate_no": rec.certificate_no or "\u2014", + "remarks": rec.remarks or "\u2014", + } + ) + + return { + "report_key": "calibration-due", + "title": "Calibration Due Report", + "filters_applied": _clean_filters( + due_from=due_from, + due_to=due_to, + department_id=dept_id, + asset_id=asset_id, + agency_id=agency_id, + status=status_filter, + ), + "summary": { + "total_records": len(rows), + "upcoming_count": counts["upcoming"], + "due_count": counts["due"], + "overdue_count": counts["overdue"], + "completed_count": counts["completed"], + }, + "columns": [ + {"key": "due_date", "label": "Due Date"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "agency_name", "label": "Agency"}, + {"key": "frequency_months", "label": "Freq (Mo)"}, + {"key": "status", "label": "Status"}, + {"key": "completed_date", "label": "Completed Date"}, + {"key": "certificate_no", "label": "Certificate No"}, + {"key": "remarks", "label": "Remarks"}, + ], + "rows": rows, + } + + +def _build_contracts_warranty( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + scope = resolve_department_scope(user, params.get("department_id")) + dept_id = scope.department_id + asset_id = params.get("asset_id") + record_kind = params.get("record_kind") or "all" + status_filter = params.get("status") + contract_type = params.get("contract_type") + + if scope.is_empty: + return { + "report_key": "contracts-warranty", + "title": "AMC / CMC & Warranty Report", + "filters_applied": _clean_filters( + department_id=None, + asset_id=asset_id, + record_kind=record_kind, + status=status_filter, + contract_type=contract_type, + ), + "summary": { + "total_records": 0, + "active_contracts": 0, + "expiring_contracts": 0, + "expired_contracts": 0, + "active_warranties": 0, + "expiring_warranties": 0, + }, + "columns": [ + {"key": "record_kind", "label": "Kind"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "type_or_duration", "label": "Type / Duration"}, + {"key": "provider_name", "label": "Provider"}, + {"key": "start_date", "label": "Start Date"}, + {"key": "end_date", "label": "End Date"}, + {"key": "days_to_expiry", "label": "Days Left"}, + {"key": "status", "label": "Status"}, + {"key": "attachment_count", "label": "Files"}, + ], + "rows": [], + } + + con_lead = int( + get_setting_value( + db, + "amc_cmc_lead_days", + get_setting_value(db, "contract_expiry_alert_days", 30), + ) + ) + war_lead = int( + get_setting_value( + db, + "warranty_lead_days", + get_setting_value(db, "warranty_expiry_alert_days", 30), + ) + ) + red_days = int(get_setting_value(db, "red_threshold_days", 7)) + + rows: list[dict[str, Any]] = [] + con_counts = {"active": 0, "expiring": 0, "expired": 0} + war_counts = {"active": 0, "expiring": 0, "expired": 0} + + if record_kind in ("all", "contracts"): + cq = ( + db.query(Contract) + .join(Asset, Contract.asset_id == Asset.id) + .options(joinedload(Contract.asset).joinedload(Asset.department), joinedload(Contract.provider)) + ) + if status_filter != "superseded": + cq = cq.filter(Contract.is_superseded.is_(False)) + if dept_id is not None: + cq = cq.filter(Asset.department_id == dept_id) + if asset_id is not None: + cq = cq.filter(Contract.asset_id == asset_id) + if contract_type: + cq = cq.filter(Contract.contract_type == contract_type) + contracts = cq.order_by(Contract.end_date.asc(), Contract.id.desc()).all() + con_att = get_attachment_counts(db, "contract", [c.id for c in contracts]) + for c in contracts: + if c.is_superseded: + st = "superseded" + else: + st, _ = coverage_status(c.start_date, c.end_date, today, con_lead, red_days) + if status_filter and st != status_filter: + continue + if st in con_counts: + con_counts[st] += 1 + rows.append( + { + "record_kind": "Contract", + "asset_code": c.asset.asset_code, + "asset_name": c.asset.name, + "department_name": c.asset.department.name if c.asset.department else "\u2014", + "type_or_duration": c.contract_type, + "provider_name": c.provider.name if c.provider else "\u2014", + "start_date": format_date(c.start_date), + "end_date": format_date(c.end_date), + "days_to_expiry": (c.end_date - today).days, + "status": st, + "attachment_count": con_att.get(c.id, 0), + } + ) + + if record_kind in ("all", "warranties") and not contract_type: + wq = ( + db.query(Warranty) + .join(Asset, Warranty.asset_id == Asset.id) + .options(joinedload(Warranty.asset).joinedload(Asset.department), joinedload(Warranty.provider)) + ) + if dept_id is not None: + wq = wq.filter(Asset.department_id == dept_id) + if asset_id is not None: + wq = wq.filter(Warranty.asset_id == asset_id) + warranties = wq.order_by(Warranty.end_date.asc(), Warranty.id.desc()).all() + war_att = get_attachment_counts(db, "warranty", [w.id for w in warranties]) + for w in warranties: + st, _ = coverage_status(w.start_date, w.end_date, today, war_lead, red_days) + if status_filter and st != status_filter: + continue + if st in war_counts: + war_counts[st] += 1 + rows.append( + { + "record_kind": "Warranty", + "asset_code": w.asset.asset_code, + "asset_name": w.asset.name, + "department_name": w.asset.department.name if w.asset.department else "\u2014", + "type_or_duration": f"{w.duration_months} mo", + "provider_name": w.provider.name if w.provider else "\u2014", + "start_date": format_date(w.start_date), + "end_date": format_date(w.end_date), + "days_to_expiry": (w.end_date - today).days, + "status": st, + "attachment_count": war_att.get(w.id, 0), + } + ) + + return { + "report_key": "contracts-warranty", + "title": "AMC / CMC & Warranty Report", + "filters_applied": _clean_filters( + department_id=dept_id, + asset_id=asset_id, + record_kind=record_kind, + status=status_filter, + contract_type=contract_type, + ), + "summary": { + "total_records": len(rows), + "active_contracts": con_counts["active"], + "expiring_contracts": con_counts["expiring"], + "expired_contracts": con_counts["expired"], + "active_warranties": war_counts["active"], + "expiring_warranties": war_counts["expiring"], + }, + "columns": [ + {"key": "record_kind", "label": "Kind"}, + {"key": "asset_code", "label": "Asset Code"}, + {"key": "asset_name", "label": "Equipment"}, + {"key": "department_name", "label": "Department"}, + {"key": "type_or_duration", "label": "Type / Duration"}, + {"key": "provider_name", "label": "Provider"}, + {"key": "start_date", "label": "Start Date"}, + {"key": "end_date", "label": "End Date"}, + {"key": "days_to_expiry", "label": "Days Left"}, + {"key": "status", "label": "Status"}, + {"key": "attachment_count", "label": "Files"}, + ], + "rows": rows, + } + + +def _build_demo_equipment( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + today = effective_today(db) + scope = resolve_department_scope(user, params.get("department_id")) + dept_id = scope.department_id + supplier_id = params.get("supplier_id") + status_filter = params.get("status") + date_from = params.get("date_from") + date_to = params.get("date_to") + + if scope.is_empty: + return { + "report_key": "demo-equipment", + "title": "Demo Equipment Report", + "filters_applied": _clean_filters( + department_id=None, + supplier_id=supplier_id, + status=status_filter, + date_from=date_from, + date_to=date_to, + ), + "summary": { + "total_items": 0, + "on_demo_count": 0, + "overdue_count": 0, + "returned_count": 0, + }, + "columns": [ + {"key": "name", "label": "Equipment Name"}, + {"key": "equipment_type", "label": "Type"}, + {"key": "supplier_name", "label": "Supplier"}, + {"key": "department_name", "label": "Department"}, + {"key": "location_name", "label": "Location"}, + {"key": "start_date", "label": "Start Date"}, + {"key": "expected_return_date", "label": "Expected Return"}, + {"key": "actual_return_date", "label": "Actual Return"}, + {"key": "status", "label": "Status"}, + {"key": "days_remaining", "label": "Days Remaining"}, + {"key": "remarks", "label": "Remarks"}, + ], + "rows": [], + } + + query = db.query(DemoEquipment).options( + joinedload(DemoEquipment.supplier), + joinedload(DemoEquipment.department), + joinedload(DemoEquipment.location), + ) + if dept_id is not None: + query = query.filter(DemoEquipment.department_id == dept_id) + if supplier_id is not None: + query = query.filter(DemoEquipment.supplier_id == supplier_id) + if date_from is not None: + query = query.filter(DemoEquipment.expected_return_date >= date_from) + if date_to is not None: + query = query.filter(DemoEquipment.expected_return_date <= date_to) + + items = query.order_by(DemoEquipment.expected_return_date.asc(), DemoEquipment.id.desc()).all() + rows: list[dict[str, Any]] = [] + counts = {"on_demo": 0, "overdue_return": 0, "returned": 0} + + for d in items: + if d.actual_return_date is not None: + st = "returned" + days_rem = (d.expected_return_date - d.actual_return_date).days + elif d.expected_return_date < today: + st = "overdue_return" + days_rem = (d.expected_return_date - today).days + else: + st = "on_demo" + days_rem = (d.expected_return_date - today).days + + if status_filter and st != status_filter: + continue + counts[st] = counts.get(st, 0) + 1 + rows.append( + { + "name": d.name, + "equipment_type": d.equipment_type, + "supplier_name": d.supplier.name if d.supplier else "\u2014", + "department_name": d.department.name if d.department else "\u2014", + "location_name": d.location.name if d.location else "\u2014", + "start_date": format_date(d.start_date), + "expected_return_date": format_date(d.expected_return_date), + "actual_return_date": format_date(d.actual_return_date) or "\u2014", + "status": st, + "days_remaining": days_rem, + "remarks": d.remarks or "\u2014", + } + ) + + return { + "report_key": "demo-equipment", + "title": "Demo Equipment Report", + "filters_applied": _clean_filters( + department_id=dept_id, + supplier_id=supplier_id, + status=status_filter, + date_from=date_from, + date_to=date_to, + ), + "summary": { + "total_items": len(rows), + "on_demo_count": counts["on_demo"], + "overdue_count": counts["overdue_return"], + "returned_count": counts["returned"], + }, + "columns": [ + {"key": "name", "label": "Equipment Name"}, + {"key": "equipment_type", "label": "Type / Model"}, + {"key": "supplier_name", "label": "Supplier"}, + {"key": "department_name", "label": "Department"}, + {"key": "location_name", "label": "Location"}, + {"key": "start_date", "label": "Start Date"}, + {"key": "expected_return_date", "label": "Expected Return"}, + {"key": "actual_return_date", "label": "Actual Return"}, + {"key": "status", "label": "Status"}, + {"key": "days_remaining", "label": "Days Remaining"}, + {"key": "remarks", "label": "Remarks"}, + ], + "rows": rows, + } + + +def _build_equipment_inventory( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + scope = resolve_department_scope(user, params.get("department_id")) + dept_id = scope.department_id + category_id = params.get("category_id") + status_filter = params.get("status") + + if scope.is_empty: + return { + "report_key": "equipment-inventory", + "title": "Equipment Inventory Report", + "filters_applied": _clean_filters(department_id=None, category_id=category_id, status=status_filter), + "summary": { + "total_assets": 0, + "in_service": 0, + "under_repair": 0, + "condemned": 0, + }, + "columns": [ + {"key": "asset_code", "label": "Asset Code"}, + {"key": "name", "label": "Equipment Name"}, + {"key": "department_name", "label": "Department"}, + {"key": "location_name", "label": "Location"}, + {"key": "category_name", "label": "Category"}, + {"key": "serial_no", "label": "Serial No"}, + {"key": "status", "label": "Status"}, + ], + "rows": [], + } + + query = ( + db.query(Asset) + .options( + joinedload(Asset.department), + joinedload(Asset.location), + joinedload(Asset.category), + ) + ) + if dept_id is not None: + query = query.filter(Asset.department_id == dept_id) + if category_id is not None: + query = query.filter(Asset.category_id == category_id) + if status_filter: + query = query.filter(Asset.status == status_filter) + + assets = query.order_by(Asset.asset_code.asc()).all() + rows = [ + { + "id": a.id, + "asset_code": a.asset_code, + "name": a.name, + "department_id": a.department_id, + "department_name": a.department.name if a.department else "\u2014", + "location_name": a.location.name if a.location else "\u2014", + "category_name": a.category.name if a.category else "\u2014", + "serial_no": a.serial_no or "\u2014", + "status": a.status, + } + for a in assets + ] + return { + "report_key": "equipment-inventory", + "title": "Equipment Inventory Report", + "filters_applied": _clean_filters(department_id=dept_id, category_id=category_id, status=status_filter), + "summary": { + "total_assets": len(rows), + "in_service": sum(1 for a in assets if a.status == "in_service"), + "under_repair": sum(1 for a in assets if a.status == "under_repair"), + "condemned": sum(1 for a in assets if a.status == "condemned"), + }, + "columns": [ + {"key": "asset_code", "label": "Asset Code"}, + {"key": "name", "label": "Equipment Name"}, + {"key": "department_name", "label": "Department"}, + {"key": "location_name", "label": "Location"}, + {"key": "category_name", "label": "Category"}, + {"key": "serial_no", "label": "Serial No"}, + {"key": "status", "label": "Status"}, + ], + "rows": rows, + } + + +def _build_condemned_equipment( + db: Session, + user: User, + params: dict[str, Any], +) -> dict[str, Any]: + condemned_params = dict(params) + condemned_params["status"] = "condemned" + rep = _build_equipment_inventory(db, user, condemned_params) + rep["report_key"] = "condemned-equipment" + rep["title"] = "Condemned Equipment Report" + return rep + + +REPORT_BUILDERS: dict[str, Callable[[Session, User, dict[str, Any]], dict[str, Any]]] = { + "monthly-maintenance": _build_monthly_maintenance, + "monthly-department": _build_monthly_department, + "daily-visit": _build_daily_visit, + "breakdown-complaints": _build_breakdown_complaints, + "pm-compliance": _build_pm_compliance, + "calibration-due": _build_calibration_due, + "contracts-warranty": _build_contracts_warranty, + "demo-equipment": _build_demo_equipment, + # Auditor & alternate aliases + "equipment-inventory": _build_equipment_inventory, + "equipment_inventory": _build_equipment_inventory, + "condemned-equipment": _build_condemned_equipment, + "condemned_equipment": _build_condemned_equipment, + "pm-schedule": _build_pm_compliance, + "pm_schedule": _build_pm_compliance, + "calibration-schedule": _build_calibration_due, + "calibration_schedule": _build_calibration_due, + "breakdown-analysis": _build_breakdown_complaints, + "breakdown_analysis": _build_breakdown_complaints, + "amc-cmc-status": _build_contracts_warranty, + "amc_cmc_status": _build_contracts_warranty, + "daily-department-visit": _build_daily_visit, + "daily_department_visit": _build_daily_visit, + "monthly_department": _build_monthly_department, + "monthly_maintenance": _build_monthly_maintenance, +} + + +def generate_report( + db: Session, + user: User, + report_key: str, + params: dict[str, Any], +) -> dict[str, Any]: + builder = REPORT_BUILDERS.get(report_key) + if builder is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Unknown report key '{report_key}'.", + ) + return builder(db, user, params) diff --git a/backend/app/services/scoping.py b/backend/app/services/scoping.py new file mode 100644 index 0000000..f4c21ac --- /dev/null +++ b/backend/app/services/scoping.py @@ -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, + ) diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.py new file mode 100644 index 0000000..09729c5 --- /dev/null +++ b/backend/app/services/settings_service.py @@ -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) diff --git a/backend/data/.gitkeep b/backend/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/backend/data/uploads/.gitkeep b/backend/data/uploads/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/backend/pytest.ini b/backend/pytest.ini new file mode 100644 index 0000000..18187b6 --- /dev/null +++ b/backend/pytest.ini @@ -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 + diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..cf53ac8 --- /dev/null +++ b/backend/requirements.txt @@ -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 diff --git a/backend/scripts/backup.py b/backend/scripts/backup.py new file mode 100644 index 0000000..7820dff --- /dev/null +++ b/backend/scripts/backup.py @@ -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()) diff --git a/backend/tests/__init__.py b/backend/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py new file mode 100644 index 0000000..57de051 --- /dev/null +++ b/backend/tests/conftest.py @@ -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() diff --git a/backend/tests/test_ai1_cost_inputs.py b/backend/tests/test_ai1_cost_inputs.py new file mode 100644 index 0000000..3beda12 --- /dev/null +++ b/backend/tests/test_ai1_cost_inputs.py @@ -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 + diff --git a/backend/tests/test_ai2_coverage_tagging.py b/backend/tests/test_ai2_coverage_tagging.py new file mode 100644 index 0000000..544d33a --- /dev/null +++ b/backend/tests/test_ai2_coverage_tagging.py @@ -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 + diff --git a/backend/tests/test_ai3_metrics.py b/backend/tests/test_ai3_metrics.py new file mode 100644 index 0000000..dc28ca2 --- /dev/null +++ b/backend/tests/test_ai3_metrics.py @@ -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}) + diff --git a/backend/tests/test_ai4_suggestions.py b/backend/tests/test_ai4_suggestions.py new file mode 100644 index 0000000..873e554 --- /dev/null +++ b/backend/tests/test_ai4_suggestions.py @@ -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 + diff --git a/backend/tests/test_ai5_narrative.py b/backend/tests/test_ai5_narrative.py new file mode 100644 index 0000000..84b271a --- /dev/null +++ b/backend/tests/test_ai5_narrative.py @@ -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 + diff --git a/backend/tests/test_ai6_api.py b/backend/tests/test_ai6_api.py new file mode 100644 index 0000000..a51efc3 --- /dev/null +++ b/backend/tests/test_ai6_api.py @@ -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 + diff --git a/backend/tests/test_asset_bulk_import.py b/backend/tests/test_asset_bulk_import.py new file mode 100644 index 0000000..5f23f0b --- /dev/null +++ b/backend/tests/test_asset_bulk_import.py @@ -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" diff --git a/backend/tests/test_assets_and_attachments.py b/backend/tests/test_assets_and_attachments.py new file mode 100644 index 0000000..cdb61c3 --- /dev/null +++ b/backend/tests/test_assets_and_attachments.py @@ -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 diff --git a/backend/tests/test_auth_and_permissions.py b/backend/tests/test_auth_and_permissions.py new file mode 100644 index 0000000..a221f19 --- /dev/null +++ b/backend/tests/test_auth_and_permissions.py @@ -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 diff --git a/backend/tests/test_backup_paths.py b/backend/tests/test_backup_paths.py new file mode 100644 index 0000000..873b1d6 --- /dev/null +++ b/backend/tests/test_backup_paths.py @@ -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) diff --git a/backend/tests/test_bulk_imports_extra.py b/backend/tests/test_bulk_imports_extra.py new file mode 100644 index 0000000..70d8df3 --- /dev/null +++ b/backend/tests/test_bulk_imports_extra.py @@ -0,0 +1,239 @@ +from io import BytesIO +import openpyxl +import pytest + +from app.models import Asset, CalibrationPlan, CalibrationRecord, Contract, InsurancePolicy, Vendor +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_extra_import_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("extra_import_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def _make_xlsx_bytes(sheet_name: str, headers: list[str], rows: list[list[object]]) -> bytes: + wb = openpyxl.Workbook() + ws = wb.active + ws.title = sheet_name + ws.append(headers) + for r in rows: + ws.append(r) + buf = BytesIO() + wb.save(buf) + return buf.getvalue() + + +def test_contracts_bulk_import_lifecycle(client, db): + admin_headers = _auth_headers(client, "admin@poona.demo") + + asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first() + vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first() + assert asset is not None + assert vendor is not None + + headers = [ + "asset_code", + "provider_name", + "contract_type", + "start_date", + "end_date", + "cost", + "coverage_details", + "remarks", + ] + + # 1 valid, 1 invalid (invalid contract_type) + rows = [ + [ + asset.asset_code, + vendor.name, + "CMC", + "2026-01-01", + "2026-12-31", + 85000, + "All parts included", + "Annual contract", + ], + [ + asset.asset_code, + vendor.name, + "INVALID_TYPE", + "2026-01-01", + "2026-12-31", + 50000, + "Test", + "Test remarks", + ], + ] + + xlsx_bytes = _make_xlsx_bytes("Contracts", headers, rows) + + # Dry run + res = client.post( + "/api/contracts/bulk-import?dry_run=true", + headers=admin_headers, + files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + ) + assert res.status_code == 200 + data = res.json() + assert data["dry_run"] is True + assert data["total_rows"] == 2 + assert data["valid_count"] == 1 + assert data["error_count"] == 1 + assert data["created_count"] == 0 + + # Fail commit without skip_invalid + res_fail = client.post( + "/api/contracts/bulk-import?dry_run=false&skip_invalid=false", + headers=admin_headers, + files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + ) + assert res_fail.status_code == 400 + + # Commit with skip_invalid + res_commit = client.post( + "/api/contracts/bulk-import?dry_run=false&skip_invalid=true", + headers=admin_headers, + files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + ) + assert res_commit.status_code == 200 + commit_data = res_commit.json() + assert commit_data["created_count"] == 1 + + created_contract = ( + db.query(Contract) + .filter(Contract.asset_id == asset.id, Contract.contract_type == "CMC") + .order_by(Contract.id.desc()) + .first() + ) + assert created_contract is not None + assert created_contract.provider_id == vendor.id + + +def test_calibration_bulk_import_lifecycle(client, db): + admin_headers = _auth_headers(client, "admin@poona.demo") + + # Find asset without calibration plan + existing_plan_ids = [p.asset_id for p in db.query(CalibrationPlan.asset_id).all()] + asset = db.query(Asset).filter(Asset.id.notin_(existing_plan_ids)).first() + assert asset is not None + vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first() + assert vendor is not None + + headers = [ + "asset_code", + "frequency_months", + "agency_name", + "scope", + "standards", + "remarks", + ] + + rows = [ + [ + asset.asset_code, + 12, + vendor.name, + "Accuracy verification", + "ISO 17025", + "Imported plan", + ], + ] + + xlsx_bytes = _make_xlsx_bytes("Calibration Plans", headers, rows) + + # Dry run + res = client.post( + "/api/calibration/bulk-import?dry_run=true", + headers=admin_headers, + files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + ) + assert res.status_code == 200 + data = res.json() + assert data["valid_count"] == 1 + assert data["error_count"] == 0 + + # Commit + res_commit = client.post( + "/api/calibration/bulk-import?dry_run=false", + headers=admin_headers, + files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + ) + assert res_commit.status_code == 200 + assert res_commit.json()["created_count"] == 1 + + plan = db.query(CalibrationPlan).filter(CalibrationPlan.asset_id == asset.id).first() + assert plan is not None + assert plan.frequency_months == 12 + + record = db.query(CalibrationRecord).filter(CalibrationRecord.plan_id == plan.id).first() + assert record is not None + + +def test_insurance_bulk_import_lifecycle(client, db): + admin_headers = _auth_headers(client, "admin@poona.demo") + + asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first() + vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first() + assert asset is not None + assert vendor is not None + + headers = [ + "asset_code", + "insurer_name", + "policy_number", + "start_date", + "end_date", + "insured_value", + "premium", + "remarks", + ] + + rows = [ + [ + asset.asset_code, + vendor.name, + "POL-TEST-9999", + "2026-04-01", + "2027-03-31", + 1200000, + 15000, + "Annual equipment insurance", + ], + ] + + xlsx_bytes = _make_xlsx_bytes("Insurance Policies", headers, rows) + + # Dry run + res = client.post( + "/api/insurance/bulk-import?dry_run=true", + headers=admin_headers, + files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + ) + assert res.status_code == 200 + data = res.json() + assert data["valid_count"] == 1 + assert data["error_count"] == 0 + + # Commit + res_commit = client.post( + "/api/insurance/bulk-import?dry_run=false", + headers=admin_headers, + files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + ) + assert res_commit.status_code == 200 + assert res_commit.json()["created_count"] == 1 + + pol = db.query(InsurancePolicy).filter(InsurancePolicy.policy_no == "POL-TEST-9999").first() + assert pol is not None + assert pol.coverage_amount == 1200000 + assert pol.asset_id == asset.id + diff --git a/backend/tests/test_complaints.py b/backend/tests/test_complaints.py new file mode 100644 index 0000000..77b63e1 --- /dev/null +++ b/backend/tests/test_complaints.py @@ -0,0 +1,602 @@ +from datetime import date, datetime, timedelta, timezone +import pytest + +from app.core.time_utils import KOLKATA +from app.models import Asset, Complaint, Department, User +from app.seed.seed import seed_database +from app.services.calculations import ( + clip_downtime_to_month, + compute_ce_response_time_minutes, + compute_downtime_minutes, + compute_response_time_minutes, +) +from app.services.numbering import generate_complaint_no + + +@pytest.fixture(scope="module", autouse=True) +def seeded_complaints_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("complaint_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def test_generate_complaint_no_and_custom_prefix(db): + dt = datetime(2026, 4, 15, 10, 0, tzinfo=timezone.utc) + # Seed created CMP-2026-0001..0030 (when run in 2026) or current year; test custom prefix cleanly + c1 = generate_complaint_no(db, "PHRC", dt) + assert c1 == "PHRC-2026-0001" + + # Existing CMP prefix in current KOLKATA year increments sequentially + now_utc = datetime.now(timezone.utc) + cur_year = now_utc.astimezone(KOLKATA).year + next_cmp = generate_complaint_no(db, "CMP", now_utc) + assert next_cmp == f"CMP-{cur_year}-0031" + + +def test_response_time_and_downtime_calculations(): + reg = datetime(2026, 5, 10, 8, 0, tzinfo=timezone.utc) + recv = datetime(2026, 5, 10, 8, 15, tzinfo=timezone.utc) + att = datetime(2026, 5, 10, 9, 0, tzinfo=timezone.utc) + rst = datetime(2026, 5, 10, 11, 30, tzinfo=timezone.utc) + cls = datetime(2026, 5, 10, 12, 0, tzinfo=timezone.utc) + ce_att = datetime(2026, 5, 10, 10, 0, tzinfo=timezone.utc) + now = datetime(2026, 5, 10, 13, 0, tzinfo=timezone.utc) + + # Response time + assert compute_response_time_minutes(reg, recv, None, "registered_at") is None + assert compute_response_time_minutes(reg, recv, att, "registered_at") == 60 + assert compute_response_time_minutes(reg, recv, att, "received_at") == 45 + + # CE response time + assert compute_ce_response_time_minutes(reg, None) is None + assert compute_ce_response_time_minutes(reg, ce_att) == 120 + + # Downtime milestones + assert compute_downtime_minutes(reg, att, rst, cls, "attended_at", now) == (60, False) + assert compute_downtime_minutes(reg, att, rst, cls, "restored_at", now) == (210, False) + assert compute_downtime_minutes(reg, att, rst, cls, "closed_at", now) == (240, False) + + # Ongoing downtime when chosen milestone is None + assert compute_downtime_minutes(reg, att, None, None, "restored_at", now) == (300, True) + + +def test_clip_downtime_to_month_across_boundary(): + # Jan 30 22:00 IST to Feb 02 04:00 IST + start_utc = KOLKATA.localize(datetime(2026, 1, 30, 22, 0, 0)).astimezone(timezone.utc) + end_utc = KOLKATA.localize(datetime(2026, 2, 2, 4, 0, 0)).astimezone(timezone.utc) + + jan_mins, jan_days = clip_downtime_to_month(start_utc, end_utc, 2026, 1) + assert jan_mins == 26 * 60 # 2h on Jan 30 + 24h on Jan 31 = 1560 mins + assert jan_days == {date(2026, 1, 30), date(2026, 1, 31)} + + feb_mins, feb_days = clip_downtime_to_month(start_utc, end_utc, 2026, 2) + assert feb_mins == 28 * 60 # 24h on Feb 1 + 4h on Feb 2 = 1680 mins + assert feb_days == {date(2026, 2, 1), date(2026, 2, 2)} + + mar_mins, mar_days = clip_downtime_to_month(start_utc, end_utc, 2026, 3) + assert mar_mins == 0 + assert mar_days == set() + + +def test_complaint_field_level_permissions(client, db): + dept_headers = _auth_headers(client, "dept@poona.demo") + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + coord_headers = _auth_headers(client, "coord@poona.demo") + bio_headers = _auth_headers(client, "bio@poona.demo") + admin_headers = _auth_headers(client, "admin@poona.demo") + + icu = db.query(Department).filter(Department.code == "ICU").first() + ot = db.query(Department).filter(Department.code == "OT").first() + icu_cmp = ( + db.query(Complaint) + .join(Asset, Complaint.asset_id == Asset.id) + .filter(Asset.department_id == icu.id, Complaint.call_status != "closed") + .first() + ) + ot_cmp = ( + db.query(Complaint) + .join(Asset, Complaint.asset_id == Asset.id) + .filter(Asset.department_id == ot.id) + .first() + ) + if icu_cmp is None: + icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first() + r = client.post( + "/api/complaints", + headers=dept_headers, + json={"asset_id": icu_asset.id, "description": "Permission test issue", "priority": "non_critical"}, + ) + assert r.status_code == 201 + icu_cmp_id = r.json()["id"] + else: + icu_cmp_id = icu_cmp.id + + # Department scoping on list and detail + if ot_cmp is not None: + assert client.get(f"/api/complaints/{ot_cmp.id}", headers=dept_headers).status_code == 403 + assert client.get(f"/api/complaints/{ot_cmp.id}/events", headers=dept_headers).status_code == 403 + list_res = client.get("/api/complaints?page_size=200", headers=dept_headers) + assert list_res.status_code == 200 + assert all(item["department_id"] == icu.id for item in list_res.json()["items"]) + + # Restricted technical fields rejected with 403 for dept_user, management, coordinator + for headers in (dept_headers, mgmt_headers, coord_headers): + for payload in ( + {"action_taken": "Replaced PCB"}, + {"root_cause": "Short circuit"}, + {"spare_required": True, "spare_cost_estimate": 5000}, + ): + r = client.patch(f"/api/complaints/{icu_cmp_id}", headers=headers, json=payload) + assert r.status_code == 403 + assert r.json()["code"] == "FORBIDDEN_TECHNICAL_FIELDS" + + # Non-restricted edit by dept_user works on own non-closed complaint, fails for mgmt/coord + assert ( + client.patch( + f"/api/complaints/{icu_cmp_id}", + headers=dept_headers, + json={"notes": "Updated ward note"}, + ).status_code + == 200 + ) + assert ( + client.patch( + f"/api/complaints/{icu_cmp_id}", + headers=mgmt_headers, + json={"notes": "Mgmt edit"}, + ).status_code + == 403 + ) + assert ( + client.patch( + f"/api/complaints/{icu_cmp_id}", + headers=coord_headers, + json={"notes": "Coord edit"}, + ).status_code + == 403 + ) + + # biomedical and system_admin succeed on technical fields + bio_patch = client.patch( + f"/api/complaints/{icu_cmp_id}", + headers=bio_headers, + json={"action_taken": "Cleaned connector", "root_cause": "Loose cable"}, + ) + assert bio_patch.status_code == 200 + assert bio_patch.json()["action_taken"] == "Cleaned connector" + + admin_patch = client.patch( + f"/api/complaints/{icu_cmp_id}", + headers=admin_headers, + json={"corrective_action": "Secured latch"}, + ) + assert admin_patch.status_code == 200 + assert admin_patch.json()["corrective_action"] == "Secured latch" + + +def test_full_complaint_workflow_and_asset_status_sync(client, db): + dept_headers = _auth_headers(client, "dept@poona.demo") + bio_headers = _auth_headers(client, "bio@poona.demo") + admin_headers = _auth_headers(client, "admin@poona.demo") + + icu = db.query(Department).filter(Department.code == "ICU").first() + asset = db.query(Asset).filter(Asset.department_id == icu.id, Asset.status == "in_service").first() + assert asset is not None + + bio1 = db.query(User).filter(User.email == "bio@poona.demo").first() + bio2 = db.query(User).filter(User.email == "vikram.shinde@poona.demo").first() + + # 1. Dept user raises critical complaint -> asset becomes under_repair + create_res = client.post( + "/api/complaints", + headers=dept_headers, + json={ + "asset_id": asset.id, + "description": "Ventilator pressure drop alarm", + "breakdown_details": "Alarm triggered during patient weaning", + "priority": "critical", + "notes": "Urgent ICU support needed", + }, + ) + assert create_res.status_code == 201, create_res.text + cmp_data = create_res.json() + cid = cmp_data["id"] + assert cmp_data["call_status"] == "open" + assert cmp_data["asset_status"] == "under_repair" + assert cmp_data["downtime_is_ongoing"] is True + + # 2. Assign -> reassign (events logged) + asg1 = client.post( + f"/api/complaints/{cid}/assign", + headers=bio_headers, + json={"assigned_to_id": bio1.id, "note": "Initial assignment"}, + ) + assert asg1.status_code == 200 + assert asg1.json()["call_status"] == "in_progress" + assert asg1.json()["assigned_to_id"] == bio1.id + + asg2 = client.post( + f"/api/complaints/{cid}/assign", + headers=bio_headers, + json={"assigned_to_id": bio2.id, "note": "Escalated to senior bio"}, + ) + assert asg2.status_code == 200 + assert asg2.json()["assigned_to_id"] == bio2.id + + # 3. Attend -> response_time_minutes computed + att_res = client.post( + f"/api/complaints/{cid}/attend", + headers=bio_headers, + json={"attended_by_id": bio2.id, "note": "Reached ICU Bay"}, + ) + assert att_res.status_code == 200 + assert att_res.json()["attended_at"] is not None + assert att_res.json()["response_time_minutes"] is not None + + # 4. Edit technical / spare / CE fields + ce_time = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat() + tech_res = client.patch( + f"/api/complaints/{cid}", + headers=bio_headers, + json={ + "action_taken": "Replaced inspiratory valve diaphragm", + "root_cause": "Diaphragm tear", + "corrective_action": "Replaced valve kit and ran leak test", + "lessons_learned": "Inspect diaphragm at every 6m PM", + "ce_name": "Mahesh Kulkarni (OEM)", + "ce_attended_at": ce_time, + "ce_action_taken": "Calibrated flow sensor post replacement", + "spare_required": True, + "spare_details": "Inspiratory valve diaphragm kit", + "spare_cost_estimate": 12500.0, + }, + ) + assert tech_res.status_code == 200 + assert tech_res.json()["spare_required"] is True + assert tech_res.json()["ce_response_time_minutes"] is not None + + # 5. Restore -> asset returns to in_service + rst_res = client.post( + f"/api/complaints/{cid}/restore", + headers=bio_headers, + json={"note": "Passed 30-min leak test"}, + ) + assert rst_res.status_code == 200 + assert rst_res.json()["restored_at"] is not None + assert rst_res.json()["asset_status"] == "in_service" + assert rst_res.json()["downtime_is_ongoing"] is False + + # 6. Close -> call_status closed + cls_res = client.post( + f"/api/complaints/{cid}/close", + headers=bio_headers, + json={"closure_remarks": "Handed over to ICU charge nurse"}, + ) + assert cls_res.status_code == 200 + assert cls_res.json()["call_status"] == "closed" + assert cls_res.json()["closed_at"] is not None + assert cls_res.json()["asset_status"] == "in_service" + + # 7. Reopen -> critical asset back to under_repair and restored_at cleared + reopen_res = client.post( + f"/api/complaints/{cid}/reopen", + headers=bio_headers, + json={"reason": "Alarm reappeared during shift change"}, + ) + assert reopen_res.status_code == 200 + assert reopen_res.json()["call_status"] == "in_progress" + assert reopen_res.json()["closed_at"] is None + assert reopen_res.json()["restored_at"] is None + assert reopen_res.json()["downtime_is_ongoing"] is True + assert reopen_res.json()["asset_status"] == "under_repair" + + # 8. Correct timestamp: biomedical -> 403, system_admin -> 200 + new_reg = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat() + bio_ts = client.post( + f"/api/complaints/{cid}/correct-timestamp", + headers=bio_headers, + json={"field": "registered_at", "new_value": new_reg, "reason": "Late entry"}, + ) + assert bio_ts.status_code == 403 + + admin_ts = client.post( + f"/api/complaints/{cid}/correct-timestamp", + headers=admin_headers, + json={"field": "registered_at", "new_value": new_reg, "reason": "Logged after phone call"}, + ) + assert admin_ts.status_code == 200 + assert admin_ts.json()["response_time_minutes"] >= 119 + + # 9. Verify events timeline + ev_res = client.get(f"/api/complaints/{cid}/events", headers=bio_headers) + assert ev_res.status_code == 200 + events = ev_res.json()["items"] + event_types = [e["event_type"] for e in events] + assert event_types == [ + "registered", + "coverage_tagged", + "assigned", + "reassigned", + "attended", + "field_edited", + "restored", + "closed", + "reopened", + "timestamp_corrected", + ] + assert events[3]["from_value"] == bio1.name + assert events[3]["to_value"] == bio2.name + assert events[9]["note"] == "registered_at: Logged after phone call" + + +def test_require_closure_remarks_and_wired_settings(client, db): + from datetime import date + from app.services.calculations import compute_sla_status + + admin_headers = _auth_headers(client, "admin@poona.demo") + bio_headers = _auth_headers(client, "bio@poona.demo") + asset = db.query(Asset).first() + assert asset is not None + + # Create a complaint to test close with require_closure_remarks True vs False + c_res = client.post( + "/api/complaints", + headers=bio_headers, + json={ + "asset_id": asset.id, + "description": "Display backlight flicker", + "priority": "non_critical", + }, + ) + assert c_res.status_code == 201 + cid = c_res.json()["id"] + assert c_res.json()["sla_target_hours"] == 24 + assert c_res.json()["sla_breached"] is False + + # Default require_closure_remarks=True -> blank remarks returns 422 CLOSURE_REMARKS_REQUIRED + fail_close = client.post( + f"/api/complaints/{cid}/close", + headers=bio_headers, + json={"closure_remarks": " "}, + ) + assert fail_close.status_code == 422 + assert fail_close.json()["code"] == "CLOSURE_REMARKS_REQUIRED" + assert fail_close.json()["detail"] == "Closure remarks are required." + + try: + # Disable require_closure_remarks -> blank remarks closes cleanly (200) + upd = client.put( + "/api/settings", + headers=admin_headers, + json={"values": {"require_closure_remarks": False}}, + ) + assert upd.status_code == 200 + + ok_close = client.post( + f"/api/complaints/{cid}/close", + headers=bio_headers, + json={"closure_remarks": ""}, + ) + assert ok_close.status_code == 200 + assert ok_close.json()["call_status"] == "closed" + + # Verify default_pm_mode setting when service_mode is omitted on POST /api/pm/schedules + pm_res = client.post( + "/api/pm/schedules", + headers=bio_headers, + json={ + "asset_id": asset.id, + "frequency_months": 6, + "responsible_team": "Biomedical Team", + "next_planned_date": str(date.today()), + }, + ) + assert pm_res.status_code == 201, pm_res.text + assert pm_res.json()["service_mode"] == "in_house" + finally: + client.put( + "/api/settings", + headers=admin_headers, + json={"values": {"require_closure_remarks": True}}, + ) + + # Pure unit test for compute_sla_status using injected SLA settings + t0 = datetime(2026, 6, 1, 8, 0, tzinfo=timezone.utc) + breached, target = compute_sla_status( + "critical", t0, None, None, critical_sla_hours=4, non_critical_sla_hours=24, now_utc=t0 + timedelta(hours=5) + ) + assert target == 4 and breached is True + not_breached, target2 = compute_sla_status( + "non_critical", t0, None, None, critical_sla_hours=4, non_critical_sla_hours=24, now_utc=t0 + timedelta(hours=5) + ) + assert target2 == 24 and not_breached is False + + +def test_close_without_restore_sets_restored_at_and_reopen_recloses(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + asset = db.query(Asset).first() + assert asset is not None + + create_res = client.post( + "/api/complaints", + headers=bio_headers, + json={ + "asset_id": asset.id, + "priority": "non_critical", + "description": "Close without explicit restore check", + }, + ) + assert create_res.status_code == 201, create_res.text + cid = create_res.json()["id"] + + # Close directly without /restore -> restored_at is backfilled to closed_at + close1 = client.post( + f"/api/complaints/{cid}/close", + headers=bio_headers, + json={"closure_remarks": "Resolved during inspection"}, + ) + assert close1.status_code == 200, close1.text + c1 = close1.json() + assert c1["call_status"] == "closed" + assert c1["closed_at"] is not None + assert c1["restored_at"] == c1["closed_at"] + assert c1["downtime_is_ongoing"] is False + + # Reopen -> restored_at is cleared and downtime is ongoing again + reopen1 = client.post( + f"/api/complaints/{cid}/reopen", + headers=bio_headers, + json={"reason": "Issue recurred"}, + ) + assert reopen1.status_code == 200, reopen1.text + r1 = reopen1.json() + assert r1["call_status"] != "closed" + assert r1["restored_at"] is None + assert r1["closed_at"] is None + assert r1["downtime_is_ongoing"] is True + + # Close again without /restore -> restored_at == closed_at again + close2 = client.post( + f"/api/complaints/{cid}/close", + headers=bio_headers, + json={"closure_remarks": "Replaced cable and verified"}, + ) + assert close2.status_code == 200, close2.text + c2 = close2.json() + assert c2["closed_at"] is not None + assert c2["restored_at"] == c2["closed_at"] + assert c2["downtime_is_ongoing"] is False + + +def test_sla_breach_alert_emitted_and_suppressed_when_restored(client, db): + from app.core.time_utils import effective_now_utc + from app.models import Notification + from app.services.alerts import run_alert_check + + bio_headers = _auth_headers(client, "bio@poona.demo") + asset = db.query(Asset).first() + assert asset is not None + + r_unrestored = client.post( + "/api/complaints", + headers=bio_headers, + json={ + "asset_id": asset.id, + "priority": "critical", + "description": "SLA breach unrestored test", + }, + ) + r_restored = client.post( + "/api/complaints", + headers=bio_headers, + json={ + "asset_id": asset.id, + "priority": "critical", + "description": "SLA breach already restored test", + }, + ) + assert r_unrestored.status_code == 201 and r_restored.status_code == 201 + cid_unrestored = r_unrestored.json()["id"] + cid_restored = r_restored.json()["id"] + + now = effective_now_utc(db) + past_5h = now - timedelta(hours=5) + try: + c_unrestored = db.query(Complaint).filter(Complaint.id == cid_unrestored).first() + c_restored = db.query(Complaint).filter(Complaint.id == cid_restored).first() + c_unrestored.registered_at = past_5h + c_unrestored.restored_at = None + c_restored.registered_at = past_5h + c_restored.restored_at = now - timedelta(hours=1) + db.commit() + + run_alert_check(db) + db.commit() + + sla_unrestored = ( + db.query(Notification) + .filter( + Notification.type == "sla_breach", + Notification.entity_type == "complaint", + Notification.entity_id == cid_unrestored, + ) + .all() + ) + assert len(sla_unrestored) == 1 + assert "SLA Breach: Open > 4h" in sla_unrestored[0].title + + # Restored complaint past SLA should NOT emit sla_breach + sla_restored = ( + db.query(Notification) + .filter( + Notification.type == "sla_breach", + Notification.entity_type == "complaint", + Notification.entity_id == cid_restored, + ) + .all() + ) + assert sla_restored == [] + + # 5h open is < default escalation_open_complaint_hours (24h), so critical_complaint stays silent + crit_unrestored = ( + db.query(Notification) + .filter( + Notification.type == "critical_complaint", + Notification.entity_type == "complaint", + Notification.entity_id == cid_unrestored, + ) + .all() + ) + assert crit_unrestored == [] + + # When open > 24h, unrestored complaint triggers critical_complaint alert, + # but restored complaint does NOT trigger it even if not closed yet + past_26h = now - timedelta(hours=26) + c_unrestored.registered_at = past_26h + c_restored.registered_at = past_26h + db.commit() + run_alert_check(db) + db.commit() + + crit_unrestored_26h = ( + db.query(Notification) + .filter( + Notification.type == "critical_complaint", + Notification.entity_type == "complaint", + Notification.entity_id == cid_unrestored, + ) + .all() + ) + assert len(crit_unrestored_26h) == 1 + assert "Critical Complaint Open > 24h" in crit_unrestored_26h[0].title + + crit_restored_26h = ( + db.query(Notification) + .filter( + Notification.type == "critical_complaint", + Notification.entity_type == "complaint", + Notification.entity_id == cid_restored, + ) + .all() + ) + assert crit_restored_26h == [] + finally: + db.query(Notification).filter( + Notification.entity_type == "complaint", + Notification.entity_id.in_([cid_unrestored, cid_restored]), + ).delete(synchronize_session=False) + db.commit() + for cid_cleanup in (cid_unrestored, cid_restored): + client.post( + f"/api/complaints/{cid_cleanup}/close", + headers=bio_headers, + json={"closure_remarks": "Cleanup after SLA alert test"}, + ) + + diff --git a/backend/tests/test_gap_features.py b/backend/tests/test_gap_features.py new file mode 100644 index 0000000..5695f9a --- /dev/null +++ b/backend/tests/test_gap_features.py @@ -0,0 +1,234 @@ +from io import BytesIO +from datetime import date, timedelta +import pytest + +from app.core.time_utils import effective_today +from app.models import Asset, Department, Location, PMRecord, PMSchedule, Vendor +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def _seed(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("uploads") + seed_database(db, upload_dir=upload_dir) + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + token = res.json()["access_token"] + return {"Authorization": f"Bearer {token}"} + + +def test_pm_record_attachment_upload_and_download(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + pm_rec = db.query(PMRecord).first() + assert pm_rec is not None + + # Valid PDF file upload against pm_record + fake_pdf = b"%PDF-1.4 sample pm service report job sheet content" + files = {"file": ("pm_service_report.pdf", BytesIO(fake_pdf), "application/pdf")} + data = {"entity_type": "pm_record", "entity_id": str(pm_rec.id)} + + upload_res = client.post("/api/attachments", headers=bio_headers, data=data, files=files) + assert upload_res.status_code == 201, upload_res.text + att_data = upload_res.json() + att_id = att_data["id"] + assert att_data["entity_type"] == "pm_record" + assert att_data["original_name"] == "pm_service_report.pdf" + + # List attachments for pm_record + list_res = client.get( + f"/api/attachments?entity_type=pm_record&entity_id={pm_rec.id}", + headers=bio_headers, + ) + assert list_res.status_code == 200 + assert any(item["id"] == att_id for item in list_res.json()["items"]) + + # Download attachment + dl_res = client.get(f"/api/attachments/{att_id}/download", headers=bio_headers) + assert dl_res.status_code == 200 + assert dl_res.content == fake_pdf + + +def test_complaint_assigned_team_and_location_filter(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + asset = db.query(Asset).filter(Asset.location_id.isnot(None)).first() + assert asset is not None + + # 1. Raise complaint with assigned_team + res = client.post( + "/api/complaints", + headers=bio_headers, + json={ + "asset_id": asset.id, + "description": "Ventilator screen flickering", + "priority": "non_critical", + "assigned_team": "Biomedical Clinical Support", + }, + ) + assert res.status_code == 201, res.text + c_data = res.json() + cid = c_data["id"] + assert c_data["assigned_team"] == "Biomedical Clinical Support" + + # 2. Assign team via /assign endpoint + assign_res = client.post( + f"/api/complaints/{cid}/assign", + headers=bio_headers, + json={"assigned_team": "External Vendor Tier 2 Team", "note": "Assigned to specialized vendor team"}, + ) + assert assign_res.status_code == 200, assign_res.text + assert assign_res.json()["assigned_team"] == "External Vendor Tier 2 Team" + + # 3. Filter by location_id + loc_res = client.get( + f"/api/complaints?location_id={asset.location_id}", + headers=bio_headers, + ) + assert loc_res.status_code == 200 + items = loc_res.json()["items"] + assert any(c["id"] == cid for c in items) + + +def test_demo_equipment_serial_no(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + dept = db.query(Department).first() + vendor = db.query(Vendor).first() + today = effective_today(db) + + # Create demo equipment with serial_no + res = client.post( + "/api/demo-equipment", + headers=bio_headers, + json={ + "name": "Trial Dialysis Unit", + "equipment_type": "Dialysis", + "serial_no": "DEMO-SN-DIAL-901", + "supplier_id": vendor.id, + "department_id": dept.id, + "start_date": str(today), + "expected_return_date": str(today + timedelta(days=14)), + "remarks": "Evaluation unit on 14-day trial", + }, + ) + assert res.status_code == 201, res.text + demo_data = res.json() + demo_id = demo_data["id"] + assert demo_data["serial_no"] == "DEMO-SN-DIAL-901" + + # List demo equipment + list_res = client.get(f"/api/demo-equipment?department_id={dept.id}", headers=bio_headers) + assert list_res.status_code == 200 + found = next((item for item in list_res.json()["items"] if item["id"] == demo_id), None) + assert found is not None + assert found["serial_no"] == "DEMO-SN-DIAL-901" + + +def test_department_visit_new_requirements_and_monthly_report(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + dept = db.query(Department).first() + today = effective_today(db) + + # Create visit with new_requirements + req_text = "Urgent: Requesting 2 additional Infusion Pumps for Bed 3 & 4" + res = client.post( + "/api/visits", + headers=bio_headers, + json={ + "department_id": dept.id, + "visit_date": str(today), + "observations": "All ICU ventilators functioning normally; routine checks complete.", + "new_requirements": req_text, + }, + ) + assert res.status_code == 201, res.text + v_data = res.json() + assert v_data["new_requirements"] == req_text + + # Monthly Department Report reflects new requirements + month_str = today.strftime("%Y-%m") + rep_res = client.get( + f"/api/reports/monthly-department?month={month_str}&department_id={dept.id}", + headers=mgmt_headers, + ) + assert rep_res.status_code == 200, rep_res.text + rows = rep_res.json()["rows"] + dept_row = next((r for r in rows if r["department_id"] == dept.id), None) + assert dept_row is not None + assert req_text in dept_row["new_equipment_requirements"] + + +def test_asset_calibration_and_insurance_filters(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + + # Filter calibration applicable + res_cal_yes = client.get("/api/assets?requires_calibration=true", headers=bio_headers) + assert res_cal_yes.status_code == 200 + for a in res_cal_yes.json()["items"]: + assert a["requires_calibration"] is True + + res_cal_no = client.get("/api/assets?requires_calibration=false", headers=bio_headers) + assert res_cal_no.status_code == 200 + for a in res_cal_no.json()["items"]: + assert a["requires_calibration"] is False + + # Filter insurance applicable + res_ins_yes = client.get("/api/assets?insurance_applicable=true", headers=bio_headers) + assert res_ins_yes.status_code == 200 + for a in res_ins_yes.json()["items"]: + assert a["insurance_applicable"] is True + + +def test_bulk_import_templates_endpoints(client): + coord_headers = _auth_headers(client, "coord@poona.demo") + + # Contracts template + r_c = client.get("/api/contracts/import-template", headers=coord_headers) + assert r_c.status_code == 200 + assert r_c.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + assert len(r_c.content) > 1000 + + # Calibration template + r_cal = client.get("/api/calibration/import-template", headers=coord_headers) + assert r_cal.status_code == 200 + assert r_cal.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + assert len(r_cal.content) > 1000 + + # Insurance template + r_ins = client.get("/api/insurance/import-template", headers=coord_headers) + assert r_ins.status_code == 200 + assert r_ins.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + assert len(r_ins.content) > 1000 + + +def test_sqlite_auto_migration_reconciles_missing_columns(): + from sqlalchemy import create_engine + from app.core.migrations import run_sqlite_migrations + + test_eng = create_engine("sqlite:///:memory:") + with test_eng.begin() as conn: + # Create complaints table without assigned_team column + conn.exec_driver_sql( + "CREATE TABLE complaints (" + "id INTEGER PRIMARY KEY, " + "complaint_no VARCHAR(50), " + "asset_id INTEGER, " + "description TEXT, " + "priority VARCHAR(50), " + "registered_at DATETIME, " + "registered_by_id INTEGER, " + "received_by_id INTEGER, " + "call_status VARCHAR(50)" + ")" + ) + cols_before = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()} + assert "assigned_team" not in cols_before + + # Run auto-migration + run_sqlite_migrations(test_eng) + + with test_eng.begin() as conn: + cols_after = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()} + assert "assigned_team" in cols_after diff --git a/backend/tests/test_health.py b/backend/tests/test_health.py new file mode 100644 index 0000000..3d55c99 --- /dev/null +++ b/backend/tests/test_health.py @@ -0,0 +1,7 @@ +def test_health_check(client): + response = client.get("/api/health") + assert response.status_code == 200 + data = response.json() + assert data["status"] == "ok" + assert data["service"] == "Poona Hospital AMS" + assert data["version"] == "0.1.0" diff --git a/backend/tests/test_notifications_and_dashboard.py b/backend/tests/test_notifications_and_dashboard.py new file mode 100644 index 0000000..a6b8261 --- /dev/null +++ b/backend/tests/test_notifications_and_dashboard.py @@ -0,0 +1,148 @@ +from datetime import timedelta +import pytest + +from app.core.time_utils import effective_today +from app.models import Asset, Complaint, Department, Notification +from app.seed.seed import seed_database +from app.services.alerts import run_alert_check + + +@pytest.fixture(scope="module", autouse=True) +def seeded_phase6_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("phase6_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def test_alert_check_dedupe_and_seed_notifications(db): + # seed_database already ran run_alert_check -> notifications exist in DB + initial_count = db.query(Notification).count() + assert initial_count > 0 + + # Running run_alert_check again immediately creates 0 duplicates + res2 = run_alert_check(db) + db.commit() + assert res2["created"] == 0 + assert db.query(Notification).count() == initial_count + + +def test_demo_clock_alert_run_and_admin_only_permission(client, db): + admin_headers = _auth_headers(client, "admin@poona.demo") + bio_headers = _auth_headers(client, "bio@poona.demo") + dept_headers = _auth_headers(client, "dept@poona.demo") + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + coord_headers = _auth_headers(client, "coord@poona.demo") + + # Non-admins get 403 on POST /api/alerts/run + for h in (bio_headers, dept_headers, mgmt_headers, coord_headers): + assert client.post("/api/alerts/run", headers=h).status_code == 403 + + base_today = effective_today(db) + future_date = base_today + timedelta(days=20) + + try: + set_res = client.post( + "/api/settings/demo-date", + headers=admin_headers, + json={"demo_as_of_date": str(future_date)}, + ) + assert set_res.status_code == 200 + + # First run at +20 days creates new notifications for newly-entered windows + run1 = client.post("/api/alerts/run", headers=admin_headers) + assert run1.status_code == 200, run1.text + data1 = run1.json() + assert data1["evaluated_today"] == str(future_date) + assert data1["created"] > 0 + + # Second run at same +20 days creates 0 (dedupe) + run2 = client.post("/api/alerts/run", headers=admin_headers) + assert run2.status_code == 200 + assert run2.json()["created"] == 0 + finally: + client.post( + "/api/settings/demo-date", + headers=admin_headers, + json={"demo_as_of_date": None}, + ) + + +def test_per_user_read_state_and_department_scoping(client, db): + admin_headers = _auth_headers(client, "admin@poona.demo") + bio_headers = _auth_headers(client, "bio@poona.demo") + dept_headers = _auth_headers(client, "dept@poona.demo") + + admin_list_before = client.get("/api/notifications?limit=100", headers=admin_headers).json() + bio_list_before = client.get("/api/notifications?limit=100", headers=bio_headers).json() + assert admin_list_before["unread_count"] > 0 + assert bio_list_before["unread_count"] > 0 + + # Pick a calibration_due notification visible to both admin and bio + cal_items = [n for n in admin_list_before["items"] if n["type"] == "calibration_due"] + assert len(cal_items) > 0 + target_id = cal_items[0]["id"] + assert cal_items[0]["link_url"] == "/calibration" + + # Admin marks single notification as read -> bio still sees it unread + mark_res = client.post(f"/api/notifications/{target_id}/read", headers=admin_headers) + assert mark_res.status_code == 200 + assert mark_res.json()["is_read"] is True + + admin_after_one = client.get("/api/notifications?limit=100", headers=admin_headers).json() + bio_after_one = client.get("/api/notifications?limit=100", headers=bio_headers).json() + assert admin_after_one["unread_count"] == admin_list_before["unread_count"] - 1 + assert bio_after_one["unread_count"] == bio_list_before["unread_count"] + + # Admin marks all calibration_due notifications read -> unread_calibration_count becomes 0 for admin, unchanged for bio + mark_cal = client.post("/api/notifications/read-all?type=calibration_due", headers=admin_headers) + assert mark_cal.status_code == 200 + admin_after_cal = client.get("/api/notifications?limit=100", headers=admin_headers).json() + bio_after_cal = client.get("/api/notifications?limit=100", headers=bio_headers).json() + assert admin_after_cal["unread_calibration_count"] == 0 + assert bio_after_cal["unread_calibration_count"] > 0 + + # department_user only sees critical_complaint alerts for their own department (ICU) + icu = db.query(Department).filter(Department.code == "ICU").first() + dept_notifs = client.get("/api/notifications?limit=100", headers=dept_headers).json() + for n in dept_notifs["items"]: + assert n["entity_type"] == "complaint" + assert n["link_url"] == f"/complaints/{n['entity_id']}" + comp = db.query(Complaint).filter(Complaint.id == n["entity_id"]).first() + assert comp.asset.department_id == icu.id + + +def test_dashboard_summary_role_scoping_and_charts(client, db): + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + dept_headers = _auth_headers(client, "dept@poona.demo") + + icu = db.query(Department).filter(Department.code == "ICU").first() + icu_asset_count = db.query(Asset).filter(Asset.department_id == icu.id).count() + total_asset_count = db.query(Asset).count() + + mgmt_res = client.get("/api/dashboard/summary", headers=mgmt_headers) + assert mgmt_res.status_code == 200, mgmt_res.text + mgmt = mgmt_res.json() + assert mgmt["department_scope"] is None + assert mgmt["kpis"]["total_assets"] == total_asset_count + assert len(mgmt["monthly_downtime_trend"]) == 6 + assert len(mgmt["pm_planned_vs_completed"]) == 6 + assert len(mgmt["complaints_by_status"]) == 3 + assert len(mgmt["complaints_by_department"]) >= 2 + assert len(mgmt["recent_complaints"]) <= 8 + + dept_res = client.get("/api/dashboard/summary", headers=dept_headers) + assert dept_res.status_code == 200, dept_res.text + dept = dept_res.json() + assert dept["department_scope"] == icu.name + assert dept["kpis"]["total_assets"] == icu_asset_count + assert dept["kpis"]["total_assets"] < mgmt["kpis"]["total_assets"] + assert len(dept["monthly_downtime_trend"]) == 6 + assert len(dept["pm_planned_vs_completed"]) == 6 + assert [d["department"] for d in dept["complaints_by_department"]] == [icu.name] + assert all(rc["department_name"] == icu.name for rc in dept["recent_complaints"]) diff --git a/backend/tests/test_phase5_modules.py b/backend/tests/test_phase5_modules.py new file mode 100644 index 0000000..4c39772 --- /dev/null +++ b/backend/tests/test_phase5_modules.py @@ -0,0 +1,397 @@ +from datetime import date, timedelta +import io +import pytest +from PIL import Image + +from app.core.time_utils import effective_today +from app.models import Asset, Category, Complaint, Contract, Department, Location, Vendor +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_phase5_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("phase5_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def _make_png_bytes() -> bytes: + buf = io.BytesIO() + Image.new("RGB", (16, 16), color=(20, 90, 160)).save(buf, format="PNG") + return buf.getvalue() + + +def test_contract_create_renew_supersede_history_and_scoping(client, db): + coord_headers = _auth_headers(client, "coord@poona.demo") + dept_headers = _auth_headers(client, "dept@poona.demo") + bio_headers = _auth_headers(client, "bio@poona.demo") + + icu = db.query(Department).filter(Department.code == "ICU").first() + ot = db.query(Department).filter(Department.code == "OT").first() + icu_loc = db.query(Location).filter(Location.department_id == icu.id).first() + cat = db.query(Category).first() + provider = db.query(Vendor).filter(Vendor.vendor_type == "service_provider").first() + + # Dedicated asset in ICU for deterministic renewal chain check + asset_res = client.post( + "/api/assets", + headers=bio_headers, + json={ + "asset_code": "PHRC-CON-001", + "serial_no": "SN-CON-001", + "name": "Contract Renewal Test Ventilator", + "category_id": cat.id, + "department_id": icu.id, + "location_id": icu_loc.id, + "status": "in_service", + "criticality": "critical", + }, + ) + assert asset_res.status_code == 201 + asset_id = asset_res.json()["id"] + + # department_user cannot create contracts + assert ( + client.post( + "/api/contracts", + headers=dept_headers, + json={ + "asset_id": asset_id, + "contract_type": "AMC", + "provider_id": provider.id, + "start_date": "2025-01-01", + "end_date": "2025-12-31", + }, + ).status_code + == 403 + ) + + # Coordinator creates initial contract + c1_res = client.post( + "/api/contracts", + headers=coord_headers, + json={ + "asset_id": asset_id, + "contract_type": "AMC", + "provider_id": provider.id, + "start_date": "2025-01-01", + "end_date": "2025-12-31", + "coverage_period_text": "1 Year", + "remarks": "Initial AMC", + }, + ) + assert c1_res.status_code == 201, c1_res.text + c1 = c1_res.json() + assert c1["is_superseded"] is False + + # Renew contract -> Note N1: old_contract.is_superseded=True, new_contract.renewed_from_id=c1.id + renew_res = client.post( + f"/api/contracts/{c1['id']}/renew", + headers=coord_headers, + json={ + "contract_type": "CMC", + "start_date": "2026-01-01", + "end_date": "2026-12-31", + "coverage_period_text": "1 Year Comprehensive", + "remarks": "Upgraded to CMC", + }, + ) + assert renew_res.status_code == 200, renew_res.text + rj = renew_res.json() + assert rj["old_contract"]["id"] == c1["id"] + assert rj["old_contract"]["is_superseded"] is True + assert rj["old_contract"]["status"] == "superseded" + assert rj["new_contract"]["renewed_from_id"] == c1["id"] + assert rj["new_contract"]["is_superseded"] is False + assert rj["new_contract"]["contract_type"] == "CMC" + + # History returns both contracts newest first + hist_res = client.get(f"/api/contracts/history/{asset_id}", headers=dept_headers) + assert hist_res.status_code == 200 + hist_items = hist_res.json()["items"] + assert len(hist_items) == 2 + assert hist_items[0]["id"] == rj["new_contract"]["id"] + assert hist_items[1]["id"] == c1["id"] + assert hist_items[1]["is_superseded"] is True + + # include_superseded=false hides superseded contract + active_only = client.get( + f"/api/contracts?asset_id={asset_id}&include_superseded=false", + headers=coord_headers, + ).json() + assert active_only["total"] == 1 + assert active_only["items"][0]["id"] == rj["new_contract"]["id"] + + # department_user gets 403 on another department's asset history and list only returns ICU + ot_asset = db.query(Asset).filter(Asset.department_id == ot.id).first() + assert client.get(f"/api/contracts/history/{ot_asset.id}", headers=dept_headers).status_code == 403 + dept_list = client.get("/api/contracts", headers=dept_headers).json()["items"] + assert all(item["department_id"] == icu.id for item in dept_list) + + +def test_warranty_and_insurance_expiry_and_permissions(client, db): + coord_headers = _auth_headers(client, "coord@poona.demo") + dept_headers = _auth_headers(client, "dept@poona.demo") + bio_headers = _auth_headers(client, "bio@poona.demo") + + icu = db.query(Department).filter(Department.code == "ICU").first() + icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first() + insurer = db.query(Vendor).filter(Vendor.vendor_type == "insurer").first() + today = effective_today(db) + + # department_user cannot write warranty or insurance + assert ( + client.post( + "/api/warranties", + headers=dept_headers, + json={ + "asset_id": icu_asset.id, + "duration_months": 12, + "start_date": str(today - timedelta(days=30)), + }, + ).status_code + == 403 + ) + assert ( + client.post( + "/api/insurance", + headers=dept_headers, + json={ + "asset_id": icu_asset.id, + "insurer_id": insurer.id, + "policy_no": "POL-DENIED", + "start_date": str(today), + "end_date": str(today + timedelta(days=365)), + }, + ).status_code + == 403 + ) + + # Coordinator creates expiring warranty (ends in 5 days -> expiring, red) + w_start = today - timedelta(days=360) + w_end = today + timedelta(days=5) + w_res = client.post( + "/api/warranties", + headers=coord_headers, + json={ + "asset_id": icu_asset.id, + "duration_months": 12, + "start_date": str(w_start), + "end_date": str(w_end), + "provider_id": icu_asset.supplier_id, + "remarks": "Expiring warranty check", + }, + ) + assert w_res.status_code == 201, w_res.text + wj = w_res.json() + assert wj["status"] == "expiring" + assert wj["severity"] == "red" + assert wj["days_to_expiry"] == 5 + + # Coordinator creates expired insurance policy (ended yesterday -> expired, red) + ins_res = client.post( + "/api/insurance", + headers=coord_headers, + json={ + "asset_id": icu_asset.id, + "insurer_id": insurer.id, + "policy_no": "PHRC-POL-TEST-99", + "start_date": str(today - timedelta(days=366)), + "end_date": str(today - timedelta(days=1)), + "coverage_amount": 450000.0, + "remarks": "Expired policy check", + }, + ) + assert ins_res.status_code == 201, ins_res.text + ij = ins_res.json() + assert ij["status"] == "expired" + assert ij["severity"] == "red" + assert ij["days_to_expiry"] == -1 + + # Upload attachment to insurance -> attachment_count increments to 1 + up = client.post( + "/api/attachments", + headers=bio_headers, + data={"entity_type": "insurance", "entity_id": str(ij["id"])}, + files={"file": ("policy.png", _make_png_bytes(), "image/png")}, + ) + assert up.status_code == 201 + fetched = client.get(f"/api/insurance?asset_id={icu_asset.id}", headers=coord_headers).json()["items"] + matched = [x for x in fetched if x["id"] == ij["id"]][0] + assert matched["attachment_count"] == 1 + + +def test_demo_equipment_overdue_detection_and_return(client, db): + admin_headers = _auth_headers(client, "admin@poona.demo") + coord_headers = _auth_headers(client, "coord@poona.demo") + dept_headers = _auth_headers(client, "dept@poona.demo") + + icu = db.query(Department).filter(Department.code == "ICU").first() + icu_loc = db.query(Location).filter(Location.department_id == icu.id).first() + supplier = db.query(Vendor).filter(Vendor.vendor_type == "supplier").first() + + # department_user gets 403 on write + assert ( + client.post( + "/api/demo-equipment", + headers=dept_headers, + json={ + "name": "Unauthorized Demo", + "equipment_type": "Monitor", + "supplier_id": supplier.id, + "department_id": icu.id, + "start_date": "2028-01-01", + "expected_return_date": "2028-01-10", + }, + ).status_code + == 403 + ) + + create_res = client.post( + "/api/demo-equipment", + headers=coord_headers, + json={ + "name": "Demo Transport Ventilator X2", + "equipment_type": "Ventilator", + "supplier_id": supplier.id, + "department_id": icu.id, + "location_id": icu_loc.id, + "start_date": "2028-04-01", + "expected_return_date": "2028-04-15", + "remarks": "Clinical trial in ICU", + }, + ) + assert create_res.status_code == 201, create_res.text + demo_id = create_res.json()["id"] + + try: + # 1) Set demo_as_of_date = 2028-04-13 (2 days left -> on_demo, yellow) + client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": "2028-04-13"}) + r1 = [x for x in client.get("/api/demo-equipment", headers=coord_headers).json()["items"] if x["id"] == demo_id][0] + assert r1["status"] == "on_demo" + assert r1["severity"] == "yellow" + assert r1["days_remaining"] == 2 + + # 2) Set demo_as_of_date = 2028-04-20 (past expected_return_date -> overdue_return, red, days_remaining=-5) + client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": "2028-04-20"}) + r2 = [x for x in client.get("/api/demo-equipment?status=overdue_return", headers=coord_headers).json()["items"] if x["id"] == demo_id][0] + assert r2["status"] == "overdue_return" + assert r2["severity"] == "red" + assert r2["days_remaining"] == -5 + + # 3) Mark returned on 2028-04-18 -> status='returned', severity='ok' + ret_res = client.post( + f"/api/demo-equipment/{demo_id}/return", + headers=coord_headers, + json={"actual_return_date": "2028-04-18", "remarks": "Picked up by vendor."}, + ) + assert ret_res.status_code == 200, ret_res.text + rj = ret_res.json() + assert rj["status"] == "returned" + assert rj["severity"] == "ok" + assert rj["actual_return_date"] == "2028-04-18" + finally: + client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": None}) + + +def test_department_visits_permissions_and_multi_linking(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + dept_headers = _auth_headers(client, "dept@poona.demo") + coord_headers = _auth_headers(client, "coord@poona.demo") + + icu = db.query(Department).filter(Department.code == "ICU").first() + icu_assets = db.query(Asset).filter(Asset.department_id == icu.id).limit(2).all() + complaints = db.query(Complaint).limit(3).all() + assert len(icu_assets) >= 2 and len(complaints) >= 3 + + # department_user and coordinator get 403 on GET and POST + assert client.get("/api/visits", headers=dept_headers).status_code == 403 + assert client.get("/api/visits", headers=coord_headers).status_code == 403 + assert ( + client.post( + "/api/visits", + headers=coord_headers, + json={ + "department_id": icu.id, + "visit_date": "2026-05-10", + "observations": "Coordinator denied", + }, + ).status_code + == 403 + ) + + # management can GET (200) but gets 403 on POST + assert client.get("/api/visits", headers=mgmt_headers).status_code == 200 + assert ( + client.post( + "/api/visits", + headers=mgmt_headers, + json={ + "department_id": icu.id, + "visit_date": "2026-05-10", + "observations": "Mgmt write denied", + }, + ).status_code + == 403 + ) + + # biomedical creates visit with multiple assets and initial complaint + create_res = client.post( + "/api/visits", + headers=bio_headers, + json={ + "department_id": icu.id, + "visit_date": "2026-05-10", + "observations": "Checked ICU beds 1-4; alarm issue noted on ventilator.", + "asset_ids": [a.id for a in icu_assets], + "complaint_ids": [complaints[0].id], + }, + ) + assert create_res.status_code == 201, create_res.text + visit = create_res.json() + visit_id = visit["id"] + assert len(visit["assets"]) == 2 + assert [c["id"] for c in visit["complaints"]] == [complaints[0].id] + + # management can GET /api/visits/{id} (200) but gets 403 on link-complaint and PATCH + assert client.get(f"/api/visits/{visit_id}", headers=mgmt_headers).status_code == 200 + assert ( + client.post( + f"/api/visits/{visit_id}/link-complaint", + headers=mgmt_headers, + json={"complaint_id": complaints[1].id}, + ).status_code + == 403 + ) + assert ( + client.patch( + f"/api/visits/{visit_id}", + headers=mgmt_headers, + json={"observations": "Should fail"}, + ).status_code + == 403 + ) + + # biomedical links a second complaint (and linking duplicate is idempotent) + link1 = client.post( + f"/api/visits/{visit_id}/link-complaint", + headers=bio_headers, + json={"complaint_id": complaints[1].id}, + ) + assert link1.status_code == 200, link1.text + assert {c["id"] for c in link1.json()["complaints"]} == {complaints[0].id, complaints[1].id} + + link_dup = client.post( + f"/api/visits/{visit_id}/link-complaint", + headers=bio_headers, + json={"complaint_id": complaints[1].id}, + ) + assert link_dup.status_code == 200 + assert len(link_dup.json()["complaints"]) == 2 diff --git a/backend/tests/test_phase8_polish.py b/backend/tests/test_phase8_polish.py new file mode 100644 index 0000000..82cb8e5 --- /dev/null +++ b/backend/tests/test_phase8_polish.py @@ -0,0 +1,153 @@ +import pytest + +from app.models import Asset, AuditLog, Base, Department, User +from app.routers.auth import MAX_LOGIN_ATTEMPTS, reset_login_rate_limiter +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_phase8_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("phase8_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def test_global_search_grouped_and_department_scoped(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + dept_headers = _auth_headers(client, "dept@poona.demo") + + dept_user = db.query(User).filter(User.email == "dept@poona.demo").first() + icu_dept = db.query(Department).filter(Department.id == dept_user.department_id).first() + assert dept_user is not None and icu_dept is not None + + icu_asset = db.query(Asset).filter(Asset.department_id == icu_dept.id).first() + non_icu_asset = db.query(Asset).filter(Asset.department_id != icu_dept.id).first() + assert icu_asset is not None and non_icu_asset is not None + + # Broad search returns grouped assets & complaints capped at 8 each + broad = client.get("/api/search?q=PHRC", headers=bio_headers) + assert broad.status_code == 200, broad.text + data = broad.json() + assert isinstance(data["assets"], list) and 0 < len(data["assets"]) <= 8 + assert isinstance(data["complaints"], list) and len(data["complaints"]) <= 8 + assert {"id", "asset_code", "name", "serial_no", "department_name", "status"}.issubset( + data["assets"][0].keys() + ) + + # Complaint search by prefix + cmp_search = client.get("/api/search?q=CMP", headers=bio_headers) + assert cmp_search.status_code == 200 + assert len(cmp_search.json()["complaints"]) > 0 + assert { + "id", + "complaint_no", + "asset_code", + "asset_name", + "department_name", + "call_status", + "priority", + }.issubset(cmp_search.json()["complaints"][0].keys()) + + # Department user sees ICU asset, cannot see non-ICU asset + icu_res = client.get(f"/api/search?q={icu_asset.asset_code}", headers=dept_headers) + assert icu_res.status_code == 200 + assert any(a["asset_code"] == icu_asset.asset_code for a in icu_res.json()["assets"]) + + other_res = client.get(f"/api/search?q={non_icu_asset.asset_code}", headers=dept_headers) + assert other_res.status_code == 200 + assert other_res.json()["assets"] == [] + assert other_res.json()["complaints"] == [] + + # Empty query rejected + assert client.get("/api/search?q=", headers=bio_headers).status_code == 422 + + +def test_audit_logs_rbac_and_filters(client, db): + admin_headers = _auth_headers(client, "admin@poona.demo") + for email in ("bio@poona.demo", "mgmt@poona.demo", "dept@poona.demo", "coord@poona.demo"): + headers = _auth_headers(client, email) + assert client.get("/api/audit-logs", headers=headers).status_code == 403 + + # Ensure there is at least one distinct AuditLog entry via API/DB + admin_user = db.query(User).filter(User.email == "admin@poona.demo").first() + assert admin_user is not None + log_entry = AuditLog( + entity_type="asset", + entity_id=9999, + action="phase8_audit_probe", + changes_json='{"status": {"old": "in_service", "new": "under_repair"}}', + by_user_id=admin_user.id, + ) + db.add(log_entry) + db.commit() + + res = client.get("/api/audit-logs?entity_type=asset&action=phase8_audit_probe", headers=admin_headers) + assert res.status_code == 200, res.text + body = res.json() + assert body["total"] >= 1 + assert len(body["items"]) >= 1 + first = body["items"][0] + assert first["entity_type"] == "asset" + assert first["action"] == "phase8_audit_probe" + assert first["by_user_id"] == admin_user.id + assert first["by_user_name"] == admin_user.name + assert "under_repair" in first["changes_json"] + + # Search filter `q` + q_res = client.get("/api/audit-logs?q=phase8_audit_probe", headers=admin_headers) + assert q_res.status_code == 200 + assert q_res.json()["total"] == 1 + + +def test_login_rate_limiter_429_and_reset(client): + reset_login_rate_limiter() + for i in range(MAX_LOGIN_ATTEMPTS): + res = client.post( + "/api/auth/login", + json={"email": "ratelimit@poona.demo", "password": "WrongPassword"}, + ) + assert res.status_code == 401, f"Attempt {i + 1} unexpected status {res.status_code}" + + # Attempt 16 triggers 429 RATE_LIMITED + blocked = client.post( + "/api/auth/login", + json={"email": "ratelimit@poona.demo", "password": "WrongPassword"}, + ) + assert blocked.status_code == 429 + assert blocked.json()["code"] == "RATE_LIMITED" + + # Reset restores login capability + reset_login_rate_limiter() + ok = client.post( + "/api/auth/login", + json={"email": "admin@poona.demo", "password": "Demo@123"}, + ) + assert ok.status_code == 200 + + +def test_database_indexes_defined(): + expected_indexed_columns = { + "assets": {"asset_code", "serial_no", "department_id", "category_id", "location_id", "status"}, + "complaints": {"complaint_no", "asset_id", "registered_at", "call_status", "assigned_to_id"}, + "contracts": {"asset_id", "start_date", "end_date"}, + "warranties": {"asset_id", "start_date", "end_date"}, + "insurance_policies": {"asset_id", "start_date", "end_date"}, + "calibration_records": {"asset_id", "plan_id", "due_date"}, + "pm_records": {"asset_id", "schedule_id", "planned_date"}, + "demo_equipment": {"department_id", "expected_return_date"}, + "department_visits": {"department_id", "visit_date"}, + "attachments": {"entity_type", "entity_id"}, + "notifications": {"created_at", "type"}, + "audit_logs": {"entity_type", "entity_id", "by_user_id", "at"}, + } + for table_name, cols in expected_indexed_columns.items(): + table = Base.metadata.tables[table_name] + indexed = {col.name for idx in table.indexes for col in idx.columns} + missing = cols - indexed + assert not missing, f"Missing indexes on {table_name}: {missing}" diff --git a/backend/tests/test_pm_and_calibration.py b/backend/tests/test_pm_and_calibration.py new file mode 100644 index 0000000..fb83398 --- /dev/null +++ b/backend/tests/test_pm_and_calibration.py @@ -0,0 +1,426 @@ +from datetime import date +import pytest + +from app.core.time_utils import add_months +from app.models import ( + Asset, + CalibrationPlan, + CalibrationRecord, + Category, + Contract, + Department, + Location, + PMRecord, + PMSchedule, + Vendor, +) +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_pm_cal_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("pm_cal_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def _create_test_asset(client, headers, db, code_suffix: str, req_cal: bool = False) -> int: + icu = db.query(Department).filter(Department.code == "ICU").first() + loc = db.query(Location).filter(Location.department_id == icu.id).first() + cat = db.query(Category).first() + res = client.post( + "/api/assets", + headers=headers, + json={ + "asset_code": f"PHRC-PMCAL-{code_suffix}", + "serial_no": f"SN-PMCAL-{code_suffix}", + "name": f"PM Cal Test Unit {code_suffix}", + "category_id": cat.id, + "department_id": icu.id, + "location_id": loc.id, + "status": "in_service", + "criticality": "critical", + "requires_calibration": req_cal, + "insurance_applicable": False, + }, + ) + assert res.status_code == 201, res.text + return res.json()["id"] + + +def test_add_months_clamping_and_db_note_n2(db): + assert add_months(date(2026, 1, 31), 1) == date(2026, 2, 28) + assert add_months(date(2024, 1, 31), 1) == date(2024, 2, 29) + assert add_months(date(2026, 3, 31), 3) == date(2026, 6, 30) + assert add_months(date(2026, 10, 15), 4) == date(2027, 2, 15) + + # Note N2: seeded DB never persists 'upcoming', 'due', or 'overdue' + bad_cal = ( + db.query(CalibrationRecord) + .filter(CalibrationRecord.status.in_(["upcoming", "due", "overdue"])) + .count() + ) + bad_pm = ( + db.query(PMRecord) + .filter(PMRecord.status.in_(["upcoming", "due", "overdue"])) + .count() + ) + assert bad_cal == 0 + assert bad_pm == 0 + + +def test_outsourced_pm_lifecycle_complete_and_reschedule(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + dept_headers = _auth_headers(client, "dept@poona.demo") + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + + provider = db.query(Vendor).filter(Vendor.vendor_type == "service_provider").first() + contract = db.query(Contract).filter(Contract.is_superseded.is_(False)).first() + asset_id = contract.asset_id + + # Forbidden for department_user and management + forbid_res = client.post( + "/api/pm/schedules", + headers=dept_headers, + json={ + "asset_id": asset_id, + "service_mode": "in_house", + "frequency_months": 3, + "responsible_team": "ICU Bio", + "next_planned_date": "2026-06-10", + }, + ) + assert forbid_res.status_code == 403 + assert ( + client.post( + "/api/pm/schedules", + headers=mgmt_headers, + json={ + "asset_id": asset_id, + "service_mode": "in_house", + "frequency_months": 3, + "responsible_team": "Bio Team", + "next_planned_date": "2026-06-10", + }, + ).status_code + == 403 + ) + + # Outsourced PM schedule without provider_id/contract_id auto-fills from active AMC/CMC + auto_out = client.post( + "/api/pm/schedules", + headers=bio_headers, + json={ + "asset_id": asset_id, + "service_mode": "outsourced", + "frequency_months": 3, + "next_planned_date": "2026-06-10", + }, + ) + assert auto_out.status_code == 201, auto_out.text + assert auto_out.json()["contract_id"] == contract.id + assert auto_out.json()["provider_id"] == contract.provider_id + + # Create outsourced PM schedule with provider + contract + sched_res = client.post( + "/api/pm/schedules", + headers=bio_headers, + json={ + "asset_id": asset_id, + "service_mode": "outsourced", + "frequency_months": 3, + "provider_id": contract.provider_id or provider.id, + "contract_id": contract.id, + "next_planned_date": "2026-06-10", + }, + ) + assert sched_res.status_code == 201, sched_res.text + sched = sched_res.json() + assert sched["service_mode"] == "outsourced" + assert sched["contract_id"] == contract.id + assert sched["contract_summary"] is not None + + # Initial PMRecord was created with planned_date=2026-06-10 and DB status=None + recs_res = client.get(f"/api/pm/records?schedule_id={sched['id']}", headers=bio_headers) + assert recs_res.status_code == 200 + items = recs_res.json()["items"] + assert len(items) == 1 + first_rec_id = items[0]["id"] + assert items[0]["planned_date"] == "2026-06-10" + db.expire_all() + assert db.query(PMRecord).filter(PMRecord.id == first_rec_id).first().status is None + + # Complete the initial PMRecord on 2026-06-12 -> next planned 2026-09-12 + comp_res = client.post( + f"/api/pm/records/{first_rec_id}/complete", + headers=bio_headers, + json={ + "completed_date": "2026-06-12", + "service_details": "Replaced flow sensor filter and verified pressure calibration.", + "remarks": "Vendor engineer visit completed.", + }, + ) + assert comp_res.status_code == 200, comp_res.text + comp_data = comp_res.json() + assert comp_data["completed_record"]["status"] == "completed" + assert comp_data["completed_record"]["completed_date"] == "2026-06-12" + assert comp_data["next_record"]["planned_date"] == "2026-09-12" + + # Re-completing same record -> 400 + recomp = client.post( + f"/api/pm/records/{first_rec_id}/complete", + headers=bio_headers, + json={"completed_date": "2026-06-13", "service_details": "Duplicate"}, + ) + assert recomp.status_code == 400 + + # Reschedule the generated next record from 2026-09-12 to 2026-09-25 + second_rec_id = comp_data["next_record"]["id"] + resched_res = client.post( + f"/api/pm/records/{second_rec_id}/reschedule", + headers=bio_headers, + json={"rescheduled_to": "2026-09-25", "remarks": "OT occupied on 12 Sep."}, + ) + assert resched_res.status_code == 200, resched_res.text + resched_data = resched_res.json() + assert resched_data["rescheduled_record"]["status"] == "rescheduled" + assert resched_data["rescheduled_record"]["rescheduled_to"] == "2026-09-25" + assert resched_data["next_record"]["planned_date"] == "2026-09-25" + + # Verify schedule next_planned_date updated and deactivate schedule works + del_res = client.delete(f"/api/pm/schedules/{sched['id']}", headers=bio_headers) + assert del_res.status_code == 200 + assert del_res.json()["is_active"] is False + + +def test_calibration_plan_approval_permissions_and_completion(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + dept_headers = _auth_headers(client, "dept@poona.demo") + + a1 = _create_test_asset(client, bio_headers, db, "001", req_cal=False) + a2 = _create_test_asset(client, bio_headers, db, "002", req_cal=False) + a3 = _create_test_asset(client, bio_headers, db, "003", req_cal=True) + agency = db.query(Vendor).filter(Vendor.vendor_type == "calibration_agency").first() + + # Biomedical cannot create with approve=True + forbid_create_app = client.post( + f"/api/calibration/plans/from-asset/{a1}", + headers=bio_headers, + json={ + "frequency_months": 6, + "agency_id": agency.id, + "next_due_date": "2026-08-01", + "approve": True, + }, + ) + assert forbid_create_app.status_code == 403 + assert forbid_create_app.json()["code"] == "FORBIDDEN_CALIBRATION_APPROVAL" + + # Biomedical creates unapproved plan from asset -> sets requires_calibration=True + c1 = client.post( + f"/api/calibration/plans/from-asset/{a1}", + headers=bio_headers, + json={ + "frequency_months": 6, + "agency_id": agency.id, + "next_due_date": "2026-08-01", + "approve": False, + }, + ) + assert c1.status_code == 201, c1.text + plan1 = c1.json() + assert plan1["calibrations_per_year"] == 2 + assert plan1["approved_by_id"] is None + db.expire_all() + assert db.query(Asset).filter(Asset.id == a1).first().requires_calibration is True + + # Duplicate from-asset -> 409 DUPLICATE_CALIBRATION_PLAN + dup = client.post( + f"/api/calibration/plans/from-asset/{a1}", + headers=bio_headers, + json={"frequency_months": 6, "next_due_date": "2026-08-01"}, + ) + assert dup.status_code == 409 + assert dup.json()["code"] == "DUPLICATE_CALIBRATION_PLAN" + + # Bulk add with a1 (already has plan) + a2 + a3 + bulk_res = client.post( + "/api/calibration/plans/bulk-from-assets", + headers=bio_headers, + json={ + "asset_ids": [a1, a2, a3], + "frequency_months": 12, + "agency_id": agency.id, + "next_due_date": "2026-10-15", + "approve": False, + }, + ) + assert bulk_res.status_code == 200, bulk_res.text + bulk_json = bulk_res.json() + assert [p["asset_id"] for p in bulk_json["created"]] == [a2, a3] + assert bulk_json["skipped_asset_ids"] == [a1] + + # Biomedical gets 403 trying to modify frequency or approve; management succeeds (200) + bio_freq = client.put( + f"/api/calibration/plans/{plan1['id']}", + headers=bio_headers, + json={"frequency_months": 12}, + ) + assert bio_freq.status_code == 403 + assert bio_freq.json()["code"] == "FORBIDDEN_CALIBRATION_APPROVAL" + + bio_app = client.post(f"/api/calibration/plans/{plan1['id']}/approve", headers=bio_headers) + assert bio_app.status_code == 403 + + assert client.post(f"/api/calibration/plans/{plan1['id']}/approve", headers=dept_headers).status_code == 403 + + mgmt_freq = client.put( + f"/api/calibration/plans/{plan1['id']}", + headers=mgmt_headers, + json={"frequency_months": 4}, + ) + assert mgmt_freq.status_code == 200 + assert mgmt_freq.json()["frequency_months"] == 4 + assert mgmt_freq.json()["calibrations_per_year"] == 3 + + mgmt_app = client.post( + f"/api/calibration/plans/{plan1['id']}/approve", + headers=mgmt_headers, + json={"frequency_months": 6}, + ) + assert mgmt_app.status_code == 200, mgmt_app.text + assert mgmt_app.json()["frequency_months"] == 6 + assert mgmt_app.json()["approved_by_name"] is not None + assert mgmt_app.json()["approved_on"] is not None + + # Complete calibration record -> creates next record at completed_date + frequency_months and preserves history + cal_recs = client.get(f"/api/calibration/records?asset_id={a1}", headers=bio_headers).json()["items"] + assert len(cal_recs) == 1 + rec1_id = cal_recs[0]["id"] + + comp = client.post( + f"/api/calibration/records/{rec1_id}/complete", + headers=bio_headers, + json={ + "completed_date": "2026-08-05", + "certificate_no": "NABL-2026-9901", + "agency_id": agency.id, + "remarks": "All channels within +/-1% tolerance.", + }, + ) + assert comp.status_code == 200, comp.text + comp_json = comp.json() + assert comp_json["completed_record"]["status"] == "completed" + assert comp_json["completed_record"]["certificate_no"] == "NABL-2026-9901" + assert comp_json["next_record"]["due_date"] == "2027-02-05" + + # Both historical and next records exist for asset + history = client.get(f"/api/calibration/records?asset_id={a1}", headers=bio_headers).json() + assert history["total"] == 2 + assert history["summary"]["completed"] == 1 + + +def test_demo_clock_transitions_statuses_dynamically_on_read(client, db): + admin_headers = _auth_headers(client, "admin@poona.demo") + bio_headers = _auth_headers(client, "bio@poona.demo") + + asset_id = _create_test_asset(client, bio_headers, db, "CLK", req_cal=True) + agency = db.query(Vendor).filter(Vendor.vendor_type == "calibration_agency").first() + + # Calibration due 2028-06-20; PM planned 2028-06-20 (far future, no interference) + cal_plan = client.post( + f"/api/calibration/plans/from-asset/{asset_id}", + headers=admin_headers, + json={ + "frequency_months": 12, + "agency_id": agency.id, + "next_due_date": "2028-06-20", + "approve": True, + }, + ) + assert cal_plan.status_code == 201 + + pm_sched = client.post( + "/api/pm/schedules", + headers=bio_headers, + json={ + "asset_id": asset_id, + "service_mode": "in_house", + "frequency_months": 6, + "responsible_team": "Bio Team A", + "next_planned_date": "2028-06-20", + }, + ) + assert pm_sched.status_code == 201 + + try: + # 1) 2028-05-01 -> 50 days before due -> both 'upcoming' (ok) + client.post( + "/api/settings/demo-date", + headers=admin_headers, + json={"demo_as_of_date": "2028-05-01"}, + ) + cal1 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0] + pm1 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0] + ov1 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json() + assert cal1["status"] == "upcoming" and cal1["severity"] == "ok" + assert pm1["status"] == "upcoming" and pm1["severity"] == "ok" + assert ov1["calibration_records"][0]["status"] == "upcoming" + assert ov1["pm_records"][0]["status"] == "upcoming" + + # 2) 2028-06-10 -> 10 days before due (<= 15 lead, > 7 red) -> both 'due' (yellow) + client.post( + "/api/settings/demo-date", + headers=admin_headers, + json={"demo_as_of_date": "2028-06-10"}, + ) + cal2 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0] + pm2 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0] + ov2 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json() + assert cal2["status"] == "due" and cal2["severity"] == "yellow" + assert pm2["status"] == "due" and pm2["severity"] == "yellow" + assert ov2["calibration_records"][0]["status"] == "due" + assert ov2["pm_records"][0]["status"] == "due" + + # 3) 2028-06-15 -> 5 days before due (<= 7 red) -> 'due' (red) + client.post( + "/api/settings/demo-date", + headers=admin_headers, + json={"demo_as_of_date": "2028-06-15"}, + ) + cal3 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0] + pm3 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0] + assert cal3["status"] == "due" and cal3["severity"] == "red" + assert pm3["status"] == "due" and pm3["severity"] == "red" + + # 4) 2028-06-25 -> 5 days past due -> 'overdue' (red) + client.post( + "/api/settings/demo-date", + headers=admin_headers, + json={"demo_as_of_date": "2028-06-25"}, + ) + cal4 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0] + pm4 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0] + ov4 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json() + assert cal4["status"] == "overdue" and cal4["severity"] == "red" + assert pm4["status"] == "overdue" and pm4["severity"] == "red" + assert ov4["calibration_records"][0]["status"] == "overdue" + assert ov4["pm_records"][0]["status"] == "overdue" + + # Confirm DB status columns stayed NULL throughout! + db.expire_all() + assert db.query(CalibrationRecord).filter(CalibrationRecord.asset_id == asset_id).first().status is None + assert db.query(PMRecord).filter(PMRecord.asset_id == asset_id).first().status is None + finally: + client.post( + "/api/settings/demo-date", + headers=admin_headers, + json={"demo_as_of_date": None}, + ) diff --git a/backend/tests/test_reports.py b/backend/tests/test_reports.py new file mode 100644 index 0000000..7988eda --- /dev/null +++ b/backend/tests/test_reports.py @@ -0,0 +1,275 @@ +import csv +from datetime import datetime, timezone +from io import BytesIO, StringIO + +import openpyxl +import pytest + +from app.core.time_utils import KOLKATA +from app.models import Asset, Category, Complaint, Department, Location, User +from app.seed.seed import seed_database + + +ALL_REPORT_KEYS = [ + "monthly-maintenance", + "monthly-department", + "daily-visit", + "breakdown-complaints", + "pm-compliance", + "calibration-due", + "contracts-warranty", + "demo-equipment", +] + + +@pytest.fixture(scope="module", autouse=True) +def seeded_phase7_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("phase7_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def test_all_eight_reports_accessible_for_management_and_admin(client): + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + admin_headers = _auth_headers(client, "admin@poona.demo") + + for headers in (mgmt_headers, admin_headers): + for key in ALL_REPORT_KEYS: + res = client.get(f"/api/reports/{key}", headers=headers) + assert res.status_code == 200, f"{key} failed: {res.text}" + body = res.json() + assert body["report_key"] == key + assert body["title"] + assert isinstance(body["filters_applied"], dict) + assert isinstance(body["summary"], dict) + assert isinstance(body["columns"], list) and len(body["columns"]) > 0 + assert isinstance(body["rows"], list) + + missing = client.get("/api/reports/non-existent-report", headers=admin_headers) + assert missing.status_code == 404 + + +def test_daily_visit_rbac_and_department_user_scoping(client, db): + dept_headers = _auth_headers(client, "dept@poona.demo") + coord_headers = _auth_headers(client, "coord@poona.demo") + bio_headers = _auth_headers(client, "bio@poona.demo") + + # daily-visit is forbidden for department_user and coordinator (JSON + export) + for headers in (dept_headers, coord_headers): + assert client.get("/api/reports/daily-visit", headers=headers).status_code == 403 + assert client.get("/api/reports/daily-visit/export?format=xlsx", headers=headers).status_code == 403 + + # Allowed for biomedical engineer + assert client.get("/api/reports/daily-visit", headers=bio_headers).status_code == 200 + + # Department user attempting to pass another department_id is still scoped to own department + dept_user = db.query(User).filter(User.email == "dept@poona.demo").first() + other_dept = db.query(Department).filter(Department.id != dept_user.department_id).first() + assert dept_user is not None and dept_user.department_id is not None + assert other_dept is not None + + for key in [k for k in ALL_REPORT_KEYS if k != "daily-visit"]: + res = client.get( + f"/api/reports/{key}?department_id={other_dept.id}", + headers=dept_headers, + ) + assert res.status_code == 200, f"{key} failed for dept user: {res.text}" + body = res.json() + if "department_id" in body["filters_applied"]: + assert body["filters_applied"]["department_id"] == dept_user.department_id + + maint = client.get( + f"/api/reports/monthly-maintenance?department_id={other_dept.id}", + headers=dept_headers, + ).json() + assert len(maint["rows"]) == 1 + assert maint["rows"][0]["department_id"] == dept_user.department_id + + +def test_monthly_maintenance_three_complaint_reconciliation(client, db): + admin_headers = _auth_headers(client, "admin@poona.demo") + admin_user = db.query(User).filter(User.email == "admin@poona.demo").first() + category = db.query(Category).first() + location = db.query(Location).first() + assert admin_user is not None and category is not None and location is not None + + # Create isolated department with 2 non-condemned assets so calculation is deterministic + dept = Department(name="Reconciliation Test Unit", code="REC-TEST-01", is_active=True) + db.add(dept) + db.flush() + + asset1 = Asset( + asset_code="REC-AST-001", + serial_no="REC-SN-001", + name="Reconciliation Monitor 1", + category_id=category.id, + department_id=dept.id, + location_id=location.id, + status="in_service", + criticality="critical", + ) + asset2 = Asset( + asset_code="REC-AST-002", + serial_no="REC-SN-002", + name="Reconciliation Monitor 2", + category_id=category.id, + department_id=dept.id, + location_id=location.id, + status="in_service", + criticality="non_critical", + ) + db.add_all([asset1, asset2]) + db.flush() + + # 3 fixed complaints for March 2027 (31 days * 24h * 60m = 44640 mins/asset -> 89280 total): + # 1) Crosses month boundary: Feb 28 22:00 IST -> Mar 01 04:00 IST => 240 mins in March, day Mar 01 + # 2) Mid-month: Mar 10 10:00 IST -> Mar 10 13:30 IST => 210 mins, day Mar 10 + # 3) Distinct day: Mar 20 09:00 IST -> Mar 20 10:15 IST => 75 mins, day Mar 20 + # Expected total downtime = 525 mins, downtime days = 3, uptime = 88755 mins + complaints = [ + Complaint( + complaint_no="REC-CMP-001", + asset_id=asset1.id, + description="Month boundary downtime test", + priority="critical", + registered_at=KOLKATA.localize(datetime(2027, 2, 28, 22, 0)).astimezone(timezone.utc), + restored_at=KOLKATA.localize(datetime(2027, 3, 1, 4, 0)).astimezone(timezone.utc), + registered_by_id=admin_user.id, + received_by_id=admin_user.id, + call_status="closed", + ), + Complaint( + complaint_no="REC-CMP-002", + asset_id=asset1.id, + description="Mid-month downtime test", + priority="non_critical", + registered_at=KOLKATA.localize(datetime(2027, 3, 10, 10, 0)).astimezone(timezone.utc), + restored_at=KOLKATA.localize(datetime(2027, 3, 10, 13, 30)).astimezone(timezone.utc), + registered_by_id=admin_user.id, + received_by_id=admin_user.id, + call_status="closed", + ), + Complaint( + complaint_no="REC-CMP-003", + asset_id=asset2.id, + description="Third distinct day downtime test", + priority="non_critical", + registered_at=KOLKATA.localize(datetime(2027, 3, 20, 9, 0)).astimezone(timezone.utc), + restored_at=KOLKATA.localize(datetime(2027, 3, 20, 10, 15)).astimezone(timezone.utc), + registered_by_id=admin_user.id, + received_by_id=admin_user.id, + call_status="closed", + ), + ] + db.add_all(complaints) + db.commit() + + res = client.get( + f"/api/reports/monthly-maintenance?month=2027-03&department_id={dept.id}", + headers=admin_headers, + ) + assert res.status_code == 200, res.text + payload = res.json() + + summary = payload["summary"] + assert summary["total_assets"] == 2 + assert summary["total_complaints"] == 3 + assert summary["total_downtime_minutes"] == 525 + assert summary["downtime_days_count"] == 3 + assert summary["total_scheduled_minutes"] == 89280 + assert summary["total_uptime_minutes"] == 88755 + assert summary["downtime_pct"] == round(525 / 89280 * 100, 2) + + assert len(payload["rows"]) == 1 + row = payload["rows"][0] + assert row["department_name"] == "Reconciliation Test Unit" + assert row["asset_count"] == 2 + assert row["complaint_count"] == 3 + assert row["total_downtime_minutes"] == 525 + assert row["downtime_days_count"] == 3 + assert row["scheduled_minutes"] == 89280 + assert row["total_uptime_minutes"] == 88755 + + +def test_report_exports_xlsx_and_csv(client): + mgmt_headers = _auth_headers(client, "mgmt@poona.demo") + + # Excel export + xlsx_res = client.get( + "/api/reports/monthly-maintenance/export?format=xlsx&month=2027-03", + headers=mgmt_headers, + ) + assert xlsx_res.status_code == 200 + assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"] + assert 'filename="monthly-maintenance.xlsx"' in xlsx_res.headers["content-disposition"] + + wb = openpyxl.load_workbook(BytesIO(xlsx_res.content)) + ws = wb.active + assert "Poona Hospital" in str(ws["A1"].value) + assert "Generated:" in str(ws["A2"].value) + assert "Filters:" in str(ws["A2"].value) + assert "Total Downtime Minutes: 525" in str(ws["A3"].value) + assert ws.freeze_panes == "A6" + assert ws.cell(row=5, column=1).value == "Department" + assert "1E3A8A" in str(ws.cell(row=5, column=1).fill.start_color.rgb) + assert ws.max_row >= 6 + + # CSV export + csv_res = client.get( + "/api/reports/breakdown-complaints/export?format=csv", + headers=mgmt_headers, + ) + assert csv_res.status_code == 200 + assert "text/csv" in csv_res.headers["content-type"] + assert 'filename="breakdown-complaints.csv"' in csv_res.headers["content-disposition"] + assert csv_res.content.startswith(b"\xef\xbb\xbf") + + decoded = csv_res.content.decode("utf-8-sig") + parsed = list(csv.reader(StringIO(decoded))) + assert len(parsed) >= 5 + assert "Poona Hospital" in parsed[0][0] + assert parsed[4][0] == "Complaint No" + + # Unsupported export format rejected + bad_fmt = client.get( + "/api/reports/monthly-maintenance/export?format=pdf", + headers=mgmt_headers, + ) + assert bad_fmt.status_code == 422 + + +def test_all_eight_reports_export_xlsx_and_csv(client): + """Verify that all 8 reports export cleanly as both XLSX and CSV without title/slash errors.""" + admin_headers = _auth_headers(client, "admin@poona.demo") + + for key in ALL_REPORT_KEYS: + # Test XLSX export + xlsx_res = client.get( + f"/api/reports/{key}/export?format=xlsx", + headers=admin_headers, + ) + assert xlsx_res.status_code == 200, f"XLSX export failed for {key}: {xlsx_res.text}" + assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"] + assert f'filename="{key}.xlsx"' in xlsx_res.headers["content-disposition"] + + wb = openpyxl.load_workbook(BytesIO(xlsx_res.content)) + ws = wb.active + assert ws is not None + assert "/" not in ws.title and "\\" not in ws.title + assert len(ws.title) <= 31 + + # Test CSV export + csv_res = client.get( + f"/api/reports/{key}/export?format=csv", + headers=admin_headers, + ) + assert csv_res.status_code == 200, f"CSV export failed for {key}: {csv_res.text}" + assert "text/csv" in csv_res.headers["content-type"] + assert f'filename="{key}.csv"' in csv_res.headers["content-disposition"] + diff --git a/backend/tests/test_task1_duplicates.py b/backend/tests/test_task1_duplicates.py new file mode 100644 index 0000000..063a33b --- /dev/null +++ b/backend/tests/test_task1_duplicates.py @@ -0,0 +1,260 @@ +from io import BytesIO +from datetime import date +import openpyxl +import pytest + +from app.models import Asset, CalibrationPlan, Contract, Department, InsurancePolicy, Vendor +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_task1_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("task1_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str = "admin@poona.demo") -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def _make_xlsx_bytes(sheet_name: str, headers: list[str], rows: list[list]) -> bytes: + wb = openpyxl.Workbook() + ws = wb.active + ws.title = sheet_name + ws.append(headers) + for r in rows: + ws.append(r) + buf = BytesIO() + wb.save(buf) + return buf.getvalue() + + +def test_contracts_api_duplicate_409(client, db): + headers = _auth_headers(client) + asset = db.query(Asset).first() + vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first() + assert asset and vendor + + payload = { + "asset_id": asset.id, + "contract_type": "AMC", + "provider_id": vendor.id, + "start_date": "2026-01-01", + "end_date": "2026-12-31", + "coverage_period_text": "2026 Annual AMC", + } + # First creation should succeed + res1 = client.post("/api/contracts", json=payload, headers=headers) + assert res1.status_code == 201 + contract_id = res1.json()["id"] + + # Second creation with identical asset, type, start_date, end_date must return 409 + res2 = client.post("/api/contracts", json=payload, headers=headers) + assert res2.status_code == 409 + assert res2.json()["detail"] == "A contract with the same asset, type and dates already exists." + + # Renewal must still work + renew_payload = { + "start_date": "2027-01-01", + "end_date": "2027-12-31", + "contract_type": "AMC", + "coverage_period_text": "2027 Annual Renewal", + } + res_renew = client.post(f"/api/contracts/{contract_id}/renew", json=renew_payload, headers=headers) + assert res_renew.status_code == 200 + assert res_renew.json()["new_contract"]["start_date"] == "2027-01-01" + + +def test_insurance_api_duplicate_409(client, db): + headers = _auth_headers(client) + asset = db.query(Asset).first() + vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first() + assert asset and vendor + + policy_no = "POL-DUP-TEST-999" + payload = { + "asset_id": asset.id, + "insurer_id": vendor.id, + "policy_no": f" {policy_no} ", + "start_date": "2026-04-01", + "end_date": "2027-03-31", + "coverage_amount": 500000.0, + } + # First creation succeeds + res1 = client.post("/api/insurance", json=payload, headers=headers) + assert res1.status_code == 201 + + # Exact duplicate (case-insensitive and trimmed) must return 409 + dup_payload = { + "asset_id": asset.id, + "insurer_id": vendor.id, + "policy_no": f"pol-dup-test-999 ", + "start_date": "2026-04-01", + "end_date": "2027-03-31", + } + res2 = client.post("/api/insurance", json=dup_payload, headers=headers) + assert res2.status_code == 409 + assert res2.json()["detail"] == "Policy number already exists." + + +def test_contracts_bulk_import_in_file_and_db_duplicates(client, db): + headers = _auth_headers(client) + asset = db.query(Asset).first() + vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first() + assert asset and vendor + + xlsx_headers = ["asset_code", "provider_name", "contract_type", "start_date", "end_date", "cost", "coverage_details", "remarks"] + rows = [ + [asset.asset_code, vendor.name, "AMC", "2028-01-01", "2028-12-31", 10000, "Coverage", "Remark 1"], + [asset.asset_code, vendor.name, "AMC", "2028-01-01", "2028-12-31", 10000, "Coverage", "Remark 2"], + ] + file_bytes = _make_xlsx_bytes("Contracts", xlsx_headers, rows) + + # Dry run should flag row 3 as duplicate of row 2 + res_dry = client.post( + "/api/contracts/bulk-import?dry_run=true", + files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + headers=headers, + ) + assert res_dry.status_code == 200 + dry_data = res_dry.json() + assert dry_data["valid_count"] == 1 + assert dry_data["error_count"] == 1 + assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"]) + + # Import with skip_invalid=true creates exactly 1 record + res_imp1 = client.post( + "/api/contracts/bulk-import?dry_run=false&skip_invalid=true", + files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + headers=headers, + ) + assert res_imp1.status_code == 200 + assert res_imp1.json()["created_count"] == 1 + + # Second import of the same file creates 0 records and reports DB duplicates + res_imp2 = client.post( + "/api/contracts/bulk-import?dry_run=false&skip_invalid=true", + files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + headers=headers, + ) + assert res_imp2.status_code == 200 + data2 = res_imp2.json() + assert data2["created_count"] == 0 + assert data2["error_count"] == 2 + messages = [e["message"] for e in data2["errors"]] + assert any("Already exists in the system." in m for m in messages) + assert any("Duplicate of row 2 in this file." in m for m in messages) + + +def test_insurance_bulk_import_in_file_and_db_duplicates(client, db): + headers = _auth_headers(client) + asset = db.query(Asset).first() + vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first() + assert asset and vendor + + xlsx_headers = ["asset_code", "insurer_name", "policy_number", "start_date", "end_date", "insured_value", "premium", "remarks"] + rows = [ + [asset.asset_code, vendor.name, "POL-BULK-101", "2028-01-01", "2028-12-31", 200000, 5000, "Policy row 2"], + [asset.asset_code, vendor.name, " pol-bulk-101 ", "2028-01-01", "2028-12-31", 200000, 5000, "Policy row 3"], + ] + file_bytes = _make_xlsx_bytes("Insurance Policies", xlsx_headers, rows) + + # Dry run should flag row 3 as duplicate of row 2 + res_dry = client.post( + "/api/insurance/bulk-import?dry_run=true", + files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + headers=headers, + ) + assert res_dry.status_code == 200 + dry_data = res_dry.json() + assert dry_data["valid_count"] == 1 + assert dry_data["error_count"] == 1 + assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"]) + + # Import with skip_invalid=true creates 1 record + res_imp1 = client.post( + "/api/insurance/bulk-import?dry_run=false&skip_invalid=true", + files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + headers=headers, + ) + assert res_imp1.status_code == 200 + assert res_imp1.json()["created_count"] == 1 + + # Second import creates 0 records + res_imp2 = client.post( + "/api/insurance/bulk-import?dry_run=false&skip_invalid=true", + files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + headers=headers, + ) + assert res_imp2.status_code == 200 + data2 = res_imp2.json() + assert data2["created_count"] == 0 + assert data2["error_count"] == 2 + messages = [e["message"] for e in data2["errors"]] + assert any("Already exists in the system." in m for m in messages) + assert any("Duplicate of row 2 in this file." in m for m in messages) + + +def test_calibration_bulk_import_in_file_and_existing_plan(client, db): + headers = _auth_headers(client) + from app.models import CalibrationPlan + planned_ids = {p.asset_id for p in db.query(CalibrationPlan.asset_id).all()} + asset = db.query(Asset).filter(~Asset.id.in_(planned_ids)).first() + if not asset: + dept = db.query(Department).first() + asset = Asset( + asset_code="PHRC-TEST-CAL-99", + name="Test Cal Asset", + department_id=dept.id, + status="in_service", + requires_calibration=True, + ) + db.add(asset) + db.commit() + + vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first() + + xlsx_headers = ["asset_code", "frequency_months", "agency_name", "next_due_date", "scope", "standards", "remarks"] + rows = [ + [asset.asset_code, 12, vendor.name if vendor else "", "2028-06-01", "Accredited scope", "ISO 17025", "Cal row 2"], + [asset.asset_code, 6, vendor.name if vendor else "", "2028-06-01", "Accredited scope", "ISO 17025", "Cal row 3"], + ] + file_bytes = _make_xlsx_bytes("Calibration Plans", xlsx_headers, rows) + + # Dry run flags row 3 as duplicate of row 2 + res_dry = client.post( + "/api/calibration/bulk-import?dry_run=true", + files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + headers=headers, + ) + assert res_dry.status_code == 200 + dry_data = res_dry.json() + assert dry_data["valid_count"] == 1 + assert dry_data["error_count"] == 1 + assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"]) + + # Import with skip_invalid=true creates 1 record + res_imp1 = client.post( + "/api/calibration/bulk-import?dry_run=false&skip_invalid=true", + files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + headers=headers, + ) + assert res_imp1.status_code == 200 + assert res_imp1.json()["created_count"] == 1 + + # Second import creates 0 records and reports "Asset already has a calibration plan." + res_imp2 = client.post( + "/api/calibration/bulk-import?dry_run=false&skip_invalid=true", + files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + headers=headers, + ) + assert res_imp2.status_code == 200 + data2 = res_imp2.json() + assert data2["created_count"] == 0 + assert data2["error_count"] == 2 + messages = [e["message"] for e in data2["errors"]] + assert any("Asset already has a calibration plan." in m for m in messages) + assert any("Duplicate of row 2 in this file." in m for m in messages) diff --git a/backend/tests/test_task2_templates.py b/backend/tests/test_task2_templates.py new file mode 100644 index 0000000..da13767 --- /dev/null +++ b/backend/tests/test_task2_templates.py @@ -0,0 +1,89 @@ +from io import BytesIO +import openpyxl +import pytest + +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_task2_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("task2_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str = "admin@poona.demo") -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +@pytest.mark.parametrize( + "template_url,import_url,file_field,filename,expected_sheet1", + [ + ( + "/api/assets/import-template", + "/api/assets/bulk-import?dry_run=true", + "file", + "asset_template.xlsx", + "Assets", + ), + ( + "/api/contracts/import-template", + "/api/contracts/bulk-import?dry_run=true", + "file", + "contracts_template.xlsx", + "Contracts", + ), + ( + "/api/calibration/import-template", + "/api/calibration/bulk-import?dry_run=true", + "file", + "calibration_template.xlsx", + "Calibration Plans", + ), + ( + "/api/insurance/import-template", + "/api/insurance/bulk-import?dry_run=true", + "file", + "insurance_template.xlsx", + "Insurance Policies", + ), + ], +) +def test_download_template_and_upload_unchanged_dry_run_zero_rows( + client, template_url, import_url, file_field, filename, expected_sheet1 +): + headers = _auth_headers(client) + + # 1. Download template + dl_res = client.get(template_url, headers=headers) + assert dl_res.status_code == 200 + content = dl_res.content + + # 2. Verify sheet structure + wb = openpyxl.load_workbook(BytesIO(content)) + assert wb.sheetnames == [expected_sheet1, "Example", "Master Reference"] + + ws1 = wb[expected_sheet1] + # First sheet has only header row (max_row == 1) + assert ws1.max_row == 1 + + ws2 = wb["Example"] + # Second sheet has disclaimer on row 1 + assert ws2.cell(row=1, column=1).value == "Example only - this sheet is ignored on import" + # Second sheet has sample row on row 2 + assert ws2.cell(row=2, column=1).value is not None + + # 3. Upload unchanged template with dry_run=true: must return total_rows == 0 + up_res = client.post( + import_url, + headers=headers, + files={file_field: (filename, content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, + ) + assert up_res.status_code == 200, up_res.text + data = up_res.json() + assert data["total_rows"] == 0 + assert data["valid_count"] == 0 + assert data["error_count"] == 0 + assert data["created_count"] == 0 diff --git a/backend/tests/test_task4_passwords.py b/backend/tests/test_task4_passwords.py new file mode 100644 index 0000000..563dc66 --- /dev/null +++ b/backend/tests/test_task4_passwords.py @@ -0,0 +1,165 @@ +import pytest +from fastapi.testclient import TestClient +from app.core.security import validate_password +from app.models.masters import User +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_task4_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("task4_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str = "admin@poona.demo") -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def test_validate_password_unit(): + # 1. Short password (< 8) + with pytest.raises(Exception) as exc1: + validate_password("Short1", email="user@hospital.com") + assert "at least 8 characters" in str(exc1.value) + + # 2. No digits + with pytest.raises(Exception) as exc2: + validate_password("NoDigitsHere", email="user@hospital.com") + assert "at least one letter and at least one digit" in str(exc2.value) + + # 3. No letters + with pytest.raises(Exception) as exc3: + validate_password("1234567890", email="user@hospital.com") + assert "at least one letter and at least one digit" in str(exc3.value) + + # 4. Leading / trailing space + with pytest.raises(Exception) as exc4a: + validate_password(" Secret123", email="user@hospital.com") + assert "space" in str(exc4a.value) + + with pytest.raises(Exception) as exc4b: + validate_password("Secret123 ", email="user@hospital.com") + assert "space" in str(exc4b.value) + + # 5. Blocklisted passwords + for bad in ("12345678", "password", "password1", "qwerty123", "admin123", "welcome1"): + with pytest.raises(Exception) as exc5: + validate_password(bad, email="user@hospital.com") + assert "easily guessable" in str(exc5.value) or "at least 8" in str(exc5.value) or "at least one" in str(exc5.value) + + # 6. Demo password MUST be allowed + validate_password("demo@123", email="admin@poona.demo") + validate_password("Demo@123", email="admin@poona.demo") + + # 7. Contains email local part (>= 4 chars) + with pytest.raises(Exception) as exc7: + validate_password("Secureadmin123", email="admin@poona.demo") + assert "username" in str(exc7.value).lower() + + # Short local part (< 4 chars) does NOT trigger username check + validate_password("Securebio123", email="bio@poona.demo") + + +def test_api_create_user_password_validation(client, db): + headers = _auth_headers(client, "admin@poona.demo") + + # Rejected: no digit + res_bad = client.post( + "/api/users", + headers=headers, + json={ + "name": "Test User", + "email": "test_pw_rule@poona.demo", + "password": "NoDigitsPassword", + "role": "biomedical", + }, + ) + assert res_bad.status_code == 422 + assert "letter and at least one digit" in res_bad.json()["detail"] + + # Rejected: contains email username "tester123" + res_username = client.post( + "/api/users", + headers=headers, + json={ + "name": "Test User 2", + "email": "tester123@poona.demo", + "password": "tester123Password1", + "role": "biomedical", + }, + ) + assert res_username.status_code == 422 + assert "username" in res_username.json()["detail"].lower() + + # Accepted: valid password with letters and numbers + res_ok = client.post( + "/api/users", + headers=headers, + json={ + "name": "Test User 3", + "email": "validuser@poona.demo", + "password": "ValidPassword123", + "role": "biomedical", + }, + ) + assert res_ok.status_code == 201 + user_id = res_ok.json()["id"] + + # Reset password with leading space rejected + res_reset_bad = client.post( + f"/api/users/{user_id}/reset-password", + headers=headers, + json={"new_password": " LeadingSpace123"}, + ) + assert res_reset_bad.status_code == 422 + assert "space" in res_reset_bad.json()["detail"] + + # Reset password with valid password succeeds + res_reset_ok = client.post( + f"/api/users/{user_id}/reset-password", + headers=headers, + json={"new_password": "NewValidSecret456"}, + ) + assert res_reset_ok.status_code == 200 + + +def test_api_change_password_validation(client, db): + # Log in as bio user + bio_headers = _auth_headers(client, "bio@poona.demo") + + # Reject new == current + res_same = client.post( + "/api/auth/change-password", + headers=bio_headers, + json={"current_password": "Demo@123", "new_password": "Demo@123"}, + ) + assert res_same.status_code == 422 + assert res_same.json()["detail"] == "New password must be different." + + # Reject trailing space + res_space = client.post( + "/api/auth/change-password", + headers=bio_headers, + json={"current_password": "Demo@123", "new_password": "NewSecretPass1 "}, + ) + assert res_space.status_code == 422 + assert "space" in res_space.json()["detail"] + + # Reject blocklisted password + res_block = client.post( + "/api/auth/change-password", + headers=bio_headers, + json={"current_password": "Demo@123", "new_password": "password1"}, + ) + assert res_block.status_code == 422 + + # Accept valid change + res_ok = client.post( + "/api/auth/change-password", + headers=bio_headers, + json={"current_password": "Demo@123", "new_password": "BrandNewSecret789"}, + ) + assert res_ok.status_code == 200 + assert res_ok.json()["message"] == "Password changed successfully." diff --git a/backend/tests/test_task6_scoping.py b/backend/tests/test_task6_scoping.py new file mode 100644 index 0000000..f08895f --- /dev/null +++ b/backend/tests/test_task6_scoping.py @@ -0,0 +1,133 @@ +import pytest +from app.core.security import hash_password +from app.models import Asset, Department, User +from app.seed.seed import seed_database +from app.services.scoping import DepartmentScope, resolve_department_scope + + +@pytest.fixture(scope="module", autouse=True) +def seeded_task6_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("task6_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def test_resolve_department_scope_rules(): + # Admin is unconstrained + admin_user = User(role="system_admin", department_id=None) + scope = resolve_department_scope(admin_user, requested_dept_id=5) + assert scope == DepartmentScope(is_unconstrained=True, department_id=5, is_empty=False) + + # Department user with department_id=None is empty + unassigned = User(role="department_user", department_id=None) + scope_empty = resolve_department_scope(unassigned, requested_dept_id=5) + assert scope_empty == DepartmentScope(is_unconstrained=False, department_id=None, is_empty=True) + + # Department user with assigned department cannot be overridden + assigned = User(role="department_user", department_id=1) + scope_assigned = resolve_department_scope(assigned, requested_dept_id=99) + assert scope_assigned == DepartmentScope(is_unconstrained=False, department_id=1, is_empty=False) + + +def test_unassigned_department_user_sees_zero_records(client, db): + # Create a department_user with department_id = None + email = "unassigned_dept_user@poona.demo" + user = db.query(User).filter(User.email == email).first() + if not user: + user = User( + email=email, + name="Unassigned Dept User", + password_hash=hash_password("Demo@123"), + role="department_user", + department_id=None, + is_active=True, + ) + db.add(user) + db.commit() + else: + user.department_id = None + db.commit() + + headers = _auth_headers(client, email) + + # 1. Dashboard summary has all-zero counters + dash_res = client.get("/api/dashboard/summary", headers=headers) + assert dash_res.status_code == 200 + dash_data = dash_res.json() + kpis = dash_data["kpis"] + assert kpis["total_assets"] == 0 + assert kpis["assets_under_repair"] == 0 + assert kpis["open_complaints"] == 0 + assert kpis["pm_due_this_month"] == 0 + assert kpis["calibrations_due"] == 0 + assert kpis["contracts_expiring"] == 0 + assert kpis["equipment_on_demo"] == 0 + assert len(dash_data["recent_complaints"]) == 0 + assert len(dash_data["needs_attention"]) == 0 + + # 2. Global search returns 0 assets and 0 complaints + search_res = client.get("/api/search?q=card", headers=headers) + assert search_res.status_code == 200 + search_data = search_res.json() + assert search_data["assets"] == [] + assert search_data["complaints"] == [] + + # 3. All accessible report endpoints return 0 rows for this user + report_keys = [ + "equipment-inventory", + "monthly-maintenance", + "monthly-department", + "breakdown-complaints", + "pm-compliance", + "calibration-due", + "contracts-warranty", + "demo-equipment", + ] + for key in report_keys: + rep_res = client.get(f"/api/reports/{key}", headers=headers) + assert rep_res.status_code == 200, f"{key} failed: {rep_res.text}" + body = rep_res.json() + assert len(body["rows"]) == 0, f"Expected 0 rows for {key}, got {len(body['rows'])}" + + +def test_assigned_department_user_scoping_ignores_query_param(client, db): + # Get two distinct departments that have assets + depts = db.query(Department).filter(Department.is_active.is_(True)).all() + assert len(depts) >= 2 + dept1, dept2 = depts[0], depts[1] + + email = "dept1_scoped_user@poona.demo" + user = db.query(User).filter(User.email == email).first() + if not user: + user = User( + email=email, + name="Dept1 Scoped User", + password_hash=hash_password("Demo@123"), + role="department_user", + department_id=dept1.id, + is_active=True, + ) + db.add(user) + db.commit() + else: + user.department_id = dept1.id + db.commit() + + headers = _auth_headers(client, email) + + # Calling with ?department_id=dept2.id MUST be ignored and scoped strictly to dept1 + res = client.get( + f"/api/reports/equipment-inventory?department_id={dept2.id}", + headers=headers, + ) + assert res.status_code == 200 + body = res.json() + assert body["filters_applied"]["department_id"] == dept1.id + for row in body["rows"]: + assert row["department_id"] == dept1.id diff --git a/backend/tests/test_task7_token_version.py b/backend/tests/test_task7_token_version.py new file mode 100644 index 0000000..72ddd2f --- /dev/null +++ b/backend/tests/test_task7_token_version.py @@ -0,0 +1,91 @@ +import pytest +from app.models import User +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_task7_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("task7_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def test_token_invalidation_on_change_password_and_admin_reset(client, db): + # 1. Login as user and save the initial token + user_email = "bio@poona.demo" + login_res = client.post( + "/api/auth/login", + json={"email": user_email, "password": "Demo@123"}, + ) + assert login_res.status_code == 200 + old_token = login_res.json()["access_token"] + + # Verify initial token works + me_res1 = client.get( + "/api/auth/me", + headers={"Authorization": f"Bearer {old_token}"}, + ) + assert me_res1.status_code == 200 + assert me_res1.json()["email"] == user_email + + # 2. Call POST /api/auth/change-password + change_res = client.post( + "/api/auth/change-password", + headers={"Authorization": f"Bearer {old_token}"}, + json={"current_password": "Demo@123", "new_password": "NewSecurePass99"}, + ) + assert change_res.status_code == 200, change_res.text + change_data = change_res.json() + assert "access_token" in change_data + assert change_data["token_type"] == "bearer" + new_token = change_data["access_token"] + + # 3. Assert the old token now gets 401 on an authenticated endpoint + old_token_res = client.get( + "/api/auth/me", + headers={"Authorization": f"Bearer {old_token}"}, + ) + assert old_token_res.status_code == 401 + assert "Token has been invalidated" in old_token_res.json()["detail"] + + # 4. Assert the new token returned by change-password works + new_token_res = client.get( + "/api/auth/me", + headers={"Authorization": f"Bearer {new_token}"}, + ) + assert new_token_res.status_code == 200 + assert new_token_res.json()["email"] == user_email + + # 5. Login as admin, reset that user's password + admin_login = client.post( + "/api/auth/login", + json={"email": "admin@poona.demo", "password": "Demo@123"}, + ) + assert admin_login.status_code == 200 + admin_token = admin_login.json()["access_token"] + + target_user = db.query(User).filter(User.email == user_email).first() + assert target_user is not None + + reset_res = client.post( + f"/api/users/{target_user.id}/reset-password", + headers={"Authorization": f"Bearer {admin_token}"}, + json={"new_password": "AdminResetPass88"}, + ) + assert reset_res.status_code == 200, reset_res.text + + # 6. Assert the user's token now gets 401 + user_after_reset_res = client.get( + "/api/auth/me", + headers={"Authorization": f"Bearer {new_token}"}, + ) + assert user_after_reset_res.status_code == 401 + assert "Token has been invalidated" in user_after_reset_res.json()["detail"] + + # 7. Assert the admin's own token is still valid + admin_me_res = client.get( + "/api/auth/me", + headers={"Authorization": f"Bearer {admin_token}"}, + ) + assert admin_me_res.status_code == 200 + assert admin_me_res.json()["role"] == "system_admin" diff --git a/backend/tests/test_task8_delivery.py b/backend/tests/test_task8_delivery.py new file mode 100644 index 0000000..b3543dd --- /dev/null +++ b/backend/tests/test_task8_delivery.py @@ -0,0 +1,41 @@ +import subprocess +import zipfile +from pathlib import Path + + +def test_package_target_creates_clean_delivery_zip(tmp_path): + repo_root = Path(__file__).resolve().parent.parent.parent + zip_path = tmp_path / "poona-ams-delivery.zip" + + # Run git archive command (matching Makefile package target) + cmd = ["git", "archive", "--format=zip", f"--output={zip_path}", "HEAD"] + res = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True) + assert res.returncode == 0, f"git archive failed: {res.stderr}" + assert zip_path.exists() + + with zipfile.ZipFile(zip_path, "r") as z: + names = z.namelist() + assert len(names) > 0 + + # Assert no .db database files + db_files = [n for n in names if n.endswith(".db") or n.endswith(".sqlite") or n.endswith(".sqlite3")] + assert db_files == [], f"Delivery archive must not contain SQLite databases: {db_files}" + + # Assert no frontend dist/ build files + dist_files = [n for n in names if "dist/" in n or n.startswith("dist/")] + assert dist_files == [], f"Delivery archive must not contain dist/ directory: {dist_files}" + + # Assert no __pycache__ or compiled bytecode + pycache_files = [n for n in names if "__pycache__" in n or n.endswith(".pyc")] + assert pycache_files == [], f"Delivery archive must not contain __pycache__: {pycache_files}" + + # Assert no node_modules or .venv + vendor_files = [n for n in names if "node_modules/" in n or ".venv/" in n] + assert vendor_files == [], f"Delivery archive must not contain vendor/env files: {vendor_files}" + + # Assert essential source files are included + assert "backend/app/main.py" in names + assert "frontend/src/App.tsx" in names + assert "Makefile" in names + assert "README.md" in names + assert ".gitignore" in names diff --git a/backend/tests/test_time_utils.py b/backend/tests/test_time_utils.py new file mode 100644 index 0000000..fb3b984 --- /dev/null +++ b/backend/tests/test_time_utils.py @@ -0,0 +1,38 @@ +from datetime import date, datetime, timezone +from app.core.time_utils import format_date, format_datetime, format_duration + + +def test_format_datetime_none(): + assert format_datetime(None) is None + + +def test_format_datetime_utc_to_kolkata(): + dt = datetime(2025, 3, 15, 10, 30, tzinfo=timezone.utc) + assert format_datetime(dt) == "15-Mar-2025 16:00" + + +def test_format_datetime_naive_assumes_kolkata(): + dt = datetime(2025, 3, 15, 9, 5) + assert format_datetime(dt) == "15-Mar-2025 09:05" + + +def test_format_date_none(): + assert format_date(None) is None + + +def test_format_date_valid(): + assert format_date(date(2025, 1, 5)) == "05-Jan-2025" + + +def test_format_duration_none(): + assert format_duration(None) == "\u2014" + + +def test_format_duration_values(): + assert format_duration(0) == "0m" + assert format_duration(45) == "45m" + assert format_duration(60) == "1h" + assert format_duration(90) == "1h 30m" + assert format_duration(1440) == "1d" + assert format_duration(1445) == "1d 5m" + assert format_duration(1505) == "1d 1h 5m" diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..473efed --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,31 @@ +services: + backend: + build: ./backend + container_name: poona-ams-backend + ports: + - "8000:8000" + environment: + DATABASE_URL: ${DATABASE_URL:-sqlite:////app/data/ams.db} + SECRET_KEY: ${SECRET_KEY:-change-me-in-production-use-a-32-char-random-string} + UPLOAD_DIR: ${UPLOAD_DIR:-/app/data/uploads} + TIMEZONE: ${TIMEZONE:-Asia/Kolkata} + ACCESS_TOKEN_EXPIRE_MINUTES: ${ACCESS_TOKEN_EXPIRE_MINUTES:-480} + ALGORITHM: ${ALGORITHM:-HS256} + MAX_UPLOAD_SIZE_MB: ${MAX_UPLOAD_SIZE_MB:-10} + AI_PROVIDER: ${AI_PROVIDER:-none} + AI_BASE_URL: ${AI_BASE_URL:-http://localhost:11434} + AI_MODEL: ${AI_MODEL:-} + AI_API_KEY: ${AI_API_KEY:-} + AI_TIMEOUT_SECONDS: ${AI_TIMEOUT_SECONDS:-25} + volumes: + - ./backend/data:/app/data + restart: unless-stopped + + frontend: + build: ./frontend + container_name: poona-ams-frontend + ports: + - "5173:80" + depends_on: + - backend + restart: unless-stopped diff --git a/docs/ACCEPTANCE_CHECKLIST.md b/docs/ACCEPTANCE_CHECKLIST.md new file mode 100644 index 0000000..6c3ea1c --- /dev/null +++ b/docs/ACCEPTANCE_CHECKLIST.md @@ -0,0 +1,45 @@ +# Poona Hospital AMS — Acceptance Checklist & UAT Sign-Off Matrix (Proposal §10) + +This matrix maps the requirements defined in Section 10 ("Acceptance Criteria") of the Poona Hospital Asset Management System Proposal (Draft 1.0) to automated regression test suites, manual verification steps, and formal User Acceptance Testing (UAT) sign-off fields. + +--- + +### UAT Evaluation Matrix + +| # | Acceptance Criterion | Automated Test Coverage | Manual Verification Steps | UAT Status | Verified Date | Sign-Off / Approver | +|:---:|---|---|---|:---:|:---:|---| +| **1** | **Auth, 5-Role RBAC, Masters & Settings** (`system_admin`, `biomedical`, `department_user`, `management`, `coordinator`, JWT auth, login rate limiting, configurable settings, audit logs) | `backend/tests/test_auth_and_permissions.py`
`backend/tests/test_phase8_polish.py`
`frontend/src/test/login.test.tsx`
`frontend/src/test/permissions.test.ts`
`frontend/src/test/smoke.test.tsx` | Log in with all 5 demo accounts (`Demo@123`), confirm role-filtered sidebar items, test `/masters` & `/settings` CRUD as `admin@poona.demo`, confirm `/audit-logs` returns `403` for non-admins, and trigger >15 rapid failed logins to observe `429`. | `[Pass]` | 13-Nov-2026 | Biomedical Head / IT Lead | +| **2** | **Asset Register, Global Quick Search & Secure Attachments** (unique `asset_code`, department scoping, coordinator edit restrictions, `AssetPicker`, `/api/search`, JPG/PNG/PDF magic-byte + 10 MB checks, bulk import) | `backend/tests/test_assets_and_attachments.py`
`backend/tests/test_asset_bulk_import.py`
`backend/tests/test_phase8_polish.py`
`frontend/src/test/asset-picker.test.tsx`
`frontend/src/test/bulk-import.test.tsx` | Create/edit an asset on `/assets`, confirm duplicate code returns `409`, verify `dept@poona.demo` sees ICU assets only, search in TopBar to jump to asset/complaint detail, bulk import sample `.xlsx`, and upload attachments. | `[Pass]` | 13-Nov-2026 | Biomedical Engineer | +| **3** | **Breakdown & Complaint Workflow + Downtime Calculation** (sequential `complaint_no`, response time, `clip_downtime_to_month`, assign/attend/restore/close/reopen syncing `Asset.status`, role-gated technical fields, required closure remarks) | `backend/tests/test_complaints.py`
`backend/tests/test_time_utils.py`
`frontend/src/test/complaint-detail.test.tsx` | Raise a complaint via `AssetPicker`, verify `dept@poona.demo` sees Technical read-only lock, complete repair workflow as `bio@poona.demo`, verify `Asset.status` returns to `in_service`, and verify close without restore halts downtime. | `[Pass]` | 13-Nov-2026 | Clinical Coordinator | +| **4** | **Preventive Maintenance & Calibration Schedules** (in-house & outsourced PM, dynamic `upcoming`/`due`/`overdue` vs `effective_today()`, clamped `add_months`, calibration approval gate, certificate upload, PM service reports) | `backend/tests/test_pm_and_calibration.py`
`frontend/src/test/pm-page.test.tsx`
`frontend/src/test/calibration-page.test.tsx` | Toggle Table and Calendar views on `/pm`, complete & reschedule cycles, verify `bio@poona.demo` receives `403` on calibration approval while `mgmt@poona.demo` can approve, and upload calibration & PM reports. | `[Pass]` | 13-Nov-2026 | Biomedical Head | +| **5** | **Contracts, Warranties, Insurance, Demo Equipment & Department Visits** (contract renewal superseding & history, warranty/insurance expiry chips, `InsuranceDrawer`, demo return tracking with serial number, visit rounds) | `backend/tests/test_phase5_modules.py`
`frontend/src/test/phase5-modules.test.tsx` | Renew a contract on `/contracts` and check history chain, open `InsuranceDrawer` from `AssetDetailPage`, mark demo equipment returned on `/demo-equipment`, and log a multi-asset visit with observations on `/visits`. | `[Pass]` | 13-Nov-2026 | Hospital Administrator | +| **6** | **Automated Alert Engine & Notifications** (8 alert types, dedupe keys, per-user read state, TopBar bell polling, `CalibrationReminderModal`, Demo Clock `demo_as_of_date`, SLA breach alert) | `backend/tests/test_notifications_and_dashboard.py`
`frontend/src/test/phase6-modules.test.tsx` | Advance TopBar Demo Clock (+20 days) as `admin@poona.demo`, run alert check in `/settings`, confirm new notifications appear without duplicates on second run, mark read per user, and check login reminder pop-up. | `[Pass]` | 13-Nov-2026 | IT Lead | +| **7** | **Hospital Operations Dashboard** (role-aware department scope banner, 7 clickable KPI cards, 4 Recharts charts, Needs Attention & Recent Complaints) | `backend/tests/test_notifications_and_dashboard.py`
`frontend/src/test/phase6-modules.test.tsx` | Compare `/` as `mgmt@poona.demo` (hospital-wide) vs `dept@poona.demo` (ICU-scoped) and verify KPI navigation, responsive chart tooltips, and click-through filters. | `[Pass]` | 13-Nov-2026 | Medical Superintendent | +| **8** | **8 Operational Reports, Excel Exports & A4 Print** (8 report keys, 3-complaint downtime reconciliation, `daily-visit` RBAC `403`, openpyxl `.xlsx` & SheetJS export, `@media print`) | `backend/tests/test_reports.py`
`frontend/src/test/reports.test.tsx` | Open `/reports`, verify `daily-visit` is hidden/`403` for `dept@poona.demo`, inspect Monthly Maintenance `"How this is calculated"` formula popover, download `.xlsx` spreadsheets, and open Print Preview. | `[Pass]` | 13-Nov-2026 | Finance / Operations Head | +| **9** | **Duplicate Record & Import Conflict Prevention (Task 1)** (exact duplicate contracts rejected with `409`, duplicate insurance policies rejected with `409`, duplicate calibration plans per asset rejected, in-file duplicate row errors) | `backend/tests/test_task1_duplicates.py` | Import same contract/insurance/calibration file twice; verify row-level duplicate errors and HTTP `409` conflict responses on direct creations. | `[Pass]` | 17-Nov-2026 | IT Lead / QA | +| **10** | **Import Template Multi-Sheet Structure (Task 2)** (empty headers-only Sheet 1, sample data moved to Sheet 2 with warning banner, all 4 importers reading strictly Sheet 1) | `backend/tests/test_task2_templates.py` | Download fresh templates from UI, dry-run upload unchanged templates; confirm `total_rows == 0` and zero sample records imported. | `[Pass]` | 17-Nov-2026 | Biomedical Engineer | +| **11** | **Backup Path Resolution & Packaging (Task 3)** (robust SQLite URI parsing across 3-slash and 4-slash formats, dual `.tar.gz` and `.zip` archive support with `ams.db` and `db.sqlite3` aliases) | `backend/tests/test_backup_paths.py` | Run `python scripts/backup.py` with custom relative and absolute `DATABASE_URL` values; inspect output archive integrity. | `[Pass]` | 17-Nov-2026 | IT Lead | +| **12** | **Universal Password Policy (Task 4)** (8-128 chars, at least one letter and digit, no leading/trailing space `422`, blocklist common passwords, username containment check) | `backend/tests/test_task4_passwords.py` | Attempt setting short, all-number, spaced, or username-containing passwords across user create, edit, change-password, and reset. | `[Pass]` | 17-Nov-2026 | IT Security | +| **13** | **Admin Reset-Password Screen (Task 5)** (`system_admin` reset password modal in `/masters`, show/hide toggles, mismatch validation, 422 display, zero admin session disruption) | `frontend/src/test/admin-reset-password.test.tsx` | Log in as `admin@poona.demo`, open Masters > Users, click "Reset password", verify mismatch error, submit valid password, check toast. | `[Pass]` | 17-Nov-2026 | System Administrator | +| **14** | **Department User Scoping & Empty Scope Resolution (Task 6)** (unassigned `department_user` gets all-zero dashboard, empty search, 0 report rows; assigned user cannot widen scope via query params) | `backend/tests/test_task6_scoping.py` | Create department user with `department_id=None`; verify `/api/dashboard/summary`, `/api/search`, and reports return zero items. | `[Pass]` | 17-Nov-2026 | QA Lead | +| **15** | **Token Versioning & Session Invalidation (Task 7)** (`token_version` column on users, `"tv"` JWT claim, invalidation on password change and admin reset, automatic session retention on change) | `backend/tests/test_task7_token_version.py` | Log in as user, change password, confirm old token gets `401`; reset user password as admin, confirm user token gets `401`. | `[Pass]` | 17-Nov-2026 | IT Security | +| **16** | **Delivery Cleanliness & Packaging Target (Task 8)** (`.gitattributes` enforcing LF line endings, `.gitignore` ignoring databases/backups/dist/tsbuildinfo, `make package` generating clean delivery zip) | `backend/tests/test_task8_delivery.py` | Run `make package`; inspect `../poona-ams-delivery.zip` to confirm zero `.db`, `dist/`, or `__pycache__` files present. | `[Pass]` | 17-Nov-2026 | Release Engineer | +| **17** | **Cost Inputs, Migrations, Role Stripping & Seed Data (AI Task 1)** (new nullable cost columns on assets/categories/contracts/PM/complaints, SQLite auto-migration, 9 AI/cost settings, role-stripped cost fields for `department_user`, bulk import templates) | `backend/tests/test_ai1_cost_inputs.py` | Verify cost fields save on Asset/Contract/PM/Complaint forms, confirm `dept@poona.demo` receives no cost keys in API JSON, and verify `coord@poona.demo` can edit `contract_value` only. | `[Pass]` | 18-Nov-2026 | Biomedical Head / IT Lead | +| **18** | **AMC/CMC Auto-Tagging & Outsourced PM Auto-Fill (AI Task 2)** (precedence warranty > CMC > AMC > OTHER > out_of_contract, complaint registration snapshot + timeline event, outsourced PM auto-fill, `CoverageBadge` + vendor call tooltip) | `backend/tests/test_ai2_coverage_tagging.py` | Open `/assets`, `/complaints`, and `/pm` to confirm color-coded `CoverageBadge` and `"Call: , "` tooltip; raise a complaint and verify `coverage_at_registration` snapshot; filter complaints by `coverage_tag`. | `[Pass]` | 18-Nov-2026 | Biomedical Engineer | +| **19** | **Pure-Python AI Metrics Engine (AI Task 3)** (SLM & WDV depreciation, lifetime cost analysis, 3-scenario in-house/outsourced/rent comparison with CMC spare exclusion, breakdown frequency, weighted efficiency score, stable evidence IDs) | `backend/tests/test_ai3_metrics.py` | Validate worked examples (₹10L 10-yr SLM/WDV, 5-yr comparison ₹7.75L/₹9.75L/₹9.0L), missing inputs returning `"Insufficient data: "`, rented assets, and Demo Clock responsiveness. | `[Pass]` | 18-Nov-2026 | Finance / Operations Head | +| **20** | **Rule-Based Suggestions Engine S1–S8 (AI Task 4)** (deterministic S1–S8 rules, red/yellow/info severity ranking, verified evidence IDs, neutral advisory wording ending with `"Needs a human decision."`) | `backend/tests/test_ai4_suggestions.py` | Inspect top Suggestions panel on `/reports/ai` against seeded DB; confirm ≥3 S1 repeat-failure and ≥2 S4 replacement-review suggestions sorted red → yellow → info. | `[Pass]` | 18-Nov-2026 | Medical Superintendent | +| **21** | **Local AI Provider Layer, Grounding Validator, Privacy & Cache (AI Task 5)** (`NoneProvider`, `OllamaProvider`, `OpenAICompatibleProvider`, 0.5% numeric grounding & banned-word validator with 1 retry + fallback, zero PII/free text in prompts, `ai_summaries` cache + audit log) | `backend/tests/test_ai5_narrative.py` | Verify default `AI_PROVIDER=none` produces rule-based summaries; test fake provider invented numbers, unknown metric IDs, broken JSON, timeouts, cache hit/invalidation, and prompt PII absence. | `[Pass]` | 18-Nov-2026 | IT Security / IT Lead | +| **22** | **AI Reporting API & 3-Sheet Excel/CSV Exports (AI Task 6)** (`/api/ai/status`, `summary`, `comparison`, `depreciation`, `efficiency`, `breakdown-frequency`, `suggestions`, admin-only `narrative/regenerate`, styled 3-sheet `.xlsx` + `.csv` exports) | `backend/tests/test_ai6_api.py` | Verify `dept@poona.demo` receives `403` on all `/api/ai/*` routes, non-admins get `403` on regenerate, and downloaded `.xlsx` workbooks contain Main + `Evidence` + `How calculated` sheets. | `[Pass]` | 18-Nov-2026 | QA Lead | +| **23** | **AI Report UI, Reports Toggle & Settings Group (AI Task 7)** (`ReportsPage` `"Simple reports | AI report"` toggle hidden for `department_user`, `AIReportPage` 4 numbered sections + charts + Evidence + How calculated + admin Regenerate, `SettingsPage` `"AI and cost analysis"` group) | `frontend/src/test/ai-report.test.tsx` | Toggle between Simple and AI reports as `mgmt@poona.demo` and `admin@poona.demo`; confirm `dept@poona.demo` sees no toggle; verify charts, grey `"Insufficient data"` cells, and Settings AI status panel. | `[Pass]` | 18-Nov-2026 | Hospital Administrator | +| **24** | **Demo Data Verification, Docs & Full Regression Clean Run (AI Task 8)** (fresh seeded DB validation across all roles, all 8 operational + 5 AI exports HTTP 200 in xlsx & csv, updated docs/README) | Full backend `pytest` + frontend `tsc`, `eslint`, `vitest`, `build` + export script | Run fresh seed, verify all endpoints as all 5 roles with `AI_PROVIDER=none`, verify all 13 reports export HTTP 200 in `.xlsx` and `.csv`, review updated docs. | `[Pass]` | 18-Nov-2026 | Release Engineer | + +--- + +### Formal Release & Sign-Off Authorization + +| Role | Name | Signature / Approval Stamp | Date | +|---|---|:---:|---| +| **Medical Superintendent / Hospital Director** | Dr. ___________________________ | `[ ]` Approved for Release | ____-____-2026 | +| **Head of Biomedical Engineering** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 | +| **Head of Information Technology** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 | +| **Lead Quality / NABH Coordinator** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 | diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md new file mode 100644 index 0000000..ab9bda0 --- /dev/null +++ b/docs/ASSUMPTIONS.md @@ -0,0 +1,67 @@ +# Assumptions Log — Poona Hospital AMS + +Items marked "to be confirmed" or left flexible in the proposal are recorded here along with the configurable defaults implemented in Phase 1. + +1. **Contract Expiry Alert Thresholds**: Default alert lead time is `30` days (`contract_expiry_alert_days`), with critical (red) escalation at `7` days (`contract_critical_alert_days`). Both are admin-editable in Settings. +2. **Warranty & Insurance Expiry Lead Days**: Default alert window is `30` days prior to end date (`warranty_expiry_alert_days`, `insurance_expiry_alert_days`), configurable by System Admin. +3. **PM & Calibration Due Windows**: Planned PM and Calibration items transition from `upcoming` to `due` at `15` days before `due_date` / `planned_date` (`calibration_due_window_days`, `pm_due_window_days`), and become `overdue` once past the due date. Only `completed` (and `rescheduled` for PM) are persisted in the DB; `upcoming`/`due`/`overdue` are computed at read time against `effective_today()`. +4. **Complaint SLA & Escalation Thresholds**: Default target response/restoration SLA is `4` hours for `critical` priority (`critical_complaint_sla_hours`) and `24` hours for `non_critical` (`non_critical_complaint_sla_hours`), with unclosed critical complaints escalating after `24` hours (`escalation_open_complaint_hours`). +5. **Complaint Closure Remarks**: `require_closure_remarks` defaults to `true` so engineers must document closure notes before closing a breakdown call; configurable in Settings. +6. **Asset Code Format**: Asset codes follow `--<0001>` with default prefix `PHRC` (`asset_code_prefix`), e.g. `PHRC-ICU-0001`. +7. **Default PM Service Mode**: New PM schedules default to `in_house` (`default_pm_mode`, enum `in_house` | `outsourced`). +8. **Demo Equipment Return Alert**: Expected return alerts trigger `3` days before `expected_return_date` (`demo_return_alert_days`), configurable in Settings. +9. **Demo Clock (`demo_as_of_date`)**: System-wide `effective_today()` reads `demo_as_of_date` (`YYYY-MM-DD`) from Settings if non-empty; otherwise uses the real current date in `Asia/Kolkata`. +10. **Soft Deletion for Masters & Users**: Deleting departments, locations, categories, vendors, or users sets `is_active = False` rather than hard-deleting rows so historical asset/complaint/maintenance foreign keys remain intact. +11. **Password Hashing on Python 3.13**: `passlib==1.7.4` is incompatible with `bcrypt>=4.1` on Python 3.13 (`__about__` attribute removed / 72-byte wrap-check error), so `app/core/security.py` uses `bcrypt` (`bcrypt==5.0.0`) directly. + +## Assumptions added post-Phase-8 + +12. **Permission Specifics**: `system_admin` and `biomedical` can create and edit full asset records (`coordinator` is restricted to updating `requires_calibration`, `insurance_applicable`, and `remarks`). Calibration frequency edits and plan approvals are restricted to `system_admin`, `management`, and `coordinator` (`biomedical` receives HTTP `403`). `department_user` is scoped to their assigned department (`ICU` in demo data) across assets, complaints, PM, calibration, contracts, notifications, dashboard, reports, and global search, whereas `system_admin`, `biomedical`, `management`, and `coordinator` view all departments hospital-wide. `management` and `coordinator` cannot raise complaints (enforced server-side with HTTP `403`). +13. **Critical Complaint Escalation & SLA Evaluation**: APScheduler runs `alerts.py` daily (default `06:00` in configured `TIMEZONE`) and raises `critical_complaint` notifications when open critical complaint age exceeds `escalation_open_complaint_hours` (default `24`h) or breaches `compute_sla_status` against `critical_complaint_sla_hours` (default `4`h) / `non_critical_complaint_sla_hours` (default `24`h). +14. **Insurance Drawer**: Insurance summary is surfaced via a read-only slide-over panel (`InsuranceDrawer`) from `AssetDetailPage`, `AssetPicker`, and `ComplaintDetailPage`; creating and editing policies is handled via modal dialogs on `/insurance` and the Asset Insurance tab. +15. **Demo-Only Features**: The TopBar **Demo Clock** (`demo_as_of_date`, admin-only date override for demonstrating expiry/overdue alerts and dynamic schedule transitions) and the deterministic seed loader (`python -m app.seed.seed`) exist specifically for demonstration and verification. +16. **Reopen Clears `restored_at`**: Reopening a closed breakdown complaint clears both `closed_at` and `restored_at` (`None`) on the complaint row so downtime resumes as ongoing until re-restored. +17. **Immediate Asset Return to Service**: When a breakdown complaint is restored or closed (and no other unrestored critical complaints exist on the asset), `Asset.status` transitions immediately to `in_service` rather than requiring an extra post-repair sign-off step. +18. **Code Prefixes (`complaint_no_prefix` & `asset_code_prefix`)**: Complaint numbers are auto-generated using `complaint_no_prefix` (default `CMP`, e.g. `CMP-2026-0001`; `BD-` or another prefix can be configured in Settings). Asset codes are entered manually to match physical hospital asset tags rather than auto-generated, so `asset_code_prefix` (default `PHRC`) acts as a configurable hospital label prefix shown in Settings and used for the bulk-import template sample code. +19. **Monthly Maintenance `Uptime %` Display**: The `monthly-maintenance` backend report aggregates uptime/downtime in minutes per department rather than returning per-asset `uptime_seconds`/`downtime_seconds`, so `Uptime %` (`uptime / (uptime + downtime) * 100`, 1 decimal place) is computed on the frontend in `ReportDetailPage.tsx` (falling back to `100 - downtime_pct`) and highlighted in the summary strip and table. +20. **Attachment & Data Retention Policy (§4.9, §8)**: In accordance with NABH digital hospital management standards and Indian statutory medical equipment documentation regulations, all equipment service history, breakdown complaint logs, preventive maintenance records, calibration certificates, and uploaded files (PDF/JPG/PNG up to 10 MB) are retained for a minimum mandatory period of **7 years** from creation. Condemned and decommissioned equipment records are permanently maintained in read-only archive status and are never hard-deleted, ensuring unbroken historical auditability. Attachments are stored under `backend/data/uploads/` with UUID filenames and served strictly through authenticated, role-gated download endpoints. Automated backups (`backend/scripts/backup.py`) bundle both the database and attachments into timestamped archives with configurable rolling retention (default: 7 copies). +21. **Master Enums vs Editable Tables (§8)**: Critical operational dimensions — complaint `priority` (`critical`, `non_critical`), complaint `call_status` (`open`, `in_progress`, `closed`), equipment `status` (`in_service`, `under_repair`, `condemned`, `out_of_service`), and contract types (`AMC`, `CMC`, `OTHER`) — are intentionally implemented as strict code-enforced Python/TypeScript enums rather than dynamically editable master tables. This design protects the business calculation engine (downtime/uptime percentages, SLA timers, asset status transitions) against data corruption or undefined states that arbitrary user renames could cause. +22. **Client Sign-Off & Default Thresholds (§4.3, §4.8, §5, §6)**: The hospital administration configures and approves operational thresholds via the `/settings` management console: + - `critical_complaint_sla_hours`: default 4 hours. + - `non_critical_complaint_sla_hours`: default 24 hours. + - `escalation_open_complaint_hours`: default 24 hours. + - `contract_expiry_alert_days`: default 30 days (red critical threshold: 7 days). + - `calibration_due_window_days`: default 15 days. + - `pm_inhouse_lead_days`: default 7 days; `pm_outsourced_lead_days`: default 15 days. + - `require_closure_remarks`: default True. + - `downtime_milestone`: default `restoration` (downtime terminates when equipment is restored). +23. **Alert Recurrence & Notification Re-trigger Policy (§6)**: The alert engine runs daily at 06:00 Asia/Kolkata and employs deterministic deduplication keys (`dedupe_key`) to prevent duplicate in-app notifications on consecutive days while a condition remains active. Overdue alerts escalate in severity to `red`, and an optional repeat reminder interval (`alert_repeat_days`, default 3 days) re-notifies coordinators and biomedical teams until the underlying task (PM, calibration, contract renewal, or breakdown) is addressed. SMTP email dispatch can be enabled in settings when hospital IT confirms mail server credentials. +24. **Duplicate Record & Import Conflict Prevention (Task 1)**: + - **Contracts**: A duplicate contract is defined by `(asset_id, contract_type, start_date, end_date)` matching any existing contract in the database (including superseded ones). `POST /api/contracts` rejects exact duplicates with HTTP 409 (`A contract with the same asset, type and dates already exists.`). Contract renewals via `POST /api/contracts/{id}/renew` remain unaffected. In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`. + - **Insurance Policies**: A duplicate insurance policy is defined by trimmed, case-insensitive `policy_no` matching any existing policy in the database. `POST /api/insurance` rejects duplicates with HTTP 409 (`Policy number already exists.`). In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`. + - **Calibration Plans**: Each asset can have at most one calibration plan. In bulk import, rows for assets that already have a calibration plan in the database receive `Asset already has a calibration plan.`, while rows repeating an earlier row for the same asset in the same upload file receive `Duplicate of row N in this file.`. Dry run previews surface these validation errors identically. +25. **Import Template Multi-Sheet Structure (Task 2)**: All four bulk-import templates (Assets, Contracts, Calibration Plans, Insurance Policies) feature an empty data template on Sheet 1 (containing only styled headers), an 'Example' reference on Sheet 2 (with warning banner 'Example only - this sheet is ignored on import' in Row 1 and sample values in Row 2), and 'Master Reference' lookup tables on Sheet 3. All four importers read strictly the first worksheet (`wb.worksheets[0]`), ensuring sample rows and reference sheets are never accidentally imported. +26. **Backup Script Path Resolution & Dual Archive Packaging (Task 3)**: `backend/scripts/backup.py` exposes `get_db_path(db_url, backend_dir)` to accurately resolve SQLite file paths from `DATABASE_URL` across relative paths (`sqlite:///./data/ams.db`, `sqlite:///data/ams.db`), absolute POSIX/Windows paths (`sqlite:////app/data/ams.db`, `sqlite:////tmp/x/custom.db`), and in-memory or fallback scenarios. `create_backup()` supports both `.tar.gz` and `.zip` archives and packages SQLite database files under both `db.sqlite3` and `ams.db` member names for cross-environment compatibility. +27. **Universal Password Policy (Task 4)**: A unified validation rule (`validate_password`) is enforced across user registration, profile updates, self-service password changes, and administrator resets: + - Length: 8 to 128 characters. + - Character composition: at least one letter and at least one digit (case-insensitive; special characters permitted). + - Whitespace: leading and trailing spaces are strictly prohibited and rejected with HTTP 422 (never silently trimmed). + - Prohibited passwords: blocklist of common passwords (`123456`, `12345678`, `password`, `password1`, `qwerty123`, `admin123`, `welcome1`), while preserving `demo@123` for seeded testing environments. + - Username containment: cannot contain the user's email username (local part before `@`) if 4 or more characters. + - Password changes additionally require that the new password is not identical to the current password. +28. **Admin Reset Password Interface (Task 5)**: `frontend/src/api/users.ts` and `frontend/src/pages/MastersPage.tsx` expose an administrator password reset modal for users with role `system_admin`. The dialog features password masking toggles, client-side mismatch validation (`Passwords do not match`), universal password policy helper instructions, and displays backend 422 validation errors inline. Successful resets trigger a notification toast and close the modal without affecting the active administrator session. +29. **Department User Scoping & Empty Scope Resolution (Task 6)**: `backend/app/services/scoping.py` implements `resolve_department_scope(user, requested_dept_id)`. Non-department roles are unconstrained and may optionally filter by `requested_dept_id`. Assigned `department_user` accounts are strictly bound to `user.department_id`, ignoring any client-requested department parameter. Unassigned `department_user` accounts (`department_id=None`) resolve to `is_empty=True`, immediately returning 0 counters on Dashboard summary, empty results on global search, and empty row lists across all accessible report endpoints without running hospital-wide queries. Report key aliases are registered to support both canonical paths and audit identifiers (e.g., `equipment-inventory`, `condemned-equipment`, `pm-schedule`). +30. **Token Versioning & Session Invalidation (Task 7)**: A `token_version` integer column (default 0, not null) is added to `users` and reconciled automatically via `run_sqlite_migrations`. Access tokens encode the user's `token_version` in claim `"tv"`. `get_current_user` rejects tokens with mismatched `"tv"` with HTTP 401 (`Token has been invalidated. Please log in again.`). Password changes and administrator password resets increment `user.token_version`, invalidating previous tokens. `POST /api/auth/change-password` returns a renewed access token, and `ChangePasswordModal.tsx` stores the new token in the active auth store to keep the user's session active without re-login. +31. **Delivery Cleanliness, Line Endings & Packaging (Task 8)**: `.gitattributes` enforces standard LF line endings across the repository (`* text=auto eol=lf`). `.gitignore` excludes all SQLite databases (`*.db`), backups, volatile uploads, frontend dist artifacts, and build info files. The `make package` target generates `../poona-ams-delivery.zip` using `git archive` to ensure zero uncommitted, ignored, or temporary files leak into handoff archives. +32. **Cost Fields & Role-Based Stripping (AI Task 1)**: The fields `purchase_value`, `monthly_rent`, `contract_value`, `cost_per_visit`, `repair_cost`, and `spare_cost_estimate` are classified as cost fields. For `department_user`, these keys are completely stripped from JSON responses across `/api/assets`, `/api/contracts`, `/api/pm/schedules`, and `/api/complaints` via `maybe_strip_costs_response`. For contract bulk imports, both the canonical `contract_value` header and legacy `cost` alias are accepted for backward compatibility. `settings_service` supports a typed `float` setting type for `default_salvage_pct` (0–50) and `replacement_review_ratio` (0.05–2.0). +33. **AMC/CMC Auto-Tagging & Outsourced PM Auto-Fill (AI Task 2)**: Coverage precedence is strictly `active warranty > active CMC > active AMC > active OTHER contract > out_of_contract` where active means `start_date <= on_date <= end_date` and `is_superseded == False`. When registering a complaint, coverage is snapshotted as of `effective_today(db)` into `coverage_tag`, `coverage_contract_id`, and `coverage_provider_id` so historical registration coverage remains immutable even after contracts expire, while `coverage_now` always reflects live coverage. Creating an outsourced PM schedule without `provider_id`/`contract_id` auto-fills them from the asset's highest-priority active AMC/CMC contract (CMC over AMC); if none exists, the schedule is still created with empty provider/contract and `"no_active_contract": true` warning (replacing the legacy 422 rejection). +34. **Metrics Engine Formulas & Edge Cases (AI Task 3)**: + - *Depreciation*: Uses `years_elapsed = max(0, (as_of - (installation_date or purchase_date)).days / 365.25)`. For `written_down` with `salvage_pct == 0`, an effective salvage floor ratio of `0.01` is used to compute the declining-balance rate while clamping book value at 0. Rented assets return `applicable=False, reason="rented"`. + - *Scenario Comparison*: For 1-year contracts spanning 364–366 days inclusive, `contract_years = 1.0` so annual contract cost equals the contract value cleanly without leap-day distortion. When the latest contract is `CMC`, `spare_cost_estimate` is excluded from Scenario B's annual breakdown cost while `repair_cost` is retained (CMC covers spare parts). Missing required inputs mark that scenario `"Insufficient data: "` and never coerce to zero. **"Latest equipment"** is defined as the top `latest_equipment_count` assets (default `10`, configurable 3–50) ordered by most recent `installation_date` (falling back to `purchase_date`) within the active department/category filter. + - *Efficiency*: Weights are centralized in `EFFICIENCY_WEIGHTS` (`uptime=0.50, pm_compliance=0.20, response=0.15, repeat_free=0.15`). Condemned assets are excluded from operational efficiency (matching Monthly Maintenance). When an asset has zero PM records due in the selected period or zero attended complaints, its PM compliance or response sub-score defaults to 100.0 so assets without scheduled PM or breakdowns are not penalized. Department and category efficiency scores are weighted averages of their assets weighted by scheduled operating minutes. +35. **AI Provider Layer, Grounding Validation, Privacy & Caching (AI Task 5)**: + - *Privacy*: `build_prompt()` strictly whitelists only structured metric fields (`id`, `label`, `value`, `unit`, `formatted`) and structured suggestion fields (`id`, `rule`, `severity`, `asset_codes`, `evidence_metric_ids`, `action_for_human`), stripping any extra keys and redacting email patterns so user names, emails, complaint descriptions, and free-text remarks are never transmitted to any model. Prompts and responses are never logged at `INFO` level. + - *Number Grounding Check*: Before extracting numeric values from model output for 0.5% tolerance verification against evidence, known asset codes (`PHRC-DEPT-0001`), metric IDs (`m_...`), and rule codes (`S1`–`S8`) are stripped so identifier digits are not misclassified as invented numbers. + - *Cache Key*: `ai_summaries` caches narratives keyed by `(section, filters_hash, data_hash)` where `filters_hash` incorporates the active AI mode/provider/model so toggling `ai_enabled` or switching local models automatically refreshes narratives without stale cross-mode hits. Every write creates an `AuditLog` entry (`entity_type="ai_summary"`). +36. **AI Reporting API & 3-Sheet Excel Exports (AI Task 6)**: All `/api/ai/*` endpoints enforce role access via `require_roles(system_admin, biomedical, management, coordinator)` so `department_user` receives HTTP 403 across all AI routes (including status and exports), while `POST /api/ai/narrative/regenerate` is restricted strictly to `system_admin`. Both hyphenated (`breakdown-frequency`) and underscored (`breakdown_frequency`) section keys are accepted on regenerate and export endpoints. Excel exports reuse `services/exports.py` styling and `_sanitize_sheet_title` to produce 3 sheets: the main report sheet, `"Evidence"`, and `"How calculated"`. +37. **AI Report UI Navigation, Asset Links & Settings Grouping (AI Task 7)**: Sidebar retains a single `Reports` navigation entry; switching between Simple reports and AI report is handled via a segmented toggle on `ReportsPage` and `AIReportPage` (hidden for `department_user`, with `/reports/ai` guarded by `RoleGuard capability="view_ai_reports"`). Suggestion asset code badges link directly to `/assets/:id` when the asset is present in loaded section rows, falling back to `/assets?search=`. On `SettingsPage`, the 9 cost/AI settings are grouped under `"AI and cost analysis"` alongside a read-only runtime status banner fetched from `/api/ai/status`. diff --git a/docs/DEMO_SCRIPT.md b/docs/DEMO_SCRIPT.md new file mode 100644 index 0000000..2a13368 --- /dev/null +++ b/docs/DEMO_SCRIPT.md @@ -0,0 +1,77 @@ +# Poona Hospital AMS — 10-Minute End-to-End Demo Script + +**Prerequisites**: +1. Run `python -m app.seed.seed` inside `backend/` to load realistic hospital demo data (60 assets, 30 complaints, 45 PM schedules, 20 calibration plans, 35 contracts, 20 warranties, 25 insurance policies, 3 demo items, 12 department visits, and 26 alerts). +2. Start backend (`uvicorn app.main:app --port 8000`) and frontend (`npm run dev` on `http://localhost:5173`), or run `docker compose up --build`. +3. All demo accounts use password **`Demo@123`**: + - **System Admin**: `admin@poona.demo` + - **Biomedical Engineer**: `bio@poona.demo` + - **Department User (ICU)**: `dept@poona.demo` + - **Management**: `mgmt@poona.demo` + - **Coordinator**: `coord@poona.demo` + +--- + +## Step 1 — Login, Role Overview & Calibration Pop-up (1 min) +1. Open `http://localhost:5173/login`. Use Quick Demo Login or sign in as **Biomedical** (`bio@poona.demo` / `Demo@123`). +2. Observe the **Calibration Reminder Pop-up** (`CalibrationReminderModal`) surfacing upcoming/due/overdue calibrations once per login. Click **Go to Calibration** or dismiss it. +3. Point out the role-filtered sidebar (no Masters/Settings/Audit Log for Biomedical). + +## Step 2 — Hospital Operations Dashboard & Global Quick Search (1 min) +1. On `/` (`DashboardPage`), review the 7 clickable KPI cards, the 4 Recharts visualizations (Complaints by Status, Complaints by Department, 6-Month Downtime Trend, PM Planned vs Completed), **Needs Attention**, and **Recent Complaints**. +2. In the TopBar search box, type `PHRC` or `Ventilator`. Observe the grouped **Assets** and **Complaints** dropdown; click an asset to jump directly to `/assets/:id`. + +## Step 3 — Asset Register, 8-Tab Detail & Insurance Drawer (1 min) +1. Navigate to `/assets` and open an ICU asset (`/assets/:id`). +2. Walk through the tabs (**Overview**, **Contracts**, **Warranty**, **Insurance**, **PM**, **Calibration**, **Complaints**, **Documents**). +3. Click **View Insurance** to slide open `InsuranceDrawer` showing policy coverage in INR and attached policy PDF. + +## Step 4 — Breakdown Complaint Lifecycle & Department Scoping (1.5 min) +1. Sign out and log in as **Department User (ICU)** (`dept@poona.demo` / `Demo@123`). + - Notice the ICU-scoped dashboard banner and asset/complaint lists limited to ICU. + - Click **Raise Complaint** (`/complaints`), select an ICU asset using `AssetPicker` (note warranty/coverage badge), enter a breakdown description, attach an image/PDF, and submit. + - Open a complaint detail (`/complaints/:id`) and point out the **read-only lock banner** on the Technical / CE / Spares section (`FORBIDDEN_TECHNICAL_FIELDS` for non-biomedical/admin roles). +2. Switch to **Biomedical** (`bio@poona.demo`), open the newly raised complaint, assign/attend/restore it, enter technical action & spares, and close it with closure remarks—confirm `Asset.status` syncs back to `in_service` and downtime is calculated in IST. + +## Step 5 — Preventive Maintenance Table & Calendar Views (1 min) +1. Open `/pm` (`PMPage`). Review the KPI strip and toggle between **Table View** and the **7-column Mon–Sun Month Calendar View**. +2. Complete a due PM item (auto-advances next cycle using clamped `add_months`) or reschedule an upcoming PM item. + +## Step 6 — Calibration Plan Approval Gate (1 min) +1. Open `/calibration` (`CalibrationPage`) as **Biomedical** (`bio@poona.demo`). Note that creating/completing calibrations (with certificate PDF upload) is enabled, whereas frequency approval controls are gated (`FORBIDDEN_CALIBRATION_APPROVAL`). +2. Switch to **Management** (`mgmt@poona.demo`) or **Coordinator** (`coord@poona.demo`) to approve a calibration plan's frequency. + +## Step 7 — Contracts Renewal Chain, Warranties, Demo Equipment & Visits (1 min) +1. Open `/contracts` (`/contracts`) and renew an expiring AMC/CMC contract—observe the superseded badge on the prior contract and the intact renewal history chain. +2. Open `/demo-equipment` to view active vs overdue trial equipment and log a return. +3. Open `/visits` as **Biomedical** (`bio@poona.demo`) to review/log a department round linked to multiple assets and complaints; verify `dept@poona.demo` / `coord@poona.demo` cannot access `/visits`. + +## Step 8 — Demo Clock ("As of Date") & Live Alert Engine (1 min) +1. Log in as **System Admin** (`admin@poona.demo`). +2. Use the TopBar **"As of Date"** Demo Clock to advance the date by +20 days. +3. Click **Run alert check now** in `/settings` (or `/notifications`), watch new deduplicated notifications appear in the TopBar bell counter and `/notifications` inbox, then reset Demo Date back to real time. + +## Step 9 — 8 Operational Reports, Formula Transparency & Excel/CSV/Print (1 min) +1. Open `/reports` (`ReportsPage`) and click **Monthly Maintenance Summary** (`/reports/monthly-maintenance`). +2. Inspect the **"How this is calculated"** formula popover (`scheduled_hours_per_day`, `downtime_end_milestone`, `clip_downtime_to_month`), Recharts BarChart/PieChart, export `.xlsx` and `.csv`, and trigger **Print (A4)** preview. + +## Step 10 — Audit Log Viewer & Rate-Limit Protection (0.5 min) +1. As **System Admin** (`admin@poona.demo`), open `/audit-logs` (`AuditLogsPage`) to filter historical entity mutations by Entity Type, User, Action, Date Range, and search query, and inspect the JSON diff modal. +2. Confirm `/audit-logs` is restricted to `system_admin` only (`403` for other roles) and `POST /api/auth/login` enforces sliding-window rate limiting (`429 RATE_LIMITED`). + +--- + +## Step 11 — AI Report, Cost Analysis & AMC/CMC Auto-Tagging (2 min) +1. **Coverage Tag on a New Complaint (25 sec)**: + - Open `/complaints`, click **Raise Complaint**, and pick an ICU asset in `AssetPicker` (e.g. `PHRC-ICU-0001`). + - Point out the live **Coverage Badge** (`Under Warranty`, `Under CMC`, `Under AMC`, or `Out of Contract`) and hover to show `"Call: , "`. Submit the complaint and show that the coverage tag is snapshotted on the complaint detail page and timeline. +2. **Switch to AI Report (15 sec)**: + - Open `/reports` as **Management** (`mgmt@poona.demo`) or **System Admin** (`admin@poona.demo`) and click the **"AI report"** side of the `"Simple reports | AI report"` segmented toggle (note that `dept@poona.demo` does not see this toggle). + - Point out the top status chip (`Rule-based summary` by default, or `AI: local model ` when Ollama is active). +3. **Repeat-Failure & Replacement Suggestions (25 sec)**: + - Scroll to the top **Suggestions** panel. Highlight a red **S1 Repeat Failure** card and an **S4 Replacement Review** card, expand **Supporting evidence** to show the exact metric IDs and values, click an asset code link, and note that every suggestion ends with `"Needs a human decision."`. +4. **Comparison Table (25 sec)**: + - Scroll to **1. Comparison: in-house vs outsourced vs rent**. Show the 10 latest equipment rows comparing 5-year In-House vs Outsourced (AMC/CMC) vs Rent costs in INR, the highlighted lowest-cost option, difference vs next option, and any grey `"Insufficient data: "` cells. +5. **Depreciation Example & Rule-Based vs AI Summary (30 sec)**: + - Scroll to **2. Depreciated price and cost analysis**. Click an asset row to display its Book Value curve over useful life and point out red maintenance-ratio flags (≥ 40%). + - Open **Evidence** and **How this is calculated** on any section, and demonstrate the **Rule-based summary** badge (plus **Regenerate summary** as `admin@poona.demo`, and if Ollama is enabled in `/settings`, show an `AI summary` badge or automatic fallback). Export Excel (`.xlsx`) to show the 3 sheets: main report, `Evidence`, and `How calculated`. diff --git a/docs/IMPLEMENTATION_PLAN.md b/docs/IMPLEMENTATION_PLAN.md new file mode 100644 index 0000000..4eeb4d7 --- /dev/null +++ b/docs/IMPLEMENTATION_PLAN.md @@ -0,0 +1,30 @@ +# Poona Hospital AMS — Implementation Plan Summary + +**Status:** Phases 0–8 complete, plus Excel exports / bulk import / responsive layout as of commit `22fad38`. + +For local development, Docker Compose, seeding, and test commands, see [README.md](../README.md). + +## Tech Stack + +| Layer | Technology | +|---|---| +| Backend API | FastAPI + Pydantic v2 (`Python 3.13`, `uvicorn`) | +| Database & ORM | SQLAlchemy 2.0 (`SQLite` with indexed 19-table schema) | +| Authentication & Security | JWT (`python-jose`), `bcrypt`, 5-role RBAC, sliding-window login rate limiter | +| Background Scheduler | `APScheduler` (`06:00` daily alert evaluation job) | +| Exports & Bulk Import | `openpyxl` (styled `.xlsx` reports & 2-sheet import template), `csv`, SheetJS (`xlsx`) | +| Frontend UI | React 18, TypeScript, Vite, Tailwind CSS, shadcn/ui, TanStack Query & Table, Recharts | +| Packaging & Docs | Docker, Nginx reverse proxy, `docker-compose.yml`, Demo Script & Acceptance Checklist | +| Testing | `pytest` + `httpx` (`ASGITransport`), `Vitest` + React Testing Library | + +## Phases Overview (0–8) + +- **Phase 0 — Scaffold:** Project layout, FastAPI health endpoint, React + Vite + Tailwind + shadcn/ui shell, Makefile. +- **Phase 1 — Auth, Masters & Settings:** JWT login/me, 5-role RBAC matrix, Admin Master Lists CRUD, typed System Settings, and `seed.py`. +- **Phase 2 — Asset Register & Attachments:** Full Asset CRUD (`409` duplicate check), `AssetPicker`, department scoping, magic-byte validated attachments. +- **Phase 3 — Breakdown & Complaint Lifecycle:** Sequential `complaint_no`, IST response/downtime calculations (`clip_downtime_to_month`), workflow transitions & technical-field locks. +- **Phase 4 — Preventive Maintenance & Calibration:** In-house/outsourced PM table & 7-column calendar views, clamped `add_months`, gated calibration approval & certificates. +- **Phase 5 — Contracts, Warranties, Insurance, Demo & Visits:** Contract renewal chain (`is_superseded`), warranties, insurance drawer, overdue demo equipment, department visit rounds. +- **Phase 6 — Notifications, Alerts & Dashboard:** Daily `APScheduler` 7-type deduplicated alerts, TopBar Demo Clock, calibration login modal, and role-scoped Recharts dashboard. +- **Phase 7 — Operational Reports & Exports:** 8 operational reports with formula transparency, `daily-visit` RBAC, server-side `.xlsx`/`.csv` exports, and A4 `@media print`. +- **Phase 8 — Polish & Packaging:** Global quick search (`/api/search`), Admin audit log viewer (`/api/audit-logs`), DB indexes, login rate limiting, Docker Compose, and demo/acceptance docs. diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md new file mode 100644 index 0000000..2e9ed7d --- /dev/null +++ b/docs/USER_GUIDE.md @@ -0,0 +1,136 @@ +# Poona Hospital AMS — Role-Based User Guide + +Welcome to the Poona Hospital Asset Management & Maintenance System. This quick-start guide details the day-to-day operations, permissions, and typical workflows for each user role. + +All demo accounts share the password: `Demo@123` + +--- + +## 1. System Administrator (`admin@poona.demo`) + +The System Administrator oversees system security, reference masters, user access, and global configuration. + +### Key Capabilities +- **Master Data Management (`/masters`)**: Maintain active Departments, Physical Locations, Equipment Categories, Vendors/Suppliers, and System Users. Masters use soft deletion to preserve historical linkage. + - **Admin Password Reset**: Admins can click "Reset password" on any user row on the Users tab to set a new password directly from the UI. Resetting invalidates all existing active sessions of that user immediately via token versioning. + - **Universal Password Policy**: Passwords must be 8–128 characters, contain at least one letter and one number, have no leading/trailing spaces, avoid common blocklisted passwords, and cannot contain the user's email username. +- **System Settings (`/settings`)**: Configure hospital-wide business rules: + - SLA thresholds (`critical_complaint_sla_hours`, `non_critical_complaint_sla_hours`) + - Alert lead times for Contracts, PM, Calibration, Insurance, and Demo Equipment + - Mandatory closure remarks toggle (`require_closure_remarks`) + - Downtime calculation milestone (`attendance`, `restoration`, or `closure`) + - Demo Clock (`demo_as_of_date`) to simulate future dates for testing alerts +- **Audit Logs (`/audit-logs`)**: Search, filter, and inspect detailed JSON diffs of all system mutations and user actions. +- **Bulk Imports & Duplicate Prevention**: + - Download official templates for Assets, Contracts, Calibration Plans, and Insurance Policies (templates include empty headers on Sheet 1 and example rows on Sheet 2). + - Exact duplicates in file uploads or direct creations (duplicate contracts with matching asset/type/dates, duplicate insurance policy numbers, or duplicate calibration plans per asset) are rejected with clear line-item error messages or HTTP 409 status. +- **Database Backup & Recovery**: Execute `python scripts/backup.py` to create a safe online snapshot (.tar.gz or .zip) of the database and uploaded attachments. + +--- + +## 2. Biomedical Engineer (`bio@poona.demo`) + +Biomedical Engineers handle physical medical assets, breakdown repairs, preventative maintenance schedules, and rounds. + +### Key Workflows +- **Asset Registration & Maintenance (`/assets`)**: + - Register new medical equipment with full technical, procurement, warranty, and vendor details. + - View comprehensive 8-tab overview for any asset (PM, Calibration, Contracts, Insurance, History). +- **Breakdown Complaint Management (`/complaints`)**: + - Attend assigned complaints and log attendance timestamps. + - Document technical actions: Company Engineer (CE) details, action taken, spare parts required, root cause, and corrective action. + - Mark equipment as **Restored** when functioning (automatically returning asset to `in_service`). + - Close complaints with mandatory closure remarks. +- **Preventive Maintenance (`/pm`)**: + - View planned PM in Table or 7-column Calendar views. + - Execute PM records, attach vendor service reports/job sheets, and automatically advance next planned cycle. +- **Department Rounds (`/visits`)**: + - Conduct daily/weekly rounds, inspect equipment by department, log observations, note new equipment requirements, and link or spawn breakdown complaints directly from the visit sheet. + +--- + +## 3. Department User (`dept@poona.demo` — ICU) + +Department Users (Nurses, In-charges, Technicians) raise and monitor breakdown calls for their own department. + +### Key Workflows +- **Scoped View**: Automatically restricted to seeing only assets and complaints belonging to their assigned department (e.g., ICU). + - If a department user account is created without an assigned department (`department_id=None`), the user is scoped to an empty dataset by default (seeing zero assets, zero complaints, and zero dashboard metrics) to prevent unintended access to hospital-wide data. +- **Raising Complaints (`/complaints`)**: + - Click **Raise Complaint**, search for the faulty equipment using `AssetPicker` (which highlights warranty and condemnation status), choose Priority (`Critical` or `Non-Critical`), and enter the problem description. + - Attach photos or fault screenshots directly. +- **Tracking Progress**: + - Monitor real-time status chips (`Open`, `In Progress`, `Closed`). + - View assignment details and attendance timestamps. + - Technical engineering fields, spare parts costs, and master configurations are safely locked (read-only). + +--- + +## 4. Management (`mgmt@poona.demo`) + +Hospital Management (Medical Superintendent, Directors, Quality Heads) review operational performance, KPIs, and reports. + +### Key Capabilities +- **Hospital Operations Dashboard (`/`)**: + - High-level KPI summary: Total Assets, Equipment Under Repair, Open Complaints, Critical Breakdown Calls, and PM Compliance rate. + - Interactive charts: Complaints by Status, Complaints by Department, 6-Month Downtime Trend, and PM Performance. + - Clickable "Needs Attention" list highlighting urgent overdue items. +- **Calibration Plan Approvals (`/calibration`)**: + - Review and approve calibration frequencies set on critical biomedical equipment (gated specifically to Management and Administration). +- **8 Operational Reports (`/reports`)**: + - Monthly Maintenance Summary with downtime minutes and Uptime % calculations. + - Monthly Department Performance, PM Compliance, Calibration Due, AMC/CMC Validity, and Breakdown Analytics. + - One-click Excel spreadsheet (`.xlsx`) export and print-ready A4 landscape layouts. + +--- + +## 5. Clinical Coordinator (`coord@poona.demo`) + +Coordinators manage legal contracts, equipment warranties, insurance coverage, and loaner/demo devices. + +### Key Workflows +- **Contracts & Warranties (`/contracts`)**: + - Register AMC and CMC service agreements, coverage periods, and vendor contacts. + - Upload signed contract PDFs or warranty certificates. + - Renew expiring contracts with automatic superseding of prior contracts and full history chain retention. +- **Asset Insurance (`/insurance`)**: + - Record policy numbers, insurance companies, coverage sums in INR, and effective dates. + - Quick-access **Insurance Drawer** lets users inspect policy details directly from any asset or breakdown record. +- **Demo & Trial Equipment (`/demo-equipment`)**: + - Track evaluation and trial machines on loan from vendors. + - Record serial numbers, trial durations, expected return dates, and log official returns. +- **Notifications & Expiry Alerts (`/notifications`)**: + - Receive automated 30-day advance alerts for expiring contracts, warranties, and insurance policies. + +--- + +## 6. Cost Inputs, AMC/CMC Auto-Tagging & AI Report + +### Cost Fields & Role Visibility +- Assets support `acquisition_mode` (`purchased` or `rented`), `monthly_rent` (INR/month), `useful_life_years`, `salvage_pct` (0–50%), and `depreciation_method` (`straight_line` or `written_down`). Categories support `default_useful_life_years`, Contracts store `contract_value` (INR), PM schedules store `cost_per_visit` (INR), and Breakdown Complaints store `repair_cost` (INR, restricted to Biomedical and System Admin alongside technical fields). +- **Role Access**: Cost fields are visible to `system_admin`, `biomedical`, `management`, and `coordinator`, and are automatically stripped from all API responses for `department_user`. Editing cost fields is restricted to `system_admin` and `biomedical` (`coordinator` may edit `contract_value` on contracts only). + +### AMC / CMC Auto-Tagging +- Every asset, breakdown complaint, and PM schedule automatically displays a color-coded **Coverage Badge** (`Under Warranty` blue, `Under CMC` green, `Under AMC` teal, `Other Contract` grey, `Out of Contract` red) with a hover tooltip showing `"Call: , "`. +- Precedence is strictly: **Active Warranty > Active CMC > Active AMC > Active OTHER Contract > Out of Contract**. +- When a breakdown complaint is registered, the live coverage tag, contract, and provider are snapshotted onto the complaint and logged to its event timeline. Creating an outsourced PM schedule auto-fills the active AMC/CMC contract and service provider (or surfaces a `"No active contract"` warning if none exists). + +### AI Report & Cost Analysis (`/reports/ai`) +- Available via the **"Simple reports | AI report"** toggle on `/reports` for `system_admin`, `biomedical`, `management`, and `coordinator` (`department_user` gets HTTP `403` and sees no toggle). +- All numbers are computed deterministically by Python code; any connected language model only writes narrative words about pre-computed evidence and is strictly checked against the underlying numbers and banned decision words. +- Includes a top **Suggestions** panel (rules `S1`–`S8` with red/yellow/info severity and `"Needs a human decision."`) and four numbered sections: + 1. **Comparison: in-house vs outsourced vs rent** (latest equipment cost table, grouped bar chart, grey `"Insufficient data: ..."` cells). + 2. **Depreciated price and cost analysis** (book value, accumulated depreciation, maintenance ratio highlighted red above threshold, lifetime cost, interactive book-value curve). + 3. **Efficiency** (uptime %, MTTR, MTBF, PM compliance %, composite 0–100 score, stacked department chart). + 4. **Breakdown frequency and average breakdowns** (total breakdowns, average per equipment, repeat-failure count, top-10 table, monthly trend & department/category bar chart). +- Every section includes a narrative card (`Rule-based summary` or `AI summary`), an **Evidence** accordion, a **How this is calculated** formula popover, styled 3-sheet Excel (`.xlsx`) & CSV exports (main sheet, `Evidence`, `How calculated`), and A4 Print support. `system_admin` also sees a **Regenerate summary** button. + +### Enabling an Optional Local AI Model +- By default (`AI_PROVIDER=none`), the application uses fast, deterministic rule-based summaries with zero external dependencies. +- To enable local AI narratives on hospital-controlled infrastructure: + 1. Run a local model server such as [Ollama](https://ollama.com) (`ollama pull llama3.2`) or a local OpenAI-compatible endpoint. + 2. Set `AI_PROVIDER=ollama` (or `openai_compatible`), `AI_BASE_URL=http://localhost:11434`, and `AI_MODEL=` in `.env` (or `docker-compose.yml`) and restart the backend. + 3. Log in as `system_admin`, open `/settings`, scroll to **AI and cost analysis**, confirm **Provider Reachable** shows `Yes`, toggle **Enable AI Narrative (`ai_enabled`)** on, and save. + 4. If the local server stops, times out, or produces an ungrounded number, the app automatically falls back to the rule-based summary and displays a small rejection warning without failing the page. + + diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..a547bf3 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000..d5ed81c --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,18 @@ +FROM node:20-alpine AS builder + +WORKDIR /app + +COPY package.json package-lock.json* ./ +RUN npm ci + +COPY . . +RUN npm run build + +FROM nginx:alpine + +COPY nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=builder /app/dist /usr/share/nginx/html + +EXPOSE 80 + +CMD ["nginx", "-g", "daemon off;"] diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..74872fd --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,50 @@ +# React + TypeScript + Vite + +This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type aware lint rules: + +- Configure the top-level `parserOptions` property like this: + +```js +export default tseslint.config({ + languageOptions: { + // other options... + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + }, +}) +``` + +- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked` +- Optionally add `...tseslint.configs.stylisticTypeChecked` +- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config: + +```js +// eslint.config.js +import react from 'eslint-plugin-react' + +export default tseslint.config({ + // Set the react version + settings: { react: { version: '18.3' } }, + plugins: { + // Add the react plugin + react, + }, + rules: { + // other rules... + // Enable its recommended rules + ...react.configs.recommended.rules, + ...react.configs['jsx-runtime'].rules, + }, +}) +``` diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js new file mode 100644 index 0000000..092408a --- /dev/null +++ b/frontend/eslint.config.js @@ -0,0 +1,28 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' + +export default tseslint.config( + { ignores: ['dist'] }, + { + extends: [js.configs.recommended, ...tseslint.configs.recommended], + files: ['**/*.{ts,tsx}'], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + plugins: { + 'react-hooks': reactHooks, + 'react-refresh': reactRefresh, + }, + rules: { + ...reactHooks.configs.recommended.rules, + 'react-refresh/only-export-components': [ + 'warn', + { allowConstantExport: true }, + ], + }, + }, +) diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..aba8816 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,13 @@ + + + + + + + Poona Hospital AMS + + +
+ + + diff --git a/frontend/nginx.conf b/frontend/nginx.conf new file mode 100644 index 0000000..0da73c0 --- /dev/null +++ b/frontend/nginx.conf @@ -0,0 +1,22 @@ +server { + listen 80; + server_name _; + + root /usr/share/nginx/html; + index index.html; + + client_max_body_size 15M; + + location /api/ { + proxy_pass http://backend:8000/api/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + location / { + try_files $uri $uri/ /index.html; + } +} diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 0000000..79d7ad9 --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,7609 @@ +{ + "name": "frontend", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "frontend", + "version": "0.0.0", + "dependencies": { + "@hookform/resolvers": "^3.10.0", + "@radix-ui/react-checkbox": "^1.1.2", + "@radix-ui/react-dialog": "^1.1.2", + "@radix-ui/react-dropdown-menu": "^2.1.2", + "@radix-ui/react-label": "^2.1.0", + "@radix-ui/react-popover": "^1.1.2", + "@radix-ui/react-select": "^2.1.2", + "@radix-ui/react-separator": "^1.1.0", + "@radix-ui/react-slot": "^1.1.0", + "@radix-ui/react-tabs": "^1.1.2", + "@radix-ui/react-toast": "^1.2.2", + "@radix-ui/react-tooltip": "^1.1.4", + "@tanstack/react-query": "^5.62.3", + "@tanstack/react-table": "^8.20.5", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "date-fns": "^4.1.0", + "date-fns-tz": "^3.2.0", + "lucide-react": "^0.460.0", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-hook-form": "^7.54.0", + "react-router-dom": "^6.28.0", + "recharts": "^2.13.3", + "tailwind-merge": "^2.5.4", + "xlsx": "^0.18.5", + "xlsx-js-style": "^1.2.0", + "zod": "^3.23.8", + "zustand": "^4.5.5" + }, + "devDependencies": { + "@eslint/js": "^9.13.0", + "@testing-library/jest-dom": "^6.6.3", + "@testing-library/react": "^16.0.1", + "@types/node": "^26.6.6", + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "^4.3.3", + "autoprefixer": "^10.4.20", + "eslint": "^9.13.0", + "eslint-plugin-react-hooks": "^5.0.0", + "eslint-plugin-react-refresh": "^0.4.14", + "globals": "^15.11.0", + "jsdom": "^25.0.1", + "postcss": "^8.4.49", + "tailwindcss": "^3.4.15", + "typescript": "~5.6.2", + "typescript-eslint": "^8.11.0", + "vite": "^5.4.10", + "vitest": "^2.1.6" + } + }, + "node_modules/@adobe/css-tools": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz", + "integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@alloc/quick-lru": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.3.0.tgz", + "integrity": "sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.14.tgz", + "integrity": "sha512-qSY56jgW5JnSXzuekLVil6zaOQxOCtOHidr65KkaMBw772IuAY28Qx4ZykAcDn8+FRF15qk80XzKwgSc/RYW6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.14", + "@babel/types": "^7.29.14", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.14.tgz", + "integrity": "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.14.tgz", + "integrity": "sha512-6E3Mi1r0B0umq6vmZa4/78q+64fqO2YY0THUdjDPKUCKhNb0yQy5NQIaPHCSD3ryTgiTss//P4JsWS80AsZ6LQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.14.tgz", + "integrity": "sha512-Y5tqevQaUAZhhj82BpYMNC1ssvLQTVAfwKdm8iy8qwmhvC2/CpcAu8OC+QEtjM7pMk7knx83u1Qj8gzkicyelw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.14.tgz", + "integrity": "sha512-RAdQJrBgmIH1FWvN0X+1hoDxzMzlP4cv/1Zi4dn4tG1H0cTb+rw7CzUxQJhp1f4ANd8j5vH3fy8BAWFGkBDEsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.14", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.14", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.14", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.3", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.3.tgz", + "integrity": "sha512-R76UKbvsqI68DJJVTVyqFKqU98CN4+B+acxNfEA2IFarSzP0SjtKf/3+fFiXzTyv5Fj3PxLkGHe2wnVWWMxobQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", + "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.7.tgz", + "integrity": "sha512-F42g89Qd5oAWtp0k0nnSrjziAKza7w8SVT4mStc18LZMaRb4J1HQAHLCalEtDCxrTuksx7NU9qsmeLwpOfPqWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.3.2", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.5", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.5.tgz", + "integrity": "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz", + "integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.8.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "license": "MIT" + }, + "node_modules/@hookform/resolvers": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz", + "integrity": "sha512-79Dv+3mDF7i+2ajj7SkypSKHhl1cbln1OGavqrsF7p6mbUv11xpqpacPsGDCTRvCSjEEIez2ef1NveSVL3b0Ag==", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.0.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@radix-ui/number": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.0.tgz", + "integrity": "sha512-V3gRzhVNU1ldS5XhAPTom1fOIo4ccrjjJgmE+LI2h/WaFpHmx0MQApT+KZHnx8abG6Avtfcz4WoEciMnpFT3HQ==", + "license": "MIT" + }, + "node_modules/@radix-ui/primitive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.0.tgz", + "integrity": "sha512-4Z8dn6Upk0qk4P74xBhZ6Hd/w0mPEzOOLxy4xiPXOXqjF7jZS0VAKk7/x/H6FyY2zCkYJqePf1G5KmkmNJ4RBA==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-arrow": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.0.tgz", + "integrity": "sha512-FmlW1rCg7hBpEBwFbjHwCW6AmWLQM6g/v0Sn8XbP9NvmSZ2San1FpQeyPtufzOMSIx7Y4dzjlHoifhp+7NkZhw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-checkbox": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.1.2.tgz", + "integrity": "sha512-/i0fl686zaJbDQLNKrkCbMyDm6FQMt4jg323k7HuqitoANm9sE23Ql8yOK3Wusk34HSLKDChhMux05FnP6KUkw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-presence": "1.1.1", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-use-previous": "1.1.0", + "@radix-ui/react-use-size": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collection": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.0.tgz", + "integrity": "sha512-GZsZslMJEyo1VKm5L1ZJY8tGDxZNPAoUeQUIbKeJfoi7Q4kmig5AsgLMYYuyYbfjd8fBmFORAIwYAkXMnXZgZw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-slot": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collection/node_modules/@radix-ui/react-context": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.0.tgz", + "integrity": "sha512-OKrckBy+sMEgYM/sMmqmErVn0kZqrHPJze+Ql3DzYsDDp0hl0L62nx/2122/Bvps1qz645jlcu2tD9lrRSdf8A==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.0.tgz", + "integrity": "sha512-b4inOtiaOnYf9KWyO3jAeeCG6FeyfY6ldiEPanbUjWd+xIk5wZeHa8yVwmrJ2vderhu/BQvzCrJI0lHd+wIiqw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-context": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.1.tgz", + "integrity": "sha512-UASk9zi+crv9WteK/NU4PLvOoL3OuE6BWVKNF6hPRBtYBDXQ2u5iu3O59zUlJiTVvkyuycnqrztsHVJwcK9K+Q==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dialog": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.1.2.tgz", + "integrity": "sha512-Yj4dZtqa2o+kG61fzB0H2qUvmwBA2oyQroGLyNtBj1beo1khoQ3q1a2AO8rrQYjd8256CO9+N8L9tvsS+bnIyA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-dismissable-layer": "1.1.1", + "@radix-ui/react-focus-guards": "1.1.1", + "@radix-ui/react-focus-scope": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-portal": "1.1.2", + "@radix-ui/react-presence": "1.1.1", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-slot": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "aria-hidden": "^1.1.1", + "react-remove-scroll": "2.6.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-direction": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.0.tgz", + "integrity": "sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.1.tgz", + "integrity": "sha512-QSxg29lfr/xcev6kSz7MAlmDnzbP1eI/Dwn3Tp1ip0KT5CUELsxkekFEMVBEoykI3oV39hKT4TKZzBNMbcTZYQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-escape-keydown": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dropdown-menu": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.2.tgz", + "integrity": "sha512-GVZMR+eqK8/Kes0a36Qrv+i20bAPXSn8rCBTHx30w+3ECnR5o3xixAlqcVaYvLeyKUsm0aqyhWfmUcqufM8nYA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-menu": "2.1.2", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-guards": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.1.tgz", + "integrity": "sha512-pSIwfrT1a6sIoDASCSpFwOasEwKTZWDw/iBdtnqKO7v6FeOzYJ7U53cPzYFVR3geGGXgVHaH+CdngrrAzqUGxg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-scope": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.0.tgz", + "integrity": "sha512-200UD8zylvEyL8Bx+z76RJnASR2gRMuxlgFCPAe/Q/679a/r0eK3MBVYMb7vZODZcffZBdob1EGnky78xmVvcA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-callback-ref": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-id": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.0.tgz", + "integrity": "sha512-EJUrI8yYh7WOjNOqpoJaf1jlFIH2LvtgAl+YcFqNCa+4hj64ZXmPkAKOFs/ukjz3byN6bdb/AVUqHkI8/uWWMA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-label": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.0.tgz", + "integrity": "sha512-peLblDlFw/ngk3UWq0VnYaOLy6agTZZ+MUO/WhVfm14vJGML+xH4FAl2XQGLqdefjNb7ApRg6Yn7U42ZhmYXdw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-menu": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.2.tgz", + "integrity": "sha512-lZ0R4qR2Al6fZ4yCCZzu/ReTFrylHFxIqy7OezIpWF4bL0o9biKo0pFIvkaew3TyZ9Fy5gYVrR5zCGZBVbO1zg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-collection": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-dismissable-layer": "1.1.1", + "@radix-ui/react-focus-guards": "1.1.1", + "@radix-ui/react-focus-scope": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.0", + "@radix-ui/react-portal": "1.1.2", + "@radix-ui/react-presence": "1.1.1", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-roving-focus": "1.1.0", + "@radix-ui/react-slot": "1.1.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "aria-hidden": "^1.1.1", + "react-remove-scroll": "2.6.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popover": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.1.2.tgz", + "integrity": "sha512-u2HRUyWW+lOiA2g0Le0tMmT55FGOEWHwPFt1EPfbLly7uXQExFo5duNKqG2DzmFXIdqOeNd+TpE8baHWJCyP9w==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-dismissable-layer": "1.1.1", + "@radix-ui/react-focus-guards": "1.1.1", + "@radix-ui/react-focus-scope": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.0", + "@radix-ui/react-portal": "1.1.2", + "@radix-ui/react-presence": "1.1.1", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-slot": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "aria-hidden": "^1.1.1", + "react-remove-scroll": "2.6.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popper": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.0.tgz", + "integrity": "sha512-ZnRMshKF43aBxVWPWvbj21+7TQCvhuULWJ4gNIKYpRlQt5xGRhLx66tMp8pya2UkGHTSlhpXwmjqltDYHhw7Vg==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.0.0", + "@radix-ui/react-arrow": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0", + "@radix-ui/react-use-rect": "1.1.0", + "@radix-ui/react-use-size": "1.1.0", + "@radix-ui/rect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popper/node_modules/@radix-ui/react-context": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.0.tgz", + "integrity": "sha512-OKrckBy+sMEgYM/sMmqmErVn0kZqrHPJze+Ql3DzYsDDp0hl0L62nx/2122/Bvps1qz645jlcu2tD9lrRSdf8A==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-portal": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.2.tgz", + "integrity": "sha512-WeDYLGPxJb/5EGBoedyJbT0MpoULmwnIPMJMSldkuiMsBAv7N1cRdsTWZWht9vpPOiN3qyiGAtbK2is47/uMFg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-presence": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.1.tgz", + "integrity": "sha512-IeFXVi4YS1K0wVZzXNrbaaUvIJ3qdY+/Ih4eHFhWA9SwGR9UDX7Ck8abvL57C4cv3wwMvUE0OG69Qc3NCcTe/A==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-primitive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.0.0.tgz", + "integrity": "sha512-ZSpFm0/uHa8zTvKBDjLFWLo8dkr4MBsiDLz0g3gMUwqgLHz9rTaRRGYDgvZPtBJgYCBKXkS9fzmoySgr8CO6Cw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-roving-focus": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.0.tgz", + "integrity": "sha512-EA6AMGeq9AEeQDeSH0aZgG198qkfHSbvWTf1HvoDmOB5bBG/qTxjYMWUKMnYiV6J/iP/J8MEFSuB2zRU2n7ODA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-collection": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-roving-focus/node_modules/@radix-ui/react-context": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.0.tgz", + "integrity": "sha512-OKrckBy+sMEgYM/sMmqmErVn0kZqrHPJze+Ql3DzYsDDp0hl0L62nx/2122/Bvps1qz645jlcu2tD9lrRSdf8A==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.1.2.tgz", + "integrity": "sha512-rZJtWmorC7dFRi0owDmoijm6nSJH1tVw64QGiNIZ9PNLyBDtG+iAq+XGsya052At4BfarzY/Dhv9wrrUr6IMZA==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.0", + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-collection": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-dismissable-layer": "1.1.1", + "@radix-ui/react-focus-guards": "1.1.1", + "@radix-ui/react-focus-scope": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.0", + "@radix-ui/react-portal": "1.1.2", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-slot": "1.1.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0", + "@radix-ui/react-use-previous": "1.1.0", + "@radix-ui/react-visually-hidden": "1.1.0", + "aria-hidden": "^1.1.1", + "react-remove-scroll": "2.6.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.0.tgz", + "integrity": "sha512-3uBAs+egzvJBDZAzvb/n4NxxOYpnspmWxO2u5NbZ8Y6FM/NdrGSF9bop3Cf6F6C71z1rTSn8KV0Fo2ZVd79lGA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.1.0.tgz", + "integrity": "sha512-FUCf5XMfmW4dtYl69pdS4DbxKy8nj4M7SafBgPllysxmdachynNflAdp/gCsnYWNDnge6tI9onzMp5ARYc1KNw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.1.2.tgz", + "integrity": "sha512-9u/tQJMcC2aGq7KXpGivMm1mgq7oRJKXphDwdypPd/j21j/2znamPU8WkXgnhUaTrSFNIt8XhOyCAupg8/GbwQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-presence": "1.1.2", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-roving-focus": "1.1.1", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs/node_modules/@radix-ui/primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.1.tgz", + "integrity": "sha512-SJ31y+Q/zAyShtXJc8x83i9TYdbAfHZ++tUZnvjJJqFjzsdUnKsxPL6IEtBlxKkU7yzer//GQtZSV4GbldL3YA==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-tabs/node_modules/@radix-ui/react-collection": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.1.tgz", + "integrity": "sha512-LwT3pSho9Dljg+wY2KN2mrrh6y3qELfftINERIzBUO9e0N+t0oMTyn3k9iv+ZqgrwGkRnLpNJrsMv9BZlt2yuA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-slot": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.1.tgz", + "integrity": "sha512-Y9VzoRDSJtgFMUCoiZBDVo084VQ5hfpXxVE+NgkdNsjiDBByiImMZKKhxMwCbdHvhlENG6a833CbFkOQvTricw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs/node_modules/@radix-ui/react-presence": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.2.tgz", + "integrity": "sha512-18TFr80t5EVgL9x1SwF/YGtfG+l0BS0PRAlCWBDoBEiDQjeKgnNZRVJp/oVBl24sr3Gbfwc/Qpj4OcWTQMsAEg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs/node_modules/@radix-ui/react-primitive": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.0.1.tgz", + "integrity": "sha512-sHCWTtxwNn3L3fH8qAfnF3WbUZycW93SM1j3NFDzXBiz8D6F5UTTy8G1+WFEaiCdvCVRJWj6N2R4Xq6HdiHmDg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs/node_modules/@radix-ui/react-roving-focus": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.1.tgz", + "integrity": "sha512-QE1RoxPGJ/Nm8Qmk0PxP8ojmoaS67i0s7hVssS7KuI2FQoc/uzVlZsqKfQvxPE6D8hICCPHJ4D88zNhT3OOmkw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.1", + "@radix-ui/react-collection": "1.1.1", + "@radix-ui/react-compose-refs": "1.1.1", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-primitive": "2.0.1", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs/node_modules/@radix-ui/react-slot": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.1.1.tgz", + "integrity": "sha512-RApLLOcINYJA+dMVbOju7MYv1Mb2EBp2nH4HdDzXTSyaR5optlm6Otrz1euW3HbdOR8UmmFK06TD+A9frYWv+g==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.1" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toast": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.2.tgz", + "integrity": "sha512-Z6pqSzmAP/bFJoqMAston4eSNa+ud44NSZTiZUmUen+IOZ5nBY8kzuU5WDBVyFXPtcW6yUalOHsxM/BP6Sv8ww==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-collection": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-dismissable-layer": "1.1.1", + "@radix-ui/react-portal": "1.1.2", + "@radix-ui/react-presence": "1.1.1", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0", + "@radix-ui/react-visually-hidden": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.1.4.tgz", + "integrity": "sha512-QpObUH/ZlpaO4YgHSaYzrLO2VuO+ZBFFgGzjMUPwtiYnAzzNNDPJeEGRrT7qNOrWm/Jr08M1vlp+vTHtnSQ0Uw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-dismissable-layer": "1.1.1", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.0", + "@radix-ui/react-portal": "1.1.2", + "@radix-ui/react-presence": "1.1.1", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-slot": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-visually-hidden": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.0.tgz", + "integrity": "sha512-CasTfvsy+frcFkbXtSJ2Zu9JHpN8TYKxkgJGWbjiZhFivxaeW7rMeZt7QELGVLaYVfFMsKHjb7Ak0nMEe+2Vfw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.1.0.tgz", + "integrity": "sha512-MtfMVJiSr2NjzS0Aa90NPTnvTSg6C/JLCV7ma0W6+OMV78vd8OyRpID+Ng9LxzsPbLeuBnWBA1Nq30AtBIDChw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-callback-ref": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-escape-keydown": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.0.tgz", + "integrity": "sha512-L7vwWlR1kTTQ3oh7g1O0CBF3YCyyTj8NmhLR+phShpyA50HCfBFKVJTpshm9PzLiKmehsrQzTYTpX9HvmC9rhw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-callback-ref": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.0.tgz", + "integrity": "sha512-+FPE0rOdziWSrH9athwI1R0HDVbWlEhd+FR+aSDk4uWGmSJ9Z54sdZVDQPZAinJhJXwfT+qnj969mCsT2gfm5w==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-previous": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.0.tgz", + "integrity": "sha512-Z/e78qg2YFnnXcW88A4JmTtm4ADckLno6F7OXotmkQfeuCVaKuYzqAATPhVzl3delXE7CxIV8shofPn3jPc5Og==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-rect": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.0.tgz", + "integrity": "sha512-0Fmkebhr6PiseyZlYAOtLS+nb7jLmpqTrJyv61Pe68MKYW6OWdRE2kI70TaYY27u7H0lajqM3hSMMLFq18Z7nQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/rect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-size": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.0.tgz", + "integrity": "sha512-XW3/vWuIXHa+2Uwcc2ABSfcCledmXhhQPlGbfcRXbiUQI5Icjcg19BGCZVKKInYbvUCut/ufbbLLPFC5cbb1hw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-visually-hidden": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.1.0.tgz", + "integrity": "sha512-N8MDZqtgCgG5S3aV60INAB475osJousYpZ4cTJ2cFbMpdHS5Y6loLTH8LPtkj2QN0x93J30HT/M3qJXM0+lyeQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/rect": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.0.tgz", + "integrity": "sha512-A9+lCBZoaMJlVKcRBz2YByCG+Cp2t6nAnMnNba+XiWxnj6r4JUFqfsgwocMBZU9LPtdxC6wB56ySYpc7LQIoJg==", + "license": "MIT" + }, + "node_modules/@remix-run/router": { + "version": "1.21.0", + "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.21.0.tgz", + "integrity": "sha512-xfSkCAchbdG5PnbrKqFWwia4Bi61nH+wm8wLEqfHDyp7Y3dZzgqS2itV8i4gAq9pC2HsTpwyBC6Ds8VHZ96JlA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.2.tgz", + "integrity": "sha512-ItKrNMkEL3hy85kLBXwB0+M6CWWVI8vr7RV+Eb7oDlQIMXLaiEhGfdaj5jAUadYn2v3nwzAhIRl/nLyjAqV9vQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.2.tgz", + "integrity": "sha512-dCkT8BMPLo6X6GCFVtuzrnr981PpJSeK4ZO/d/mZdJ/ao61Qa1Usd/OHIQ69MQgw4qQclR/X6uRRUONiWwD8cw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.2.tgz", + "integrity": "sha512-p2jkKiscqQOGmyL6qu+KvJctvBc3SQTd+Xi2lQYn5QvFLEWz+QI8Z9iI+xcIjez6vKRsSnWP56Y3Ep7g3Stiug==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.2.tgz", + "integrity": "sha512-aVIfOteo5zoX8aL742H/S3QsyN6aokNYjdzrLnQBKxgRVoh4cibTErpi61RzSmrv2hBzDB1i751hwwdc8QK0vQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.2.tgz", + "integrity": "sha512-+Wuf4TFTHiE/WnjKgH1SkNf/9D5ddoed1UR0p3jxjNAGemdeeQRL+r1bJ1LlZyha0VKDBYLB2U/a9a9KlSw4Kw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.2.tgz", + "integrity": "sha512-feKK2dc13j/6D9mAp7XKhBM/VUqn0N/xRgP6rT7/mdRVVJUaeZ4lsJ9hN90aTi0k3OD+mkjlcN01vQ96Ac9VzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.2.tgz", + "integrity": "sha512-s1oGXPGX1PNqdi9TLWD+RwtPEYf/BOTbCcq4anJBqNbzyjucti86ldYH37eKvsyTP7Bl5/Hf8XmbIxCz/iafTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.2.tgz", + "integrity": "sha512-ksR3ZmzHrm6HOUP8UlDBy5hNTcG9cEIa3EyGnxn5BjorLRjBh4ucxhwjwwVEm0dqcIN4Egc/XjDUiPQwN1ic9A==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.2.tgz", + "integrity": "sha512-STZVVBM35wULVsQah0xKfCBQMPpHliOfjnRaUNT35jrbpfapUrD8ix6Yhl7tLHW0xQSWotXSSghjUi/DclwRSw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.2.tgz", + "integrity": "sha512-Fm/GPC2R0zlJYQIp9aY9L1lO2z+P+UrcvXG6fhubfo/BbMOLZlLXshnbECOTqr3pxfZFb6nNn0QgDETDtrX7TQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.2.tgz", + "integrity": "sha512-VoqlckWcwNF3WqsUkLZg91zYFgBvrC37Lc5e8AU+BKdCUFDMPoN0Rsin/LvF+rBVF527gWo5KT0oHkaAZaL1GA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.2.tgz", + "integrity": "sha512-Zr8X/SUf7Jjwxt99BqPDF/Wq+sz4oUBIP6HBaFQWwb8wO1nV6LBIpD6jB9cMybLho93Z+B8rrN0uXEL6oNOUJQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.2.tgz", + "integrity": "sha512-2EhrYEJNXIyhSZESwm/kCke1tiH7QAPOU3v3MsLM9J+Nfn2QCDe/pGROUAvYFK0BL2MEbzNgfrqrbnE5CFXkLw==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.2.tgz", + "integrity": "sha512-IC0dYuEQknw0m2FYBNBKlbrgBJBH5OMRiaRfCc4CFSpYnmDnqTpNSv+TgX+loezGTdRjBNZuYZi3t+Oc5NxNYg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.2.tgz", + "integrity": "sha512-Zlzm6fGuDvtAqMEl071/g17vxq6u2Y2v/rON/gDY4NvzWLJ41BGAlwhF3QuAzwq05zIPo4LYzdqwhx3oisYCUw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.2.tgz", + "integrity": "sha512-KhEpYRtHZ3Kj4shavjXeH+K1bQlA6UbP6MJ45rMPF/11JlZb1SRNLeuWCdigUEoMMaFO4+LwwcS+ew1SoLJu/g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.2.tgz", + "integrity": "sha512-LPn9qvPsM/Ofd6Ekq3im6nB8Tk1ruJhTd3x/2bJkTR8m/XTsfxA+EU0RJ23WJqgJg123kitHAqbEK7B4cL1uPg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.2.tgz", + "integrity": "sha512-Q1+E+pzSP+FiXuIZtxKR+pK7l2KQ9gsM+VaFPv1LR277kp7l61crG46WGLKLLay3Js5cvyU9Keqdzxa1EcFO+g==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.2.tgz", + "integrity": "sha512-3Btp4Lca/WzsmbaKu9Lh9d/XwyRDIegd/5khRBusHGw/Ll6SoF5Shn63OrjPdkLcpNi2PGDApXzNmxriRxGYjA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.2.tgz", + "integrity": "sha512-5SKVaUiVs18+DGBnpg0mORGxgq/0udczngGxV/vf2nvK1djqpOKIxY/+8rBWxAbWGRE4RnnwxWabDwJN3pCwIQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.2.tgz", + "integrity": "sha512-KBpm48/lESsHgWd+dRlcy18APBYhXU4Jb6VlJoqbpWNwfpztFXwP22qVv9aHd3k1quSrmLeJwYLc7rpQ+BFZrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.2.tgz", + "integrity": "sha512-o0D0bfRW8QGA1Ph6OzqVHMq5LRu1xkr1iM7qQIXUSFuR60ddXeDhN9UR4bUBPLYsrT46sZwwgQa51TWtBV3r5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.2.tgz", + "integrity": "sha512-r17kcu5kmd6WQwokYmfBnfwM/icureCWCPjpJVALcrSv5Lfy6Ggk9azxXor6hILhCHbc/4IfEiv+L5RXaOHinA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.2.tgz", + "integrity": "sha512-yUtOqq7ZrQoZ3WiHSR6QGTdOl4YgMHqXIYSBYU6siIcC0YF0pEwx7aGsPTm2mRwrmW6SMJkxzEdFm6wqXpmbNw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.2.tgz", + "integrity": "sha512-5IYoWxQGo5WECbJbImIf2w33uCHJNLv4o/FQtSyeYDed7AC6zx84NsEcGYccoI2geDEYkrxUXcsYK/6EhwVSIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.2.tgz", + "integrity": "sha512-ee+c14ggUiM7lg4PtCjSBYU9O9dHp4FFespRnd5yj7SilUBJCL3x3aHlB+sIqbGjcPo3pEyODASnfKJuZ26YBw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tanstack/query-core": { + "version": "5.62.3", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.62.3.tgz", + "integrity": "sha512-Jp/nYoz8cnO7kqhOlSv8ke/0MJRJVGuZ0P/JO9KQ+f45mpN90hrerzavyTKeSoT/pOzeoOUkv1Xd0wPsxAWXfg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.62.3", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.62.3.tgz", + "integrity": "sha512-y2zDNKuhgiuMgsKkqd4AcsLIBiCfEO8U11AdrtAUihmLbRNztPrlcZqx2lH1GacZsx+y1qRRbCcJLYTtF1vKsw==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.62.3" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^18 || ^19" + } + }, + "node_modules/@tanstack/react-table": { + "version": "8.20.5", + "resolved": "https://registry.npmjs.org/@tanstack/react-table/-/react-table-8.20.5.tgz", + "integrity": "sha512-WEHopKw3znbUZ61s9i0+i9g8drmDo6asTWbrQh8Us63DAk/M0FkmIqERew6P71HI75ksZ2Pxyuf4vvKh9rAkiA==", + "license": "MIT", + "dependencies": { + "@tanstack/table-core": "8.20.5" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, + "node_modules/@tanstack/table-core": { + "version": "8.20.5", + "resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.20.5.tgz", + "integrity": "sha512-P9dF7XbibHph2PFRz8gfBKEXEY/HJPOhym8CHmjF8y3q5mWpKx9xtZapXQUWCgkqvsK0R46Azuz+VaxD4Xl+Tg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@testing-library/dom": { + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/jest-dom": { + "version": "6.6.3", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.6.3.tgz", + "integrity": "sha512-IteBhl4XqYNkM54f4ejhLRJiZNqcSCoXUOG2CPK7qbD322KjQozM4kHQOfkG2oln9b9HTYqs+Sae8vBATubxxA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@adobe/css-tools": "^4.4.0", + "aria-query": "^5.0.0", + "chalk": "^3.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.6.3", + "lodash": "^4.17.21", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=14", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/@testing-library/jest-dom/node_modules/chalk": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", + "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz", + "integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/react": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.0.1.tgz", + "integrity": "sha512-dSmwJVtJXmku+iocRhWOUFbrERC76TX2Mnf0ATODz8brzAZrMBbzLwQixlBSanZxR6LddK3eiwpSFZgDET1URg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0", + "@types/react-dom": "^18.0.0", + "react": "^18.0.0", + "react-dom": "^18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/d3-array": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz", + "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==", + "license": "MIT" + }, + "node_modules/@types/d3-color": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", + "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", + "license": "MIT" + }, + "node_modules/@types/d3-ease": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", + "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==", + "license": "MIT" + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", + "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@types/d3-path": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz", + "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==", + "license": "MIT" + }, + "node_modules/@types/d3-scale": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz", + "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@types/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/d3-time": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", + "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", + "license": "MIT" + }, + "node_modules/@types/d3-timer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", + "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "18.3.31", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz", + "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "18.3.7", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz", + "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", + "devOptional": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^18.0.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.2.tgz", + "integrity": "sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/type-utils": "8.72.2", + "@typescript-eslint/utils": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.72.2", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.14", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz", + "integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.2.tgz", + "integrity": "sha512-llP+T1YuJOLlxEciP6OyQGtz5SMxyn+9LA2BvZw5RmToGVa1y4beEDVQL6Gje7T5WFYh19WREjDCN9Ev4gm5AA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.2.tgz", + "integrity": "sha512-6y5dLTZdHhI8Eh3yIQ/bfQhRKwn5e+TpJj64o18Cngc0iW/BCrVvrr6zGYqXPnYH31u6YXAYiFh0+qxX5mybJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.72.2", + "@typescript-eslint/types": "^8.72.2", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.2.tgz", + "integrity": "sha512-iIoMJ6/8c1/QpFNyFjU0d1YzPco4MsZjQw0k3V+vfzNWAFmUmvhlyMoYEoYYDQZXc+J6Gi1X5XcxlzW2taIIGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.2.tgz", + "integrity": "sha512-+h3iCgZXuTNtoLXcnnjP12ZUHLMqoUcIHPfQrFEXTUqvb9dF8QK9b5nv5VtSo5fLkdHuks8ehbTzZj3rImAm9w==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.2.tgz", + "integrity": "sha512-STfkR38qIdhfkLpgtXnUjAzsNy4xouqiBO0lrVc/Wpk9Kem5/aHXUx1J8dGC16zpdYN1+yc2ILQ28er1kXX7ag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/utils": "8.72.2", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.2.tgz", + "integrity": "sha512-Xfn37OLZx03+PCU7qWx9DTv2FCRh1E6fk2+wONeNY15HXIwtcwuveaSwVpGAUptkNmPQegRxW5JyRel9T7wrog==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.2.tgz", + "integrity": "sha512-pQEGqIK/cqEvKivVWaFLYpe7XYejFxfuAOi4mu1oAWFvIo36aRHI9esRFTUxcIy/z8N482RJyH+LpZB0ZIU7Ow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.72.2", + "@typescript-eslint/tsconfig-utils": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.2.tgz", + "integrity": "sha512-hv3eRYbpPbbpezuax1EfGrzpa3C4ySgNZkPUkLOWOAjU8HsOKowEDAr8C7nsNl1C+SBSKDpvno6VKHnlhvp9iA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.2.tgz", + "integrity": "sha512-NAGrjn0Pitjqzq/GkgMC4kBYm233PQ8GffyQ9+kTA3AlNQYEzOf25EIM02BAHZv5FRJSpHpJk+OGUxVkOB93GQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.72.2", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/@vitest/expect": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.6.tgz", + "integrity": "sha512-9M1UR9CAmrhJOMoSwVnPh2rELPKhYo0m/CSgqw9PyStpxtkwhmdM6XYlXGKeYyERY1N6EIuzkQ7e3Lm1WKCoUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "2.1.6", + "@vitest/utils": "2.1.6", + "chai": "^5.1.2", + "tinyrainbow": "^1.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-2.1.6.tgz", + "integrity": "sha512-MHZp2Z+Q/A3am5oD4WSH04f9B0T7UvwEb+v5W0kCYMhtXGYbdyl2NUk1wdSMqGthmhpiThPDp/hEoVwu16+u1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "2.1.6", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.12" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz", + "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^1.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.6.tgz", + "integrity": "sha512-SjkRGSFyrA82m5nz7To4CkRSEVWn/rwQISHoia/DB8c6IHIhaE/UNAo+7UfeaeJRE979XceGl00LNkIz09RFsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "2.1.6", + "pathe": "^1.1.2" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.6.tgz", + "integrity": "sha512-5JTWHw8iS9l3v4/VSuthCndw1lN/hpPB+mlgn1BUhFbobeIUj1J1V/Bj2t2ovGEmkXLTckFjQddsxS5T6LuVWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "2.1.6", + "magic-string": "^0.30.12", + "pathe": "^1.1.2" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot/node_modules/@vitest/pretty-format": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.6.tgz", + "integrity": "sha512-exZyLcEnHgDMKc54TtHca4McV4sKT+NKAe9ix/yhd/qkYb/TP8HTyXRFDijV19qKqTZM0hPL4753zU/U8L/gAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^1.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.6.tgz", + "integrity": "sha512-oTFObV8bd4SDdRka5O+mSh5w9irgx5IetrD5i+OsUUsk/shsBoHifwCzy45SAORzAhtNiprUVaK3hSCCzZh1jQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^3.0.2" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.6.tgz", + "integrity": "sha512-ixNkFy3k4vokOUTU2blIUvOgKq/N2PW8vKIjZZYsGJCMX69MRa9J2sKqX5hY/k5O5Gty3YJChepkqZ3KM9LyIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "2.1.6", + "loupe": "^3.1.2", + "tinyrainbow": "^1.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils/node_modules/@vitest/pretty-format": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.6.tgz", + "integrity": "sha512-exZyLcEnHgDMKc54TtHca4McV4sKT+NKAe9ix/yhd/qkYb/TP8HTyXRFDijV19qKqTZM0hPL4753zU/U8L/gAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^1.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/adler-32": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz", + "integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/anymatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/arg": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", + "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", + "dev": true, + "license": "MIT" + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/aria-hidden": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz", + "integrity": "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/autoprefixer": { + "version": "10.4.20", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.20.tgz", + "integrity": "sha512-XY25y5xSv/wEoqzDyXXME4AFfkZI0P23z6Fs3YgymDnKJkCGOnkL0iTxCa85UTqaSgfcqyf3UA6+c7wUvx/16g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.3", + "caniuse-lite": "^1.0.30001646", + "fraction.js": "^4.3.7", + "normalize-range": "^0.1.2", + "picocolors": "^1.0.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.36", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.36.tgz", + "integrity": "sha512-AbPFGS4K9S3meMRCLTM0Zas+e9X7b5ygUBOboDT5zevCZt9ByKSbMtKhwyVqW+oL8WemPVsbP7X3rdZcIyOa0w==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.22", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.22.tgz", + "integrity": "sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase-css": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", + "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001826", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz", + "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/cfb": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz", + "integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "crc-32": "~1.2.0" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chokidar/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/class-variance-authority": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", + "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", + "license": "Apache-2.0", + "dependencies": { + "clsx": "^2.1.1" + }, + "funding": { + "url": "https://polar.sh/cva" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/codepage": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz", + "integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/crc-32": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", + "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", + "license": "Apache-2.0", + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/cssstyle/node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/d3-array": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.5.tgz", + "integrity": "sha512-Th8qGXoBalmWsstpkuhmBuTsBQIFqYOJtjlBvNVvBfJ8E3uYusBUwUR8HU20U0qKKQkgCvKyR1YjiozWadk5QA==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.1.tgz", + "integrity": "sha512-lfab8x0Bj0UO7SNsY8dZSbNIA6ipbkE3X0NG9nqjCu6CfCHZseuDnOSJY7hidKrjpP++i1M2qT+FlAdPKYRilA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-ease": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.2.tgz", + "integrity": "sha512-B5znKqRmKROAN4oHWQ50W/qisVjA9GXh2WMsVKdFVp4DxWmcrOsweqgUOUVsv5th96kwaZlokU6SlV4J3gak1w==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.3.tgz", + "integrity": "sha512-+F+/49swqmGuQJmSKnVMIDH/QkEFV5li9QRj0xm/KhyAUBv099O5PrvpQFxBp24PYph17Mnvt9mjKQV0ii0nMA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.2.tgz", + "integrity": "sha512-IRzGU62DtxhvsnSTWMQIdnoZ6gA+BCWwBon1EJI6SjoN595799b6z/QRBzXfFhE8iupUPp3042yBNo0STPqnzQ==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-path": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.1.tgz", + "integrity": "sha512-jsbgV8zIT38ReB9O7X7gcLndTQRONSqNNd+oGIaTBdUug4r5jFmp0N6RY9R5GWbdUDucn0qoTGyfjapT4tDhcg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.3.tgz", + "integrity": "sha512-66cWobCNzcMvlfoaDHCxuIv9TBUWG1BLOWdv9kHHFuCr1JdqAWPvTmsaEYDD5NRMyWZ5+7u0GqiCDfMXMqh3hg==", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-shape": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.1.tgz", + "integrity": "sha512-dm2o+lbKdzg9tY7GEag/dB9hcbodLfwkE/DkvqbELJXaMz0yKzWWhZqhbI7CKubukA7HnRyz0avdtvi7EPxPvw==", + "license": "ISC", + "dependencies": { + "d3-path": "^3.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.1.tgz", + "integrity": "sha512-Ze7rjrhMzdeulh0/hjcfFj7XLAHOfowtEMfsoG6DU866HPynQNW7Wfen6hzXcqKTv8XzxvF6Hzr5XD6bMHr2ug==", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.1.tgz", + "integrity": "sha512-22XaqjyCjpqgda20erhsOjGmC3vvYwTNYniKAd45W5UWLDF43moeOuV9qYpRqobIlsnK0UhnKZjUUJm3VgORUA==", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-timer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.2.tgz", + "integrity": "sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/date-fns": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", + "integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/date-fns-tz": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/date-fns-tz/-/date-fns-tz-3.2.0.tgz", + "integrity": "sha512-sg8HqoTEulcbbbVXeg84u5UnlsQa8GS5QXMqjjYIhS4abEVVKIUwe0/l/UhrZdKaL/W5eWZNlbTeEIiOXTcsBQ==", + "license": "MIT", + "peerDependencies": { + "date-fns": "^3.0.0 || ^4.0.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/decimal.js-light": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", + "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==", + "license": "MIT" + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/detect-node-es": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz", + "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", + "license": "MIT" + }, + "node_modules/didyoumean": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", + "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/dlv": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", + "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/dom-helpers": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz", + "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.8.7", + "csstype": "^3.0.2" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.482", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.482.tgz", + "integrity": "sha512-CAj2EpyffocZkpJA1yUDSA/wgoo+JkSFkx5ywA00X5biWrmBGecoFyKlyZw2Tlt0mZFFfHqP9S4PMLwtXXeHXg==", + "dev": true, + "license": "ISC" + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.5", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.5.tgz", + "integrity": "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==", + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.6", + "@eslint/js": "9.39.5", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-5.2.0.tgz", + "integrity": "sha512-+f15FfK64YQwZdJNELETdn5ibXEUQmW1DZL6KXhNnc2heoy/sg9VJJeT7n8TlMWouzWqSWavFkIhHyIbIAEapg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" + } + }, + "node_modules/eslint-plugin-react-refresh": { + "version": "0.4.26", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.4.26.tgz", + "integrity": "sha512-1RETEylht2O6FM/MvgnyvT+8K21wLqDNg4qD51Zj3guhjt433XbnnkVttHMyaVyAFD03QSV4LPS5iE3VQmO7XQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "eslint": ">=8.40" + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "license": "MIT" + }, + "node_modules/exit-on-epipe": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/exit-on-epipe/-/exit-on-epipe-1.0.1.tgz", + "integrity": "sha512-h2z5mrROTxce56S+pnvAV890uu7ls7f1kEvVGJbw1OlFH3/mlJ5bkXu0KRyW94v37zzHPiUd55iLn3DA7TjWpw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-equals": { + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.4.5.tgz", + "integrity": "sha512-yKEpcFuRPu/pTQL2VB8YKE2yFldrLlIsoWtJeBnAdqEhvu21OgkFT0C8njf/xYc2LSZGEr3K9JGjthHJxnVLvQ==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fflate": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.3.11.tgz", + "integrity": "sha512-Rr5QlUeGN1mbOHlaqcSYMKVpPbgLy0AWT/W0EHxA6NGI12yO1jpoui2zBBvU2G824ltM6Ut8BFgfHSBGfkmS0A==", + "license": "MIT" + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", + "dev": true, + "license": "ISC" + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/frac": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz", + "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/fraction.js": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", + "integrity": "sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-nonce": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", + "integrity": "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "15.15.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-15.15.0.tgz", + "integrity": "sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.18.0.tgz", + "integrity": "sha512-qyax9fgaKOEC4qK8WZn7Q4IcoZC9RC1O1fFxRcRTq/oMMkWT/uXpqpXa12kzWR409zAt1drYN9N9BO26UmBCmw==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/jiti": { + "version": "1.21.7", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz", + "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "bin/jiti.js" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsdom": { + "version": "25.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-25.0.1.tgz", + "integrity": "sha512-8i7LzZj7BF8uplX+ZyOlIz86V6TAsSs+np6m1kpW9u0JWi4z/1t+FzcK1aek+ybTnAC4KhBL4uXCNT0wcUIeCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.1.0", + "data-urls": "^5.0.0", + "decimal.js": "^10.4.3", + "form-data": "^4.0.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.5", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.12", + "parse5": "^7.1.2", + "rrweb-cssom": "^0.7.1", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.0.0", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^2.11.2" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lilconfig": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz", + "integrity": "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/lucide-react": { + "version": "0.460.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.460.0.tgz", + "integrity": "sha512-BVtq/DykVeIvRTJvRAgCsOwaGL8Un3Bxh8MbDxMhEWlZay3T4IpEKDEpwt5KZ0KJMHzgm6jrltxlT5eXOWXDHg==", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc" + } + }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "peer": true, + "bin": { + "lz-string": "bin/bin.js" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.63", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.63.tgz", + "integrity": "sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/normalize-range": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", + "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nwsapi": { + "version": "2.2.28", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz", + "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/postcss": { + "version": "8.4.49", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.49.tgz", + "integrity": "sha512-OCVPnIObs4N29kxTjzLfUryOkvZEq+pf8jTF0lg8E7uETuWHA+v7j3c/xJmiqpX450191LlmZfUKkXxkTry7nA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-import": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", + "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-js": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz", + "integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "camelcase-css": "^2.0.1" + }, + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "peerDependencies": { + "postcss": "^8.4.21" + } + }, + "node_modules/postcss-load-config": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-4.0.2.tgz", + "integrity": "sha512-bSVhyJGL00wMVoPUzAVAnbEoWyqRxkjv64tUl427SKnPrENtq6hJwUojroMz2VB+Q1edmi4IfrAPpami5VVgMQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.0.0", + "yaml": "^2.3.4" + }, + "engines": { + "node": ">= 14" + }, + "peerDependencies": { + "postcss": ">=8.0.9", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "postcss": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/postcss-load-config/node_modules/lilconfig": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.5.tgz", + "integrity": "sha512-aRAOI9Ia43ygL4o1EOmC/sc/0OFxrm7qcQngiIyWaqVnSnz932ybJ07zyCcgMNGSDP8Yxaf88Xj1zHEXmvQ4SA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", + "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.6", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.6.tgz", + "integrity": "sha512-BK87/Qgti3DIcgS2PaCVoteFIkjIFvCJBizZDIVSjdlFNg4Jv+SRqbN2JONb/qQUH4ZFqfXYF+izg15W2HVRvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/printj": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/printj/-/printj-1.1.2.tgz", + "integrity": "sha512-zA2SmoLaxZyArQTOPj5LXecR+RagfPSU5Kw1qP+jkWeNlrq+eJZyY2oS68SU1Z/7/myXM4lo9716laOFAVStCQ==", + "license": "Apache-2.0", + "bin": { + "printj": "bin/printj.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/prop-types/node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-hook-form": { + "version": "7.54.0", + "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.54.0.tgz", + "integrity": "sha512-PS05+UQy/IdSbJNojBypxAo9wllhHgGmyr8/dyGQcPoiMf3e7Dfb9PWYVRco55bLbxH9S+1yDDJeTdlYCSxO3A==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/react-hook-form" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17 || ^18 || ^19" + } + }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-remove-scroll": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.6.0.tgz", + "integrity": "sha512-I2U4JVEsQenxDAKaVa3VZ/JeJZe0/2DxPWL8Tj8yLKctQJQiZM52pn/GWFpSp8dftjM3pSAHVJZscAnC/y+ySQ==", + "license": "MIT", + "dependencies": { + "react-remove-scroll-bar": "^2.3.6", + "react-style-singleton": "^2.2.1", + "tslib": "^2.1.0", + "use-callback-ref": "^1.3.0", + "use-sidecar": "^1.1.2" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-remove-scroll-bar": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.8.tgz", + "integrity": "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==", + "license": "MIT", + "dependencies": { + "react-style-singleton": "^2.2.2", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-router": { + "version": "6.28.0", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.28.0.tgz", + "integrity": "sha512-HrYdIFqdrnhDw0PqG/AKjAqEqM7AvxCz0DQ4h2W8k6nqmc5uRBYDag0SBxx9iYz5G8gnuNVLzUe13wl9eAsXXg==", + "license": "MIT", + "dependencies": { + "@remix-run/router": "1.21.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8" + } + }, + "node_modules/react-router-dom": { + "version": "6.28.0", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.28.0.tgz", + "integrity": "sha512-kQ7Unsl5YdyOltsPGl31zOjLrDv+m2VcIEcIHqYYD3Lp0UppLjrzcfJqDJwXxFw3TH/yvapbnUvPlAj7Kx5nbg==", + "license": "MIT", + "dependencies": { + "@remix-run/router": "1.21.0", + "react-router": "6.28.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, + "node_modules/react-smooth": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz", + "integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==", + "license": "MIT", + "dependencies": { + "fast-equals": "^5.0.1", + "prop-types": "^15.8.1", + "react-transition-group": "^4.4.5" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/react-style-singleton": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz", + "integrity": "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==", + "license": "MIT", + "dependencies": { + "get-nonce": "^1.0.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-transition-group": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", + "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==", + "license": "BSD-3-Clause", + "dependencies": { + "@babel/runtime": "^7.5.5", + "dom-helpers": "^5.0.1", + "loose-envify": "^1.4.0", + "prop-types": "^15.6.2" + }, + "peerDependencies": { + "react": ">=16.6.0", + "react-dom": ">=16.6.0" + } + }, + "node_modules/read-cache": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.2.tgz", + "integrity": "sha512-/peqiBB/n07gQGLsWaHho3WfvUyRscw0gYTsEFMhrIe/nWLkYaf5SbKYjGYqtRV3aPwykJgF2VEMo1ac4bnsGA==", + "dev": true, + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/readdirp/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/recharts": { + "version": "2.13.3", + "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.13.3.tgz", + "integrity": "sha512-YDZ9dOfK9t3ycwxgKbrnDlRC4BHdjlY73fet3a0C1+qGMjXVZe6+VXmpOIIhzkje5MMEL8AN4hLIe4AMskBzlA==", + "deprecated": "1.x and 2.x branches are no longer active. Bump to Recharts v3 to receive latest features and bugfixes. See https://github.com/recharts/recharts/wiki/3.0-migration-guide", + "license": "MIT", + "dependencies": { + "clsx": "^2.0.0", + "eventemitter3": "^4.0.1", + "lodash": "^4.17.21", + "react-is": "^18.3.1", + "react-smooth": "^4.0.0", + "recharts-scale": "^0.4.4", + "tiny-invariant": "^1.3.1", + "victory-vendor": "^36.6.8" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "react": "^16.0.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/recharts-scale": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.5.tgz", + "integrity": "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==", + "license": "MIT", + "dependencies": { + "decimal.js-light": "^2.4.1" + } + }, + "node_modules/recharts/node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "license": "MIT" + }, + "node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve": { + "version": "1.22.14", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.14.tgz", + "integrity": "sha512-1ZjYvR9sbkiwC5+9QHetqW5HmA2pHRMaoupD01t2HlYnV/vydC2zPwLixhsMieSWVZt0JJRg5LVIk0Ow1D/TrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.18.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.68.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.2.tgz", + "integrity": "sha512-xzt45rKOxzEuqjTdkGTIEaePcq9xRELlFI1uoazlKap8T6bENJkONSCfhK51P6XFTixa4rosPcDHihSdduXndQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.2", + "@rollup/rollup-android-arm64": "4.68.2", + "@rollup/rollup-android-x64": "4.68.2", + "@rollup/rollup-darwin-arm64": "4.68.2", + "@rollup/rollup-darwin-x64": "4.68.2", + "@rollup/rollup-freebsd-arm64": "4.68.2", + "@rollup/rollup-freebsd-x64": "4.68.2", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.2", + "@rollup/rollup-linux-arm-musleabihf": "4.68.2", + "@rollup/rollup-linux-arm64-gnu": "4.68.2", + "@rollup/rollup-linux-arm64-musl": "4.68.2", + "@rollup/rollup-linux-loong64-gnu": "4.68.2", + "@rollup/rollup-linux-loong64-musl": "4.68.2", + "@rollup/rollup-linux-ppc64-gnu": "4.68.2", + "@rollup/rollup-linux-ppc64-musl": "4.68.2", + "@rollup/rollup-linux-riscv64-gnu": "4.68.2", + "@rollup/rollup-linux-riscv64-musl": "4.68.2", + "@rollup/rollup-linux-s390x-gnu": "4.68.2", + "@rollup/rollup-linux-x64-gnu": "4.68.2", + "@rollup/rollup-linux-x64-musl": "4.68.2", + "@rollup/rollup-openbsd-x64": "4.68.2", + "@rollup/rollup-openharmony-arm64": "4.68.2", + "@rollup/rollup-win32-arm64-msvc": "4.68.2", + "@rollup/rollup-win32-ia32-msvc": "4.68.2", + "@rollup/rollup-win32-x64-gnu": "4.68.2", + "@rollup/rollup-win32-x64-msvc": "4.68.2", + "fsevents": "~2.3.2" + } + }, + "node_modules/rrweb-cssom": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.7.1.tgz", + "integrity": "sha512-TrEMa7JGdVm0UThDJSx7ddw5nVm3UJS9o9CCIZ72B1vSyEZoziDqBYP3XIoi/12lKrJR8rE3jeFHMok2F/Mnsg==", + "dev": true, + "license": "MIT" + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ssf": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz", + "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", + "license": "Apache-2.0", + "dependencies": { + "frac": "~1.1.2" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tailwind-merge": { + "version": "2.5.4", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.5.4.tgz", + "integrity": "sha512-0q8cfZHMu9nuYP/b5Shb7Y7Sh1B7Nnl5GqNr1U+n2p6+mybvRtayrQ+0042Z5byvTA8ihjlP8Odo8/VnHbZu4Q==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, + "node_modules/tailwindcss": { + "version": "3.4.15", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.15.tgz", + "integrity": "sha512-r4MeXnfBmSOuKUWmXe6h2CcyfzJCEk4F0pptO5jlnYSIViUkVmsawj80N5h2lO3gwcmSb4n3PuN+e+GC1Guylw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "arg": "^5.0.2", + "chokidar": "^3.6.0", + "didyoumean": "^1.2.2", + "dlv": "^1.1.3", + "fast-glob": "^3.3.2", + "glob-parent": "^6.0.2", + "is-glob": "^4.0.3", + "jiti": "^1.21.6", + "lilconfig": "^2.1.0", + "micromatch": "^4.0.8", + "normalize-path": "^3.0.0", + "object-hash": "^3.0.0", + "picocolors": "^1.1.1", + "postcss": "^8.4.47", + "postcss-import": "^15.1.0", + "postcss-js": "^4.0.1", + "postcss-load-config": "^4.0.2", + "postcss-nested": "^6.2.0", + "postcss-selector-parser": "^6.1.2", + "resolve": "^1.22.8", + "sucrase": "^3.35.0" + }, + "bin": { + "tailwind": "lib/cli.js", + "tailwindcss": "lib/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tiny-invariant": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", + "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==", + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz", + "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz", + "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD" + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typescript": { + "version": "5.6.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", + "integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.72.2.tgz", + "integrity": "sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.72.2", + "@typescript-eslint/parser": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/utils": "8.72.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/use-callback-ref": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz", + "integrity": "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-sidecar": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.3.tgz", + "integrity": "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==", + "license": "MIT", + "dependencies": { + "detect-node-es": "^1.1.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-sync-external-store": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.2.tgz", + "integrity": "sha512-PElTlVMwpblvbNqQ82d2n6RjStvdSoNe9FG28kNfz3WiXilJm4DdNkEzRhCZuIDwY8U08WVihhGR5iRqAwfDiw==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/victory-vendor": { + "version": "36.9.2", + "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz", + "integrity": "sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==", + "license": "MIT AND ISC", + "dependencies": { + "@types/d3-array": "^3.0.3", + "@types/d3-ease": "^3.0.0", + "@types/d3-interpolate": "^3.0.1", + "@types/d3-scale": "^4.0.2", + "@types/d3-shape": "^3.1.0", + "@types/d3-time": "^3.0.0", + "@types/d3-timer": "^3.0.0", + "d3-array": "^3.1.6", + "d3-ease": "^3.0.1", + "d3-interpolate": "^3.0.1", + "d3-scale": "^4.0.2", + "d3-shape": "^3.1.0", + "d3-time": "^3.0.0", + "d3-timer": "^3.0.1" + } + }, + "node_modules/vite": { + "version": "5.4.21", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", + "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-2.1.6.tgz", + "integrity": "sha512-DBfJY0n9JUwnyLxPSSUmEePT21j8JZp/sR9n+/gBwQU6DcQOioPdb8/pibWfXForbirSagZCilseYIwaL3f95A==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.3.7", + "es-module-lexer": "^1.5.4", + "pathe": "^1.1.2", + "vite": "^5.0.0 || ^6.0.0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-2.1.6.tgz", + "integrity": "sha512-isUCkvPL30J4c5O5hgONeFRsDmlw6kzFEdLQHLezmDdKQHy8Ke/B/dgdTMEgU0vm+iZ0TjW8GuK83DiahBoKWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "2.1.6", + "@vitest/mocker": "2.1.6", + "@vitest/pretty-format": "^2.1.6", + "@vitest/runner": "2.1.6", + "@vitest/snapshot": "2.1.6", + "@vitest/spy": "2.1.6", + "@vitest/utils": "2.1.6", + "chai": "^5.1.2", + "debug": "^4.3.7", + "expect-type": "^1.1.0", + "magic-string": "^0.30.12", + "pathe": "^1.1.2", + "std-env": "^3.8.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.1", + "tinypool": "^1.0.1", + "tinyrainbow": "^1.2.0", + "vite": "^5.0.0 || ^6.0.0", + "vite-node": "2.1.6", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "2.1.6", + "@vitest/ui": "2.1.6", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wmf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz", + "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/word": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz", + "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ws": { + "version": "8.22.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", + "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xlsx": { + "version": "0.18.5", + "resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz", + "integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "cfb": "~1.2.1", + "codepage": "~1.15.0", + "crc-32": "~1.2.1", + "ssf": "~0.11.2", + "wmf": "~1.0.1", + "word": "~0.3.0" + }, + "bin": { + "xlsx": "bin/xlsx.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/xlsx-js-style": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/xlsx-js-style/-/xlsx-js-style-1.2.0.tgz", + "integrity": "sha512-DDT4FXFSWfT4DXMSok/m3TvmP1gvO3dn0Eu/c+eXHW5Kzmp7IczNkxg/iEPnImbG9X0Vb8QhROda5eatSR/97Q==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.2.0", + "cfb": "^1.1.4", + "codepage": "~1.14.0", + "commander": "~2.17.1", + "crc-32": "~1.2.0", + "exit-on-epipe": "~1.0.1", + "fflate": "^0.3.8", + "ssf": "~0.11.2", + "wmf": "~1.0.1", + "word": "~0.3.0" + }, + "bin": { + "xlsx": "bin/xlsx.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/xlsx-js-style/node_modules/adler-32": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.2.0.tgz", + "integrity": "sha512-/vUqU/UY4MVeFsg+SsK6c+/05RZXIHZMGJA+PX5JyWI0ZRcBpupnRuPLU/NXXoFwMYCPCoxIfElM2eS+DUXCqQ==", + "license": "Apache-2.0", + "dependencies": { + "exit-on-epipe": "~1.0.1", + "printj": "~1.1.0" + }, + "bin": { + "adler32": "bin/adler32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/xlsx-js-style/node_modules/codepage": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.14.0.tgz", + "integrity": "sha512-iz3zJLhlrg37/gYRWgEPkaFTtzmnEv1h+r7NgZum2lFElYQPi0/5bnmuDfODHxfp0INEfnRqyfyeIJDbb7ahRw==", + "license": "Apache-2.0", + "dependencies": { + "commander": "~2.14.1", + "exit-on-epipe": "~1.0.1" + }, + "bin": { + "codepage": "bin/codepage.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/xlsx-js-style/node_modules/codepage/node_modules/commander": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.14.1.tgz", + "integrity": "sha512-+YR16o3rK53SmWHU3rEM3tPAh2rwb1yPcQX5irVn7mb0gXbwuCCrnkbV5+PBfETdfg1vui07nM6PCG1zndcjQw==", + "license": "MIT" + }, + "node_modules/xlsx-js-style/node_modules/commander": { + "version": "2.17.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz", + "integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==", + "license": "MIT" + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "3.23.8", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", + "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zustand": { + "version": "4.5.5", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.5.tgz", + "integrity": "sha512-+0PALYNJNgK6hldkgDq2vLrw5f6g/jCInz52n9RTpropGgeAf/ioFUCdtsjCqu4gNhW9D01rUQBROoRjdzyn2Q==", + "license": "MIT", + "dependencies": { + "use-sync-external-store": "1.2.2" + }, + "engines": { + "node": ">=12.7.0" + }, + "peerDependencies": { + "@types/react": ">=16.8", + "immer": ">=9.0.6", + "react": ">=16.8" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + } + } + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..a1b6e47 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,65 @@ +{ + "name": "frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview", + "test": "vitest run" + }, + "dependencies": { + "@hookform/resolvers": "^3.10.0", + "@radix-ui/react-checkbox": "^1.1.2", + "@radix-ui/react-dialog": "^1.1.2", + "@radix-ui/react-dropdown-menu": "^2.1.2", + "@radix-ui/react-label": "^2.1.0", + "@radix-ui/react-popover": "^1.1.2", + "@radix-ui/react-select": "^2.1.2", + "@radix-ui/react-separator": "^1.1.0", + "@radix-ui/react-slot": "^1.1.0", + "@radix-ui/react-tabs": "^1.1.2", + "@radix-ui/react-toast": "^1.2.2", + "@radix-ui/react-tooltip": "^1.1.4", + "@tanstack/react-query": "^5.62.3", + "@tanstack/react-table": "^8.20.5", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "date-fns": "^4.1.0", + "date-fns-tz": "^3.2.0", + "lucide-react": "^0.460.0", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-hook-form": "^7.54.0", + "react-router-dom": "^6.28.0", + "recharts": "^2.13.3", + "tailwind-merge": "^2.5.4", + "xlsx": "^0.18.5", + "xlsx-js-style": "^1.2.0", + "zod": "^3.23.8", + "zustand": "^4.5.5" + }, + "devDependencies": { + "@eslint/js": "^9.13.0", + "@testing-library/jest-dom": "^6.6.3", + "@testing-library/react": "^16.0.1", + "@types/node": "^26.6.6", + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "^4.3.3", + "autoprefixer": "^10.4.20", + "eslint": "^9.13.0", + "eslint-plugin-react-hooks": "^5.0.0", + "eslint-plugin-react-refresh": "^0.4.14", + "globals": "^15.11.0", + "jsdom": "^25.0.1", + "postcss": "^8.4.49", + "tailwindcss": "^3.4.15", + "typescript": "~5.6.2", + "typescript-eslint": "^8.11.0", + "vite": "^5.4.10", + "vitest": "^2.1.6" + } +} diff --git a/frontend/postcss.config.js b/frontend/postcss.config.js new file mode 100644 index 0000000..e008c9c --- /dev/null +++ b/frontend/postcss.config.js @@ -0,0 +1,3 @@ +export default { + plugins: { tailwindcss: {}, autoprefixer: {} }, +}; diff --git a/frontend/public/logo.jpg b/frontend/public/logo.jpg new file mode 100644 index 0000000..13d4755 Binary files /dev/null and b/frontend/public/logo.jpg differ diff --git a/frontend/public/vite.svg b/frontend/public/vite.svg new file mode 100644 index 0000000..e7b8dfb --- /dev/null +++ b/frontend/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/App.css b/frontend/src/App.css new file mode 100644 index 0000000..b9d355d --- /dev/null +++ b/frontend/src/App.css @@ -0,0 +1,42 @@ +#root { + max-width: 1280px; + margin: 0 auto; + padding: 2rem; + text-align: center; +} + +.logo { + height: 6em; + padding: 1.5em; + will-change: filter; + transition: filter 300ms; +} +.logo:hover { + filter: drop-shadow(0 0 2em #646cffaa); +} +.logo.react:hover { + filter: drop-shadow(0 0 2em #61dafbaa); +} + +@keyframes logo-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: no-preference) { + a:nth-of-type(2) .logo { + animation: logo-spin infinite 20s linear; + } +} + +.card { + padding: 2em; +} + +.read-the-docs { + color: #888; +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx new file mode 100644 index 0000000..727fd8b --- /dev/null +++ b/frontend/src/App.tsx @@ -0,0 +1,156 @@ +import { useEffect } from "react"; +import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { AppShell } from "@/components/layout/AppShell"; +import { DataTableDemoPage } from "@/pages/DataTableDemoPage"; +import { LoginPage } from "@/pages/LoginPage"; +import { AccessDeniedPage } from "@/pages/AccessDeniedPage"; +import { MastersPage } from "@/pages/MastersPage"; +import { SettingsPage } from "@/pages/SettingsPage"; +import { AssetsPage } from "@/pages/AssetsPage"; +import { AssetDetailPage } from "@/pages/AssetDetailPage"; +import { ComplaintsPage } from "@/pages/ComplaintsPage"; +import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage"; +import { PMPage } from "@/pages/PMPage"; +import { CalibrationPage } from "@/pages/CalibrationPage"; +import { ContractsPage } from "@/pages/ContractsPage"; +import { InsurancePage } from "@/pages/InsurancePage"; +import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage"; +import { VisitsPage } from "@/pages/VisitsPage"; +import { DashboardPage } from "@/pages/DashboardPage"; +import { NotificationsPage } from "@/pages/NotificationsPage"; +import { ReportsPage } from "@/pages/ReportsPage"; +import { AIReportPage } from "@/pages/AIReportPage"; +import { ReportDetailPage } from "@/pages/ReportDetailPage"; +import { AuditLogsPage } from "@/pages/AuditLogsPage"; +import { ToastProvider } from "@/components/ToastProvider"; +import { useAuthStore } from "@/hooks/useAuth"; +import { can, type Capability } from "@/lib/permissions"; + +const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: 1, staleTime: 30_000 } }, +}); + +function ProtectedRoute({ children }: { children: React.ReactNode }) { + const { user, token, hydrating } = useAuthStore(); + + if (hydrating) { + return ( +
+
+
+

Loading Poona Hospital AMS...

+
+
+ ); + } + + if (!token || !user) { + return ; + } + + return <>{children}; +} + +function RoleGuard({ + capability, + children, +}: { + capability: Capability; + children: React.ReactNode; +}) { + const user = useAuthStore((s) => s.user); + if (!can(user?.role, capability)) { + return ; + } + return <>{children}; +} + +function AppRoutes() { + const hydrate = useAuthStore((s) => s.hydrate); + + useEffect(() => { + hydrate(); + }, [hydrate]); + + return ( + + } /> + + + + } + > + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + + + } + /> + } /> + + + + } + /> + } /> + } /> + + + + } + /> + + + + } + /> + + + + } + /> + } /> + + } /> + + ); +} + +export default function App() { + return ( + + + + + + + + ); +} diff --git a/frontend/src/api/ai.ts b/frontend/src/api/ai.ts new file mode 100644 index 0000000..39d440d --- /dev/null +++ b/frontend/src/api/ai.ts @@ -0,0 +1,340 @@ +import { api } from "./client"; + +export type AIPeriod = "3m" | "6m" | "12m" | "custom"; +export type AISectionKey = + | "summary" + | "comparison" + | "depreciation" + | "efficiency" + | "breakdown-frequency"; + +export interface AIFilterParams { + period?: AIPeriod; + date_from?: string; + date_to?: string; + department_id?: number; + category_id?: number; +} + +export interface AIStatus { + enabled: boolean; + ai_enabled_setting: boolean; + provider: string; + model: string; + reachable: boolean; +} + +export interface AIMetric { + id: string; + label: string; + value: number | string | null; + unit: string; + formatted: string; +} + +export interface AINarrativeBullet { + text: string; + metric_ids: string[]; +} + +export interface AINarrative { + source: "ai" | "rule_based"; + model: string | null; + validated: boolean; + failure_reason: string | null; + generated_at: string; + headline: string; + bullets: AINarrativeBullet[]; +} + +export interface AIHowCalculated { + formulas: string[]; + latest_equipment_rule?: string; + missing_data_rule?: string; + weights?: Record; + settings_used?: Record; +} + +export interface AISuggestion { + id: string; + rule: string; + severity: "red" | "yellow" | "info"; + title: string; + detail: string; + asset_codes: string[]; + evidence_metric_ids: string[]; + action_for_human: string; +} + +export interface AIComparisonRow { + asset_id: number; + asset_code: string; + asset_name: string; + department_name: string; + category_name: string; + installation_date: string | null; + purchase_date: string | null; + purchase_value: number | null; + in_house_cost: number | null; + in_house_reason: string | null; + outsourced_cost: number | null; + outsourced_reason: string | null; + rent_cost: number | null; + rent_reason: string | null; + lowest_scenario: string | null; + lowest_scenario_label: string | null; + lowest_cost: number | null; + savings_vs_next: number | null; + current_setup: string | null; +} + +export interface AIComparisonChartPoint { + asset_code: string; + asset_name: string; + in_house: number | null; + outsourced: number | null; + rent: number | null; +} + +export interface AIComparisonResponse { + section: "comparison"; + title: string; + period_start: string; + period_end: string; + horizon_years: number; + summary: { + latest_count: number; + horizon_years: number; + in_house_lowest_count: number; + outsourced_lowest_count: number; + rent_lowest_count: number; + }; + rows: AIComparisonRow[]; + chart_data: AIComparisonChartPoint[]; + metrics: AIMetric[]; + narrative: AINarrative; + how_calculated: AIHowCalculated; +} + +export interface AIDepreciationCurvePoint { + year: number; + book_value: number; +} + +export interface AIDepreciationRow { + asset_id: number; + asset_code: string; + asset_name: string; + department_name: string; + category_name: string; + acquisition_mode: string; + purchase_value: number | null; + depreciation_applicable: boolean; + depreciation_reason: string | null; + method: string | null; + useful_life_years: number | null; + book_value: number | null; + accumulated_depreciation: number | null; + annual_charge: number | null; + fully_depreciated: boolean; + contract_cost_to_date: number; + repair_and_spare_cost_to_date: number; + inhouse_pm_cost_to_date: number; + maintenance_cost: number; + maintenance_ratio: number | null; + lifetime_cost: number | null; + cost_per_year_of_use: number | null; + review_flag: boolean; + curve: AIDepreciationCurvePoint[]; +} + +export interface AIDepreciationResponse { + section: "depreciation"; + title: string; + period_start: string; + period_end: string; + summary: { + total_purchase_value: number; + total_book_value: number; + total_accumulated_depreciation: number; + total_maintenance_cost: number; + fully_depreciated_count: number; + review_flag_count: number; + replacement_review_ratio: number; + excluded_count: number; + }; + rows: AIDepreciationRow[]; + chart_data: AIDepreciationCurvePoint[]; + metrics: AIMetric[]; + narrative: AINarrative; + how_calculated: AIHowCalculated; +} + +export interface AIEfficiencyGroupRow { + group: string; + group_type: "department" | "category"; + assets_in_scope: number; + uptime_pct: number; + pm_compliance_pct: number; + response_score: number; + repeat_free_score: number; + mttr_hours: number | null; + mtbf_hours: number | null; + avg_response_minutes: number | null; + efficiency_score: number; + parts: { + uptime: number; + pm_compliance: number; + response: number; + repeat_free: number; + }; +} + +export interface AIEfficiencyChartPoint { + group: string; + uptime: number; + pm_compliance: number; + response: number; + repeat_free: number; + efficiency_score: number; +} + +export interface AIEfficiencyResponse { + section: "efficiency"; + title: string; + period_start: string; + period_end: string; + weights: Record; + summary: { + assets_in_scope: number; + avg_uptime_pct: number; + mttr_hours: number | null; + mtbf_hours: number | null; + avg_response_minutes: number | null; + pm_compliance_pct: number; + avg_efficiency_score: number; + }; + rows: AIEfficiencyGroupRow[]; + by_department: AIEfficiencyGroupRow[]; + by_category: AIEfficiencyGroupRow[]; + chart_data: AIEfficiencyChartPoint[]; + metrics: AIMetric[]; + narrative: AINarrative; + how_calculated: AIHowCalculated; +} + +export interface AIBreakdownAssetRow { + asset_id: number; + asset_code: string; + asset_name: string; + department_name: string; + category_name: string; + breakdown_count: number; + avg_downtime_minutes: number; + avg_downtime_hours: number; + repeat_window_count: number; + repeat_failure: boolean; +} + +export interface AIBreakdownGroupRow { + group: string; + group_type: "department" | "category"; + breakdowns: number; + assets_in_scope: number; + avg_breakdowns_per_equipment: number; + breakdowns_per_1000_hours: number; +} + +export interface AIBreakdownFrequencyResponse { + section: "breakdown_frequency"; + title: string; + period_start: string; + period_end: string; + summary: { + total_breakdowns: number; + assets_in_scope: number; + avg_breakdowns_per_equipment: number; + repeat_failure_count: number; + repeat_threshold: number; + repeat_window_days: number; + }; + rows: AIBreakdownAssetRow[]; + by_department: AIBreakdownGroupRow[]; + by_category: AIBreakdownGroupRow[]; + chart_data: { + monthly_trend: { month: string; label: string; breakdowns: number }[]; + by_department: AIBreakdownGroupRow[]; + by_category: AIBreakdownGroupRow[]; + }; + metrics: AIMetric[]; + narrative: AINarrative; + how_calculated: AIHowCalculated; +} + +export interface AISummaryResponse { + section: "summary"; + title: string; + period_start: string; + period_end: string; + sections: { + comparison: AIComparisonResponse["summary"]; + depreciation: AIDepreciationResponse["summary"]; + efficiency: AIEfficiencyResponse["summary"]; + breakdown_frequency: AIBreakdownFrequencyResponse["summary"]; + }; + suggestions: AISuggestion[]; + suggestions_evidence: AIMetric[]; + metrics: AIMetric[]; + narrative: AINarrative; + how_calculated: AIHowCalculated; +} + +function buildAIQuery(params: AIFilterParams & { format?: "xlsx" | "csv" } = {}): string { + const sp = new URLSearchParams(); + if (params.period) sp.set("period", params.period); + if (params.period === "custom") { + if (params.date_from) sp.set("date_from", params.date_from); + if (params.date_to) sp.set("date_to", params.date_to); + } + if (params.department_id != null) sp.set("department_id", String(params.department_id)); + if (params.category_id != null) sp.set("category_id", String(params.category_id)); + if (params.format) sp.set("format", params.format); + const qs = sp.toString(); + return qs ? `?${qs}` : ""; +} + +export const aiApi = { + getStatus: () => api.get("/ai/status"), + getSummary: (filters: AIFilterParams = {}) => + api.get(`/ai/summary${buildAIQuery(filters)}`), + getComparison: (filters: AIFilterParams = {}) => + api.get(`/ai/comparison${buildAIQuery(filters)}`), + getDepreciation: (filters: AIFilterParams = {}) => + api.get(`/ai/depreciation${buildAIQuery(filters)}`), + getEfficiency: (filters: AIFilterParams = {}) => + api.get(`/ai/efficiency${buildAIQuery(filters)}`), + getBreakdownFrequency: (filters: AIFilterParams = {}) => + api.get(`/ai/breakdown-frequency${buildAIQuery(filters)}`), + regenerateNarrative: (section: AISectionKey, filters: AIFilterParams = {}) => + api.post<{ section: string; narrative: AINarrative }>("/ai/narrative/regenerate", { + section, + filters, + }), + exportSection: async ( + section: AISectionKey, + format: "xlsx" | "csv", + filters: AIFilterParams = {} + ) => { + const qs = buildAIQuery({ ...filters, format }); + const { blob } = await api.downloadBlob(`/ai/${section}/export${qs}`); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `ai-${section}.${format}`; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 10_000); + }, +}; + diff --git a/frontend/src/api/assets.ts b/frontend/src/api/assets.ts new file mode 100644 index 0000000..600751a --- /dev/null +++ b/frontend/src/api/assets.ts @@ -0,0 +1,341 @@ +import { api } from "./client"; +import type { AttachmentItem } from "./attachments"; + +export type AssetStatus = "in_service" | "under_repair" | "out_of_service" | "condemned"; +export type AssetCriticality = "critical" | "non_critical"; +export type AcquisitionMode = "purchased" | "rented"; +export type DepreciationMethod = "straight_line" | "written_down"; +export type CoverageTag = "warranty" | "cmc" | "amc" | "other_contract" | "out_of_contract"; +export type CoverageStatus = "active" | "expiring" | "expired" | "none"; +export type AlertSeverity = "ok" | "yellow" | "red" | "none"; +export type CalibrationStatus = "upcoming" | "due" | "overdue" | "completed" | "none"; + +export interface CoverageInfo { + tag: CoverageTag; + contract_id: number | null; + warranty_id: number | null; + provider_id: number | null; + provider_name: string | null; + provider_contact: string | null; + valid_from: string | null; + valid_until: string | null; + days_left: number | null; + severity: "ok" | "yellow" | "red"; +} + +export interface AssetItem { + id: number; + asset_code: string; + serial_no: string; + name: string; + category_id: number; + category_name: string | null; + department_id: number; + department_name: string | null; + location_id: number; + location_name: string | null; + supplier_id: number | null; + supplier_name: string | null; + purchase_value?: number | null; + acquisition_mode?: AcquisitionMode | string; + monthly_rent?: number | null; + useful_life_years?: number | null; + salvage_pct?: number | null; + depreciation_method?: DepreciationMethod | string | null; + purchase_date: string | null; + installation_date: string | null; + status: AssetStatus; + criticality: AssetCriticality; + requires_calibration: boolean; + insurance_applicable: boolean; + remarks: string | null; + warranty_status: CoverageStatus; + warranty_end_date: string | null; + warranty_severity: AlertSeverity; + contract_status: CoverageStatus; + contract_type: string | null; + contract_end_date: string | null; + contract_severity: AlertSeverity; + calibration_status: CalibrationStatus; + calibration_due_date: string | null; + calibration_severity: AlertSeverity; + insurance_status: CoverageStatus; + insurance_end_date: string | null; + coverage_tag?: CoverageTag | string; + coverage?: CoverageInfo | null; + created_at: string; + updated_at: string; +} + +export interface AssetLookupItem { + id: number; + asset_code: string; + serial_no: string; + name: string; + category_id: number; + category_name: string | null; + department_id: number; + department_name: string | null; + location_id: number; + location_name: string | null; + supplier_id: number | null; + supplier_name: string | null; + status: AssetStatus; + criticality: AssetCriticality; + requires_calibration: boolean; + insurance_applicable: boolean; + warranty_status: CoverageStatus; + warranty_end_date: string | null; + contract_status: CoverageStatus; + contract_type: string | null; + contract_end_date: string | null; + contract_summary: string; + insurance_status: CoverageStatus; + insurance_end_date: string | null; + insurance_summary: string; + coverage_tag?: CoverageTag | string; + coverage?: CoverageInfo | null; +} + +export interface WarrantySummary { + id: number; + asset_id: number; + duration_months: number; + start_date: string; + end_date: string; + provider_id: number | null; + provider_name: string | null; + status: CoverageStatus | string; + severity: AlertSeverity | string; + remarks: string | null; +} + +export interface ContractSummary { + id: number; + asset_id: number; + contract_type: string; + provider_id: number; + provider_name: string | null; + start_date: string; + end_date: string; + contract_value?: number | null; + coverage_period_text: string | null; + renewed_from_id: number | null; + is_superseded: boolean; + status: CoverageStatus | string; + severity: AlertSeverity | string; + remarks: string | null; +} + +export interface InsuranceSummary { + id: number; + asset_id: number; + insurer_id: number; + insurer_name: string | null; + policy_no: string; + start_date: string; + end_date: string; + coverage_amount: number | null; + status: CoverageStatus | string; + severity: AlertSeverity | string; + remarks: string | null; +} + +export interface CalibrationPlanSummary { + id: number; + asset_id: number; + frequency_months: number; + calibrations_per_year: number; + agency_id: number | null; + agency_name: string | null; + approved_by_id: number | null; + approved_on: string | null; + next_due_date: string; + is_active: boolean; +} + +export interface CalibrationRecordSummary { + id: number; + asset_id: number; + plan_id: number; + due_date: string; + completed_date: string | null; + agency_id: number | null; + agency_name: string | null; + certificate_no: string | null; + remarks: string | null; + status: CalibrationStatus | string; + severity: AlertSeverity | string; +} + +export interface PMScheduleSummary { + id: number; + asset_id: number; + service_mode: string; + frequency_months: number; + responsible_team: string | null; + provider_id: number | null; + provider_name: string | null; + contract_id: number | null; + cost_per_visit?: number | null; + next_planned_date: string; + is_active: boolean; +} + +export interface PMRecordSummary { + id: number; + schedule_id: number; + asset_id: number; + planned_date: string; + completed_date: string | null; + status: string; + severity: string; + service_details: string | null; + remarks: string | null; + rescheduled_to: string | null; +} + +export interface ComplaintSummary { + id: number; + complaint_no: string; + asset_id: number; + description: string; + priority: string; + call_status: string; + registered_at: string; + closed_at: string | null; +} + +export interface AssetOverview { + asset: AssetItem; + coverage?: CoverageInfo; + warranties: WarrantySummary[]; + contracts: ContractSummary[]; + insurance_policies: InsuranceSummary[]; + calibration_plan: CalibrationPlanSummary | null; + calibration_records: CalibrationRecordSummary[]; + pm_schedules: PMScheduleSummary[]; + pm_records: PMRecordSummary[]; + complaints: ComplaintSummary[]; + attachments: AttachmentItem[]; +} + +export interface AssetListParams { + q?: string; + department_id?: number; + category_id?: number; + location_id?: number; + supplier_id?: number; + status?: AssetStatus | ""; + criticality?: AssetCriticality | ""; + requires_calibration?: boolean; + insurance_applicable?: boolean; + page?: number; + page_size?: number; + sort?: string; +} + +export interface AssetCreatePayload { + asset_code: string; + serial_no: string; + name: string; + category_id: number; + department_id: number; + location_id: number; + supplier_id?: number | null; + purchase_value?: number | null; + acquisition_mode?: AcquisitionMode; + monthly_rent?: number | null; + useful_life_years?: number | null; + salvage_pct?: number | null; + depreciation_method?: DepreciationMethod | null; + purchase_date?: string | null; + installation_date?: string | null; + status: AssetStatus; + criticality: AssetCriticality; + requires_calibration: boolean; + insurance_applicable: boolean; + remarks?: string | null; +} + +export type AssetUpdatePayload = Partial; + +export interface BulkImportErrorItem { + row: number; + asset_code: string | null; + error: string; +} + +export interface BulkImportPreviewRow { + row: number; + asset_code: string | null; + serial_no: string | null; + name: string | null; + category_name: string | null; + department_name: string | null; + location_name: string | null; + status: string | null; + valid: boolean; + error: string | null; +} + +export interface BulkImportResult { + dry_run: boolean; + total_rows: number; + valid_count: number; + error_count: number; + created_count: number; + errors: BulkImportErrorItem[]; + preview_rows: BulkImportPreviewRow[]; +} + +export const assetsApi = { + list: (params: AssetListParams = {}) => { + const qs = new URLSearchParams(); + if (params.q) qs.set("q", params.q); + if (params.department_id) qs.set("department_id", String(params.department_id)); + if (params.category_id) qs.set("category_id", String(params.category_id)); + if (params.location_id) qs.set("location_id", String(params.location_id)); + if (params.supplier_id) qs.set("supplier_id", String(params.supplier_id)); + if (params.status) qs.set("status", params.status); + if (params.criticality) qs.set("criticality", params.criticality); + if (params.requires_calibration !== undefined) qs.set("requires_calibration", String(params.requires_calibration)); + if (params.insurance_applicable !== undefined) qs.set("insurance_applicable", String(params.insurance_applicable)); + qs.set("page", String(params.page ?? 1)); + qs.set("page_size", String(params.page_size ?? 200)); + if (params.sort) qs.set("sort", params.sort); + return api.get<{ items: AssetItem[]; total: number }>(`/assets?${qs.toString()}`); + }, + lookup: (params: { q?: string; department_id?: number; limit?: number } = {}) => { + const qs = new URLSearchParams(); + if (params.q !== undefined) qs.set("q", params.q); + if (params.department_id) qs.set("department_id", String(params.department_id)); + qs.set("limit", String(params.limit ?? 25)); + return api.get<{ items: AssetLookupItem[] }>(`/assets/lookup?${qs.toString()}`); + }, + get: (id: number) => api.get(`/assets/${id}`), + coverage: (id: number, onDate?: string) => + api.get(`/assets/${id}/coverage${onDate ? `?on_date=${onDate}` : ""}`), + overview: (id: number) => api.get(`/assets/${id}/overview`), + create: (data: AssetCreatePayload) => api.post("/assets", data), + update: (id: number, data: AssetUpdatePayload) => api.patch(`/assets/${id}`, data), + downloadImportTemplate: async () => { + const { blob } = await api.downloadBlob("/assets/import-template"); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = "asset_import_template.xlsx"; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + }, + bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => { + const formData = new FormData(); + formData.append("file", file); + return api.upload( + `/assets/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`, + formData + ); + }, +}; diff --git a/frontend/src/api/attachments.ts b/frontend/src/api/attachments.ts new file mode 100644 index 0000000..5b51f7e --- /dev/null +++ b/frontend/src/api/attachments.ts @@ -0,0 +1,57 @@ +import { api } from "./client"; + +export type AttachmentEntityType = + | "complaint" + | "contract" + | "calibration_record" + | "insurance" + | "demo_equipment" + | "asset" + | "warranty" + | "pm_record"; + +export interface AttachmentItem { + id: number; + entity_type: AttachmentEntityType | string; + entity_id: number; + original_name: string; + mime_type: string; + size_bytes: number; + uploaded_by_id?: number | null; + uploaded_by_name?: string | null; + uploaded_at: string; +} + +export const attachmentsApi = { + list: (entityType: AttachmentEntityType, entityId: number) => { + const qs = new URLSearchParams({ + entity_type: entityType, + entity_id: String(entityId), + }); + return api.get<{ items: AttachmentItem[]; total: number }>(`/attachments?${qs.toString()}`); + }, + upload: (entityType: AttachmentEntityType, entityId: number, file: File) => { + const formData = new FormData(); + formData.append("entity_type", entityType); + formData.append("entity_id", String(entityId)); + formData.append("file", file); + return api.upload("/attachments", formData); + }, + download: async (id: number, originalName: string, preview = false) => { + const { blob } = await api.downloadBlob(`/attachments/${id}/download`); + const url = URL.createObjectURL(blob); + if (preview) { + window.open(url, "_blank", "noopener,noreferrer"); + setTimeout(() => URL.revokeObjectURL(url), 30_000); + } else { + const a = document.createElement("a"); + a.href = url; + a.download = originalName; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + } + }, + remove: (id: number) => api.delete(`/attachments/${id}`), +}; diff --git a/frontend/src/api/audit.ts b/frontend/src/api/audit.ts new file mode 100644 index 0000000..87ca790 --- /dev/null +++ b/frontend/src/api/audit.ts @@ -0,0 +1,45 @@ +import { api } from "./client"; + +export interface AuditLogItem { + id: number; + entity_type: string; + entity_id: number; + action: string; + changes_json: string | null; + by_user_id: number | null; + by_user_name: string | null; + at: string; +} + +export interface AuditLogsResponse { + items: AuditLogItem[]; + total: number; +} + +export interface AuditLogFilters { + entity_type?: string; + by_user_id?: number; + action?: string; + date_from?: string; + date_to?: string; + q?: string; + page?: number; + page_size?: number; +} + +export const auditApi = { + list: (filters: AuditLogFilters = {}) => { + const params = new URLSearchParams(); + if (filters.entity_type) params.set("entity_type", filters.entity_type); + if (filters.by_user_id != null) { + params.set("by_user_id", String(filters.by_user_id)); + } + if (filters.action) params.set("action", filters.action); + if (filters.date_from) params.set("date_from", filters.date_from); + if (filters.date_to) params.set("date_to", filters.date_to); + if (filters.q) params.set("q", filters.q); + if (filters.page != null) params.set("page", String(filters.page)); + params.set("page_size", String(filters.page_size ?? 200)); + return api.get(`/audit-logs?${params.toString()}`); + }, +}; diff --git a/frontend/src/api/auth.ts b/frontend/src/api/auth.ts new file mode 100644 index 0000000..67befa1 --- /dev/null +++ b/frontend/src/api/auth.ts @@ -0,0 +1,40 @@ +import { api } from "./client"; +import type { Role } from "@/lib/permissions"; + +export interface UserOut { + id: number; + name: string; + email: string; + role: Role; + department_id: number | null; + department_name: string | null; + is_active: boolean; + demo_as_of_date?: string | null; +} + +export interface LoginResponse { + access_token: string; + token_type: string; + user: UserOut; +} + +export function loginApi(email: string, password: string) { + return api.post("/auth/login", { email, password }); +} + +export function fetchMeApi() { + return api.get("/auth/me"); +} + +export interface ChangePasswordResponse { + message: string; + access_token?: string; + token_type?: string; +} + +export function changePasswordApi(current_password: string, new_password: string) { + return api.post("/auth/change-password", { + current_password, + new_password, + }); +} diff --git a/frontend/src/api/calibration.ts b/frontend/src/api/calibration.ts new file mode 100644 index 0000000..7d8d788 --- /dev/null +++ b/frontend/src/api/calibration.ts @@ -0,0 +1,165 @@ +import { api } from "./client"; +import type { BulkImportResult } from "./assets"; + +export interface CalibrationPlanItem { + id: number; + asset_id: number; + asset_code: string; + asset_name: string; + department_id: number; + department_name: string | null; + frequency_months: number; + calibrations_per_year: number; + agency_id: number | null; + agency_name: string | null; + approved_by_id: number | null; + approved_by_name: string | null; + approved_on: string | null; + next_due_date: string; + is_active: boolean; +} + +export interface CalibrationRecordItem { + id: number; + plan_id: number; + asset_id: number; + asset_code: string; + asset_name: string; + department_id: number; + department_name: string | null; + location_name: string | null; + due_date: string; + completed_date: string | null; + agency_id: number | null; + agency_name: string | null; + certificate_no: string | null; + remarks: string | null; + status: "upcoming" | "due" | "overdue" | "completed" | string; + severity: "ok" | "yellow" | "red" | string; + frequency_months: number; + approved_by_name: string | null; + approved_on: string | null; +} + +export interface CalibrationSummary { + upcoming: number; + due: number; + overdue: number; + completed: number; +} + +export interface CalibrationPlanFromAssetPayload { + frequency_months: number; + calibrations_per_year?: number; + agency_id?: number | null; + next_due_date: string; + approve?: boolean; +} + +export const calibrationApi = { + listPlans: ( + params: { + q?: string; + department_id?: number; + agency_id?: number; + is_active?: boolean; + page?: number; + page_size?: number; + } = {} + ) => { + const qs = new URLSearchParams(); + if (params.q) qs.set("q", params.q); + if (params.department_id) qs.set("department_id", String(params.department_id)); + if (params.agency_id) qs.set("agency_id", String(params.agency_id)); + if (params.is_active !== undefined) qs.set("is_active", String(params.is_active)); + qs.set("page", String(params.page ?? 1)); + qs.set("page_size", String(params.page_size ?? 200)); + return api.get<{ items: CalibrationPlanItem[]; total: number }>( + `/calibration/plans?${qs.toString()}` + ); + }, + createPlanFromAsset: (assetId: number, data: CalibrationPlanFromAssetPayload) => + api.post(`/calibration/plans/from-asset/${assetId}`, data), + bulkCreatePlansFromAssets: ( + data: CalibrationPlanFromAssetPayload & { asset_ids: number[] } + ) => + api.post<{ created: CalibrationPlanItem[]; skipped_asset_ids: number[] }>( + "/calibration/plans/bulk-from-assets", + data + ), + updatePlan: ( + id: number, + data: Partial<{ + frequency_months: number; + calibrations_per_year: number; + agency_id: number | null; + next_due_date: string; + is_active: boolean; + }> + ) => api.put(`/calibration/plans/${id}`, data), + approvePlan: ( + id: number, + data: { frequency_months?: number; calibrations_per_year?: number } = {} + ) => api.post(`/calibration/plans/${id}/approve`, data), + listRecords: ( + params: { + q?: string; + department_id?: number; + asset_id?: number; + agency_id?: number; + status?: string; + due_from?: string; + due_to?: string; + page?: number; + page_size?: number; + } = {} + ) => { + const qs = new URLSearchParams(); + if (params.q) qs.set("q", params.q); + if (params.department_id) qs.set("department_id", String(params.department_id)); + if (params.asset_id) qs.set("asset_id", String(params.asset_id)); + if (params.agency_id) qs.set("agency_id", String(params.agency_id)); + if (params.status) qs.set("status", params.status); + if (params.due_from) qs.set("due_from", params.due_from); + if (params.due_to) qs.set("due_to", params.due_to); + qs.set("page", String(params.page ?? 1)); + qs.set("page_size", String(params.page_size ?? 200)); + return api.get<{ + items: CalibrationRecordItem[]; + total: number; + summary: CalibrationSummary; + }>(`/calibration/records?${qs.toString()}`); + }, + completeRecord: ( + id: number, + data: { + completed_date: string; + certificate_no: string; + agency_id?: number | null; + remarks?: string | null; + } + ) => + api.post<{ + completed_record: CalibrationRecordItem; + next_record: CalibrationRecordItem; + }>(`/calibration/records/${id}/complete`, data), + downloadImportTemplate: async () => { + const { blob } = await api.downloadBlob("/calibration/import-template"); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = "calibration_import_template.xlsx"; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + }, + bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => { + const formData = new FormData(); + formData.append("file", file); + return api.upload( + `/calibration/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`, + formData + ); + }, +}; diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts new file mode 100644 index 0000000..8b4a7a8 --- /dev/null +++ b/frontend/src/api/client.ts @@ -0,0 +1,73 @@ +const BASE_URL = "/api"; + +export class ApiError extends Error { + constructor( + public status: number, + public detail: string, + public code?: string + ) { + super(detail); + } +} + +let onUnauthorizedCallback: (() => void) | null = null; + +export function setUnauthorizedHandler(cb: () => void) { + onUnauthorizedCallback = cb; +} + +function handleUnauthorized(path: string) { + sessionStorage.removeItem("access_token"); + if (!path.startsWith("/auth/login")) { + onUnauthorizedCallback?.(); + } +} + +async function request(path: string, options: RequestInit = {}): Promise { + const token = sessionStorage.getItem("access_token"); + const isFormData = typeof FormData !== "undefined" && options.body instanceof FormData; + const headers: Record = { + ...(isFormData ? {} : { "Content-Type": "application/json" }), + ...(options.headers as Record), + }; + if (token) headers["Authorization"] = `Bearer ${token}`; + + const res = await fetch(`${BASE_URL}${path}`, { ...options, headers }); + if (!res.ok) { + const body = await res.json().catch(() => ({ detail: res.statusText })); + if (res.status === 401) handleUnauthorized(path); + throw new ApiError(res.status, body.detail ?? res.statusText, body.code); + } + if (res.status === 204) return undefined as T; + return res.json(); +} + +async function downloadBlob(path: string): Promise<{ blob: Blob; contentType: string }> { + const token = sessionStorage.getItem("access_token"); + const headers: Record = {}; + if (token) headers["Authorization"] = `Bearer ${token}`; + + const res = await fetch(`${BASE_URL}${path}`, { headers }); + if (!res.ok) { + const body = await res.json().catch(() => ({ detail: res.statusText })); + if (res.status === 401) handleUnauthorized(path); + throw new ApiError(res.status, body.detail ?? res.statusText, body.code); + } + const blob = await res.blob(); + const contentType = res.headers.get("Content-Type") || blob.type || "application/octet-stream"; + return { blob, contentType }; +} + +export const api = { + get: (path: string) => request(path), + post: (path: string, data?: unknown) => + request(path, { method: "POST", body: data !== undefined ? JSON.stringify(data) : undefined }), + patch: (path: string, data: unknown) => + request(path, { method: "PATCH", body: JSON.stringify(data) }), + put: (path: string, data: unknown) => + request(path, { method: "PUT", body: JSON.stringify(data) }), + delete: (path: string) => request(path, { method: "DELETE" }), + upload: (path: string, formData: FormData) => + request(path, { method: "POST", body: formData }), + downloadBlob, +}; diff --git a/frontend/src/api/complaints.ts b/frontend/src/api/complaints.ts new file mode 100644 index 0000000..c19ff8f --- /dev/null +++ b/frontend/src/api/complaints.ts @@ -0,0 +1,167 @@ +import { api } from "./client"; +import type { AssetCriticality, AssetStatus, CoverageInfo, CoverageTag } from "./assets"; + +export type CallStatus = "open" | "in_progress" | "closed"; + +export type TimestampField = + | "registered_at" + | "received_at" + | "attended_at" + | "restored_at" + | "closed_at" + | "ce_attended_at"; + +export interface ComplaintItem { + id: number; + complaint_no: string; + asset_id: number; + asset_code: string; + asset_name: string; + asset_status: AssetStatus | string; + department_id: number; + department_name: string | null; + location_name: string | null; + description: string; + breakdown_details: string | null; + priority: AssetCriticality | string; + notes: string | null; + registered_at: string; + registered_by_id: number; + registered_by_name: string | null; + received_by_id: number | null; + received_by_name: string | null; + received_at: string | null; + assigned_to_id: number | null; + assigned_to_name: string | null; + assigned_team?: string | null; + assigned_at: string | null; + attended_by_id: number | null; + attended_by_name: string | null; + attended_at: string | null; + restored_at: string | null; + closed_by_id: number | null; + closed_by_name: string | null; + closed_at: string | null; + call_status: CallStatus; + closure_remarks: string | null; + action_taken: string | null; + root_cause: string | null; + corrective_action: string | null; + lessons_learned: string | null; + ce_name: string | null; + ce_attended_at: string | null; + ce_action_taken: string | null; + spare_required: boolean; + spare_details: string | null; + spare_cost_estimate?: number | null; + repair_cost?: number | null; + coverage_tag?: CoverageTag | string | null; + coverage_contract_id?: number | null; + coverage_provider_id?: number | null; + coverage_at_registration?: CoverageInfo | null; + coverage_now?: CoverageInfo | null; + response_time_minutes: number | null; + downtime_minutes: number; + downtime_is_ongoing: boolean; + downtime_end_milestone: string; + response_start_setting: string; + ce_response_time_minutes: number | null; + updated_at: string; +} + +export interface ComplaintEventItem { + id: number; + complaint_id: number; + event_type: string; + from_value: string | null; + to_value: string | null; + by_user_id: number | null; + by_user_name: string | null; + at: string; + note: string | null; +} + +export interface ComplaintListParams { + q?: string; + department_id?: number; + location_id?: number; + asset_id?: number; + call_status?: CallStatus | ""; + priority?: AssetCriticality | ""; + coverage_tag?: CoverageTag | ""; + assigned_to_id?: number; + closure_state?: "open_only" | "closed_only" | ""; + date_from?: string; + date_to?: string; + page?: number; + page_size?: number; +} + +export interface ComplaintCreatePayload { + asset_id: number; + description: string; + breakdown_details?: string | null; + priority: AssetCriticality; + notes?: string | null; + assigned_team?: string | null; + received_by_id?: number | null; +} + +export interface ComplaintUpdatePayload { + description?: string; + breakdown_details?: string | null; + priority?: AssetCriticality; + notes?: string | null; + assigned_team?: string | null; + action_taken?: string | null; + root_cause?: string | null; + corrective_action?: string | null; + lessons_learned?: string | null; + ce_name?: string | null; + ce_attended_at?: string | null; + ce_action_taken?: string | null; + spare_required?: boolean; + spare_details?: string | null; + spare_cost_estimate?: number | null; + repair_cost?: number | null; +} + +export const complaintsApi = { + list: (params: ComplaintListParams = {}) => { + const qs = new URLSearchParams(); + if (params.q) qs.set("q", params.q); + if (params.department_id) qs.set("department_id", String(params.department_id)); + if (params.location_id) qs.set("location_id", String(params.location_id)); + if (params.asset_id) qs.set("asset_id", String(params.asset_id)); + if (params.call_status) qs.set("call_status", params.call_status); + if (params.priority) qs.set("priority", params.priority); + if (params.coverage_tag) qs.set("coverage_tag", params.coverage_tag); + if (params.assigned_to_id) qs.set("assigned_to_id", String(params.assigned_to_id)); + if (params.closure_state) qs.set("closure_state", params.closure_state); + if (params.date_from) qs.set("date_from", params.date_from); + if (params.date_to) qs.set("date_to", params.date_to); + qs.set("page", String(params.page ?? 1)); + qs.set("page_size", String(params.page_size ?? 200)); + return api.get<{ items: ComplaintItem[]; total: number }>(`/complaints?${qs.toString()}`); + }, + create: (data: ComplaintCreatePayload) => api.post("/complaints", data), + get: (id: number) => api.get(`/complaints/${id}`), + events: (id: number) => + api.get<{ items: ComplaintEventItem[]; total: number }>(`/complaints/${id}/events`), + update: (id: number, data: ComplaintUpdatePayload) => + api.patch(`/complaints/${id}`, data), + assign: (id: number, data: { assigned_to_id?: number | null; assigned_team?: string | null; note?: string }) => + api.post(`/complaints/${id}/assign`, data), + attend: (id: number, data: { attended_by_id?: number; note?: string } = {}) => + api.post(`/complaints/${id}/attend`, data), + restore: (id: number, data: { note?: string } = {}) => + api.post(`/complaints/${id}/restore`, data), + close: (id: number, data: { closure_remarks?: string } = {}) => + api.post(`/complaints/${id}/close`, data), + reopen: (id: number, data: { reason: string }) => + api.post(`/complaints/${id}/reopen`, data), + correctTimestamp: ( + id: number, + data: { field: TimestampField; new_value: string; reason: string } + ) => api.post(`/complaints/${id}/correct-timestamp`, data), +}; diff --git a/frontend/src/api/dashboard.ts b/frontend/src/api/dashboard.ts new file mode 100644 index 0000000..4311804 --- /dev/null +++ b/frontend/src/api/dashboard.ts @@ -0,0 +1,77 @@ +import { api } from "./client"; + +export interface DashboardKPIs { + total_assets: number; + assets_under_repair: number; + open_complaints: number; + pm_due_this_month: number; + calibrations_due: number; + contracts_expiring: number; + equipment_on_demo: number; +} + +export interface StatusCountItem { + status: string; + count: number; +} + +export interface DeptComplaintCountItem { + department: string; + critical: number; + non_critical: number; +} + +export interface MonthlyDowntimePoint { + month: string; + label: string; + downtime_minutes: number; + downtime_hours: number; +} + +export interface MonthlyPMPoint { + month: string; + label: string; + planned: number; + completed: number; +} + +export interface NeedsAttentionItem { + id: number; + type: string; + severity: string; + title: string; + message: string; + entity_type: string | null; + entity_id: number | null; + due_date: string | null; + link_url: string; +} + +export interface RecentComplaintItem { + id: number; + complaint_no: string; + asset_code: string; + asset_name: string; + department_name: string | null; + priority: string; + call_status: string; + registered_at: string; + downtime_minutes: number; + downtime_is_ongoing: boolean; +} + +export interface DashboardSummary { + department_scope: string | null; + effective_today: string; + kpis: DashboardKPIs; + complaints_by_status: StatusCountItem[]; + complaints_by_department: DeptComplaintCountItem[]; + monthly_downtime_trend: MonthlyDowntimePoint[]; + pm_planned_vs_completed: MonthlyPMPoint[]; + needs_attention: NeedsAttentionItem[]; + recent_complaints: RecentComplaintItem[]; +} + +export const dashboardApi = { + summary: () => api.get("/dashboard/summary"), +}; diff --git a/frontend/src/api/health.ts b/frontend/src/api/health.ts new file mode 100644 index 0000000..c7e7f46 --- /dev/null +++ b/frontend/src/api/health.ts @@ -0,0 +1,4 @@ +import { api } from "./client"; + +export const fetchHealth = () => + api.get<{ status: string; service: string; version: string }>("/health"); diff --git a/frontend/src/api/masters.ts b/frontend/src/api/masters.ts new file mode 100644 index 0000000..f499fa1 --- /dev/null +++ b/frontend/src/api/masters.ts @@ -0,0 +1,183 @@ +import { api } from "./client"; +import type { Role } from "@/lib/permissions"; + +export interface PaginatedResponse { + items: T[]; + total: number; +} + +export interface Department { + id: number; + name: string; + code: string; + description: string | null; + is_active: boolean; +} + +export interface LocationItem { + id: number; + department_id: number; + department_name: string | null; + name: string; + floor_wing: string | null; + is_active: boolean; +} + +export interface Category { + id: number; + name: string; + description: string | null; + default_useful_life_years?: number | null; + is_active: boolean; +} + +export type VendorType = + | "supplier" + | "service_provider" + | "calibration_agency" + | "insurer" + | "oem"; + +export const VENDOR_TYPE_LABELS: Record = { + supplier: "Supplier", + service_provider: "Service Provider", + calibration_agency: "Calibration Agency", + insurer: "Insurer", + oem: "OEM", +}; + +export interface Vendor { + id: number; + name: string; + vendor_type: VendorType; + contact_person: string | null; + phone: string | null; + email: string | null; + address: string | null; + is_active: boolean; +} + +export interface MasterUser { + id: number; + name: string; + email: string; + role: Role; + department_id: number | null; + department_name: string | null; + is_active: boolean; +} + +function buildListQuery(includeInactive: boolean) { + const params = new URLSearchParams(); + params.set("page_size", "500"); + if (includeInactive) params.set("include_inactive", "true"); + return `?${params.toString()}`; +} + +export const departmentsApi = { + list: (includeInactive = false) => + api.get>(`/departments${buildListQuery(includeInactive)}`), + create: (data: { name: string; code: string; description?: string | null }) => + api.post("/departments", data), + update: (id: number, data: Partial<{ name: string; code: string; description: string | null; is_active: boolean }>) => + api.patch(`/departments/${id}`, data), + remove: (id: number) => api.delete(`/departments/${id}`), +}; + +export const locationsApi = { + list: (includeInactive = false) => + api.get>(`/locations${buildListQuery(includeInactive)}`), + create: (data: { department_id: number; name: string; floor_wing?: string | null }) => + api.post("/locations", data), + update: ( + id: number, + data: Partial<{ department_id: number; name: string; floor_wing: string | null; is_active: boolean }> + ) => api.patch(`/locations/${id}`, data), + remove: (id: number) => api.delete(`/locations/${id}`), +}; + +export const categoriesApi = { + list: (includeInactive = false) => + api.get>(`/categories${buildListQuery(includeInactive)}`), + create: (data: { name: string; description?: string | null; default_useful_life_years?: number | null }) => + api.post("/categories", data), + update: ( + id: number, + data: Partial<{ + name: string; + description: string | null; + default_useful_life_years: number | null; + is_active: boolean; + }> + ) => api.patch(`/categories/${id}`, data), + remove: (id: number) => api.delete(`/categories/${id}`), +}; + +export const vendorsApi = { + list: (includeInactive = false) => + api.get>(`/vendors${buildListQuery(includeInactive)}`), + create: (data: { + name: string; + vendor_type: VendorType; + contact_person?: string | null; + phone?: string | null; + email?: string | null; + address?: string | null; + }) => api.post("/vendors", data), + update: ( + id: number, + data: Partial<{ + name: string; + vendor_type: VendorType; + contact_person: string | null; + phone: string | null; + email: string | null; + address: string | null; + is_active: boolean; + }> + ) => api.patch(`/vendors/${id}`, data), + remove: (id: number) => api.delete(`/vendors/${id}`), +}; + +export const usersApi = { + list: (includeInactive = false) => + api.get>(`/users${buildListQuery(includeInactive)}`), + create: (data: { + name: string; + email: string; + role: Role; + department_id?: number | null; + password: string; + }) => api.post("/users", data), + update: ( + id: number, + data: Partial<{ + name: string; + email: string; + role: Role; + department_id: number | null; + password: string; + is_active: boolean; + }> + ) => api.patch(`/users/${id}`, data), + remove: (id: number) => api.delete(`/users/${id}`), + resetPassword: (id: number, new_password: string) => + api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password }), +}; + +export interface UserLookupItem { + id: number; + name: string; + role: Role; + department_id: number | null; +} + +export async function fetchUsersLookup(): Promise<{ items: UserLookupItem[]; total: number }> { + const res = await api.get( + "/users/lookup" + ); + if (Array.isArray(res)) { + return { items: res, total: res.length }; + } + return res; +} diff --git a/frontend/src/api/notifications.ts b/frontend/src/api/notifications.ts new file mode 100644 index 0000000..6cf6401 --- /dev/null +++ b/frontend/src/api/notifications.ts @@ -0,0 +1,68 @@ +import { api } from "./client"; + +export type NotificationSeverity = "info" | "yellow" | "red"; + +export type NotificationType = + | "amc_expiry" + | "calibration_due" + | "pm_due" + | "insurance_expiry" + | "warranty_expiry" + | "demo_overdue" + | "critical_complaint" + | "sla_breach"; + +export interface NotificationItem { + id: number; + type: NotificationType | string; + severity: NotificationSeverity | string; + title: string; + message: string; + entity_type: string | null; + entity_id: number | null; + due_date: string | null; + created_at: string; + is_read: boolean; + read_at: string | null; + link_url: string; +} + +export interface NotificationListResponse { + items: NotificationItem[]; + total: number; + unread_count: number; + unread_calibration_count: number; +} + +export interface NotificationListParams { + type?: string; + severity?: string; + unread_only?: boolean; + limit?: number; + page?: number; + page_size?: number; +} + +export const notificationsApi = { + list: (params: NotificationListParams = {}) => { + const sp = new URLSearchParams(); + if (params.type) sp.set("type", params.type); + if (params.severity) sp.set("severity", params.severity); + if (params.unread_only) sp.set("unread_only", "true"); + if (params.limit != null) sp.set("limit", String(params.limit)); + if (params.page != null) sp.set("page", String(params.page)); + if (params.page_size != null) sp.set("page_size", String(params.page_size)); + const qs = sp.toString(); + return api.get(`/notifications${qs ? `?${qs}` : ""}`); + }, + markRead: (id: number) => + api.post<{ status: string; id: number }>(`/notifications/${id}/read`), + markAllRead: (type?: string) => { + const qs = type ? `?type=${encodeURIComponent(type)}` : ""; + return api.post<{ status: string; marked_count?: number }>( + `/notifications/read-all${qs}` + ); + }, + runAlertsNow: () => + api.post<{ created: number; evaluated_today: string }>("/alerts/run"), +}; diff --git a/frontend/src/api/phase5.ts b/frontend/src/api/phase5.ts new file mode 100644 index 0000000..c04cfac --- /dev/null +++ b/frontend/src/api/phase5.ts @@ -0,0 +1,354 @@ +import { api } from "./client"; +import type { AlertSeverity, BulkImportResult, CoverageStatus } from "./assets"; + +export type ContractStatus = CoverageStatus | "superseded"; +export type DemoStatus = "on_demo" | "overdue_return" | "returned"; + +export interface ContractItem { + id: number; + asset_id: number; + asset_code: string; + asset_name: string; + department_id: number; + department_name: string | null; + contract_type: string; + provider_id: number; + provider_name: string | null; + start_date: string; + end_date: string; + contract_value?: number | null; + coverage_period_text: string | null; + renewed_from_id: number | null; + is_superseded: boolean; + status: ContractStatus | string; + severity: AlertSeverity | string; + days_to_expiry: number; + attachment_count: number; + remarks: string | null; + created_at: string; +} + +export interface ContractListParams { + q?: string; + department_id?: number; + asset_id?: number; + provider_id?: number; + contract_type?: string; + status?: string; + include_superseded?: boolean; + expiry_from?: string; + expiry_to?: string; + page?: number; + page_size?: number; +} + +export interface ContractCreatePayload { + asset_id: number; + contract_type: string; + provider_id: number; + start_date: string; + end_date: string; + contract_value?: number | null; + coverage_period_text?: string | null; + remarks?: string | null; +} + +export interface ContractRenewPayload { + contract_type?: string; + provider_id?: number; + start_date: string; + end_date: string; + contract_value?: number | null; + coverage_period_text?: string | null; + remarks?: string | null; +} + +export interface WarrantyItem { + id: number; + asset_id: number; + asset_code: string; + asset_name: string; + department_id: number; + department_name: string | null; + duration_months: number; + start_date: string; + end_date: string; + provider_id: number | null; + provider_name: string | null; + status: CoverageStatus | string; + severity: AlertSeverity | string; + days_to_expiry: number; + attachment_count: number; + remarks: string | null; + created_at: string; +} + +export interface WarrantyListParams { + q?: string; + department_id?: number; + asset_id?: number; + status?: string; + expiry_from?: string; + expiry_to?: string; + page?: number; + page_size?: number; +} + +export interface WarrantyCreatePayload { + asset_id: number; + duration_months: number; + start_date: string; + end_date: string; + provider_id?: number | null; + remarks?: string | null; +} + +export interface InsuranceItem { + id: number; + asset_id: number; + asset_code: string; + asset_name: string; + department_id: number; + department_name: string | null; + insurer_id: number; + insurer_name: string | null; + policy_no: string; + start_date: string; + end_date: string; + coverage_amount: number | null; + status: CoverageStatus | string; + severity: AlertSeverity | string; + days_to_expiry: number; + attachment_count: number; + remarks: string | null; + created_at: string; +} + +export interface InsuranceListParams { + q?: string; + department_id?: number; + asset_id?: number; + insurer_id?: number; + status?: string; + expiry_from?: string; + expiry_to?: string; + page?: number; + page_size?: number; +} + +export interface InsuranceCreatePayload { + asset_id: number; + insurer_id: number; + policy_no: string; + start_date: string; + end_date: string; + coverage_amount?: number | null; + remarks?: string | null; +} + +export interface DemoEquipmentItem { + id: number; + name: string; + equipment_type: string; + serial_no?: string | null; + supplier_id: number; + supplier_name: string | null; + department_id: number; + department_name: string | null; + location_id: number | null; + location_name: string | null; + start_date: string; + expected_return_date: string; + actual_return_date: string | null; + status: DemoStatus | string; + severity: AlertSeverity | string; + days_remaining: number; + attachment_count: number; + remarks: string | null; + created_at: string; +} + +export interface DemoListParams { + q?: string; + supplier_id?: number; + department_id?: number; + status?: string; + date_from?: string; + date_to?: string; + page?: number; + page_size?: number; +} + +export interface DemoCreatePayload { + name: string; + equipment_type: string; + serial_no?: string | null; + supplier_id: number; + department_id: number; + location_id?: number | null; + start_date: string; + expected_return_date: string; + remarks?: string | null; +} + +export interface VisitAssetBrief { + id: number; + asset_code: string; + name: string; +} + +export interface VisitComplaintBrief { + id: number; + complaint_no: string; + call_status: string; + priority: string; + description: string; +} + +export interface VisitItem { + id: number; + department_id: number; + department_name: string | null; + visited_by_id: number; + visited_by_name: string | null; + visit_date: string; + observations: string; + new_requirements?: string | null; + assets: VisitAssetBrief[]; + complaints: VisitComplaintBrief[]; + created_at: string; +} + +export interface VisitListParams { + q?: string; + department_id?: number; + visited_by_id?: number; + date_from?: string; + date_to?: string; + page?: number; + page_size?: number; +} + +export interface VisitCreatePayload { + department_id: number; + visit_date: string; + observations: string; + new_requirements?: string | null; + asset_ids?: number[]; + complaint_ids?: number[]; +} + +function toQS(params: Record): string { + const sp = new URLSearchParams(); + for (const [k, v] of Object.entries(params)) { + if (v === undefined || v === "") continue; + sp.set(k, String(v)); + } + const s = sp.toString(); + return s ? `?${s}` : ""; +} + +export const contractsApi = { + list: (params: ContractListParams = {}) => + api.get<{ items: ContractItem[]; total: number }>( + `/contracts${toQS(params as Record)}` + ), + create: (data: ContractCreatePayload) => api.post("/contracts", data), + update: (id: number, data: Partial) => + api.patch(`/contracts/${id}`, data), + remove: (id: number) => api.delete(`/contracts/${id}`), + renew: (id: number, data: ContractRenewPayload) => + api.post<{ old_contract: ContractItem; new_contract: ContractItem }>( + `/contracts/${id}/renew`, + data + ), + history: (assetId: number) => + api.get<{ items: ContractItem[] }>(`/contracts/history/${assetId}`), + downloadImportTemplate: async () => { + const { blob } = await api.downloadBlob("/contracts/import-template"); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = "contracts_import_template.xlsx"; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + }, + bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => { + const formData = new FormData(); + formData.append("file", file); + return api.upload( + `/contracts/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`, + formData + ); + }, +}; + +export const warrantiesApi = { + list: (params: WarrantyListParams = {}) => + api.get<{ items: WarrantyItem[]; total: number }>( + `/warranties${toQS(params as Record)}` + ), + create: (data: WarrantyCreatePayload) => api.post("/warranties", data), + update: (id: number, data: Partial) => + api.patch(`/warranties/${id}`, data), + remove: (id: number) => api.delete(`/warranties/${id}`), +}; + +export const insuranceApi = { + list: (params: InsuranceListParams = {}) => + api.get<{ items: InsuranceItem[]; total: number }>( + `/insurance${toQS(params as Record)}` + ), + create: (data: InsuranceCreatePayload) => api.post("/insurance", data), + update: (id: number, data: Partial) => + api.patch(`/insurance/${id}`, data), + remove: (id: number) => api.delete(`/insurance/${id}`), + downloadImportTemplate: async () => { + const { blob } = await api.downloadBlob("/insurance/import-template"); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = "insurance_import_template.xlsx"; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + }, + bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => { + const formData = new FormData(); + formData.append("file", file); + return api.upload( + `/insurance/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`, + formData + ); + }, +}; + +export const demoEquipmentApi = { + list: (params: DemoListParams = {}) => + api.get<{ items: DemoEquipmentItem[]; total: number }>( + `/demo-equipment${toQS(params as Record)}` + ), + create: (data: DemoCreatePayload) => + api.post("/demo-equipment", data), + update: (id: number, data: Partial) => + api.patch(`/demo-equipment/${id}`, data), + remove: (id: number) => api.delete(`/demo-equipment/${id}`), + markReturned: (id: number, data: { actual_return_date: string; remarks?: string | null }) => + api.post(`/demo-equipment/${id}/return`, data), +}; + +export const visitsApi = { + list: (params: VisitListParams = {}) => + api.get<{ items: VisitItem[]; total: number }>( + `/visits${toQS(params as Record)}` + ), + get: (id: number) => api.get(`/visits/${id}`), + create: (data: VisitCreatePayload) => api.post("/visits", data), + update: (id: number, data: Partial) => + api.patch(`/visits/${id}`, data), + linkComplaint: (id: number, complaintId: number) => + api.post(`/visits/${id}/link-complaint`, { complaint_id: complaintId }), +}; diff --git a/frontend/src/api/pm.ts b/frontend/src/api/pm.ts new file mode 100644 index 0000000..1f243eb --- /dev/null +++ b/frontend/src/api/pm.ts @@ -0,0 +1,145 @@ +import { api } from "./client"; +import type { CoverageInfo, CoverageTag } from "./assets"; + +export type ServiceMode = "in_house" | "outsourced"; +export type ScheduleStatus = "upcoming" | "due" | "overdue" | "completed" | "rescheduled"; + +export interface PMScheduleItem { + id: number; + asset_id: number; + asset_code: string; + asset_name: string; + department_id: number; + department_name: string | null; + location_name: string | null; + service_mode: ServiceMode; + frequency_months: number; + responsible_team: string | null; + provider_id: number | null; + provider_name: string | null; + contract_id: number | null; + contract_summary: string | null; + cost_per_visit?: number | null; + coverage_tag?: CoverageTag | string | null; + coverage?: CoverageInfo | null; + no_active_contract?: boolean | null; + next_planned_date: string; + is_active: boolean; + created_at: string; +} + +export interface PMRecordItem { + id: number; + schedule_id: number; + asset_id: number; + asset_code: string; + asset_name: string; + department_id: number; + department_name: string | null; + location_name: string | null; + service_mode: ServiceMode; + responsible_team: string | null; + provider_id: number | null; + provider_name: string | null; + contract_id: number | null; + planned_date: string; + completed_date: string | null; + status: ScheduleStatus | string; + severity: "ok" | "yellow" | "red" | string; + service_details: string | null; + remarks: string | null; + rescheduled_to: string | null; + frequency_months: number; + coverage_tag?: CoverageTag | string | null; + coverage?: CoverageInfo | null; +} + +export interface PMSummary { + upcoming: number; + due: number; + overdue: number; + completed_this_month: number; +} + +export interface PMScheduleCreatePayload { + asset_id: number; + service_mode: ServiceMode; + frequency_months: number; + responsible_team?: string | null; + provider_id?: number | null; + contract_id?: number | null; + cost_per_visit?: number | null; + next_planned_date: string; +} + +export const pmApi = { + listSchedules: ( + params: { + q?: string; + department_id?: number; + asset_id?: number; + service_mode?: ServiceMode | ""; + is_active?: boolean; + page?: number; + page_size?: number; + } = {} + ) => { + const qs = new URLSearchParams(); + if (params.q) qs.set("q", params.q); + if (params.department_id) qs.set("department_id", String(params.department_id)); + if (params.asset_id) qs.set("asset_id", String(params.asset_id)); + if (params.service_mode) qs.set("service_mode", params.service_mode); + if (params.is_active !== undefined) qs.set("is_active", String(params.is_active)); + qs.set("page", String(params.page ?? 1)); + qs.set("page_size", String(params.page_size ?? 200)); + return api.get<{ items: PMScheduleItem[]; total: number }>(`/pm/schedules?${qs.toString()}`); + }, + createSchedule: (data: PMScheduleCreatePayload) => + api.post("/pm/schedules", data), + updateSchedule: (id: number, data: Partial) => + api.patch(`/pm/schedules/${id}`, data), + deleteSchedule: (id: number) => api.delete(`/pm/schedules/${id}`), + listRecords: ( + params: { + q?: string; + month?: string; + department_id?: number; + asset_id?: number; + schedule_id?: number; + service_mode?: ServiceMode | ""; + status?: ScheduleStatus | ""; + page?: number; + page_size?: number; + } = {} + ) => { + const qs = new URLSearchParams(); + if (params.q) qs.set("q", params.q); + if (params.month) qs.set("month", params.month); + if (params.department_id) qs.set("department_id", String(params.department_id)); + if (params.asset_id) qs.set("asset_id", String(params.asset_id)); + if (params.schedule_id) qs.set("schedule_id", String(params.schedule_id)); + if (params.service_mode) qs.set("service_mode", params.service_mode); + if (params.status) qs.set("status", params.status); + qs.set("page", String(params.page ?? 1)); + qs.set("page_size", String(params.page_size ?? 200)); + return api.get<{ items: PMRecordItem[]; total: number; summary: PMSummary }>( + `/pm/records?${qs.toString()}` + ); + }, + completeRecord: ( + id: number, + data: { completed_date: string; service_details: string; remarks?: string | null } + ) => + api.post<{ completed_record: PMRecordItem; next_record: PMRecordItem }>( + `/pm/records/${id}/complete`, + data + ), + rescheduleRecord: ( + id: number, + data: { rescheduled_to: string; remarks?: string | null } + ) => + api.post<{ rescheduled_record: PMRecordItem; next_record: PMRecordItem }>( + `/pm/records/${id}/reschedule`, + data + ), +}; diff --git a/frontend/src/api/reports.ts b/frontend/src/api/reports.ts new file mode 100644 index 0000000..52661fd --- /dev/null +++ b/frontend/src/api/reports.ts @@ -0,0 +1,143 @@ +import { api } from "./client"; +import type { Role } from "@/lib/permissions"; + +export type ReportKey = + | "monthly-maintenance" + | "monthly-department" + | "daily-visit" + | "breakdown-complaints" + | "pm-compliance" + | "calibration-due" + | "contracts-warranty" + | "demo-equipment"; + +export interface ReportColumn { + key: string; + label: string; +} + +export interface FormulaInfo { + scheduled_hours_per_day: number; + downtime_end_milestone: string; + days_in_month: number; + uptime_formula: string; + downtime_formula: string; +} + +export interface ReportChartPoint { + department: string; + downtime_hours: number; + uptime_hours: number; +} + +export interface ReportPayload { + report_key: ReportKey | string; + title: string; + filters_applied: Record; + formula_info?: FormulaInfo | null; + summary: Record; + columns: ReportColumn[]; + rows: Record[]; + chart_data?: ReportChartPoint[] | null; +} + +export interface ReportMeta { + key: ReportKey; + title: string; + description: string; + category: string; + hiddenForRoles?: Role[]; +} + +export const REPORT_CATALOG: ReportMeta[] = [ + { + key: "monthly-maintenance", + title: "Monthly Maintenance Summary", + description: + "Department-wise uptime vs downtime, clipped breakdown hours, distinct downtime days, and availability %.", + category: "Maintenance & Uptime", + }, + { + key: "monthly-department", + title: "Monthly Department Report", + description: + "Asset health counts, under-repair equipment, outstanding complaints, visit counts, and requirement notes per department.", + category: "Department Operations", + }, + { + key: "daily-visit", + title: "Daily Department Visit Report", + description: + "Daily biomedical round logs, equipment checked, observations, and linked breakdown complaints.", + category: "Department Operations", + hiddenForRoles: ["department_user", "coordinator"], + }, + { + key: "breakdown-complaints", + title: "Breakdown / Complaint Report", + description: + "Full breakdown register with response time, total downtime, ongoing status, action taken, and closure remarks.", + category: "Breakdowns", + }, + { + key: "pm-compliance", + title: "PM Compliance Report", + description: + "Planned vs completed preventive maintenance schedules across in-house and outsourced teams with compliance %.", + category: "Compliance & Schedules", + }, + { + key: "calibration-due", + title: "Calibration Due Report", + description: + "Calibration status, due/completed dates, agencies, certificate numbers, and overdue tracking.", + category: "Compliance & Schedules", + }, + { + key: "contracts-warranty", + title: "AMC / CMC & Warranty Report", + description: + "Active, expiring, expired, and superseded AMC/CMC contracts and equipment warranties with days to expiry.", + category: "Commercial & Coverage", + }, + { + key: "demo-equipment", + title: "Demo Equipment Report", + description: + "Supplier trial equipment register highlighting expected return dates, returned units, and overdue days.", + category: "Commercial & Coverage", + }, +]; + +export type ReportFilterParams = Record; + +function buildQuery(params: ReportFilterParams): string { + const sp = new URLSearchParams(); + for (const [k, v] of Object.entries(params)) { + if (v === undefined || v === "") continue; + sp.set(k, String(v)); + } + const qs = sp.toString(); + return qs ? `?${qs}` : ""; +} + +export function fetchReport(key: ReportKey, params: ReportFilterParams = {}) { + return api.get(`/reports/${key}${buildQuery(params)}`); +} + +export async function exportReport( + key: ReportKey, + format: "xlsx" | "csv", + params: ReportFilterParams = {} +) { + const qs = buildQuery({ ...params, format }); + const { blob } = await api.downloadBlob(`/reports/${key}/export${qs}`); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `${key}.${format}`; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 10_000); +} diff --git a/frontend/src/api/search.ts b/frontend/src/api/search.ts new file mode 100644 index 0000000..ce522bf --- /dev/null +++ b/frontend/src/api/search.ts @@ -0,0 +1,32 @@ +import { api } from "./client"; + +export interface SearchAssetItem { + id: number; + asset_code: string; + name: string; + serial_no: string | null; + department_name: string | null; + status: string; +} + +export interface SearchComplaintItem { + id: number; + complaint_no: string; + asset_code: string | null; + asset_name: string | null; + department_name: string | null; + call_status: string; + priority: string; +} + +export interface GlobalSearchResponse { + assets: SearchAssetItem[]; + complaints: SearchComplaintItem[]; +} + +export const searchApi = { + query: (q: string) => { + const params = new URLSearchParams({ q }); + return api.get(`/search?${params.toString()}`); + }, +}; diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts new file mode 100644 index 0000000..083f211 --- /dev/null +++ b/frontend/src/api/settings.ts @@ -0,0 +1,32 @@ +import { api } from "./client"; + +export type SettingType = "int" | "float" | "bool" | "enum" | "str" | "date_or_empty"; + +export interface SettingItem { + key: string; + value: unknown; + type: SettingType; + label: string; + description: string; + default: unknown; + min?: number | null; + max?: number | null; + options?: string[] | null; +} + +export interface SettingsResponse { + items: SettingItem[]; +} + +export interface DemoDateResponse { + demo_as_of_date: string | null; + effective_today: string; +} + +export const settingsApi = { + getAll: () => api.get("/settings"), + updateAll: (values: Record) => + api.put("/settings", { values }), + setDemoDate: (demo_as_of_date: string | null) => + api.post("/settings/demo-date", { demo_as_of_date }), +}; diff --git a/frontend/src/api/users.ts b/frontend/src/api/users.ts new file mode 100644 index 0000000..e646f81 --- /dev/null +++ b/frontend/src/api/users.ts @@ -0,0 +1,7 @@ +import { api } from "./client"; +import { usersApi } from "./masters"; + +export { usersApi }; + +export const resetPassword = (id: number, new_password: string) => + api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password }); diff --git a/frontend/src/assets/react.svg b/frontend/src/assets/react.svg new file mode 100644 index 0000000..6c87de9 --- /dev/null +++ b/frontend/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/components/AssetFormModal.tsx b/frontend/src/components/AssetFormModal.tsx new file mode 100644 index 0000000..9e9688e --- /dev/null +++ b/frontend/src/components/AssetFormModal.tsx @@ -0,0 +1,541 @@ +import { useState, useEffect, useMemo } from "react"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { z } from "zod"; +import { AlertCircle } from "lucide-react"; +import { Modal } from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { ApiError } from "@/api/client"; +import { + assetsApi, + type AssetItem, + type AssetStatus, + type AssetCriticality, + type AcquisitionMode, + type DepreciationMethod, +} from "@/api/assets"; +import { + departmentsApi, + locationsApi, + categoriesApi, + vendorsApi, +} from "@/api/masters"; + +const assetSchema = z.object({ + asset_code: z.string().trim().min(1, "Asset code is required"), + serial_no: z.string().trim().min(1, "Serial number is required"), + name: z.string().trim().min(1, "Equipment name is required"), + category_id: z.coerce.number().int().min(1, "Select a category"), + department_id: z.coerce.number().int().min(1, "Select a department"), + location_id: z.coerce.number().int().min(1, "Select a location"), + supplier_id: z.string().optional(), + acquisition_mode: z.enum(["purchased", "rented"]), + purchase_value: z.string().optional(), + monthly_rent: z.string().optional(), + useful_life_years: z.string().optional(), + salvage_pct: z.string().optional(), + depreciation_method: z.string().optional(), + purchase_date: z.string().optional(), + installation_date: z.string().optional(), + status: z.enum(["in_service", "under_repair", "out_of_service", "condemned"]), + criticality: z.enum(["critical", "non_critical"]), + requires_calibration: z.boolean(), + insurance_applicable: z.boolean(), + remarks: z.string().optional(), +}); + +type AssetFormValues = z.infer; + +interface AssetFormModalProps { + open: boolean; + onClose: () => void; + editing?: AssetItem | null; + coordinatorOnly?: boolean; +} + +const inputCls = + "w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:text-gray-500"; +const labelCls = "block text-sm font-medium text-gray-700 mb-1"; +const errCls = "text-xs text-red-600 mt-1"; + +export function AssetFormModal({ + open, + onClose, + editing = null, + coordinatorOnly = false, +}: AssetFormModalProps) { + const qc = useQueryClient(); + const [serverError, setServerError] = useState(null); + + const deptsQuery = useQuery({ + queryKey: ["departments", "active-only"], + queryFn: () => departmentsApi.list(false), + enabled: open, + }); + const locsQuery = useQuery({ + queryKey: ["locations", "active-only"], + queryFn: () => locationsApi.list(false), + enabled: open, + }); + const catsQuery = useQuery({ + queryKey: ["categories", "active-only"], + queryFn: () => categoriesApi.list(false), + enabled: open, + }); + const vendorsQuery = useQuery({ + queryKey: ["vendors", "active-only"], + queryFn: () => vendorsApi.list(false), + enabled: open, + }); + + const departments = deptsQuery.data?.items ?? []; + const allLocations = useMemo( + () => locsQuery.data?.items ?? [], + [locsQuery.data?.items] + ); + const categories = useMemo( + () => catsQuery.data?.items ?? [], + [catsQuery.data?.items] + ); + const vendors = vendorsQuery.data?.items ?? []; + + const defaultDeptId = editing?.department_id ?? departments[0]?.id ?? 0; + const defaultLocId = + editing?.location_id ?? + allLocations.find((l) => l.department_id === defaultDeptId)?.id ?? + 0; + + const { + register, + handleSubmit, + watch, + setValue, + reset, + formState: { errors, isSubmitting }, + } = useForm({ + resolver: zodResolver(assetSchema), + defaultValues: { + asset_code: "", + serial_no: "", + name: "", + category_id: 0, + department_id: 0, + location_id: 0, + supplier_id: "", + acquisition_mode: "purchased", + purchase_value: "", + monthly_rent: "", + useful_life_years: "", + salvage_pct: "", + depreciation_method: "", + purchase_date: "", + installation_date: "", + status: "in_service", + criticality: "non_critical", + requires_calibration: false, + insurance_applicable: false, + remarks: "", + }, + }); + + useEffect(() => { + if (!open) return; + setServerError(null); + if (editing) { + reset({ + asset_code: editing.asset_code, + serial_no: editing.serial_no ?? "", + name: editing.name, + category_id: editing.category_id, + department_id: editing.department_id, + location_id: editing.location_id, + supplier_id: editing.supplier_id ? String(editing.supplier_id) : "", + acquisition_mode: (editing.acquisition_mode === "rented" ? "rented" : "purchased") as AcquisitionMode, + purchase_value: editing.purchase_value != null ? String(editing.purchase_value) : "", + monthly_rent: editing.monthly_rent != null ? String(editing.monthly_rent) : "", + useful_life_years: editing.useful_life_years != null ? String(editing.useful_life_years) : "", + salvage_pct: editing.salvage_pct != null ? String(editing.salvage_pct) : "", + depreciation_method: editing.depreciation_method ?? "", + purchase_date: editing.purchase_date ?? "", + installation_date: editing.installation_date ?? "", + status: editing.status, + criticality: editing.criticality, + requires_calibration: editing.requires_calibration, + insurance_applicable: editing.insurance_applicable, + remarks: editing.remarks ?? "", + }); + } else { + reset({ + asset_code: "", + serial_no: "", + name: "", + category_id: categories[0]?.id ?? 0, + department_id: defaultDeptId, + location_id: defaultLocId, + supplier_id: "", + acquisition_mode: "purchased", + purchase_value: "", + monthly_rent: "", + useful_life_years: "", + salvage_pct: "", + depreciation_method: "", + purchase_date: "", + installation_date: "", + status: "in_service", + criticality: "non_critical", + requires_calibration: false, + insurance_applicable: false, + remarks: "", + }); + } + }, [open, editing, categories, defaultDeptId, defaultLocId, reset]); + + const watchedDeptId = Number(watch("department_id")); + const filteredLocations = useMemo( + () => allLocations.filter((l) => l.department_id === watchedDeptId), + [allLocations, watchedDeptId] + ); + + useEffect(() => { + if (!open || coordinatorOnly) return; + const currentLoc = Number(watch("location_id")); + if ( + watchedDeptId > 0 && + filteredLocations.length > 0 && + !filteredLocations.some((l) => l.id === currentLoc) + ) { + setValue("location_id", filteredLocations[0].id); + } else if (watchedDeptId > 0 && filteredLocations.length === 0 && currentLoc !== 0) { + setValue("location_id", 0); + } + }, [watchedDeptId, filteredLocations, open, coordinatorOnly, setValue, watch]); + + async function onSubmit(values: AssetFormValues) { + setServerError(null); + try { + if (editing && coordinatorOnly) { + await assetsApi.update(editing.id, { + requires_calibration: values.requires_calibration, + insurance_applicable: values.insurance_applicable, + remarks: values.remarks?.trim() || null, + }); + } else { + const payload = { + asset_code: values.asset_code.trim(), + serial_no: values.serial_no.trim(), + name: values.name.trim(), + category_id: values.category_id, + department_id: values.department_id, + location_id: values.location_id, + supplier_id: values.supplier_id ? Number(values.supplier_id) : null, + acquisition_mode: values.acquisition_mode as AcquisitionMode, + purchase_value: + values.purchase_value && values.purchase_value.trim() !== "" + ? Number(values.purchase_value) + : null, + monthly_rent: + values.monthly_rent && values.monthly_rent.trim() !== "" + ? Number(values.monthly_rent) + : null, + useful_life_years: + values.useful_life_years && values.useful_life_years.trim() !== "" + ? Math.trunc(Number(values.useful_life_years)) + : null, + salvage_pct: + values.salvage_pct && values.salvage_pct.trim() !== "" + ? Number(values.salvage_pct) + : null, + depreciation_method: + values.depreciation_method && values.depreciation_method.trim() !== "" + ? (values.depreciation_method as DepreciationMethod) + : null, + purchase_date: values.purchase_date || null, + installation_date: values.installation_date || null, + status: values.status as AssetStatus, + criticality: values.criticality as AssetCriticality, + requires_calibration: values.requires_calibration, + insurance_applicable: values.insurance_applicable, + remarks: values.remarks?.trim() || null, + }; + if (editing) { + await assetsApi.update(editing.id, payload); + } else { + await assetsApi.create(payload); + } + } + + await qc.invalidateQueries({ queryKey: ["assets"] }); + if (editing) { + await qc.invalidateQueries({ queryKey: ["asset-overview", editing.id] }); + } + onClose(); + } catch (err) { + setServerError(err instanceof ApiError ? err.detail : "Failed to save asset."); + } + } + + return ( + !o && onClose()} + title={editing ? `Edit Asset — ${editing.asset_code}` : "Add New Asset"} + className="max-w-2xl" + > + {coordinatorOnly && ( +
+ Coordinator permissions: only calibration requirement, insurance applicability, and remarks can be edited. +
+ )} + + {serverError && ( +
+ + {serverError} +
+ )} + +
+
+
+ + + {errors.asset_code &&

{errors.asset_code.message}

} +
+
+ + + {errors.serial_no &&

{errors.serial_no.message}

} +
+
+ +
+
+ + + {errors.name &&

{errors.name.message}

} +
+
+ + + {errors.category_id &&

{errors.category_id.message}

} +
+
+ +
+
+ + + {errors.department_id &&

{errors.department_id.message}

} +
+
+ + + {errors.location_id &&

{errors.location_id.message}

} +
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+ + +
+ +
+ +