diff --git a/.env.example b/.env.example index f21a9a1..562c72b 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,20 @@ +# Database connection URL (SQLite default persists under backend/data/) DATABASE_URL=sqlite:///./data/ams.db + +# JWT signing secret (replace with a 32+ character random string in production) SECRET_KEY=change-me-in-production-use-a-32-char-random-string + +# Directory for uploaded attachments (PDF, JPG, PNG) UPLOAD_DIR=./data/uploads + +# Application display & scheduler timezone TIMEZONE=Asia/Kolkata + +# JWT access token expiration duration in minutes (default: 480 = 8 hours) +ACCESS_TOKEN_EXPIRE_MINUTES=480 + +# JWT signing algorithm +ALGORITHM=HS256 + +# Maximum allowed attachment file size in megabytes +MAX_UPLOAD_SIZE_MB=10 diff --git a/README.md b/README.md index 3f3dbb6..5b4973e 100644 --- a/README.md +++ b/README.md @@ -37,18 +37,37 @@ make dev ### Run tests ```bash -make test -# Or directly: +# Backend cd backend .venv/Scripts/python -m pytest tests/ -v +# Or via Make: make test + +# Frontend (build + Vitest) +cd frontend +npm run build +npm test ``` ### Seed demo data ```bash cd backend .venv/Scripts/python -m app.seed.seed +# Or via Make: make seed ``` +### Docker Compose (Production-style local container run) +```bash +cp .env.example .env +docker compose up --build +``` +- Frontend (Nginx + `/api` reverse proxy): http://localhost:5173 +- Backend API & Swagger docs: http://localhost:8000/docs +- SQLite DB and uploads persist under `./backend/data` (mounted to `/app/data`). + +## Documentation & Walkthroughs +- [10-Minute Demo Script](docs/DEMO_SCRIPT.md) +- [Acceptance Checklist (Proposal §10)](docs/ACCEPTANCE_CHECKLIST.md) + ## Demo Accounts | Email | Password | Role | |---|---|---| @@ -58,11 +77,12 @@ cd backend | mgmt@poona.demo | Demo@123 | Management | | coord@poona.demo | Demo@123 | Coordinator | -## What exists now (Phase 7) -- Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules -- JWT authentication (`/api/auth/login`, `/api/auth/me`), RBAC permission matrix for 5 roles, and Quick Demo Login -- Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users) +## 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, and audit logging - 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 @@ -77,10 +97,10 @@ cd backend - Reusable `AssetPicker` (`/api/assets/lookup`) with warranty/condemned status badges - Secure Document Attachments (`/api/attachments`: JPG/PNG/PDF validation with magic-byte check, 10 MB limit, authenticated preview/download, role-based upload/delete) - Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data -- React + TypeScript frontend app shell with role-filtered sidebar, route guards, DataTable, and Tailwind CSS + shadcn/ui -- Makefile for common tasks +- Responsive React + TypeScript frontend app shell (mobile slide-over navigation, accessible ``, role-filtered sidebar, route guards, DataTable, Tailwind CSS + shadcn/ui) +- Docker packaging (`docker-compose.yml`, `backend/Dockerfile`, `frontend/Dockerfile`, `frontend/nginx.conf`, `.env.example`) & `Makefile` -## Modules (all phases) +## Modules (Phases 0–8 Complete) Phase 0: Scaffold | Phase 1: Auth & Masters | Phase 2: Assets | Phase 3: Complaints Phase 4: PM & Calibration | Phase 5: Contracts, Warranty, Insurance, Demo, Visits -Phase 6: Notifications & Dashboard | Phase 7: Reports | Phase 8: Polish +Phase 6: Notifications & Dashboard | Phase 7: Reports | Phase 8: Polish, Search, Audit Log, Packaging & Docs 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/main.py b/backend/app/main.py index feda783..6835042 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -14,6 +14,7 @@ from .models import Base from .routers import ( assets, attachments, + audit, auth, calibration, complaints, @@ -26,6 +27,7 @@ from .routers import ( notifications, pm, reports, + search, settings, users, visits, @@ -126,3 +128,5 @@ app.include_router(visits.router, prefix="/api") app.include_router(notifications.router, prefix="/api") app.include_router(dashboard.router, prefix="/api") app.include_router(reports.router, prefix="/api") +app.include_router(search.router, prefix="/api") +app.include_router(audit.router, prefix="/api") diff --git a/backend/app/models/assets.py b/backend/app/models/assets.py index bd33212..3585b4c 100644 --- a/backend/app/models/assets.py +++ b/backend/app/models/assets.py @@ -13,14 +13,14 @@ class Asset(Base): asset_code: Mapped[str] = mapped_column(String(60), unique=True, index=True, nullable=False) serial_no: Mapped[str] = mapped_column(String(100), index=True, nullable=False) name: Mapped[str] = mapped_column(String(200), nullable=False) - category_id: Mapped[int] = mapped_column(ForeignKey("categories.id"), nullable=False) - department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False) - location_id: Mapped[int] = mapped_column(ForeignKey("locations.id"), nullable=False) + category_id: Mapped[int] = mapped_column(ForeignKey("categories.id"), index=True, nullable=False) + department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False) + location_id: Mapped[int] = mapped_column(ForeignKey("locations.id"), index=True, nullable=False) supplier_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True) purchase_value: Mapped[Optional[float]] = mapped_column(Float, nullable=True) purchase_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) installation_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) - status: Mapped[str] = mapped_column(String(40), default="in_service", nullable=False) + status: Mapped[str] = mapped_column(String(40), default="in_service", index=True, nullable=False) criticality: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False) requires_calibration: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) insurance_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) @@ -40,11 +40,11 @@ class Contract(Base): __tablename__ = "contracts" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) - asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False) + asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False) contract_type: Mapped[str] = mapped_column(String(20), nullable=False) provider_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False) - start_date: Mapped[date] = mapped_column(Date, nullable=False) - end_date: Mapped[date] = mapped_column(Date, nullable=False) + start_date: Mapped[date] = mapped_column(Date, index=True, nullable=False) + end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False) coverage_period_text: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) renewed_from_id: Mapped[Optional[int]] = mapped_column(ForeignKey("contracts.id"), nullable=True) is_superseded: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) @@ -62,10 +62,10 @@ class Warranty(Base): __tablename__ = "warranties" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) - asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False) + asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False) duration_months: Mapped[int] = mapped_column(Integer, nullable=False) - start_date: Mapped[date] = mapped_column(Date, nullable=False) - end_date: Mapped[date] = mapped_column(Date, nullable=False) + start_date: Mapped[date] = mapped_column(Date, index=True, nullable=False) + end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False) provider_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True) remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False) @@ -81,11 +81,11 @@ class InsurancePolicy(Base): __tablename__ = "insurance_policies" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) - asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False) + asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False) insurer_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False) policy_no: Mapped[str] = mapped_column(String(100), nullable=False) - start_date: Mapped[date] = mapped_column(Date, nullable=False) - end_date: Mapped[date] = mapped_column(Date, nullable=False) + start_date: Mapped[date] = mapped_column(Date, index=True, nullable=False) + end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False) coverage_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True) remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False) diff --git a/backend/app/models/complaints.py b/backend/app/models/complaints.py index e8832c2..ec6da21 100644 --- a/backend/app/models/complaints.py +++ b/backend/app/models/complaints.py @@ -11,23 +11,23 @@ class Complaint(Base): id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) complaint_no: Mapped[str] = mapped_column(String(60), unique=True, index=True, nullable=False) - asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False) + asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False) description: Mapped[str] = mapped_column(Text, nullable=False) breakdown_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True) priority: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False) notes: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - registered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False) + registered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False) registered_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False) received_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False) received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) - assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True) + assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True) assigned_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) attended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True) attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) restored_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) closed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True) closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) - call_status: Mapped[str] = mapped_column(String(30), default="open", nullable=False) + call_status: Mapped[str] = mapped_column(String(30), default="open", index=True, nullable=False) closure_remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True) action_taken: Mapped[Optional[str]] = mapped_column(Text, nullable=True) root_cause: Mapped[Optional[str]] = mapped_column(Text, nullable=True) diff --git a/backend/app/models/maintenance.py b/backend/app/models/maintenance.py index b939a8b..a9c8f19 100644 --- a/backend/app/models/maintenance.py +++ b/backend/app/models/maintenance.py @@ -32,9 +32,9 @@ class CalibrationRecord(Base): __tablename__ = "calibration_records" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) - asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False) - plan_id: Mapped[int] = mapped_column(ForeignKey("calibration_plans.id"), nullable=False) - due_date: Mapped[date] = mapped_column(Date, nullable=False) + asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False) + plan_id: Mapped[int] = mapped_column(ForeignKey("calibration_plans.id"), index=True, nullable=False) + due_date: Mapped[date] = mapped_column(Date, index=True, nullable=False) completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) agency_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True) certificate_no: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) @@ -77,9 +77,9 @@ class PMRecord(Base): __tablename__ = "pm_records" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) - schedule_id: Mapped[int] = mapped_column(ForeignKey("pm_schedules.id"), nullable=False) - asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False) - planned_date: Mapped[date] = mapped_column(Date, nullable=False) + schedule_id: Mapped[int] = mapped_column(ForeignKey("pm_schedules.id"), index=True, nullable=False) + asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False) + planned_date: Mapped[date] = mapped_column(Date, index=True, nullable=False) completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) # Only "completed" or "rescheduled" is persisted; upcoming/due/overdue are computed at read time. status: Mapped[Optional[str]] = mapped_column(String(30), nullable=True) diff --git a/backend/app/models/operations.py b/backend/app/models/operations.py index 3877511..1be436b 100644 --- a/backend/app/models/operations.py +++ b/backend/app/models/operations.py @@ -28,10 +28,10 @@ class DemoEquipment(Base): name: Mapped[str] = mapped_column(String(200), nullable=False) equipment_type: Mapped[str] = mapped_column(String(100), nullable=False) supplier_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False) - department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False) + department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False) location_id: Mapped[Optional[int]] = mapped_column(ForeignKey("locations.id"), nullable=True) start_date: Mapped[date] = mapped_column(Date, nullable=False) - expected_return_date: Mapped[date] = mapped_column(Date, nullable=False) + expected_return_date: Mapped[date] = mapped_column(Date, index=True, nullable=False) actual_return_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False) @@ -48,9 +48,9 @@ class DepartmentVisit(Base): __tablename__ = "department_visits" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) - department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False) + department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False) visited_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False) - visit_date: Mapped[date] = mapped_column(Date, nullable=False) + visit_date: Mapped[date] = mapped_column(Date, index=True, nullable=False) observations: Mapped[Optional[str]] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False) created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True) diff --git a/backend/app/models/system.py b/backend/app/models/system.py index a9c4e9f..7655eca 100644 --- a/backend/app/models/system.py +++ b/backend/app/models/system.py @@ -10,8 +10,8 @@ class Attachment(Base): __tablename__ = "attachments" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) - entity_type: Mapped[str] = mapped_column(String(60), nullable=False) - entity_id: Mapped[int] = mapped_column(Integer, nullable=False) + entity_type: Mapped[str] = mapped_column(String(60), index=True, nullable=False) + entity_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False) original_name: Mapped[str] = mapped_column(String(255), nullable=False) stored_name: Mapped[str] = mapped_column(String(255), nullable=False) mime_type: Mapped[str] = mapped_column(String(120), nullable=False) @@ -24,7 +24,7 @@ class Notification(Base): __tablename__ = "notifications" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) - type: Mapped[str] = mapped_column(String(60), nullable=False) + type: Mapped[str] = mapped_column(String(60), index=True, nullable=False) severity: Mapped[str] = mapped_column(String(20), nullable=False) title: Mapped[str] = mapped_column(String(200), nullable=False) message: Mapped[str] = mapped_column(Text, nullable=False) @@ -34,7 +34,7 @@ class Notification(Base): target_role: Mapped[Optional[str]] = mapped_column(String(50), nullable=True) target_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True) dedupe_key: Mapped[str] = mapped_column(String(200), unique=True, nullable=False) - created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False) class NotificationRead(Base): @@ -53,9 +53,9 @@ class AuditLog(Base): __tablename__ = "audit_logs" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) - entity_type: Mapped[str] = mapped_column(String(60), nullable=False) - entity_id: Mapped[int] = mapped_column(Integer, nullable=False) + entity_type: Mapped[str] = mapped_column(String(60), index=True, nullable=False) + entity_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False) action: Mapped[str] = mapped_column(String(50), nullable=False) changes_json: Mapped[str] = mapped_column(Text, nullable=False) - by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True) - at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False) + by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True) + at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False) diff --git a/backend/app/routers/__init__.py b/backend/app/routers/__init__.py index a16718c..8225d12 100644 --- a/backend/app/routers/__init__.py +++ b/backend/app/routers/__init__.py @@ -1,6 +1,7 @@ from . import ( assets, attachments, + audit, auth, calibration, complaints, @@ -13,6 +14,7 @@ from . import ( notifications, pm, reports, + search, settings, users, visits, @@ -22,6 +24,7 @@ from . import ( __all__ = [ "assets", "attachments", + "audit", "auth", "calibration", "complaints", @@ -34,6 +37,7 @@ __all__ = [ "notifications", "pm", "reports", + "search", "settings", "users", "visits", 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 index 8f6ffba..9ebda43 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -1,7 +1,11 @@ -from fastapi import APIRouter, Depends, HTTPException, status +from collections import defaultdict, deque +import threading +import time +from fastapi import APIRouter, Depends, HTTPException, Request, status from sqlalchemy.orm import Session, joinedload from ..core.db import get_db from ..core.deps import get_current_user +from ..core.exceptions import CodedHTTPException from ..core.security import create_access_token, verify_password from ..models.masters import User from ..schemas.auth import LoginRequest, TokenResponse, UserOut @@ -9,6 +13,34 @@ from ..services.settings_service import get_demo_as_of_date router = APIRouter(prefix="/auth", tags=["auth"]) +MAX_LOGIN_ATTEMPTS = 15 +LOGIN_WINDOW_SECONDS = 60.0 +_login_attempts: dict[str, deque[float]] = defaultdict(deque) +_rate_limit_lock = threading.Lock() + + +def reset_login_rate_limiter() -> None: + """Clear sliding-window login attempt counters (used in tests).""" + with _rate_limit_lock: + _login_attempts.clear() + + +def _enforce_login_rate_limit(client_ip: str, email_norm: str) -> None: + now = time.monotonic() + cutoff = now - LOGIN_WINDOW_SECONDS + key = f"{client_ip}:{email_norm}" + with _rate_limit_lock: + attempts = _login_attempts[key] + while attempts and attempts[0] <= cutoff: + attempts.popleft() + if len(attempts) >= MAX_LOGIN_ATTEMPTS: + raise CodedHTTPException( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + detail="Too many login attempts. Please wait a minute.", + code="RATE_LIMITED", + ) + attempts.append(now) + def _build_user_out(user: User, db: Session) -> UserOut: return UserOut( @@ -24,8 +56,10 @@ def _build_user_out(user: User, db: Session) -> UserOut: @router.post("/login", response_model=TokenResponse) -def login(payload: LoginRequest, db: Session = Depends(get_db)): +def login(payload: LoginRequest, request: Request, db: Session = Depends(get_db)): email_norm = payload.email.strip().lower() + client_ip = request.client.host if request.client else "unknown" + _enforce_login_rate_limit(client_ip, email_norm) user = ( db.query(User) .options(joinedload(User.department)) diff --git a/backend/app/routers/search.py b/backend/app/routers/search.py new file mode 100644 index 0000000..751f833 --- /dev/null +++ b/backend/app/routers/search.py @@ -0,0 +1,84 @@ +from fastapi import APIRouter, Depends, Query +from sqlalchemy import or_ +from sqlalchemy.orm import Session, joinedload + +from ..core.db import get_db +from ..core.deps import get_current_user +from ..models import Asset, Complaint, User +from ..services.permissions import Role + +router = APIRouter(prefix="/search", tags=["search"]) + + +@router.get("") +def global_search( + q: str = Query(..., min_length=1), + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +): + term = q.strip() + if not term: + return {"assets": [], "complaints": []} + + pattern = f"%{term}%" + is_dept_scoped = current_user.role == Role.department_user.value + + asset_q = db.query(Asset).options(joinedload(Asset.department)).filter( + or_( + Asset.asset_code.ilike(pattern), + Asset.name.ilike(pattern), + Asset.serial_no.ilike(pattern), + ) + ) + if is_dept_scoped: + asset_q = asset_q.filter(Asset.department_id == current_user.department_id) + assets = asset_q.order_by(Asset.asset_code.asc()).limit(8).all() + + complaint_q = ( + db.query(Complaint) + .join(Asset, Complaint.asset_id == Asset.id) + .options(joinedload(Complaint.asset).joinedload(Asset.department)) + .filter( + or_( + Complaint.complaint_no.ilike(pattern), + Complaint.description.ilike(pattern), + Asset.asset_code.ilike(pattern), + Asset.name.ilike(pattern), + ) + ) + ) + if is_dept_scoped: + complaint_q = complaint_q.filter(Asset.department_id == current_user.department_id) + complaints = ( + complaint_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc()) + .limit(8) + .all() + ) + + return { + "assets": [ + { + "id": a.id, + "asset_code": a.asset_code, + "name": a.name, + "serial_no": a.serial_no, + "department_name": a.department.name if a.department else "—", + "status": a.status, + } + for a in assets + ], + "complaints": [ + { + "id": c.id, + "complaint_no": c.complaint_no, + "asset_code": c.asset.asset_code if c.asset else "—", + "asset_name": c.asset.name if c.asset else "—", + "department_name": ( + c.asset.department.name if c.asset and c.asset.department else "—" + ), + "call_status": c.call_status, + "priority": c.priority, + } + for c in complaints + ], + } diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 7ec5038..57de051 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -8,6 +8,7 @@ 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}) @@ -111,3 +112,10 @@ def client(db): 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_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/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..15a16d3 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,26 @@ +services: + backend: + build: ./backend + container_name: poona-ams-backend + ports: + - "8000:8000" + environment: + DATABASE_URL: ${DATABASE_URL:-sqlite:////app/data/ams.db} + SECRET_KEY: ${SECRET_KEY:-change-me-in-production-use-a-32-char-random-string} + UPLOAD_DIR: ${UPLOAD_DIR:-/app/data/uploads} + TIMEZONE: ${TIMEZONE:-Asia/Kolkata} + ACCESS_TOKEN_EXPIRE_MINUTES: ${ACCESS_TOKEN_EXPIRE_MINUTES:-480} + ALGORITHM: ${ALGORITHM:-HS256} + MAX_UPLOAD_SIZE_MB: ${MAX_UPLOAD_SIZE_MB:-10} + volumes: + - ./backend/data:/app/data + restart: unless-stopped + + frontend: + build: ./frontend + container_name: poona-ams-frontend + ports: + - "5173:80" + depends_on: + - backend + restart: unless-stopped diff --git a/docs/ACCEPTANCE_CHECKLIST.md b/docs/ACCEPTANCE_CHECKLIST.md new file mode 100644 index 0000000..d883969 --- /dev/null +++ b/docs/ACCEPTANCE_CHECKLIST.md @@ -0,0 +1,12 @@ +# Poona Hospital AMS — Acceptance Checklist (Proposal §10 Mapping) + +| # | Acceptance Criterion | Automated Test Coverage | Manual Verification Steps | +|---|---|---|---| +| **1** | **Auth, 5-Role RBAC, Masters & Settings** (`system_admin`, `biomedical`, `department_user`, `management`, `coordinator`, JWT auth, login rate limiting, configurable settings, audit logs) | `backend/tests/test_auth_and_permissions.py`
`backend/tests/test_phase8_polish.py` (`test_audit_logs_rbac_and_filters`, `test_login_rate_limiter_429_and_reset`)
`frontend/src/test/login.test.tsx`
`frontend/src/test/permissions.test.ts`
`frontend/src/test/smoke.test.tsx`
`frontend/src/test/phase8-polish.test.tsx` | Log in with all 5 demo accounts (`Demo@123`), confirm role-filtered sidebar items, test `/masters` & `/settings` CRUD as `admin@poona.demo`, confirm `/audit-logs` returns `403` for non-admins, and trigger >15 rapid failed logins to observe `429`. | +| **2** | **Asset Register, Global Quick Search & Secure Attachments** (unique `asset_code`, department scoping, coordinator edit restrictions, `AssetPicker`, `/api/search`, JPG/PNG/PDF magic-byte + 10 MB checks) | `backend/tests/test_assets_and_attachments.py`
`backend/tests/test_phase8_polish.py` (`test_global_search_grouped_and_department_scoped`)
`frontend/src/test/asset-picker.test.tsx`
`frontend/src/test/attachments.test.tsx`
`frontend/src/test/phase8-polish.test.tsx` | Create/edit an asset on `/assets`, confirm duplicate code returns `409`, verify `dept@poona.demo` sees ICU assets only, search in TopBar to jump to asset/complaint detail, and upload/preview/delete attachments on `/assets/:id`. | +| **3** | **Breakdown & Complaint Workflow + Ist Downtime Calculation** (sequential `complaint_no`, response time, `clip_downtime_to_month`, assign/attend/restore/close/reopen syncing `Asset.status`, role-gated technical fields) | `backend/tests/test_complaints.py`
`backend/tests/test_time_utils.py`
`frontend/src/test/complaint-detail.test.tsx` | Raise a complaint via `AssetPicker`, verify `dept@poona.demo` sees the Technical/CE/Spares read-only lock, complete the repair workflow as `bio@poona.demo`, and verify `Asset.status` returns to `in_service`. | +| **4** | **Preventive Maintenance & Calibration Schedules** (in-house & outsourced PM, dynamic `upcoming`/`due`/`overdue` vs `effective_today()`, clamped `add_months`, calibration approval gate, certificate upload) | `backend/tests/test_pm_and_calibration.py`
`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`/`coord@poona.demo` can approve, and upload calibration certificates. | +| **5** | **Contracts, Warranties, Insurance, Demo Equipment & Department Visits** (contract renewal superseding & history, warranty/insurance expiry chips, `InsuranceDrawer`, demo return tracking, visit `403` for `department_user`/`coordinator`) | `backend/tests/test_phase5_modules.py`
`frontend/src/test/phase5-modules.test.tsx` | Renew a contract on `/contracts` and check history chain, open `InsuranceDrawer` from `AssetDetailPage`, mark a demo equipment returned on `/demo-equipment`, and log a multi-asset visit on `/visits` as `bio@poona.demo`. | +| **6** | **Automated Alert Engine, `06:00 Asia/Kolkata` Scheduler & Notifications** (7 alert types, dedupe keys, per-user read state, TopBar bell polling, `CalibrationReminderModal`, Demo Clock `demo_as_of_date`) | `backend/tests/test_notifications_and_dashboard.py`
`frontend/src/test/phase6-modules.test.tsx` | Advance TopBar Demo Clock (+20 days) as `admin@poona.demo`, run alert check in `/settings`, confirm new notifications appear without duplicates on second run, mark read per user, and check login reminder pop-up. | +| **7** | **Hospital Operations Dashboard** (role-aware department scope banner, 7 clickable KPI cards, 4 Recharts charts, Needs Attention & Recent Complaints) | `backend/tests/test_notifications_and_dashboard.py` (`test_dashboard_summary_role_scoping_and_charts`)
`frontend/src/test/phase6-modules.test.tsx` | Compare `/` as `mgmt@poona.demo` (hospital-wide) vs `dept@poona.demo` (ICU-scoped) and verify KPI navigation and chart tooltips. | +| **8** | **8 Operational Reports, Excel/CSV Exports & A4 Print** (8 report keys, 3-complaint downtime reconciliation, `daily-visit` RBAC `403`, openpyxl `.xlsx` & UTF-8 BOM `.csv` exports, `@media print`) | `backend/tests/test_reports.py`
`frontend/src/test/reports.test.tsx` | Open `/reports`, verify `daily-visit` is hidden/`403` for `dept@poona.demo` & `coord@poona.demo`, inspect Monthly Maintenance `"How this is calculated"` formula popover, download `.xlsx`/`.csv`, and open Print Preview (A4 landscape). | diff --git a/docs/DEMO_SCRIPT.md b/docs/DEMO_SCRIPT.md new file mode 100644 index 0000000..236dd6c --- /dev/null +++ b/docs/DEMO_SCRIPT.md @@ -0,0 +1,60 @@ +# Poona Hospital AMS — 10-Minute End-to-End Demo Script + +**Prerequisites**: +1. Run `python -m app.seed.seed` inside `backend/` to load realistic hospital demo data (60 assets, 30 complaints, 45 PM schedules, 20 calibration plans, 35 contracts, 20 warranties, 25 insurance policies, 3 demo items, 12 department visits, and 26 alerts). +2. Start backend (`uvicorn app.main:app --port 8000`) and frontend (`npm run dev` on `http://localhost:5173`), or run `docker compose up --build`. +3. All demo accounts use password **`Demo@123`**: + - **System Admin**: `admin@poona.demo` + - **Biomedical Engineer**: `bio@poona.demo` + - **Department User (ICU)**: `dept@poona.demo` + - **Management**: `mgmt@poona.demo` + - **Coordinator**: `coord@poona.demo` + +--- + +## Step 1 — Login, Role Overview & Calibration Pop-up (1 min) +1. Open `http://localhost:5173/login`. Use Quick Demo Login or sign in as **Biomedical** (`bio@poona.demo` / `Demo@123`). +2. Observe the **Calibration Reminder Pop-up** (`CalibrationReminderModal`) surfacing upcoming/due/overdue calibrations once per login. Click **Go to Calibration** or dismiss it. +3. Point out the role-filtered sidebar (no Masters/Settings/Audit Log for Biomedical). + +## Step 2 — Hospital Operations Dashboard & Global Quick Search (1 min) +1. On `/` (`DashboardPage`), review the 7 clickable KPI cards, the 4 Recharts visualizations (Complaints by Status, Complaints by Department, 6-Month Downtime Trend, PM Planned vs Completed), **Needs Attention**, and **Recent Complaints**. +2. In the TopBar search box, type `PHRC` or `Ventilator`. Observe the grouped **Assets** and **Complaints** dropdown; click an asset to jump directly to `/assets/:id`. + +## Step 3 — Asset Register, 8-Tab Detail & Insurance Drawer (1 min) +1. Navigate to `/assets` and open an ICU asset (`/assets/:id`). +2. Walk through the tabs (**Overview**, **Contracts**, **Warranty**, **Insurance**, **PM**, **Calibration**, **Complaints**, **Documents**). +3. Click **View Insurance** to slide open `InsuranceDrawer` showing policy coverage in INR and attached policy PDF. + +## Step 4 — Breakdown Complaint Lifecycle & Department Scoping (1.5 min) +1. Sign out and log in as **Department User (ICU)** (`dept@poona.demo` / `Demo@123`). + - Notice the ICU-scoped dashboard banner and asset/complaint lists limited to ICU. + - Click **Raise Complaint** (`/complaints`), select an ICU asset using `AssetPicker` (note warranty/coverage badge), enter a breakdown description, attach an image/PDF, and submit. + - Open a complaint detail (`/complaints/:id`) and point out the **read-only lock banner** on the Technical / CE / Spares section (`FORBIDDEN_TECHNICAL_FIELDS` for non-biomedical/admin roles). +2. Switch to **Biomedical** (`bio@poona.demo`), open the newly raised complaint, assign/attend/restore it, enter technical action & spares, and close it with closure remarks—confirm `Asset.status` syncs back to `in_service` and downtime is calculated in IST. + +## Step 5 — Preventive Maintenance Table & Calendar Views (1 min) +1. Open `/pm` (`PMPage`). Review the KPI strip and toggle between **Table View** and the **7-column Mon–Sun Month Calendar View**. +2. Complete a due PM item (auto-advances next cycle using clamped `add_months`) or reschedule an upcoming PM item. + +## Step 6 — Calibration Plan Approval Gate (1 min) +1. Open `/calibration` (`CalibrationPage`) as **Biomedical** (`bio@poona.demo`). Note that creating/completing calibrations (with certificate PDF upload) is enabled, whereas frequency approval controls are gated (`FORBIDDEN_CALIBRATION_APPROVAL`). +2. Switch to **Management** (`mgmt@poona.demo`) or **Coordinator** (`coord@poona.demo`) to approve a calibration plan's frequency. + +## Step 7 — Contracts Renewal Chain, Warranties, Demo Equipment & Visits (1 min) +1. Open `/contracts` (`/contracts`) and renew an expiring AMC/CMC contract—observe the superseded badge on the prior contract and the intact renewal history chain. +2. Open `/demo-equipment` to view active vs overdue trial equipment and log a return. +3. Open `/visits` as **Biomedical** (`bio@poona.demo`) to review/log a department round linked to multiple assets and complaints; verify `dept@poona.demo` / `coord@poona.demo` cannot access `/visits`. + +## Step 8 — Demo Clock ("As of Date") & Live Alert Engine (1 min) +1. Log in as **System Admin** (`admin@poona.demo`). +2. Use the TopBar **"As of Date"** Demo Clock to advance the date by +20 days. +3. Click **Run alert check now** in `/settings` (or `/notifications`), watch new deduplicated notifications appear in the TopBar bell counter and `/notifications` inbox, then reset Demo Date back to real time. + +## Step 9 — 8 Operational Reports, Formula Transparency & Excel/CSV/Print (1 min) +1. Open `/reports` (`ReportsPage`) and click **Monthly Maintenance Summary** (`/reports/monthly-maintenance`). +2. Inspect the **"How this is calculated"** formula popover (`scheduled_hours_per_day`, `downtime_end_milestone`, `clip_downtime_to_month`), Recharts BarChart/PieChart, export `.xlsx` and `.csv`, and trigger **Print (A4)** preview. + +## Step 10 — Audit Log Viewer & Rate-Limit Protection (0.5 min) +1. As **System Admin** (`admin@poona.demo`), open `/audit-logs` (`AuditLogsPage`) to filter historical entity mutations by Entity Type, User, Action, Date Range, and search query, and inspect the JSON diff modal. +2. Confirm `/audit-logs` is restricted to `system_admin` only (`403` for other roles) and `POST /api/auth/login` enforces sliding-window rate limiting (`429 RATE_LIMITED`). 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/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/src/App.tsx b/frontend/src/App.tsx index 843fb80..d6762d5 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -21,6 +21,7 @@ import { DashboardPage } from "@/pages/DashboardPage"; import { NotificationsPage } from "@/pages/NotificationsPage"; import { ReportsPage } from "@/pages/ReportsPage"; import { ReportDetailPage } from "@/pages/ReportDetailPage"; +import { AuditLogsPage } from "@/pages/AuditLogsPage"; import { ToastProvider } from "@/components/ToastProvider"; import { useAuthStore } from "@/hooks/useAuth"; import { can, type Capability } from "@/lib/permissions"; @@ -110,6 +111,14 @@ function AppRoutes() { } /> + + + + } + /> { + 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/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/components/ConfirmDialog.tsx b/frontend/src/components/ConfirmDialog.tsx new file mode 100644 index 0000000..fd87828 --- /dev/null +++ b/frontend/src/components/ConfirmDialog.tsx @@ -0,0 +1,69 @@ +import { AlertTriangle } from "lucide-react"; +import { Modal } from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; + +export interface ConfirmDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + title: string; + message: string; + confirmLabel?: string; + cancelLabel?: string; + variant?: "danger" | "default"; + loading?: boolean; + onConfirm: () => void | Promise; +} + +export function ConfirmDialog({ + open, + onOpenChange, + title, + message, + confirmLabel = "Confirm", + cancelLabel = "Cancel", + variant = "danger", + loading = false, + onConfirm, +}: ConfirmDialogProps) { + return ( + { + if (!loading) onOpenChange(next); + }} + title={title} + description={message} + className="max-w-md" + > +
+ {variant === "danger" && ( +
+ + This action cannot be undone. +
+ )} + +
+ + +
+
+
+ ); +} diff --git a/frontend/src/components/layout/AppShell.tsx b/frontend/src/components/layout/AppShell.tsx index 5614ea8..80dbf7c 100644 --- a/frontend/src/components/layout/AppShell.tsx +++ b/frontend/src/components/layout/AppShell.tsx @@ -1,14 +1,20 @@ +import { useState } from "react"; import { Outlet } from "react-router-dom"; import { Sidebar } from "./Sidebar"; import { TopBar } from "./TopBar"; import { CalibrationReminderModal } from "@/components/CalibrationReminderModal"; export function AppShell() { + const [mobileNavOpen, setMobileNavOpen] = useState(false); + return (
- + setMobileNavOpen(false)} + />
- + setMobileNavOpen(true)} />
diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index bda22fb..eb47250 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -12,8 +12,10 @@ import { BarChart3, Bell, Database, + History, Settings, ChevronRight, + X, type LucideIcon, } from "lucide-react"; import { cn } from "@/lib/utils"; @@ -71,10 +73,16 @@ const NAV_ITEMS: NavItem[] = [ }, { to: "/notifications", label: "Notifications", icon: Bell }, { to: "/masters", label: "Masters", icon: Database, capability: "manage_admin" }, + { to: "/audit-logs", label: "Audit Log", icon: History, capability: "manage_admin" }, { to: "/settings", label: "Settings", icon: Settings, capability: "manage_admin" }, ]; -export function Sidebar() { +interface SidebarProps { + mobileOpen?: boolean; + onClose?: () => void; +} + +export function Sidebar({ mobileOpen, onClose }: SidebarProps = {}) { const user = useAuthStore((s) => s.user); const role = user?.role; @@ -84,10 +92,23 @@ export function Sidebar() { return true; }); - return ( -
); } diff --git a/frontend/src/test/phase8-polish.test.tsx b/frontend/src/test/phase8-polish.test.tsx new file mode 100644 index 0000000..c085f3b --- /dev/null +++ b/frontend/src/test/phase8-polish.test.tsx @@ -0,0 +1,201 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { render, screen, fireEvent, waitFor } from "@testing-library/react"; +import { MemoryRouter, Routes, Route, useLocation } from "react-router-dom"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { TopBar } from "@/components/layout/TopBar"; +import { AuditLogsPage } from "@/pages/AuditLogsPage"; +import { ConfirmDialog } from "@/components/ConfirmDialog"; +import { ToastProvider } from "@/components/ToastProvider"; +import { useAuthStore } from "@/hooks/useAuth"; +import * as searchModule from "@/api/search"; +import * as auditModule from "@/api/audit"; +import * as mastersModule from "@/api/masters"; +import * as notificationsModule from "@/api/notifications"; + +function LocationEcho() { + const loc = useLocation(); + return
{loc.pathname}
; +} + +function renderWithProviders(ui: React.ReactNode, initialEntries = ["/"]) { + const qc = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + return render( + + + {ui} + + + ); +} + +describe("Phase 8 Frontend Polish", () => { + beforeEach(() => { + vi.restoreAllMocks(); + useAuthStore.setState({ + user: { + id: 1, + name: "System Admin", + email: "admin@poona.demo", + role: "system_admin", + department_id: null, + department_name: null, + is_active: true, + }, + token: "test-token", + demoAsOfDate: null, + hydrating: false, + }); + }); + + it("TopBar global quick search displays grouped Assets and Complaints and navigates on click", async () => { + vi.spyOn(notificationsModule.notificationsApi, "list").mockResolvedValue({ + items: [], + total: 0, + unread_count: 0, + unread_calibration_count: 0, + }); + const searchSpy = vi + .spyOn(searchModule.searchApi, "query") + .mockResolvedValue({ + assets: [ + { + id: 42, + asset_code: "PHRC-ICU-0042", + name: "Drager Ventilator", + serial_no: "SN-9901", + department_name: "ICU", + status: "in_service", + }, + ], + complaints: [ + { + id: 17, + complaint_no: "CMP-2026-0017", + asset_code: "PHRC-ICU-0042", + asset_name: "Drager Ventilator", + department_name: "ICU", + call_status: "open", + priority: "high", + }, + ], + }); + + renderWithProviders( + <> + + + + } /> + Asset Detail View
} /> + Complaint Detail View} + /> + + + ); + + const searchInput = screen.getByLabelText("Search assets and complaints"); + fireEvent.change(searchInput, { target: { value: "Ventilator" } }); + + await waitFor(() => { + expect(searchSpy).toHaveBeenCalledWith("Ventilator"); + expect(screen.getByText("Assets (1)")).toBeInTheDocument(); + expect(screen.getByText("Complaints (1)")).toBeInTheDocument(); + expect(screen.getByText("Drager Ventilator")).toBeInTheDocument(); + expect(screen.getByText("CMP-2026-0017")).toBeInTheDocument(); + }); + + fireEvent.click(screen.getByText("Drager Ventilator")); + + await waitFor(() => { + expect(screen.getByTestId("current-location")).toHaveTextContent( + "/assets/42" + ); + expect(screen.getByText("Asset Detail View")).toBeInTheDocument(); + }); + }); + + it("AuditLogsPage renders filter controls, audit log rows, and opens JSON changes modal", async () => { + vi.spyOn(mastersModule.usersApi, "list").mockResolvedValue({ + items: [ + { + id: 1, + name: "System Admin", + email: "admin@poona.demo", + role: "system_admin", + department_id: null, + department_name: null, + is_active: true, + }, + ], + total: 1, + }); + + vi.spyOn(auditModule.auditApi, "list").mockResolvedValue({ + items: [ + { + id: 101, + entity_type: "asset", + entity_id: 55, + action: "update", + changes_json: JSON.stringify({ + status: { old: "in_service", new: "under_repair" }, + }), + by_user_id: 1, + by_user_name: "System Admin", + at: "2026-11-12T08:30:00Z", + }, + ], + total: 1, + }); + + renderWithProviders(); + + await waitFor(() => { + expect( + screen.getByRole("heading", { name: "Audit Log" }) + ).toBeInTheDocument(); + expect(screen.getByLabelText("Filter by Entity Type")).toBeInTheDocument(); + expect(screen.getByLabelText("Filter by User")).toBeInTheDocument(); + expect(screen.getByLabelText("Filter by Action")).toBeInTheDocument(); + expect(screen.getByText("#55")).toBeInTheDocument(); + expect(screen.getByText("asset")).toBeInTheDocument(); + }); + + const jsonBtn = screen.getByLabelText("View JSON changes for audit entry 101"); + fireEvent.click(jsonBtn); + + await waitFor(() => { + expect( + screen.getByText(/Audit Entry #101 — asset #55/i) + ).toBeInTheDocument(); + expect(screen.getByText(/"under_repair"/)).toBeInTheDocument(); + }); + }); + + it("ConfirmDialog renders danger warning and invokes onConfirm", () => { + const onConfirm = vi.fn(); + const onOpenChange = vi.fn(); + + render( + + ); + + expect(screen.getByText("Delete Contract")).toBeInTheDocument(); + expect(screen.getByText("This action cannot be undone.")).toBeInTheDocument(); + + fireEvent.click(screen.getByRole("button", { name: "Delete" })); + expect(onConfirm).toHaveBeenCalledTimes(1); + }); +}); diff --git a/frontend/src/test/smoke.test.tsx b/frontend/src/test/smoke.test.tsx index c48e607..46b95ef 100644 --- a/frontend/src/test/smoke.test.tsx +++ b/frontend/src/test/smoke.test.tsx @@ -49,11 +49,13 @@ describe("Phase 1 Frontend Smoke Tests", () => { "Reports", "Notifications", "Masters", + "Audit Log", "Settings", ]; for (const label of labels) { expect(screen.getByText(label)).toBeInTheDocument(); } + expect(screen.getByText("Poona Hospital AMS • v1.0")).toBeInTheDocument(); }); it("hides Masters, Settings, and Department Visits for department_user and coordinator", () => { @@ -74,6 +76,7 @@ describe("Phase 1 Frontend Smoke Tests", () => { ); expect(screen.queryByText("Masters")).not.toBeInTheDocument(); + expect(screen.queryByText("Audit Log")).not.toBeInTheDocument(); expect(screen.queryByText("Settings")).not.toBeInTheDocument(); expect(screen.queryByText("Department Visits")).not.toBeInTheDocument(); expect(screen.getByText("Assets")).toBeInTheDocument(); @@ -95,6 +98,7 @@ describe("Phase 1 Frontend Smoke Tests", () => { ); expect(screen.queryByText("Masters")).not.toBeInTheDocument(); + expect(screen.queryByText("Audit Log")).not.toBeInTheDocument(); expect(screen.queryByText("Settings")).not.toBeInTheDocument(); expect(screen.queryByText("Department Visits")).not.toBeInTheDocument(); expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument(); diff --git a/frontend/tsconfig.tsbuildinfo b/frontend/tsconfig.tsbuildinfo index 12acecd..fd8e243 100644 --- a/frontend/tsconfig.tsbuildinfo +++ b/frontend/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/dashboard.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/notifications.ts","./src/api/phase5.ts","./src/api/pm.ts","./src/api/reports.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/calibrationremindermodal.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/toastprovider.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/contractspage.tsx","./src/pages/dashboardpage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/notificationspage.tsx","./src/pages/pmpage.tsx","./src/pages/reportdetailpage.tsx","./src/pages/reportspage.tsx","./src/pages/settingspage.tsx","./src/pages/visitspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/phase5-modules.test.tsx","./src/test/phase6-modules.test.tsx","./src/test/pm-page.test.tsx","./src/test/reports.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/audit.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/dashboard.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/notifications.ts","./src/api/phase5.ts","./src/api/pm.ts","./src/api/reports.ts","./src/api/search.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/calibrationremindermodal.tsx","./src/components/confirmdialog.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/toastprovider.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/auditlogspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/contractspage.tsx","./src/pages/dashboardpage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/notificationspage.tsx","./src/pages/pmpage.tsx","./src/pages/reportdetailpage.tsx","./src/pages/reportspage.tsx","./src/pages/settingspage.tsx","./src/pages/visitspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/phase5-modules.test.tsx","./src/test/phase6-modules.test.tsx","./src/test/phase8-polish.test.tsx","./src/test/pm-page.test.tsx","./src/test/reports.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"} \ No newline at end of file