phase-8: polish, global search, audit log, packaging, and demo docs
This commit is contained in:
@@ -1,4 +1,20 @@
|
|||||||
|
# Database connection URL (SQLite default persists under backend/data/)
|
||||||
DATABASE_URL=sqlite:///./data/ams.db
|
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
|
SECRET_KEY=change-me-in-production-use-a-32-char-random-string
|
||||||
|
|
||||||
|
# Directory for uploaded attachments (PDF, JPG, PNG)
|
||||||
UPLOAD_DIR=./data/uploads
|
UPLOAD_DIR=./data/uploads
|
||||||
|
|
||||||
|
# Application display & scheduler timezone
|
||||||
TIMEZONE=Asia/Kolkata
|
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
|
||||||
|
|||||||
@@ -37,18 +37,37 @@ make dev
|
|||||||
|
|
||||||
### Run tests
|
### Run tests
|
||||||
```bash
|
```bash
|
||||||
make test
|
# Backend
|
||||||
# Or directly:
|
|
||||||
cd backend
|
cd backend
|
||||||
.venv/Scripts/python -m pytest tests/ -v
|
.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
|
### Seed demo data
|
||||||
```bash
|
```bash
|
||||||
cd backend
|
cd backend
|
||||||
.venv/Scripts/python -m app.seed.seed
|
.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
|
## Demo Accounts
|
||||||
| Email | Password | Role |
|
| Email | Password | Role |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
@@ -58,11 +77,12 @@ cd backend
|
|||||||
| mgmt@poona.demo | Demo@123 | Management |
|
| mgmt@poona.demo | Demo@123 | Management |
|
||||||
| coord@poona.demo | Demo@123 | Coordinator |
|
| coord@poona.demo | Demo@123 | Coordinator |
|
||||||
|
|
||||||
## What exists now (Phase 7)
|
## Implemented Application (Phases 0–8 Complete)
|
||||||
- Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules
|
- 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`), RBAC permission matrix for 5 roles, and Quick Demo Login
|
- 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)
|
- 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`)
|
- 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
|
- 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)
|
- 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
|
- 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
|
- 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)
|
- 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
|
- 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
|
- Responsive React + TypeScript frontend app shell (mobile slide-over navigation, accessible `<ConfirmDialog />`, role-filtered sidebar, route guards, DataTable, Tailwind CSS + shadcn/ui)
|
||||||
- Makefile for common tasks
|
- 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 0: Scaffold | Phase 1: Auth & Masters | Phase 2: Assets | Phase 3: Complaints
|
||||||
Phase 4: PM & Calibration | Phase 5: Contracts, Warranty, Insurance, Demo, Visits
|
Phase 4: PM & Calibration | Phase 5: Contracts, Warranty, Insurance, Demo, Visits
|
||||||
Phase 6: Notifications & Dashboard | Phase 7: Reports | Phase 8: Polish
|
Phase 6: Notifications & Dashboard | Phase 7: Reports | Phase 8: Polish, Search, Audit Log, Packaging & Docs
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
FROM python:3.13-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1
|
||||||
|
ENV PYTHONUNBUFFERED=1
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN mkdir -p /app/data/uploads
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
@@ -14,6 +14,7 @@ from .models import Base
|
|||||||
from .routers import (
|
from .routers import (
|
||||||
assets,
|
assets,
|
||||||
attachments,
|
attachments,
|
||||||
|
audit,
|
||||||
auth,
|
auth,
|
||||||
calibration,
|
calibration,
|
||||||
complaints,
|
complaints,
|
||||||
@@ -26,6 +27,7 @@ from .routers import (
|
|||||||
notifications,
|
notifications,
|
||||||
pm,
|
pm,
|
||||||
reports,
|
reports,
|
||||||
|
search,
|
||||||
settings,
|
settings,
|
||||||
users,
|
users,
|
||||||
visits,
|
visits,
|
||||||
@@ -126,3 +128,5 @@ app.include_router(visits.router, prefix="/api")
|
|||||||
app.include_router(notifications.router, prefix="/api")
|
app.include_router(notifications.router, prefix="/api")
|
||||||
app.include_router(dashboard.router, prefix="/api")
|
app.include_router(dashboard.router, prefix="/api")
|
||||||
app.include_router(reports.router, prefix="/api")
|
app.include_router(reports.router, prefix="/api")
|
||||||
|
app.include_router(search.router, prefix="/api")
|
||||||
|
app.include_router(audit.router, prefix="/api")
|
||||||
|
|||||||
@@ -13,14 +13,14 @@ class Asset(Base):
|
|||||||
asset_code: Mapped[str] = mapped_column(String(60), unique=True, index=True, nullable=False)
|
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)
|
serial_no: Mapped[str] = mapped_column(String(100), index=True, nullable=False)
|
||||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
category_id: Mapped[int] = mapped_column(ForeignKey("categories.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"), nullable=False)
|
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
|
||||||
location_id: Mapped[int] = mapped_column(ForeignKey("locations.id"), 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)
|
supplier_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
|
||||||
purchase_value: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
purchase_value: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||||
purchase_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
purchase_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||||
installation_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)
|
criticality: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False)
|
||||||
requires_calibration: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
requires_calibration: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
insurance_applicable: 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"
|
__tablename__ = "contracts"
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
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)
|
contract_type: Mapped[str] = mapped_column(String(20), nullable=False)
|
||||||
provider_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
|
provider_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
|
||||||
start_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, 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)
|
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)
|
renewed_from_id: Mapped[Optional[int]] = mapped_column(ForeignKey("contracts.id"), nullable=True)
|
||||||
is_superseded: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
is_superseded: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
@@ -62,10 +62,10 @@ class Warranty(Base):
|
|||||||
__tablename__ = "warranties"
|
__tablename__ = "warranties"
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
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)
|
duration_months: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
start_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, 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)
|
provider_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
|
||||||
remarks: Mapped[Optional[str]] = mapped_column(Text, 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_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||||
@@ -81,11 +81,11 @@ class InsurancePolicy(Base):
|
|||||||
__tablename__ = "insurance_policies"
|
__tablename__ = "insurance_policies"
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
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)
|
insurer_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
|
||||||
policy_no: Mapped[str] = mapped_column(String(100), nullable=False)
|
policy_no: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
start_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, nullable=False)
|
end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
|
||||||
coverage_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
coverage_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||||
remarks: Mapped[Optional[str]] = mapped_column(Text, 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_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||||
|
|||||||
@@ -11,23 +11,23 @@ class Complaint(Base):
|
|||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
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)
|
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)
|
description: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
breakdown_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
breakdown_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
priority: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False)
|
priority: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False)
|
||||||
notes: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
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)
|
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_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||||
received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), 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)
|
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_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||||
attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), 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)
|
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_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), 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)
|
closure_remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
action_taken: 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)
|
root_cause: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
|||||||
@@ -32,9 +32,9 @@ class CalibrationRecord(Base):
|
|||||||
__tablename__ = "calibration_records"
|
__tablename__ = "calibration_records"
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
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)
|
||||||
plan_id: Mapped[int] = mapped_column(ForeignKey("calibration_plans.id"), nullable=False)
|
plan_id: Mapped[int] = mapped_column(ForeignKey("calibration_plans.id"), index=True, nullable=False)
|
||||||
due_date: Mapped[date] = mapped_column(Date, nullable=False)
|
due_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
|
||||||
completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||||
agency_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), 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)
|
certificate_no: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||||
@@ -77,9 +77,9 @@ class PMRecord(Base):
|
|||||||
__tablename__ = "pm_records"
|
__tablename__ = "pm_records"
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
schedule_id: Mapped[int] = mapped_column(ForeignKey("pm_schedules.id"), 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"), nullable=False)
|
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
|
||||||
planned_date: Mapped[date] = mapped_column(Date, nullable=False)
|
planned_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
|
||||||
completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||||
# Only "completed" or "rescheduled" is persisted; upcoming/due/overdue are computed at read time.
|
# Only "completed" or "rescheduled" is persisted; upcoming/due/overdue are computed at read time.
|
||||||
status: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
|
status: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
|
||||||
|
|||||||
@@ -28,10 +28,10 @@ class DemoEquipment(Base):
|
|||||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
equipment_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
equipment_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
supplier_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), 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)
|
location_id: Mapped[Optional[int]] = mapped_column(ForeignKey("locations.id"), nullable=True)
|
||||||
start_date: Mapped[date] = mapped_column(Date, nullable=False)
|
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)
|
actual_return_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||||
remarks: Mapped[Optional[str]] = mapped_column(Text, 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_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||||
@@ -48,9 +48,9 @@ class DepartmentVisit(Base):
|
|||||||
__tablename__ = "department_visits"
|
__tablename__ = "department_visits"
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
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)
|
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)
|
observations: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
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, nullable=False)
|
||||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ class Attachment(Base):
|
|||||||
__tablename__ = "attachments"
|
__tablename__ = "attachments"
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
entity_type: Mapped[str] = mapped_column(String(60), nullable=False)
|
entity_type: Mapped[str] = mapped_column(String(60), index=True, nullable=False)
|
||||||
entity_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
entity_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False)
|
||||||
original_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
original_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
stored_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)
|
mime_type: Mapped[str] = mapped_column(String(120), nullable=False)
|
||||||
@@ -24,7 +24,7 @@ class Notification(Base):
|
|||||||
__tablename__ = "notifications"
|
__tablename__ = "notifications"
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
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)
|
severity: Mapped[str] = mapped_column(String(20), nullable=False)
|
||||||
title: Mapped[str] = mapped_column(String(200), nullable=False)
|
title: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
message: Mapped[str] = mapped_column(Text, 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_role: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||||
target_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), 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)
|
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):
|
class NotificationRead(Base):
|
||||||
@@ -53,9 +53,9 @@ class AuditLog(Base):
|
|||||||
__tablename__ = "audit_logs"
|
__tablename__ = "audit_logs"
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
entity_type: Mapped[str] = mapped_column(String(60), nullable=False)
|
entity_type: Mapped[str] = mapped_column(String(60), index=True, nullable=False)
|
||||||
entity_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
entity_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False)
|
||||||
action: Mapped[str] = mapped_column(String(50), nullable=False)
|
action: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||||
changes_json: Mapped[str] = mapped_column(Text, nullable=False)
|
changes_json: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
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, nullable=False)
|
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from . import (
|
from . import (
|
||||||
assets,
|
assets,
|
||||||
attachments,
|
attachments,
|
||||||
|
audit,
|
||||||
auth,
|
auth,
|
||||||
calibration,
|
calibration,
|
||||||
complaints,
|
complaints,
|
||||||
@@ -13,6 +14,7 @@ from . import (
|
|||||||
notifications,
|
notifications,
|
||||||
pm,
|
pm,
|
||||||
reports,
|
reports,
|
||||||
|
search,
|
||||||
settings,
|
settings,
|
||||||
users,
|
users,
|
||||||
visits,
|
visits,
|
||||||
@@ -22,6 +24,7 @@ from . import (
|
|||||||
__all__ = [
|
__all__ = [
|
||||||
"assets",
|
"assets",
|
||||||
"attachments",
|
"attachments",
|
||||||
|
"audit",
|
||||||
"auth",
|
"auth",
|
||||||
"calibration",
|
"calibration",
|
||||||
"complaints",
|
"complaints",
|
||||||
@@ -34,6 +37,7 @@ __all__ = [
|
|||||||
"notifications",
|
"notifications",
|
||||||
"pm",
|
"pm",
|
||||||
"reports",
|
"reports",
|
||||||
|
"search",
|
||||||
"settings",
|
"settings",
|
||||||
"users",
|
"users",
|
||||||
"visits",
|
"visits",
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
from datetime import date, datetime, time, timedelta, timezone
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
from sqlalchemy import String, cast, or_
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..core.db import get_db
|
||||||
|
from ..core.deps import require_roles
|
||||||
|
from ..core.time_utils import KOLKATA
|
||||||
|
from ..models import AuditLog, User
|
||||||
|
from ..services.permissions import Role
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/audit-logs", tags=["audit"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_audit_logs(
|
||||||
|
entity_type: str | None = Query(None),
|
||||||
|
by_user_id: int | None = Query(None),
|
||||||
|
action: str | None = Query(None),
|
||||||
|
date_from: date | None = Query(None),
|
||||||
|
date_to: date | None = Query(None),
|
||||||
|
q: str | None = Query(None),
|
||||||
|
page: int = Query(1, ge=1),
|
||||||
|
page_size: int = Query(100, ge=1, le=500),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
_admin: User = Depends(require_roles(Role.system_admin)),
|
||||||
|
):
|
||||||
|
query = db.query(AuditLog, User.name).outerjoin(User, AuditLog.by_user_id == User.id)
|
||||||
|
|
||||||
|
if entity_type:
|
||||||
|
query = query.filter(AuditLog.entity_type == entity_type.strip())
|
||||||
|
if by_user_id is not None:
|
||||||
|
query = query.filter(AuditLog.by_user_id == by_user_id)
|
||||||
|
if action:
|
||||||
|
query = query.filter(AuditLog.action == action.strip())
|
||||||
|
if date_from is not None:
|
||||||
|
dt_from_utc = KOLKATA.localize(
|
||||||
|
datetime.combine(date_from, time(0, 0, 0))
|
||||||
|
).astimezone(timezone.utc)
|
||||||
|
query = query.filter(AuditLog.at >= dt_from_utc)
|
||||||
|
if date_to is not None:
|
||||||
|
dt_to_utc = KOLKATA.localize(
|
||||||
|
datetime.combine(date_to + timedelta(days=1), time(0, 0, 0))
|
||||||
|
).astimezone(timezone.utc)
|
||||||
|
query = query.filter(AuditLog.at < dt_to_utc)
|
||||||
|
if q and q.strip():
|
||||||
|
pat = f"%{q.strip()}%"
|
||||||
|
query = query.filter(
|
||||||
|
or_(
|
||||||
|
AuditLog.entity_type.ilike(pat),
|
||||||
|
AuditLog.action.ilike(pat),
|
||||||
|
AuditLog.changes_json.ilike(pat),
|
||||||
|
cast(AuditLog.entity_id, String).ilike(pat),
|
||||||
|
User.name.ilike(pat),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
total = query.count()
|
||||||
|
rows = (
|
||||||
|
query.order_by(AuditLog.at.desc(), AuditLog.id.desc())
|
||||||
|
.offset((page - 1) * page_size)
|
||||||
|
.limit(page_size)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"id": log.id,
|
||||||
|
"entity_type": log.entity_type,
|
||||||
|
"entity_id": log.entity_id,
|
||||||
|
"action": log.action,
|
||||||
|
"changes_json": log.changes_json,
|
||||||
|
"by_user_id": log.by_user_id,
|
||||||
|
"by_user_name": user_name or "System",
|
||||||
|
"at": log.at,
|
||||||
|
}
|
||||||
|
for log, user_name in rows
|
||||||
|
],
|
||||||
|
"total": total,
|
||||||
|
}
|
||||||
@@ -1,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 sqlalchemy.orm import Session, joinedload
|
||||||
from ..core.db import get_db
|
from ..core.db import get_db
|
||||||
from ..core.deps import get_current_user
|
from ..core.deps import get_current_user
|
||||||
|
from ..core.exceptions import CodedHTTPException
|
||||||
from ..core.security import create_access_token, verify_password
|
from ..core.security import create_access_token, verify_password
|
||||||
from ..models.masters import User
|
from ..models.masters import User
|
||||||
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
|
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"])
|
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:
|
def _build_user_out(user: User, db: Session) -> UserOut:
|
||||||
return UserOut(
|
return UserOut(
|
||||||
@@ -24,8 +56,10 @@ def _build_user_out(user: User, db: Session) -> UserOut:
|
|||||||
|
|
||||||
|
|
||||||
@router.post("/login", response_model=TokenResponse)
|
@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()
|
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 = (
|
user = (
|
||||||
db.query(User)
|
db.query(User)
|
||||||
.options(joinedload(User.department))
|
.options(joinedload(User.department))
|
||||||
|
|||||||
@@ -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
|
||||||
|
],
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ from sqlalchemy.orm import sessionmaker
|
|||||||
from app.core.db import get_db
|
from app.core.db import get_db
|
||||||
from app.main import app
|
from app.main import app
|
||||||
from app.models import Base
|
from app.models import Base
|
||||||
|
from app.routers.auth import reset_login_rate_limiter
|
||||||
|
|
||||||
SQLALCHEMY_TEST_URL = "sqlite:///./data/test.db"
|
SQLALCHEMY_TEST_URL = "sqlite:///./data/test.db"
|
||||||
engine_test = create_engine(SQLALCHEMY_TEST_URL, connect_args={"check_same_thread": False})
|
engine_test = create_engine(SQLALCHEMY_TEST_URL, connect_args={"check_same_thread": False})
|
||||||
@@ -111,3 +112,10 @@ def client(db):
|
|||||||
finally:
|
finally:
|
||||||
c.close()
|
c.close()
|
||||||
app.dependency_overrides.clear()
|
app.dependency_overrides.clear()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _clear_login_rate_limiter():
|
||||||
|
reset_login_rate_limiter()
|
||||||
|
yield
|
||||||
|
reset_login_rate_limiter()
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.models import Asset, AuditLog, Base, Department, User
|
||||||
|
from app.routers.auth import MAX_LOGIN_ATTEMPTS, reset_login_rate_limiter
|
||||||
|
from app.seed.seed import seed_database
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def seeded_phase8_db(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("phase8_test_uploads")
|
||||||
|
seed_database(db, upload_dir=upload_dir)
|
||||||
|
return upload_dir
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||||
|
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_global_search_grouped_and_department_scoped(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||||
|
|
||||||
|
dept_user = db.query(User).filter(User.email == "dept@poona.demo").first()
|
||||||
|
icu_dept = db.query(Department).filter(Department.id == dept_user.department_id).first()
|
||||||
|
assert dept_user is not None and icu_dept is not None
|
||||||
|
|
||||||
|
icu_asset = db.query(Asset).filter(Asset.department_id == icu_dept.id).first()
|
||||||
|
non_icu_asset = db.query(Asset).filter(Asset.department_id != icu_dept.id).first()
|
||||||
|
assert icu_asset is not None and non_icu_asset is not None
|
||||||
|
|
||||||
|
# Broad search returns grouped assets & complaints capped at 8 each
|
||||||
|
broad = client.get("/api/search?q=PHRC", headers=bio_headers)
|
||||||
|
assert broad.status_code == 200, broad.text
|
||||||
|
data = broad.json()
|
||||||
|
assert isinstance(data["assets"], list) and 0 < len(data["assets"]) <= 8
|
||||||
|
assert isinstance(data["complaints"], list) and len(data["complaints"]) <= 8
|
||||||
|
assert {"id", "asset_code", "name", "serial_no", "department_name", "status"}.issubset(
|
||||||
|
data["assets"][0].keys()
|
||||||
|
)
|
||||||
|
|
||||||
|
# Complaint search by prefix
|
||||||
|
cmp_search = client.get("/api/search?q=CMP", headers=bio_headers)
|
||||||
|
assert cmp_search.status_code == 200
|
||||||
|
assert len(cmp_search.json()["complaints"]) > 0
|
||||||
|
assert {
|
||||||
|
"id",
|
||||||
|
"complaint_no",
|
||||||
|
"asset_code",
|
||||||
|
"asset_name",
|
||||||
|
"department_name",
|
||||||
|
"call_status",
|
||||||
|
"priority",
|
||||||
|
}.issubset(cmp_search.json()["complaints"][0].keys())
|
||||||
|
|
||||||
|
# Department user sees ICU asset, cannot see non-ICU asset
|
||||||
|
icu_res = client.get(f"/api/search?q={icu_asset.asset_code}", headers=dept_headers)
|
||||||
|
assert icu_res.status_code == 200
|
||||||
|
assert any(a["asset_code"] == icu_asset.asset_code for a in icu_res.json()["assets"])
|
||||||
|
|
||||||
|
other_res = client.get(f"/api/search?q={non_icu_asset.asset_code}", headers=dept_headers)
|
||||||
|
assert other_res.status_code == 200
|
||||||
|
assert other_res.json()["assets"] == []
|
||||||
|
assert other_res.json()["complaints"] == []
|
||||||
|
|
||||||
|
# Empty query rejected
|
||||||
|
assert client.get("/api/search?q=", headers=bio_headers).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_audit_logs_rbac_and_filters(client, db):
|
||||||
|
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||||
|
for email in ("bio@poona.demo", "mgmt@poona.demo", "dept@poona.demo", "coord@poona.demo"):
|
||||||
|
headers = _auth_headers(client, email)
|
||||||
|
assert client.get("/api/audit-logs", headers=headers).status_code == 403
|
||||||
|
|
||||||
|
# Ensure there is at least one distinct AuditLog entry via API/DB
|
||||||
|
admin_user = db.query(User).filter(User.email == "admin@poona.demo").first()
|
||||||
|
assert admin_user is not None
|
||||||
|
log_entry = AuditLog(
|
||||||
|
entity_type="asset",
|
||||||
|
entity_id=9999,
|
||||||
|
action="phase8_audit_probe",
|
||||||
|
changes_json='{"status": {"old": "in_service", "new": "under_repair"}}',
|
||||||
|
by_user_id=admin_user.id,
|
||||||
|
)
|
||||||
|
db.add(log_entry)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
res = client.get("/api/audit-logs?entity_type=asset&action=phase8_audit_probe", headers=admin_headers)
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
body = res.json()
|
||||||
|
assert body["total"] >= 1
|
||||||
|
assert len(body["items"]) >= 1
|
||||||
|
first = body["items"][0]
|
||||||
|
assert first["entity_type"] == "asset"
|
||||||
|
assert first["action"] == "phase8_audit_probe"
|
||||||
|
assert first["by_user_id"] == admin_user.id
|
||||||
|
assert first["by_user_name"] == admin_user.name
|
||||||
|
assert "under_repair" in first["changes_json"]
|
||||||
|
|
||||||
|
# Search filter `q`
|
||||||
|
q_res = client.get("/api/audit-logs?q=phase8_audit_probe", headers=admin_headers)
|
||||||
|
assert q_res.status_code == 200
|
||||||
|
assert q_res.json()["total"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_rate_limiter_429_and_reset(client):
|
||||||
|
reset_login_rate_limiter()
|
||||||
|
for i in range(MAX_LOGIN_ATTEMPTS):
|
||||||
|
res = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": "ratelimit@poona.demo", "password": "WrongPassword"},
|
||||||
|
)
|
||||||
|
assert res.status_code == 401, f"Attempt {i + 1} unexpected status {res.status_code}"
|
||||||
|
|
||||||
|
# Attempt 16 triggers 429 RATE_LIMITED
|
||||||
|
blocked = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": "ratelimit@poona.demo", "password": "WrongPassword"},
|
||||||
|
)
|
||||||
|
assert blocked.status_code == 429
|
||||||
|
assert blocked.json()["code"] == "RATE_LIMITED"
|
||||||
|
|
||||||
|
# Reset restores login capability
|
||||||
|
reset_login_rate_limiter()
|
||||||
|
ok = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": "admin@poona.demo", "password": "Demo@123"},
|
||||||
|
)
|
||||||
|
assert ok.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_database_indexes_defined():
|
||||||
|
expected_indexed_columns = {
|
||||||
|
"assets": {"asset_code", "serial_no", "department_id", "category_id", "location_id", "status"},
|
||||||
|
"complaints": {"complaint_no", "asset_id", "registered_at", "call_status", "assigned_to_id"},
|
||||||
|
"contracts": {"asset_id", "start_date", "end_date"},
|
||||||
|
"warranties": {"asset_id", "start_date", "end_date"},
|
||||||
|
"insurance_policies": {"asset_id", "start_date", "end_date"},
|
||||||
|
"calibration_records": {"asset_id", "plan_id", "due_date"},
|
||||||
|
"pm_records": {"asset_id", "schedule_id", "planned_date"},
|
||||||
|
"demo_equipment": {"department_id", "expected_return_date"},
|
||||||
|
"department_visits": {"department_id", "visit_date"},
|
||||||
|
"attachments": {"entity_type", "entity_id"},
|
||||||
|
"notifications": {"created_at", "type"},
|
||||||
|
"audit_logs": {"entity_type", "entity_id", "by_user_id", "at"},
|
||||||
|
}
|
||||||
|
for table_name, cols in expected_indexed_columns.items():
|
||||||
|
table = Base.metadata.tables[table_name]
|
||||||
|
indexed = {col.name for idx in table.indexes for col in idx.columns}
|
||||||
|
missing = cols - indexed
|
||||||
|
assert not missing, f"Missing indexes on {table_name}: {missing}"
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
services:
|
||||||
|
backend:
|
||||||
|
build: ./backend
|
||||||
|
container_name: poona-ams-backend
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: ${DATABASE_URL:-sqlite:////app/data/ams.db}
|
||||||
|
SECRET_KEY: ${SECRET_KEY:-change-me-in-production-use-a-32-char-random-string}
|
||||||
|
UPLOAD_DIR: ${UPLOAD_DIR:-/app/data/uploads}
|
||||||
|
TIMEZONE: ${TIMEZONE:-Asia/Kolkata}
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES: ${ACCESS_TOKEN_EXPIRE_MINUTES:-480}
|
||||||
|
ALGORITHM: ${ALGORITHM:-HS256}
|
||||||
|
MAX_UPLOAD_SIZE_MB: ${MAX_UPLOAD_SIZE_MB:-10}
|
||||||
|
volumes:
|
||||||
|
- ./backend/data:/app/data
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
build: ./frontend
|
||||||
|
container_name: poona-ams-frontend
|
||||||
|
ports:
|
||||||
|
- "5173:80"
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
restart: unless-stopped
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# Poona Hospital AMS — Acceptance Checklist (Proposal §10 Mapping)
|
||||||
|
|
||||||
|
| # | Acceptance Criterion | Automated Test Coverage | Manual Verification Steps |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **1** | **Auth, 5-Role RBAC, Masters & Settings** (`system_admin`, `biomedical`, `department_user`, `management`, `coordinator`, JWT auth, login rate limiting, configurable settings, audit logs) | `backend/tests/test_auth_and_permissions.py`<br>`backend/tests/test_phase8_polish.py` (`test_audit_logs_rbac_and_filters`, `test_login_rate_limiter_429_and_reset`)<br>`frontend/src/test/login.test.tsx`<br>`frontend/src/test/permissions.test.ts`<br>`frontend/src/test/smoke.test.tsx`<br>`frontend/src/test/phase8-polish.test.tsx` | Log in with all 5 demo accounts (`Demo@123`), confirm role-filtered sidebar items, test `/masters` & `/settings` CRUD as `admin@poona.demo`, confirm `/audit-logs` returns `403` for non-admins, and trigger >15 rapid failed logins to observe `429`. |
|
||||||
|
| **2** | **Asset Register, Global Quick Search & Secure Attachments** (unique `asset_code`, department scoping, coordinator edit restrictions, `AssetPicker`, `/api/search`, JPG/PNG/PDF magic-byte + 10 MB checks) | `backend/tests/test_assets_and_attachments.py`<br>`backend/tests/test_phase8_polish.py` (`test_global_search_grouped_and_department_scoped`)<br>`frontend/src/test/asset-picker.test.tsx`<br>`frontend/src/test/attachments.test.tsx`<br>`frontend/src/test/phase8-polish.test.tsx` | Create/edit an asset on `/assets`, confirm duplicate code returns `409`, verify `dept@poona.demo` sees ICU assets only, search in TopBar to jump to asset/complaint detail, and upload/preview/delete attachments on `/assets/:id`. |
|
||||||
|
| **3** | **Breakdown & Complaint Workflow + Ist Downtime Calculation** (sequential `complaint_no`, response time, `clip_downtime_to_month`, assign/attend/restore/close/reopen syncing `Asset.status`, role-gated technical fields) | `backend/tests/test_complaints.py`<br>`backend/tests/test_time_utils.py`<br>`frontend/src/test/complaint-detail.test.tsx` | Raise a complaint via `AssetPicker`, verify `dept@poona.demo` sees the Technical/CE/Spares read-only lock, complete the repair workflow as `bio@poona.demo`, and verify `Asset.status` returns to `in_service`. |
|
||||||
|
| **4** | **Preventive Maintenance & Calibration Schedules** (in-house & outsourced PM, dynamic `upcoming`/`due`/`overdue` vs `effective_today()`, clamped `add_months`, calibration approval gate, certificate upload) | `backend/tests/test_pm_and_calibration.py`<br>`frontend/src/test/pm-page.test.tsx`<br>`frontend/src/test/calibration-page.test.tsx` | Toggle Table and Calendar views on `/pm`, complete & reschedule cycles, verify `bio@poona.demo` receives `403` on calibration approval while `mgmt@poona.demo`/`coord@poona.demo` can approve, and upload calibration certificates. |
|
||||||
|
| **5** | **Contracts, Warranties, Insurance, Demo Equipment & Department Visits** (contract renewal superseding & history, warranty/insurance expiry chips, `InsuranceDrawer`, demo return tracking, visit `403` for `department_user`/`coordinator`) | `backend/tests/test_phase5_modules.py`<br>`frontend/src/test/phase5-modules.test.tsx` | Renew a contract on `/contracts` and check history chain, open `InsuranceDrawer` from `AssetDetailPage`, mark a demo equipment returned on `/demo-equipment`, and log a multi-asset visit on `/visits` as `bio@poona.demo`. |
|
||||||
|
| **6** | **Automated Alert Engine, `06:00 Asia/Kolkata` Scheduler & Notifications** (7 alert types, dedupe keys, per-user read state, TopBar bell polling, `CalibrationReminderModal`, Demo Clock `demo_as_of_date`) | `backend/tests/test_notifications_and_dashboard.py`<br>`frontend/src/test/phase6-modules.test.tsx` | Advance TopBar Demo Clock (+20 days) as `admin@poona.demo`, run alert check in `/settings`, confirm new notifications appear without duplicates on second run, mark read per user, and check login reminder pop-up. |
|
||||||
|
| **7** | **Hospital Operations Dashboard** (role-aware department scope banner, 7 clickable KPI cards, 4 Recharts charts, Needs Attention & Recent Complaints) | `backend/tests/test_notifications_and_dashboard.py` (`test_dashboard_summary_role_scoping_and_charts`)<br>`frontend/src/test/phase6-modules.test.tsx` | Compare `/` as `mgmt@poona.demo` (hospital-wide) vs `dept@poona.demo` (ICU-scoped) and verify KPI navigation and chart tooltips. |
|
||||||
|
| **8** | **8 Operational Reports, Excel/CSV Exports & A4 Print** (8 report keys, 3-complaint downtime reconciliation, `daily-visit` RBAC `403`, openpyxl `.xlsx` & UTF-8 BOM `.csv` exports, `@media print`) | `backend/tests/test_reports.py`<br>`frontend/src/test/reports.test.tsx` | Open `/reports`, verify `daily-visit` is hidden/`403` for `dept@poona.demo` & `coord@poona.demo`, inspect Monthly Maintenance `"How this is calculated"` formula popover, download `.xlsx`/`.csv`, and open Print Preview (A4 landscape). |
|
||||||
@@ -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`).
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package.json package-lock.json* ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
client_max_body_size 15M;
|
||||||
|
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://backend:8000/api/;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@ import { DashboardPage } from "@/pages/DashboardPage";
|
|||||||
import { NotificationsPage } from "@/pages/NotificationsPage";
|
import { NotificationsPage } from "@/pages/NotificationsPage";
|
||||||
import { ReportsPage } from "@/pages/ReportsPage";
|
import { ReportsPage } from "@/pages/ReportsPage";
|
||||||
import { ReportDetailPage } from "@/pages/ReportDetailPage";
|
import { ReportDetailPage } from "@/pages/ReportDetailPage";
|
||||||
|
import { AuditLogsPage } from "@/pages/AuditLogsPage";
|
||||||
import { ToastProvider } from "@/components/ToastProvider";
|
import { ToastProvider } from "@/components/ToastProvider";
|
||||||
import { useAuthStore } from "@/hooks/useAuth";
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
import { can, type Capability } from "@/lib/permissions";
|
import { can, type Capability } from "@/lib/permissions";
|
||||||
@@ -110,6 +111,14 @@ function AppRoutes() {
|
|||||||
</RoleGuard>
|
</RoleGuard>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Route
|
||||||
|
path="/audit-logs"
|
||||||
|
element={
|
||||||
|
<RoleGuard capability="manage_admin">
|
||||||
|
<AuditLogsPage />
|
||||||
|
</RoleGuard>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="/settings"
|
path="/settings"
|
||||||
element={
|
element={
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { api } from "./client";
|
||||||
|
|
||||||
|
export interface AuditLogItem {
|
||||||
|
id: number;
|
||||||
|
entity_type: string;
|
||||||
|
entity_id: number;
|
||||||
|
action: string;
|
||||||
|
changes_json: string | null;
|
||||||
|
by_user_id: number | null;
|
||||||
|
by_user_name: string | null;
|
||||||
|
at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuditLogsResponse {
|
||||||
|
items: AuditLogItem[];
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuditLogFilters {
|
||||||
|
entity_type?: string;
|
||||||
|
by_user_id?: number;
|
||||||
|
action?: string;
|
||||||
|
date_from?: string;
|
||||||
|
date_to?: string;
|
||||||
|
q?: string;
|
||||||
|
page?: number;
|
||||||
|
page_size?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const auditApi = {
|
||||||
|
list: (filters: AuditLogFilters = {}) => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.entity_type) params.set("entity_type", filters.entity_type);
|
||||||
|
if (filters.by_user_id != null) {
|
||||||
|
params.set("by_user_id", String(filters.by_user_id));
|
||||||
|
}
|
||||||
|
if (filters.action) params.set("action", filters.action);
|
||||||
|
if (filters.date_from) params.set("date_from", filters.date_from);
|
||||||
|
if (filters.date_to) params.set("date_to", filters.date_to);
|
||||||
|
if (filters.q) params.set("q", filters.q);
|
||||||
|
if (filters.page != null) params.set("page", String(filters.page));
|
||||||
|
params.set("page_size", String(filters.page_size ?? 200));
|
||||||
|
return api.get<AuditLogsResponse>(`/audit-logs?${params.toString()}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { api } from "./client";
|
||||||
|
|
||||||
|
export interface SearchAssetItem {
|
||||||
|
id: number;
|
||||||
|
asset_code: string;
|
||||||
|
name: string;
|
||||||
|
serial_no: string | null;
|
||||||
|
department_name: string | null;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SearchComplaintItem {
|
||||||
|
id: number;
|
||||||
|
complaint_no: string;
|
||||||
|
asset_code: string | null;
|
||||||
|
asset_name: string | null;
|
||||||
|
department_name: string | null;
|
||||||
|
call_status: string;
|
||||||
|
priority: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GlobalSearchResponse {
|
||||||
|
assets: SearchAssetItem[];
|
||||||
|
complaints: SearchComplaintItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const searchApi = {
|
||||||
|
query: (q: string) => {
|
||||||
|
const params = new URLSearchParams({ q });
|
||||||
|
return api.get<GlobalSearchResponse>(`/search?${params.toString()}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { AlertTriangle } from "lucide-react";
|
||||||
|
import { Modal } from "@/components/ui/dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
export interface ConfirmDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
title: string;
|
||||||
|
message: string;
|
||||||
|
confirmLabel?: string;
|
||||||
|
cancelLabel?: string;
|
||||||
|
variant?: "danger" | "default";
|
||||||
|
loading?: boolean;
|
||||||
|
onConfirm: () => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ConfirmDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
confirmLabel = "Confirm",
|
||||||
|
cancelLabel = "Cancel",
|
||||||
|
variant = "danger",
|
||||||
|
loading = false,
|
||||||
|
onConfirm,
|
||||||
|
}: ConfirmDialogProps) {
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
if (!loading) onOpenChange(next);
|
||||||
|
}}
|
||||||
|
title={title}
|
||||||
|
description={message}
|
||||||
|
className="max-w-md"
|
||||||
|
>
|
||||||
|
<div className="space-y-5">
|
||||||
|
{variant === "danger" && (
|
||||||
|
<div className="flex items-start gap-3 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800">
|
||||||
|
<AlertTriangle className="h-4 w-4 shrink-0 text-red-600 mt-0.5" />
|
||||||
|
<span>This action cannot be undone.</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end gap-2 pt-1">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={loading}
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
>
|
||||||
|
{cancelLabel}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={variant === "danger" ? "danger" : "default"}
|
||||||
|
size="sm"
|
||||||
|
loading={loading}
|
||||||
|
onClick={() => void onConfirm()}
|
||||||
|
>
|
||||||
|
{confirmLabel}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,14 +1,20 @@
|
|||||||
|
import { useState } from "react";
|
||||||
import { Outlet } from "react-router-dom";
|
import { Outlet } from "react-router-dom";
|
||||||
import { Sidebar } from "./Sidebar";
|
import { Sidebar } from "./Sidebar";
|
||||||
import { TopBar } from "./TopBar";
|
import { TopBar } from "./TopBar";
|
||||||
import { CalibrationReminderModal } from "@/components/CalibrationReminderModal";
|
import { CalibrationReminderModal } from "@/components/CalibrationReminderModal";
|
||||||
|
|
||||||
export function AppShell() {
|
export function AppShell() {
|
||||||
|
const [mobileNavOpen, setMobileNavOpen] = useState(false);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen bg-gray-50">
|
<div className="flex min-h-screen bg-gray-50">
|
||||||
<Sidebar />
|
<Sidebar
|
||||||
|
mobileOpen={mobileNavOpen}
|
||||||
|
onClose={() => setMobileNavOpen(false)}
|
||||||
|
/>
|
||||||
<div className="flex-1 flex flex-col min-w-0">
|
<div className="flex-1 flex flex-col min-w-0">
|
||||||
<TopBar />
|
<TopBar onMenuClick={() => setMobileNavOpen(true)} />
|
||||||
<main className="flex-1 p-6 overflow-auto">
|
<main className="flex-1 p-6 overflow-auto">
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -12,8 +12,10 @@ import {
|
|||||||
BarChart3,
|
BarChart3,
|
||||||
Bell,
|
Bell,
|
||||||
Database,
|
Database,
|
||||||
|
History,
|
||||||
Settings,
|
Settings,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
|
X,
|
||||||
type LucideIcon,
|
type LucideIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@@ -71,10 +73,16 @@ const NAV_ITEMS: NavItem[] = [
|
|||||||
},
|
},
|
||||||
{ to: "/notifications", label: "Notifications", icon: Bell },
|
{ to: "/notifications", label: "Notifications", icon: Bell },
|
||||||
{ to: "/masters", label: "Masters", icon: Database, capability: "manage_admin" },
|
{ 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" },
|
{ 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 user = useAuthStore((s) => s.user);
|
||||||
const role = user?.role;
|
const role = user?.role;
|
||||||
|
|
||||||
@@ -84,10 +92,23 @@ export function Sidebar() {
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
const asideContent = (
|
||||||
<aside className="w-56 lg:w-64 shrink-0 min-h-screen bg-[#1e3a8a] text-white flex flex-col">
|
<aside
|
||||||
|
aria-label="Primary Navigation"
|
||||||
|
className="w-56 lg:w-64 shrink-0 min-h-screen bg-[#1e3a8a] text-white flex flex-col"
|
||||||
|
>
|
||||||
{/* Logo */}
|
{/* Logo */}
|
||||||
<div className="px-4 py-4 border-b border-blue-700 space-y-2">
|
<div className="px-4 py-4 border-b border-blue-700 space-y-2 relative">
|
||||||
|
{onClose && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
aria-label="Close navigation menu"
|
||||||
|
className="md:hidden absolute right-2 top-2 p-1 rounded text-blue-200 hover:text-white hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<div className="bg-white rounded-lg p-2">
|
<div className="bg-white rounded-lg p-2">
|
||||||
<img
|
<img
|
||||||
src="/logo.jpg"
|
src="/logo.jpg"
|
||||||
@@ -107,9 +128,10 @@ export function Sidebar() {
|
|||||||
key={to}
|
key={to}
|
||||||
to={to}
|
to={to}
|
||||||
end={to === "/"}
|
end={to === "/"}
|
||||||
|
onClick={() => onClose?.()}
|
||||||
className={({ isActive }) =>
|
className={({ isActive }) =>
|
||||||
cn(
|
cn(
|
||||||
"flex items-center gap-3 px-3 py-2.5 rounded-md text-sm transition-colors group",
|
"flex items-center gap-3 px-3 py-2.5 rounded-md text-sm transition-colors group focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white",
|
||||||
isActive
|
isActive
|
||||||
? "bg-blue-700 text-white"
|
? "bg-blue-700 text-white"
|
||||||
: "text-blue-100 hover:bg-blue-700/50 hover:text-white"
|
: "text-blue-100 hover:bg-blue-700/50 hover:text-white"
|
||||||
@@ -125,8 +147,29 @@ export function Sidebar() {
|
|||||||
|
|
||||||
{/* Footer */}
|
{/* Footer */}
|
||||||
<div className="px-4 py-3 border-t border-blue-700 text-xs text-blue-300">
|
<div className="px-4 py-3 border-t border-blue-700 text-xs text-blue-300">
|
||||||
Phase 1 — Foundation
|
Poona Hospital AMS • v1.0
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// When controlled by AppShell, hide desktop rail on small screens and render slide-over drawer when open
|
||||||
|
if (mobileOpen === undefined) {
|
||||||
|
return asideContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="hidden md:flex shrink-0">{asideContent}</div>
|
||||||
|
{mobileOpen && (
|
||||||
|
<div className="fixed inset-0 z-40 flex md:hidden">
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-black/40"
|
||||||
|
onClick={onClose}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<div className="relative z-50 flex">{asideContent}</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,10 @@ import {
|
|||||||
AlertTriangle,
|
AlertTriangle,
|
||||||
Info,
|
Info,
|
||||||
Clock,
|
Clock,
|
||||||
|
Menu,
|
||||||
|
X,
|
||||||
|
Package,
|
||||||
|
AlertCircle,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { formatDate, formatRelative } from "@/lib/format";
|
import { formatDate, formatRelative } from "@/lib/format";
|
||||||
@@ -21,14 +25,17 @@ import { ROLE_LABELS } from "@/lib/permissions";
|
|||||||
import { useAuthStore } from "@/hooks/useAuth";
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
import { settingsApi } from "@/api/settings";
|
import { settingsApi } from "@/api/settings";
|
||||||
import { notificationsApi, type NotificationItem } from "@/api/notifications";
|
import { notificationsApi, type NotificationItem } from "@/api/notifications";
|
||||||
|
import { searchApi } from "@/api/search";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { AssetStatusBadge, CallStatusBadge } from "@/components/StatusBadge";
|
||||||
import { toast } from "@/components/ToastProvider";
|
import { toast } from "@/components/ToastProvider";
|
||||||
|
|
||||||
interface TopBarProps {
|
interface TopBarProps {
|
||||||
title?: string;
|
title?: string;
|
||||||
|
onMenuClick?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TopBar({ title }: TopBarProps) {
|
export function TopBar({ title, onMenuClick }: TopBarProps) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
|
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
|
||||||
@@ -39,26 +46,72 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
const [savingDate, setSavingDate] = useState(false);
|
const [savingDate, setSavingDate] = useState(false);
|
||||||
const [runningAlerts, setRunningAlerts] = useState(false);
|
const [runningAlerts, setRunningAlerts] = useState(false);
|
||||||
|
|
||||||
|
const [searchInput, setSearchInput] = useState("");
|
||||||
|
const [debouncedQuery, setDebouncedQuery] = useState("");
|
||||||
|
const [searchOpen, setSearchOpen] = useState(false);
|
||||||
|
|
||||||
const bellContainerRef = useRef<HTMLDivElement>(null);
|
const bellContainerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const searchContainerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const userMenuRef = useRef<HTMLDivElement>(null);
|
||||||
const seenIdsRef = useRef<Set<number> | null>(null);
|
const seenIdsRef = useRef<Set<number> | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setDateInput(demoAsOfDate ?? "");
|
setDateInput(demoAsOfDate ?? "");
|
||||||
}, [demoAsOfDate]);
|
}, [demoAsOfDate]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const trimmed = searchInput.trim();
|
||||||
|
if (trimmed.length < 2) {
|
||||||
|
setDebouncedQuery("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const timer = window.setTimeout(() => {
|
||||||
|
setDebouncedQuery(trimmed);
|
||||||
|
}, 200);
|
||||||
|
return () => window.clearTimeout(timer);
|
||||||
|
}, [searchInput]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
function handleOutside(e: MouseEvent) {
|
function handleOutside(e: MouseEvent) {
|
||||||
|
const target = e.target as Node;
|
||||||
if (
|
if (
|
||||||
bellContainerRef.current &&
|
bellContainerRef.current &&
|
||||||
!bellContainerRef.current.contains(e.target as Node)
|
!bellContainerRef.current.contains(target)
|
||||||
) {
|
) {
|
||||||
setBellOpen(false);
|
setBellOpen(false);
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
searchContainerRef.current &&
|
||||||
|
!searchContainerRef.current.contains(target)
|
||||||
|
) {
|
||||||
|
setSearchOpen(false);
|
||||||
|
}
|
||||||
|
if (userMenuRef.current && !userMenuRef.current.contains(target)) {
|
||||||
|
setMenuOpen(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function handleKeyDown(e: KeyboardEvent) {
|
||||||
|
if (e.key === "Escape") {
|
||||||
|
setSearchOpen(false);
|
||||||
|
setBellOpen(false);
|
||||||
|
setMenuOpen(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
document.addEventListener("mousedown", handleOutside);
|
document.addEventListener("mousedown", handleOutside);
|
||||||
return () => document.removeEventListener("mousedown", handleOutside);
|
document.addEventListener("keydown", handleKeyDown);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("mousedown", handleOutside);
|
||||||
|
document.removeEventListener("keydown", handleKeyDown);
|
||||||
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const searchQuery = useQuery({
|
||||||
|
queryKey: ["global-search", debouncedQuery, user?.id],
|
||||||
|
queryFn: () => searchApi.query(debouncedQuery),
|
||||||
|
enabled: Boolean(user) && debouncedQuery.length >= 2,
|
||||||
|
staleTime: 10_000,
|
||||||
|
});
|
||||||
|
|
||||||
const isAdmin = user?.role === "system_admin";
|
const isAdmin = user?.role === "system_admin";
|
||||||
|
|
||||||
const bellQuery = useQuery({
|
const bellQuery = useQuery({
|
||||||
@@ -178,6 +231,18 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-4 py-2 gap-3 sticky top-0 z-10">
|
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-4 py-2 gap-3 sticky top-0 z-10">
|
||||||
|
{/* Mobile nav toggle */}
|
||||||
|
{onMenuClick && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onMenuClick}
|
||||||
|
aria-label="Open navigation menu"
|
||||||
|
className="md:hidden p-1.5 rounded-md text-gray-600 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||||
|
>
|
||||||
|
<Menu className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Page title */}
|
{/* Page title */}
|
||||||
{title && (
|
{title && (
|
||||||
<h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">
|
<h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">
|
||||||
@@ -185,14 +250,151 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
</h1>
|
</h1>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Global search placeholder */}
|
{/* Live Global Quick Search */}
|
||||||
<div className={cn("relative", title ? "" : "flex-1 max-w-xs sm:max-w-sm")}>
|
<div
|
||||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
ref={searchContainerRef}
|
||||||
|
className={cn("relative", title ? "w-64 sm:w-80" : "flex-1 max-w-xs sm:max-w-md")}
|
||||||
|
>
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Search assets, complaints... (Phase 8)"
|
aria-label="Search assets and complaints"
|
||||||
className="w-full pl-9 pr-4 py-1.5 text-sm border border-gray-200 rounded-md bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white"
|
value={searchInput}
|
||||||
|
onChange={(e) => {
|
||||||
|
const val = e.target.value;
|
||||||
|
setSearchInput(val);
|
||||||
|
setSearchOpen(val.trim().length >= 2);
|
||||||
|
}}
|
||||||
|
onFocus={() => {
|
||||||
|
if (searchInput.trim().length >= 2) {
|
||||||
|
setSearchOpen(true);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder="Search assets, complaints..."
|
||||||
|
className="w-full pl-9 pr-8 py-1.5 text-sm border border-gray-200 rounded-md bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white"
|
||||||
/>
|
/>
|
||||||
|
{searchInput && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Clear search"
|
||||||
|
onClick={() => {
|
||||||
|
setSearchInput("");
|
||||||
|
setDebouncedQuery("");
|
||||||
|
setSearchOpen(false);
|
||||||
|
}}
|
||||||
|
className="absolute right-2 top-1/2 -translate-y-1/2 p-0.5 rounded text-gray-400 hover:text-gray-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{searchOpen && searchInput.trim().length >= 2 && (
|
||||||
|
<div
|
||||||
|
role="listbox"
|
||||||
|
aria-label="Global search results"
|
||||||
|
className="absolute left-0 right-0 mt-1.5 bg-white border border-gray-200 rounded-lg shadow-xl z-30 max-h-96 overflow-y-auto divide-y divide-gray-100"
|
||||||
|
>
|
||||||
|
{searchQuery.isFetching && !searchQuery.data ? (
|
||||||
|
<div className="px-4 py-6 text-center text-xs text-gray-500">
|
||||||
|
Searching assets & complaints...
|
||||||
|
</div>
|
||||||
|
) : searchQuery.isError ? (
|
||||||
|
<div className="px-4 py-5 text-center text-xs text-red-600">
|
||||||
|
Unable to load search results.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
(() => {
|
||||||
|
const assets = searchQuery.data?.assets ?? [];
|
||||||
|
const complaints = searchQuery.data?.complaints ?? [];
|
||||||
|
if (assets.length === 0 && complaints.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="px-4 py-6 text-center text-xs text-gray-500">
|
||||||
|
No matching assets or complaints found.
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{assets.length > 0 && (
|
||||||
|
<div className="py-1.5">
|
||||||
|
<div className="px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500 flex items-center gap-1.5">
|
||||||
|
<Package className="h-3.5 w-3.5 text-[#1e3a8a]" />
|
||||||
|
Assets ({assets.length})
|
||||||
|
</div>
|
||||||
|
{assets.map((asset) => (
|
||||||
|
<button
|
||||||
|
key={`asset-${asset.id}`}
|
||||||
|
type="button"
|
||||||
|
role="option"
|
||||||
|
onClick={() => {
|
||||||
|
setSearchOpen(false);
|
||||||
|
navigate(`/assets/${asset.id}`);
|
||||||
|
}}
|
||||||
|
className="w-full text-left px-3 py-2 hover:bg-blue-50/70 focus-visible:outline-none focus-visible:bg-blue-50 flex items-center justify-between gap-2 transition-colors"
|
||||||
|
>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="font-mono text-xs font-semibold text-[#1e3a8a]">
|
||||||
|
{asset.asset_code}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs font-medium text-gray-900 truncate">
|
||||||
|
{asset.name}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-gray-500 truncate mt-0.5">
|
||||||
|
{asset.department_name ?? "No Dept"}
|
||||||
|
{asset.serial_no ? ` • SN: ${asset.serial_no}` : ""}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<AssetStatusBadge status={asset.status} />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{complaints.length > 0 && (
|
||||||
|
<div className="py-1.5">
|
||||||
|
<div className="px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500 flex items-center gap-1.5">
|
||||||
|
<AlertCircle className="h-3.5 w-3.5 text-red-600" />
|
||||||
|
Complaints ({complaints.length})
|
||||||
|
</div>
|
||||||
|
{complaints.map((c) => (
|
||||||
|
<button
|
||||||
|
key={`complaint-${c.id}`}
|
||||||
|
type="button"
|
||||||
|
role="option"
|
||||||
|
onClick={() => {
|
||||||
|
setSearchOpen(false);
|
||||||
|
navigate(`/complaints/${c.id}`);
|
||||||
|
}}
|
||||||
|
className="w-full text-left px-3 py-2 hover:bg-blue-50/70 focus-visible:outline-none focus-visible:bg-blue-50 flex items-center justify-between gap-2 transition-colors"
|
||||||
|
>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="font-mono text-xs font-semibold text-gray-900">
|
||||||
|
{c.complaint_no}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-gray-700 truncate">
|
||||||
|
{c.asset_code
|
||||||
|
? `${c.asset_code}${c.asset_name ? ` — ${c.asset_name}` : ""}`
|
||||||
|
: c.asset_name ?? "Equipment"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-gray-500 truncate mt-0.5">
|
||||||
|
{c.department_name ?? "—"} • Priority: {c.priority}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<CallStatusBadge status={c.call_status} />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
})()
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Active Demo Date Pill */}
|
{/* Active Demo Date Pill */}
|
||||||
@@ -254,8 +456,9 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setBellOpen((o) => !o)}
|
onClick={() => setBellOpen((o) => !o)}
|
||||||
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-600"
|
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||||
aria-label="Notifications"
|
aria-label="Notifications"
|
||||||
|
aria-expanded={bellOpen}
|
||||||
>
|
>
|
||||||
<Bell className="h-5 w-5" />
|
<Bell className="h-5 w-5" />
|
||||||
{unreadCount > 0 && (
|
{unreadCount > 0 && (
|
||||||
@@ -348,11 +551,13 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* User menu */}
|
{/* User menu */}
|
||||||
<div className="relative">
|
<div ref={userMenuRef} className="relative">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setMenuOpen((o) => !o)}
|
onClick={() => setMenuOpen((o) => !o)}
|
||||||
className="flex items-center gap-2 px-2.5 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700"
|
aria-label="User menu"
|
||||||
|
aria-expanded={menuOpen}
|
||||||
|
className="flex items-center gap-2 px-2.5 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||||
>
|
>
|
||||||
<div className="h-7 w-7 rounded-full bg-[#1e3a8a] flex items-center justify-center text-white text-xs font-bold shrink-0">
|
<div className="h-7 w-7 rounded-full bg-[#1e3a8a] flex items-center justify-center text-white text-xs font-bold shrink-0">
|
||||||
<User className="h-4 w-4" />
|
<User className="h-4 w-4" />
|
||||||
|
|||||||
@@ -0,0 +1,460 @@
|
|||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import type { ColumnDef } from "@tanstack/react-table";
|
||||||
|
import { History, Search, RotateCcw, Eye } from "lucide-react";
|
||||||
|
import { auditApi, type AuditLogItem } from "@/api/audit";
|
||||||
|
import { usersApi } from "@/api/masters";
|
||||||
|
import { formatDateTime } from "@/lib/format";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { DataTable } from "@/components/DataTable";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Modal } from "@/components/ui/dialog";
|
||||||
|
|
||||||
|
const ENTITY_TYPES = [
|
||||||
|
{ value: "", label: "All Entity Types" },
|
||||||
|
{ value: "asset", label: "Asset" },
|
||||||
|
{ value: "complaint", label: "Complaint" },
|
||||||
|
{ value: "pm_schedule", label: "PM Schedule" },
|
||||||
|
{ value: "pm_record", label: "PM Record" },
|
||||||
|
{ value: "calibration_plan", label: "Calibration Plan" },
|
||||||
|
{ value: "calibration_record", label: "Calibration Record" },
|
||||||
|
{ value: "contract", label: "Contract" },
|
||||||
|
{ value: "warranty", label: "Warranty" },
|
||||||
|
{ value: "insurance_policy", label: "Insurance Policy" },
|
||||||
|
{ value: "demo_equipment", label: "Demo Equipment" },
|
||||||
|
{ value: "department_visit", label: "Department Visit" },
|
||||||
|
{ value: "attachment", label: "Attachment" },
|
||||||
|
{ value: "setting", label: "Setting" },
|
||||||
|
{ value: "user", label: "User" },
|
||||||
|
{ value: "department", label: "Department" },
|
||||||
|
{ value: "location", label: "Location" },
|
||||||
|
{ value: "category", label: "Category" },
|
||||||
|
{ value: "vendor", label: "Vendor" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const ACTIONS = [
|
||||||
|
{ value: "", label: "All Actions" },
|
||||||
|
{ value: "create", label: "Create" },
|
||||||
|
{ value: "update", label: "Update" },
|
||||||
|
{ value: "delete", label: "Delete" },
|
||||||
|
{ value: "status_change", label: "Status Change" },
|
||||||
|
{ value: "complete", label: "Complete" },
|
||||||
|
{ value: "reschedule", label: "Reschedule" },
|
||||||
|
{ value: "renew", label: "Renew" },
|
||||||
|
{ value: "return", label: "Return" },
|
||||||
|
{ value: "login", label: "Login" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function ActionBadge({ action }: { action: string }) {
|
||||||
|
const lower = action.toLowerCase();
|
||||||
|
let cls = "bg-slate-100 text-slate-700 border-slate-200";
|
||||||
|
if (lower.includes("create") || lower.includes("upload")) {
|
||||||
|
cls = "bg-green-100 text-green-800 border-green-200";
|
||||||
|
} else if (lower.includes("delete") || lower.includes("deactivate") || lower.includes("remove")) {
|
||||||
|
cls = "bg-red-100 text-red-800 border-red-200";
|
||||||
|
} else if (
|
||||||
|
lower.includes("update") ||
|
||||||
|
lower.includes("status") ||
|
||||||
|
lower.includes("reschedule")
|
||||||
|
) {
|
||||||
|
cls = "bg-blue-100 text-blue-800 border-blue-200";
|
||||||
|
} else if (
|
||||||
|
lower.includes("complete") ||
|
||||||
|
lower.includes("renew") ||
|
||||||
|
lower.includes("return") ||
|
||||||
|
lower.includes("approve")
|
||||||
|
) {
|
||||||
|
cls = "bg-emerald-100 text-emerald-800 border-emerald-200";
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border whitespace-nowrap capitalize",
|
||||||
|
cls
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{action.replace(/_/g, " ")}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function summarizeChanges(changesJson: string | null): string {
|
||||||
|
if (!changesJson) return "—";
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(changesJson);
|
||||||
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||||
|
const keys = Object.keys(parsed);
|
||||||
|
if (keys.length === 0) return "—";
|
||||||
|
const preview = keys
|
||||||
|
.slice(0, 3)
|
||||||
|
.map((k) => {
|
||||||
|
const val = (parsed as Record<string, unknown>)[k];
|
||||||
|
if (val && typeof val === "object" && "old" in val && "new" in val) {
|
||||||
|
const pair = val as { old: unknown; new: unknown };
|
||||||
|
return `${k}: ${String(pair.old ?? "∅")} → ${String(pair.new ?? "∅")}`;
|
||||||
|
}
|
||||||
|
const str = typeof val === "string" ? val : JSON.stringify(val);
|
||||||
|
return `${k}: ${str}`;
|
||||||
|
})
|
||||||
|
.join(", ");
|
||||||
|
return keys.length > 3 ? `${preview} (+${keys.length - 3} more)` : preview;
|
||||||
|
}
|
||||||
|
return String(parsed);
|
||||||
|
} catch {
|
||||||
|
return changesJson.length > 90 ? `${changesJson.slice(0, 90)}…` : changesJson;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatJsonPretty(changesJson: string | null): string {
|
||||||
|
if (!changesJson) return "No payload recorded.";
|
||||||
|
try {
|
||||||
|
return JSON.stringify(JSON.parse(changesJson), null, 2);
|
||||||
|
} catch {
|
||||||
|
return changesJson;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AuditLogsPage() {
|
||||||
|
const [entityType, setEntityType] = useState("");
|
||||||
|
const [byUserId, setByUserId] = useState("");
|
||||||
|
const [action, setAction] = useState("");
|
||||||
|
const [dateFrom, setDateFrom] = useState("");
|
||||||
|
const [dateTo, setDateTo] = useState("");
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
const [selectedEntry, setSelectedEntry] = useState<AuditLogItem | null>(null);
|
||||||
|
|
||||||
|
const usersQuery = useQuery({
|
||||||
|
queryKey: ["users", "audit-filter"],
|
||||||
|
queryFn: () => usersApi.list(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
const logsQuery = useQuery({
|
||||||
|
queryKey: [
|
||||||
|
"audit-logs",
|
||||||
|
entityType,
|
||||||
|
byUserId,
|
||||||
|
action,
|
||||||
|
dateFrom,
|
||||||
|
dateTo,
|
||||||
|
q,
|
||||||
|
],
|
||||||
|
queryFn: () =>
|
||||||
|
auditApi.list({
|
||||||
|
entity_type: entityType || undefined,
|
||||||
|
by_user_id: byUserId ? Number(byUserId) : undefined,
|
||||||
|
action: action || undefined,
|
||||||
|
date_from: dateFrom || undefined,
|
||||||
|
date_to: dateTo || undefined,
|
||||||
|
q: q.trim() || undefined,
|
||||||
|
page_size: 200,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const hasFilters = Boolean(
|
||||||
|
entityType || byUserId || action || dateFrom || dateTo || q.trim()
|
||||||
|
);
|
||||||
|
|
||||||
|
function handleReset() {
|
||||||
|
setEntityType("");
|
||||||
|
setByUserId("");
|
||||||
|
setAction("");
|
||||||
|
setDateFrom("");
|
||||||
|
setDateTo("");
|
||||||
|
setQ("");
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = useMemo<ColumnDef<AuditLogItem, unknown>[]>(
|
||||||
|
() => [
|
||||||
|
{
|
||||||
|
accessorKey: "at",
|
||||||
|
header: "Timestamp",
|
||||||
|
cell: ({ getValue }) => (
|
||||||
|
<span className="whitespace-nowrap text-xs text-gray-700">
|
||||||
|
{formatDateTime(getValue() as string)}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "user",
|
||||||
|
accessorFn: (r) => r.by_user_name ?? `User #${r.by_user_id ?? "System"}`,
|
||||||
|
header: "User",
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<span className="text-sm font-medium text-gray-900">
|
||||||
|
{row.original.by_user_name ||
|
||||||
|
(row.original.by_user_id != null
|
||||||
|
? `User #${row.original.by_user_id}`
|
||||||
|
: "System")}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "entity_type",
|
||||||
|
header: "Entity Type",
|
||||||
|
cell: ({ getValue }) => (
|
||||||
|
<span className="inline-flex items-center px-2 py-0.5 rounded bg-gray-100 text-gray-700 font-mono text-xs">
|
||||||
|
{String(getValue() ?? "")}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "entity_id",
|
||||||
|
header: "Entity ID",
|
||||||
|
cell: ({ getValue }) => (
|
||||||
|
<span className="font-mono text-xs text-gray-700">
|
||||||
|
#{String(getValue() ?? "")}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "action",
|
||||||
|
header: "Action",
|
||||||
|
cell: ({ getValue }) => <ActionBadge action={String(getValue() ?? "")} />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "changes",
|
||||||
|
accessorFn: (r) => r.changes_json ?? "",
|
||||||
|
header: "Changes",
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const summary = summarizeChanges(row.original.changes_json);
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-between gap-2 max-w-md">
|
||||||
|
<span className="text-xs text-gray-600 truncate" title={summary}>
|
||||||
|
{summary}
|
||||||
|
</span>
|
||||||
|
{row.original.changes_json && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setSelectedEntry(row.original);
|
||||||
|
}}
|
||||||
|
aria-label={`View JSON changes for audit entry ${row.original.id}`}
|
||||||
|
className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium text-[#1e3a8a] hover:bg-blue-50 border border-blue-200 shrink-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||||
|
>
|
||||||
|
<Eye className="h-3 w-3" />
|
||||||
|
JSON
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
const items = logsQuery.data?.items ?? [];
|
||||||
|
const total = logsQuery.data?.total ?? items.length;
|
||||||
|
const users = usersQuery.data?.items ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-5">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<History className="h-6 w-6 text-[#1e3a8a]" />
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Audit Log</h1>
|
||||||
|
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-[#1e3a8a] border border-blue-200">
|
||||||
|
{total} {total === 1 ? "entry" : "entries"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-gray-500 mt-0.5">
|
||||||
|
Track system-wide creations, updates, status transitions, and deletions.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filter Bar */}
|
||||||
|
<div className="bg-white border border-gray-200 rounded-lg p-3.5 shadow-sm">
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-2.5 items-end">
|
||||||
|
<div className="lg:col-span-2">
|
||||||
|
<label
|
||||||
|
htmlFor="audit-search"
|
||||||
|
className="block text-xs font-medium text-gray-600 mb-1"
|
||||||
|
>
|
||||||
|
Search
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="h-3.5 w-3.5 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
|
||||||
|
<input
|
||||||
|
id="audit-search"
|
||||||
|
type="text"
|
||||||
|
aria-label="Search audit logs"
|
||||||
|
value={q}
|
||||||
|
onChange={(e) => setQ(e.target.value)}
|
||||||
|
placeholder="Search entity ID, action, changes..."
|
||||||
|
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="audit-entity-type"
|
||||||
|
className="block text-xs font-medium text-gray-600 mb-1"
|
||||||
|
>
|
||||||
|
Entity Type
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="audit-entity-type"
|
||||||
|
aria-label="Filter by Entity Type"
|
||||||
|
value={entityType}
|
||||||
|
onChange={(e) => setEntityType(e.target.value)}
|
||||||
|
className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
>
|
||||||
|
{ENTITY_TYPES.map((opt) => (
|
||||||
|
<option key={opt.value} value={opt.value}>
|
||||||
|
{opt.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="audit-user"
|
||||||
|
className="block text-xs font-medium text-gray-600 mb-1"
|
||||||
|
>
|
||||||
|
User
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="audit-user"
|
||||||
|
aria-label="Filter by User"
|
||||||
|
value={byUserId}
|
||||||
|
onChange={(e) => setByUserId(e.target.value)}
|
||||||
|
className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
>
|
||||||
|
<option value="">All Users</option>
|
||||||
|
{users.map((u) => (
|
||||||
|
<option key={u.id} value={String(u.id)}>
|
||||||
|
{u.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="audit-action"
|
||||||
|
className="block text-xs font-medium text-gray-600 mb-1"
|
||||||
|
>
|
||||||
|
Action
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="audit-action"
|
||||||
|
aria-label="Filter by Action"
|
||||||
|
value={action}
|
||||||
|
onChange={(e) => setAction(e.target.value)}
|
||||||
|
className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
>
|
||||||
|
{ACTIONS.map((opt) => (
|
||||||
|
<option key={opt.value} value={opt.value}>
|
||||||
|
{opt.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-end gap-1.5">
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<label
|
||||||
|
htmlFor="audit-date-from"
|
||||||
|
className="block text-xs font-medium text-gray-600 mb-1"
|
||||||
|
>
|
||||||
|
From
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="audit-date-from"
|
||||||
|
type="date"
|
||||||
|
aria-label="Date from"
|
||||||
|
value={dateFrom}
|
||||||
|
onChange={(e) => setDateFrom(e.target.value)}
|
||||||
|
className="w-full px-2 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<label
|
||||||
|
htmlFor="audit-date-to"
|
||||||
|
className="block text-xs font-medium text-gray-600 mb-1"
|
||||||
|
>
|
||||||
|
To
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="audit-date-to"
|
||||||
|
type="date"
|
||||||
|
aria-label="Date to"
|
||||||
|
value={dateTo}
|
||||||
|
onChange={(e) => setDateTo(e.target.value)}
|
||||||
|
className="w-full px-2 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{hasFilters && (
|
||||||
|
<div className="mt-2.5 flex justify-end">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={handleReset}
|
||||||
|
className="text-xs h-7 px-2.5"
|
||||||
|
>
|
||||||
|
<RotateCcw className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Reset filters
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Table */}
|
||||||
|
<DataTable
|
||||||
|
data={items}
|
||||||
|
columns={columns}
|
||||||
|
loading={logsQuery.isLoading}
|
||||||
|
globalFilterPlaceholder="Quick filter loaded audit entries..."
|
||||||
|
exportFilename="audit-logs"
|
||||||
|
emptyMessage="No audit log entries match your selected filters."
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* JSON Diff Modal */}
|
||||||
|
<Modal
|
||||||
|
open={Boolean(selectedEntry)}
|
||||||
|
onOpenChange={(o) => !o && setSelectedEntry(null)}
|
||||||
|
title={
|
||||||
|
selectedEntry
|
||||||
|
? `Audit Entry #${selectedEntry.id} — ${selectedEntry.entity_type} #${selectedEntry.entity_id}`
|
||||||
|
: "Audit Entry Details"
|
||||||
|
}
|
||||||
|
description={
|
||||||
|
selectedEntry
|
||||||
|
? `${selectedEntry.action.replace(/_/g, " ")} by ${
|
||||||
|
selectedEntry.by_user_name || "System"
|
||||||
|
} at ${formatDateTime(selectedEntry.at)}`
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
className="max-w-2xl"
|
||||||
|
>
|
||||||
|
{selectedEntry && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<pre className="rounded-md bg-gray-900 text-gray-100 p-4 text-xs overflow-x-auto max-h-96 font-mono leading-relaxed">
|
||||||
|
{formatJsonPretty(selectedEntry.changes_json)}
|
||||||
|
</pre>
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setSelectedEntry(null)}
|
||||||
|
>
|
||||||
|
Close
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -31,6 +31,8 @@ import { Modal } from "@/components/ui/dialog";
|
|||||||
import { ExpiryChip } from "@/components/StatusBadge";
|
import { ExpiryChip } from "@/components/StatusBadge";
|
||||||
import { AssetPicker } from "@/components/AssetPicker";
|
import { AssetPicker } from "@/components/AssetPicker";
|
||||||
import { Attachments } from "@/components/Attachments";
|
import { Attachments } from "@/components/Attachments";
|
||||||
|
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||||
|
import { toast } from "@/components/ToastProvider";
|
||||||
|
|
||||||
type TabKey = "contracts" | "warranties";
|
type TabKey = "contracts" | "warranties";
|
||||||
|
|
||||||
@@ -101,6 +103,13 @@ export function ContractsPage() {
|
|||||||
title: string;
|
title: string;
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
|
|
||||||
|
// Confirm delete dialog
|
||||||
|
const [deleteTarget, setDeleteTarget] = useState<{
|
||||||
|
kind: "contract" | "warranty";
|
||||||
|
id: number;
|
||||||
|
label: string;
|
||||||
|
} | null>(null);
|
||||||
|
|
||||||
const deptsQuery = useQuery({
|
const deptsQuery = useQuery({
|
||||||
queryKey: ["departments", "active-only"],
|
queryKey: ["departments", "active-only"],
|
||||||
queryFn: () => departmentsApi.list(false),
|
queryFn: () => departmentsApi.list(false),
|
||||||
@@ -150,16 +159,26 @@ export function ContractsPage() {
|
|||||||
const deleteContractMutation = useMutation({
|
const deleteContractMutation = useMutation({
|
||||||
mutationFn: (id: number) => contractsApi.remove(id),
|
mutationFn: (id: number) => contractsApi.remove(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
|
setDeleteTarget(null);
|
||||||
qc.invalidateQueries({ queryKey: ["contracts"] });
|
qc.invalidateQueries({ queryKey: ["contracts"] });
|
||||||
qc.invalidateQueries({ queryKey: ["assets"] });
|
qc.invalidateQueries({ queryKey: ["assets"] });
|
||||||
|
toast.success("Contract deleted");
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
toast.error(err instanceof ApiError ? err.detail : "Failed to delete contract");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const deleteWarrantyMutation = useMutation({
|
const deleteWarrantyMutation = useMutation({
|
||||||
mutationFn: (id: number) => warrantiesApi.remove(id),
|
mutationFn: (id: number) => warrantiesApi.remove(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
|
setDeleteTarget(null);
|
||||||
qc.invalidateQueries({ queryKey: ["warranties"] });
|
qc.invalidateQueries({ queryKey: ["warranties"] });
|
||||||
qc.invalidateQueries({ queryKey: ["assets"] });
|
qc.invalidateQueries({ queryKey: ["assets"] });
|
||||||
|
toast.success("Warranty deleted");
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
toast.error(err instanceof ApiError ? err.detail : "Failed to delete warranty");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -303,11 +322,13 @@ export function ContractsPage() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
className="text-red-600 hover:text-red-700"
|
className="text-red-600 hover:text-red-700"
|
||||||
onClick={() => {
|
onClick={() =>
|
||||||
if (window.confirm("Delete this contract?")) {
|
setDeleteTarget({
|
||||||
deleteContractMutation.mutate(row.original.id);
|
kind: "contract",
|
||||||
}
|
id: row.original.id,
|
||||||
}}
|
label: `${row.original.asset_code} (${row.original.contract_type})`,
|
||||||
|
})
|
||||||
|
}
|
||||||
aria-label={`Delete contract ${row.original.id}`}
|
aria-label={`Delete contract ${row.original.id}`}
|
||||||
>
|
>
|
||||||
<Trash2 className="h-3.5 w-3.5" />
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
@@ -412,6 +433,7 @@ export function ContractsPage() {
|
|||||||
setEditingWarranty(row.original);
|
setEditingWarranty(row.original);
|
||||||
setWarrantyFormOpen(true);
|
setWarrantyFormOpen(true);
|
||||||
}}
|
}}
|
||||||
|
aria-label={`Edit warranty ${row.original.id}`}
|
||||||
>
|
>
|
||||||
<Pencil className="h-3.5 w-3.5" />
|
<Pencil className="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
@@ -419,11 +441,14 @@ export function ContractsPage() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
className="text-red-600 hover:text-red-700"
|
className="text-red-600 hover:text-red-700"
|
||||||
onClick={() => {
|
onClick={() =>
|
||||||
if (window.confirm("Delete this warranty?")) {
|
setDeleteTarget({
|
||||||
deleteWarrantyMutation.mutate(row.original.id);
|
kind: "warranty",
|
||||||
}
|
id: row.original.id,
|
||||||
}}
|
label: `${row.original.asset_code} warranty`,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
aria-label={`Delete warranty ${row.original.id}`}
|
||||||
>
|
>
|
||||||
<Trash2 className="h-3.5 w-3.5" />
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
@@ -652,6 +677,28 @@ export function ContractsPage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
open={Boolean(deleteTarget)}
|
||||||
|
onOpenChange={(o) => !o && setDeleteTarget(null)}
|
||||||
|
title={
|
||||||
|
deleteTarget?.kind === "warranty" ? "Delete Warranty" : "Delete Contract"
|
||||||
|
}
|
||||||
|
message={`Are you sure you want to delete ${deleteTarget?.label ?? "this record"}?`}
|
||||||
|
confirmLabel="Delete"
|
||||||
|
variant="danger"
|
||||||
|
loading={
|
||||||
|
deleteContractMutation.isPending || deleteWarrantyMutation.isPending
|
||||||
|
}
|
||||||
|
onConfirm={() => {
|
||||||
|
if (!deleteTarget) return;
|
||||||
|
if (deleteTarget.kind === "warranty") {
|
||||||
|
deleteWarrantyMutation.mutate(deleteTarget.id);
|
||||||
|
} else {
|
||||||
|
deleteContractMutation.mutate(deleteTarget.id);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Modal } from "@/components/ui/dialog";
|
import { Modal } from "@/components/ui/dialog";
|
||||||
import { DemoStatusBadge } from "@/components/StatusBadge";
|
import { DemoStatusBadge } from "@/components/StatusBadge";
|
||||||
import { Attachments } from "@/components/Attachments";
|
import { Attachments } from "@/components/Attachments";
|
||||||
|
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||||
|
import { toast } from "@/components/ToastProvider";
|
||||||
|
|
||||||
type ViewTab = "active" | "returned" | "all";
|
type ViewTab = "active" | "returned" | "all";
|
||||||
|
|
||||||
@@ -45,6 +47,7 @@ export function DemoEquipmentPage() {
|
|||||||
const [editing, setEditing] = useState<DemoEquipmentItem | null>(null);
|
const [editing, setEditing] = useState<DemoEquipmentItem | null>(null);
|
||||||
const [returnTarget, setReturnTarget] = useState<DemoEquipmentItem | null>(null);
|
const [returnTarget, setReturnTarget] = useState<DemoEquipmentItem | null>(null);
|
||||||
const [attachTarget, setAttachTarget] = useState<DemoEquipmentItem | null>(null);
|
const [attachTarget, setAttachTarget] = useState<DemoEquipmentItem | null>(null);
|
||||||
|
const [deleteTarget, setDeleteTarget] = useState<DemoEquipmentItem | null>(null);
|
||||||
|
|
||||||
const deptsQuery = useQuery({
|
const deptsQuery = useQuery({
|
||||||
queryKey: ["departments", "active-only"],
|
queryKey: ["departments", "active-only"],
|
||||||
@@ -86,7 +89,14 @@ export function DemoEquipmentPage() {
|
|||||||
|
|
||||||
const deleteMutation = useMutation({
|
const deleteMutation = useMutation({
|
||||||
mutationFn: (id: number) => demoEquipmentApi.remove(id),
|
mutationFn: (id: number) => demoEquipmentApi.remove(id),
|
||||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["demo-equipment"] }),
|
onSuccess: () => {
|
||||||
|
setDeleteTarget(null);
|
||||||
|
qc.invalidateQueries({ queryKey: ["demo-equipment"] });
|
||||||
|
toast.success("Demo equipment entry deleted");
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
toast.error(err instanceof ApiError ? err.detail : "Failed to delete demo entry");
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const items = useMemo(() => {
|
const items = useMemo(() => {
|
||||||
@@ -227,11 +237,7 @@ export function DemoEquipmentPage() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
className="text-red-600 hover:text-red-700"
|
className="text-red-600 hover:text-red-700"
|
||||||
onClick={() => {
|
onClick={() => setDeleteTarget(row.original)}
|
||||||
if (window.confirm(`Delete demo entry "${row.original.name}"?`)) {
|
|
||||||
deleteMutation.mutate(row.original.id);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
aria-label={`Delete demo equipment ${row.original.name}`}
|
aria-label={`Delete demo equipment ${row.original.name}`}
|
||||||
>
|
>
|
||||||
<Trash2 className="h-3.5 w-3.5" />
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
@@ -387,6 +393,19 @@ export function DemoEquipmentPage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
open={Boolean(deleteTarget)}
|
||||||
|
onOpenChange={(o) => !o && setDeleteTarget(null)}
|
||||||
|
title="Delete Demo Equipment Entry"
|
||||||
|
message={`Are you sure you want to delete "${deleteTarget?.name ?? "this demo entry"}"?`}
|
||||||
|
confirmLabel="Delete"
|
||||||
|
variant="danger"
|
||||||
|
loading={deleteMutation.isPending}
|
||||||
|
onConfirm={() => {
|
||||||
|
if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ import { ExpiryChip } from "@/components/StatusBadge";
|
|||||||
import { AssetPicker } from "@/components/AssetPicker";
|
import { AssetPicker } from "@/components/AssetPicker";
|
||||||
import { Attachments } from "@/components/Attachments";
|
import { Attachments } from "@/components/Attachments";
|
||||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||||
|
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||||
|
import { toast } from "@/components/ToastProvider";
|
||||||
|
|
||||||
const inputCls =
|
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";
|
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||||||
@@ -55,6 +57,7 @@ export function InsurancePage() {
|
|||||||
label: string;
|
label: string;
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
const [attachPolicy, setAttachPolicy] = useState<InsuranceItem | null>(null);
|
const [attachPolicy, setAttachPolicy] = useState<InsuranceItem | null>(null);
|
||||||
|
const [deleteTarget, setDeleteTarget] = useState<InsuranceItem | null>(null);
|
||||||
|
|
||||||
const deptsQuery = useQuery({
|
const deptsQuery = useQuery({
|
||||||
queryKey: ["departments", "active-only"],
|
queryKey: ["departments", "active-only"],
|
||||||
@@ -82,8 +85,13 @@ export function InsurancePage() {
|
|||||||
const deleteMutation = useMutation({
|
const deleteMutation = useMutation({
|
||||||
mutationFn: (id: number) => insuranceApi.remove(id),
|
mutationFn: (id: number) => insuranceApi.remove(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
|
setDeleteTarget(null);
|
||||||
qc.invalidateQueries({ queryKey: ["insurance"] });
|
qc.invalidateQueries({ queryKey: ["insurance"] });
|
||||||
qc.invalidateQueries({ queryKey: ["assets"] });
|
qc.invalidateQueries({ queryKey: ["assets"] });
|
||||||
|
toast.success("Insurance policy deleted");
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
toast.error(err instanceof ApiError ? err.detail : "Failed to delete insurance policy");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -208,11 +216,7 @@ export function InsurancePage() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
className="text-red-600 hover:text-red-700"
|
className="text-red-600 hover:text-red-700"
|
||||||
onClick={() => {
|
onClick={() => setDeleteTarget(row.original)}
|
||||||
if (window.confirm(`Delete policy ${row.original.policy_no}?`)) {
|
|
||||||
deleteMutation.mutate(row.original.id);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
aria-label={`Delete policy ${row.original.policy_no}`}
|
aria-label={`Delete policy ${row.original.policy_no}`}
|
||||||
>
|
>
|
||||||
<Trash2 className="h-3.5 w-3.5" />
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
@@ -347,6 +351,19 @@ export function InsurancePage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
open={Boolean(deleteTarget)}
|
||||||
|
onOpenChange={(o) => !o && setDeleteTarget(null)}
|
||||||
|
title="Delete Insurance Policy"
|
||||||
|
message={`Are you sure you want to delete policy ${deleteTarget?.policy_no ?? ""}?`}
|
||||||
|
confirmLabel="Delete"
|
||||||
|
variant="danger"
|
||||||
|
loading={deleteMutation.isPending}
|
||||||
|
onConfirm={() => {
|
||||||
|
if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 <div data-testid="current-location">{loc.pathname}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderWithProviders(ui: React.ReactNode, initialEntries = ["/"]) {
|
||||||
|
const qc = new QueryClient({
|
||||||
|
defaultOptions: { queries: { retry: false } },
|
||||||
|
});
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={qc}>
|
||||||
|
<ToastProvider>
|
||||||
|
<MemoryRouter initialEntries={initialEntries}>{ui}</MemoryRouter>
|
||||||
|
</ToastProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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(
|
||||||
|
<>
|
||||||
|
<TopBar />
|
||||||
|
<LocationEcho />
|
||||||
|
<Routes>
|
||||||
|
<Route path="/" element={<div />} />
|
||||||
|
<Route path="/assets/:id" element={<div>Asset Detail View</div>} />
|
||||||
|
<Route
|
||||||
|
path="/complaints/:id"
|
||||||
|
element={<div>Complaint Detail View</div>}
|
||||||
|
/>
|
||||||
|
</Routes>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
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(<AuditLogsPage />);
|
||||||
|
|
||||||
|
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(
|
||||||
|
<ConfirmDialog
|
||||||
|
open={true}
|
||||||
|
onOpenChange={onOpenChange}
|
||||||
|
title="Delete Contract"
|
||||||
|
message="Are you sure you want to delete PHRC-ICU-0001 (AMC)?"
|
||||||
|
confirmLabel="Delete"
|
||||||
|
variant="danger"
|
||||||
|
onConfirm={onConfirm}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -49,11 +49,13 @@ describe("Phase 1 Frontend Smoke Tests", () => {
|
|||||||
"Reports",
|
"Reports",
|
||||||
"Notifications",
|
"Notifications",
|
||||||
"Masters",
|
"Masters",
|
||||||
|
"Audit Log",
|
||||||
"Settings",
|
"Settings",
|
||||||
];
|
];
|
||||||
for (const label of labels) {
|
for (const label of labels) {
|
||||||
expect(screen.getByText(label)).toBeInTheDocument();
|
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", () => {
|
it("hides Masters, Settings, and Department Visits for department_user and coordinator", () => {
|
||||||
@@ -74,6 +76,7 @@ describe("Phase 1 Frontend Smoke Tests", () => {
|
|||||||
</MemoryRouter>
|
</MemoryRouter>
|
||||||
);
|
);
|
||||||
expect(screen.queryByText("Masters")).not.toBeInTheDocument();
|
expect(screen.queryByText("Masters")).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByText("Audit Log")).not.toBeInTheDocument();
|
||||||
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
|
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
|
||||||
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
|
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
|
||||||
expect(screen.getByText("Assets")).toBeInTheDocument();
|
expect(screen.getByText("Assets")).toBeInTheDocument();
|
||||||
@@ -95,6 +98,7 @@ describe("Phase 1 Frontend Smoke Tests", () => {
|
|||||||
</MemoryRouter>
|
</MemoryRouter>
|
||||||
);
|
);
|
||||||
expect(screen.queryByText("Masters")).not.toBeInTheDocument();
|
expect(screen.queryByText("Masters")).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByText("Audit Log")).not.toBeInTheDocument();
|
||||||
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
|
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
|
||||||
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
|
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
|
||||||
expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument();
|
expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument();
|
||||||
|
|||||||
@@ -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"}
|
{"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"}
|
||||||
Reference in New Issue
Block a user