phase-1: data model, auth, permissions, masters, settings, seed

This commit is contained in:
Atharv1705
2026-11-12 12:28:55 +05:30
parent cb2f48620c
commit e58232a657
48 changed files with 5463 additions and 98 deletions
+9 -8
View File
@@ -43,13 +43,13 @@ cd backend
.venv/Scripts/python -m pytest tests/ -v
```
### Seed demo data (available after Phase 1)
### Seed demo data
```bash
cd backend
.venv/Scripts/python -m app.seed.seed
```
## Demo Accounts (available after Phase 1)
## Demo Accounts
| Email | Password | Role |
|---|---|---|
| admin@poona.demo | Demo@123 | System Admin |
@@ -58,12 +58,13 @@ cd backend
| mgmt@poona.demo | Demo@123 | Management |
| coord@poona.demo | Demo@123 | Coordinator |
## What exists now (Phase 0)
- FastAPI backend scaffold with `/api/health` endpoint
- React + TypeScript frontend with full app shell
- Left sidebar with all module links (stubbed pages)
- DataTable component with column filters, sort, pagination, CSV export
- Tailwind CSS + shadcn/ui design system
## What exists now (Phase 1)
- Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules
- JWT authentication (`/api/auth/login`, `/api/auth/me`), RBAC permission matrix for 5 roles, and Quick Demo Login
- Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users)
- Typed System Settings (`/settings`) and TopBar "As of Date" Demo Clock (`POST /api/settings/demo-date`)
- Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data
- React + TypeScript frontend app shell with role-filtered sidebar, route guards, DataTable, and Tailwind CSS + shadcn/ui
- Makefile for common tasks
## Modules (all phases)
+43 -2
View File
@@ -1,7 +1,48 @@
# Placeholder — full implementation in Phase 1 when User model exists.
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError
from sqlalchemy.orm import Session
from .db import get_db
from .security import decode_token
from ..models.masters import User
from ..services.permissions import Role
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
# get_current_user and require_roles will be implemented in Phase 1.
def get_current_user(
token: str = Depends(oauth2_scheme),
db: Session = Depends(get_db),
) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = decode_token(token)
sub = payload.get("sub")
if sub is None:
raise credentials_exception
user_id = int(sub)
except (JWTError, ValueError, TypeError):
raise credentials_exception
user = db.query(User).filter(User.id == user_id).first()
if user is None or not user.is_active:
raise credentials_exception
return user
def require_roles(*roles: Role | str):
allowed = {r.value if isinstance(r, Role) else r for r in roles}
def _dependency(current_user: User = Depends(get_current_user)) -> User:
if current_user.role not in allowed:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Insufficient permissions for this action.",
)
return current_user
return _dependency
+12 -5
View File
@@ -1,18 +1,25 @@
from datetime import timedelta
import bcrypt
from jose import JWTError, jwt
from passlib.context import CryptContext
from .config import settings
from .time_utils import utc_now
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)
if not plain or not hashed:
return False
try:
return bcrypt.checkpw(
plain.encode("utf-8")[:72],
hashed.encode("utf-8"),
)
except ValueError:
return False
def hash_password(plain: str) -> str:
return pwd_context.hash(plain)
hashed = bcrypt.hashpw(plain.encode("utf-8")[:72], bcrypt.gensalt())
return hashed.decode("utf-8")
def create_access_token(data: dict, expires_minutes: int | None = None) -> str:
+28 -3
View File
@@ -1,4 +1,5 @@
from datetime import date, datetime, timezone
import json
import pytz
KOLKATA = pytz.timezone("Asia/Kolkata")
@@ -8,9 +9,33 @@ def utc_now() -> datetime:
return datetime.now(timezone.utc)
def effective_today() -> date:
"""Returns demo_as_of_date from settings if set, else real today (Asia/Kolkata).
Phase 0: always real today. Phase 1 wires in DB settings lookup."""
def _read_demo_date_from_db(db) -> date | None:
from ..models.masters import Setting
row = db.query(Setting).filter(Setting.key == "demo_as_of_date").first()
if row and row.value_json:
val = json.loads(row.value_json)
if isinstance(val, str) and val.strip():
return date.fromisoformat(val.strip())
return None
def effective_today(db=None) -> date:
"""Returns demo_as_of_date from settings if set, else real today (Asia/Kolkata)."""
try:
if db is not None:
demo_date = _read_demo_date_from_db(db)
if demo_date is not None:
return demo_date
else:
from .db import SessionLocal
with SessionLocal() as session:
demo_date = _read_demo_date_from_db(session)
if demo_date is not None:
return demo_date
except Exception:
pass
return datetime.now(KOLKATA).date()
+26 -11
View File
@@ -1,20 +1,38 @@
import logging
import traceback
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from .core.db import engine
from .core.db import SessionLocal, engine
from .models import Base
from .routers import health
from .routers import auth, health, masters, settings, users
from .services.settings_service import ensure_default_settings
# Logging setup
logging.basicConfig(
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
level=logging.INFO,
)
logger = logging.getLogger("poona_ams")
app = FastAPI(title="Poona Hospital AMS", version="0.1.0", docs_url="/docs")
@asynccontextmanager
async def lifespan(app: FastAPI):
Base.metadata.create_all(bind=engine)
with SessionLocal() as db:
ensure_default_settings(db)
db.commit()
logger.info("Database tables created/verified.")
logger.info("Poona Hospital AMS started.")
yield
app = FastAPI(
title="Poona Hospital AMS",
version="0.1.0",
docs_url="/docs",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
@@ -35,10 +53,7 @@ async def global_exception_handler(request: Request, exc: Exception):
app.include_router(health.router, prefix="/api")
@app.on_event("startup")
def startup():
Base.metadata.create_all(bind=engine)
logger.info("Database tables created/verified.")
logger.info("Poona Hospital AMS started.")
app.include_router(auth.router, prefix="/api")
app.include_router(settings.router, prefix="/api")
app.include_router(masters.router, prefix="/api")
app.include_router(users.router, prefix="/api")
+39
View File
@@ -1 +1,40 @@
from .base import Base
from .masters import Category, Department, Location, Setting, User, Vendor
from .assets import Asset, Contract, InsurancePolicy, Warranty
from .maintenance import CalibrationPlan, CalibrationRecord, PMRecord, PMSchedule
from .complaints import Complaint, ComplaintEvent
from .operations import (
DemoEquipment,
DepartmentVisit,
department_visit_assets,
department_visit_complaints,
)
from .system import Attachment, AuditLog, Notification, NotificationRead
__all__ = [
"Base",
"Department",
"Location",
"Category",
"Vendor",
"User",
"Setting",
"Asset",
"Contract",
"Warranty",
"InsurancePolicy",
"CalibrationPlan",
"CalibrationRecord",
"PMSchedule",
"PMRecord",
"Complaint",
"ComplaintEvent",
"DemoEquipment",
"DepartmentVisit",
"department_visit_assets",
"department_visit_complaints",
"Attachment",
"Notification",
"NotificationRead",
"AuditLog",
]
+97
View File
@@ -0,0 +1,97 @@
from datetime import date, datetime
from typing import Optional
from sqlalchemy import Boolean, Date, DateTime, Float, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
from ..core.time_utils import utc_now
class Asset(Base):
__tablename__ = "assets"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_code: Mapped[str] = mapped_column(String(60), unique=True, index=True, nullable=False)
serial_no: Mapped[str] = mapped_column(String(100), index=True, nullable=False)
name: Mapped[str] = mapped_column(String(200), nullable=False)
category_id: Mapped[int] = mapped_column(ForeignKey("categories.id"), nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
location_id: Mapped[int] = mapped_column(ForeignKey("locations.id"), nullable=False)
supplier_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
purchase_value: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
purchase_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
installation_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
status: Mapped[str] = mapped_column(String(40), default="in_service", nullable=False)
criticality: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False)
requires_calibration: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
insurance_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
category = relationship("Category")
department = relationship("Department")
location = relationship("Location")
supplier = relationship("Vendor")
class Contract(Base):
__tablename__ = "contracts"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
contract_type: Mapped[str] = mapped_column(String(20), nullable=False)
provider_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
end_date: Mapped[date] = mapped_column(Date, nullable=False)
coverage_period_text: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
renewed_from_id: Mapped[Optional[int]] = mapped_column(ForeignKey("contracts.id"), nullable=True)
is_superseded: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
asset = relationship("Asset")
provider = relationship("Vendor")
class Warranty(Base):
__tablename__ = "warranties"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
duration_months: Mapped[int] = mapped_column(Integer, nullable=False)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
end_date: Mapped[date] = mapped_column(Date, nullable=False)
provider_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
asset = relationship("Asset")
provider = relationship("Vendor")
class InsurancePolicy(Base):
__tablename__ = "insurance_policies"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
insurer_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
policy_no: Mapped[str] = mapped_column(String(100), nullable=False)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
end_date: Mapped[date] = mapped_column(Date, nullable=False)
coverage_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
asset = relationship("Asset")
insurer = relationship("Vendor")
+59
View File
@@ -0,0 +1,59 @@
from datetime import datetime
from typing import Optional
from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
from ..core.time_utils import utc_now
class Complaint(Base):
__tablename__ = "complaints"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
complaint_no: Mapped[str] = mapped_column(String(60), unique=True, index=True, nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
description: Mapped[str] = mapped_column(Text, nullable=False)
breakdown_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
priority: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False)
notes: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
registered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
registered_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
received_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
assigned_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
attended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
restored_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
closed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
call_status: Mapped[str] = mapped_column(String(30), default="open", nullable=False)
closure_remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
action_taken: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
root_cause: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
corrective_action: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
lessons_learned: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
ce_name: Mapped[Optional[str]] = mapped_column(String(150), nullable=True)
ce_attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
ce_action_taken: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
spare_required: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
spare_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
spare_cost_estimate: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
asset = relationship("Asset")
class ComplaintEvent(Base):
__tablename__ = "complaint_events"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
complaint_id: Mapped[int] = mapped_column(ForeignKey("complaints.id"), nullable=False)
event_type: Mapped[str] = mapped_column(String(60), nullable=False)
from_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
to_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
by_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
complaint = relationship("Complaint")
+94
View File
@@ -0,0 +1,94 @@
from datetime import date, datetime
from typing import Optional
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
from ..core.time_utils import utc_now
class CalibrationPlan(Base):
__tablename__ = "calibration_plans"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), unique=True, nullable=False)
frequency_months: Mapped[int] = mapped_column(Integer, nullable=False)
calibrations_per_year: Mapped[int] = mapped_column(Integer, nullable=False)
agency_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
approved_on: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
next_due_date: Mapped[date] = mapped_column(Date, nullable=False)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
asset = relationship("Asset")
agency = relationship("Vendor")
class CalibrationRecord(Base):
__tablename__ = "calibration_records"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
plan_id: Mapped[int] = mapped_column(ForeignKey("calibration_plans.id"), nullable=False)
due_date: Mapped[date] = mapped_column(Date, nullable=False)
completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
agency_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
certificate_no: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# Only "completed" is persisted; upcoming/due/overdue are computed at read time.
status: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
asset = relationship("Asset")
plan = relationship("CalibrationPlan")
agency = relationship("Vendor")
class PMSchedule(Base):
__tablename__ = "pm_schedules"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
service_mode: Mapped[str] = mapped_column(String(30), nullable=False)
frequency_months: Mapped[int] = mapped_column(Integer, nullable=False)
responsible_team: Mapped[Optional[str]] = mapped_column(String(150), nullable=True)
provider_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
contract_id: Mapped[Optional[int]] = mapped_column(ForeignKey("contracts.id"), nullable=True)
next_planned_date: Mapped[date] = mapped_column(Date, nullable=False)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
asset = relationship("Asset")
provider = relationship("Vendor")
contract = relationship("Contract")
class PMRecord(Base):
__tablename__ = "pm_records"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
schedule_id: Mapped[int] = mapped_column(ForeignKey("pm_schedules.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
planned_date: Mapped[date] = mapped_column(Date, nullable=False)
completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
# Only "completed" or "rescheduled" is persisted; upcoming/due/overdue are computed at read time.
status: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
service_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
rescheduled_to: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
schedule = relationship("PMSchedule")
asset = relationship("Asset")
+83
View File
@@ -0,0 +1,83 @@
from datetime import datetime
from typing import Optional
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
from ..core.time_utils import utc_now
class Department(Base):
__tablename__ = "departments"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(150), unique=True, nullable=False)
code: Mapped[str] = mapped_column(String(30), unique=True, nullable=False)
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
class Location(Base):
__tablename__ = "locations"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
name: Mapped[str] = mapped_column(String(150), nullable=False)
floor_wing: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
department: Mapped["Department"] = relationship("Department")
class Category(Base):
__tablename__ = "categories"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(150), unique=True, nullable=False)
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
class Vendor(Base):
__tablename__ = "vendors"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(200), nullable=False)
vendor_type: Mapped[str] = mapped_column(String(50), nullable=False)
contact_person: Mapped[Optional[str]] = mapped_column(String(150), nullable=True)
phone: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
email: Mapped[Optional[str]] = mapped_column(String(150), nullable=True)
address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(150), nullable=False)
email: Mapped[str] = mapped_column(String(200), unique=True, index=True, nullable=False)
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
role: Mapped[str] = mapped_column(String(50), nullable=False)
department_id: Mapped[Optional[int]] = mapped_column(ForeignKey("departments.id"), nullable=True)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
department: Mapped[Optional["Department"]] = relationship("Department")
class Setting(Base):
__tablename__ = "settings"
key: Mapped[str] = mapped_column(String(100), primary_key=True)
value_json: Mapped[str] = mapped_column(Text, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
+62
View File
@@ -0,0 +1,62 @@
from datetime import date, datetime
from typing import Optional
from sqlalchemy import Column, Date, DateTime, ForeignKey, Integer, String, Table, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
from ..core.time_utils import utc_now
department_visit_assets = Table(
"department_visit_assets",
Base.metadata,
Column("visit_id", ForeignKey("department_visits.id"), primary_key=True),
Column("asset_id", ForeignKey("assets.id"), primary_key=True),
)
department_visit_complaints = Table(
"department_visit_complaints",
Base.metadata,
Column("visit_id", ForeignKey("department_visits.id"), primary_key=True),
Column("complaint_id", ForeignKey("complaints.id"), primary_key=True),
)
class DemoEquipment(Base):
__tablename__ = "demo_equipment"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(200), nullable=False)
equipment_type: Mapped[str] = mapped_column(String(100), nullable=False)
supplier_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
location_id: Mapped[Optional[int]] = mapped_column(ForeignKey("locations.id"), nullable=True)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
expected_return_date: Mapped[date] = mapped_column(Date, nullable=False)
actual_return_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
supplier = relationship("Vendor")
department = relationship("Department")
location = relationship("Location")
class DepartmentVisit(Base):
__tablename__ = "department_visits"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
visited_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
visit_date: Mapped[date] = mapped_column(Date, nullable=False)
observations: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
department = relationship("Department")
assets = relationship("Asset", secondary=department_visit_assets)
complaints = relationship("Complaint", secondary=department_visit_complaints)
+61
View File
@@ -0,0 +1,61 @@
from datetime import date, datetime
from typing import Optional
from sqlalchemy import Date, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base
from ..core.time_utils import utc_now
class Attachment(Base):
__tablename__ = "attachments"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
entity_type: Mapped[str] = mapped_column(String(60), nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, nullable=False)
original_name: Mapped[str] = mapped_column(String(255), nullable=False)
stored_name: Mapped[str] = mapped_column(String(255), nullable=False)
mime_type: Mapped[str] = mapped_column(String(120), nullable=False)
size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)
uploaded_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
uploaded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
class Notification(Base):
__tablename__ = "notifications"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
type: Mapped[str] = mapped_column(String(60), nullable=False)
severity: Mapped[str] = mapped_column(String(20), nullable=False)
title: Mapped[str] = mapped_column(String(200), nullable=False)
message: Mapped[str] = mapped_column(Text, nullable=False)
entity_type: Mapped[str] = mapped_column(String(60), nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, nullable=False)
due_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
target_role: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
target_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
dedupe_key: Mapped[str] = mapped_column(String(200), unique=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
class NotificationRead(Base):
__tablename__ = "notification_reads"
__table_args__ = (
UniqueConstraint("notification_id", "user_id", name="uq_notification_user_read"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
notification_id: Mapped[int] = mapped_column(ForeignKey("notifications.id"), nullable=False)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
read_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
class AuditLog(Base):
__tablename__ = "audit_logs"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
entity_type: Mapped[str] = mapped_column(String(60), nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, nullable=False)
action: Mapped[str] = mapped_column(String(50), nullable=False)
changes_json: Mapped[str] = mapped_column(Text, nullable=False)
by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
+3
View File
@@ -0,0 +1,3 @@
from . import auth, health, masters, settings, users
__all__ = ["auth", "health", "masters", "settings", "users"]
+59
View File
@@ -0,0 +1,59 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user
from ..core.security import create_access_token, verify_password
from ..models.masters import User
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
from ..services.settings_service import get_demo_as_of_date
router = APIRouter(prefix="/auth", tags=["auth"])
def _build_user_out(user: User, db: Session) -> UserOut:
return UserOut(
id=user.id,
name=user.name,
email=user.email,
role=user.role,
department_id=user.department_id,
department_name=user.department.name if user.department else None,
is_active=user.is_active,
demo_as_of_date=get_demo_as_of_date(db),
)
@router.post("/login", response_model=TokenResponse)
def login(payload: LoginRequest, db: Session = Depends(get_db)):
email_norm = payload.email.strip().lower()
user = (
db.query(User)
.options(joinedload(User.department))
.filter(User.email == email_norm)
.first()
)
if user is None or not verify_password(payload.password, user.password_hash):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid email or password.",
)
if not user.is_active:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="User account is inactive.",
)
token = create_access_token({"sub": str(user.id), "role": user.role})
return TokenResponse(
access_token=token,
token_type="bearer",
user=_build_user_out(user, db),
)
@router.get("/me", response_model=UserOut)
def get_me(
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
return _build_user_out(current_user, db)
+392
View File
@@ -0,0 +1,392 @@
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user, require_roles
from ..models.masters import Category, Department, Location, User, Vendor
from ..schemas.masters import (
CategoryCreate,
CategoryOut,
CategoryUpdate,
DepartmentCreate,
DepartmentOut,
DepartmentUpdate,
LocationCreate,
LocationOut,
LocationUpdate,
PaginatedOut,
VendorCreate,
VendorOut,
VendorUpdate,
)
from ..services.permissions import Role
router = APIRouter(tags=["masters"])
def _paginate(query, page: int, page_size: int):
total = query.count()
if page_size > 0:
query = query.offset((page - 1) * page_size).limit(page_size)
return query.all(), total
def _loc_out(loc: Location) -> LocationOut:
return LocationOut(
id=loc.id,
department_id=loc.department_id,
department_name=loc.department.name if loc.department else None,
name=loc.name,
floor_wing=loc.floor_wing,
is_active=loc.is_active,
)
# ---------------- Departments ----------------
@router.get("/departments", response_model=PaginatedOut[DepartmentOut])
def list_departments(
q: Optional[str] = None,
page: int = Query(1, ge=1),
page_size: int = Query(100, ge=0, le=500),
include_inactive: bool = False,
db: Session = Depends(get_db),
_: User = Depends(get_current_user),
):
query = db.query(Department)
if not include_inactive:
query = query.filter(Department.is_active.is_(True))
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(or_(Department.name.ilike(like), Department.code.ilike(like)))
query = query.order_by(Department.name.asc())
items, total = _paginate(query, page, page_size)
return {"items": items, "total": total}
@router.post("/departments", response_model=DepartmentOut, status_code=status.HTTP_201_CREATED)
def create_department(
payload: DepartmentCreate,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
dept = Department(
name=payload.name.strip(),
code=payload.code.strip().upper(),
description=payload.description,
is_active=payload.is_active,
)
db.add(dept)
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Department with this name or code already exists.",
)
db.refresh(dept)
return dept
@router.patch("/departments/{dept_id}", response_model=DepartmentOut)
def update_department(
dept_id: int,
payload: DepartmentUpdate,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
dept = db.query(Department).filter(Department.id == dept_id).first()
if dept is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
data = payload.model_dump(exclude_unset=True)
if "name" in data and data["name"] is not None:
data["name"] = data["name"].strip()
if "code" in data and data["code"] is not None:
data["code"] = data["code"].strip().upper()
for k, v in data.items():
setattr(dept, k, v)
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Department with this name or code already exists.",
)
db.refresh(dept)
return dept
@router.delete("/departments/{dept_id}", response_model=DepartmentOut)
def delete_department(
dept_id: int,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
dept = db.query(Department).filter(Department.id == dept_id).first()
if dept is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
dept.is_active = False
db.commit()
db.refresh(dept)
return dept
# ---------------- Locations ----------------
@router.get("/locations", response_model=PaginatedOut[LocationOut])
def list_locations(
q: Optional[str] = None,
department_id: Optional[int] = None,
page: int = Query(1, ge=1),
page_size: int = Query(100, ge=0, le=500),
include_inactive: bool = False,
db: Session = Depends(get_db),
_: User = Depends(get_current_user),
):
query = db.query(Location).options(joinedload(Location.department))
if not include_inactive:
query = query.filter(Location.is_active.is_(True))
if department_id is not None:
query = query.filter(Location.department_id == department_id)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(or_(Location.name.ilike(like), Location.floor_wing.ilike(like)))
query = query.order_by(Location.name.asc())
items, total = _paginate(query, page, page_size)
return {"items": [_loc_out(loc) for loc in items], "total": total}
@router.post("/locations", response_model=LocationOut, status_code=status.HTTP_201_CREATED)
def create_location(
payload: LocationCreate,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
dept = db.query(Department).filter(Department.id == payload.department_id).first()
if dept is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
loc = Location(
department_id=payload.department_id,
name=payload.name.strip(),
floor_wing=payload.floor_wing,
is_active=payload.is_active,
)
db.add(loc)
db.commit()
db.refresh(loc)
loc.department = dept
return _loc_out(loc)
@router.patch("/locations/{location_id}", response_model=LocationOut)
def update_location(
location_id: int,
payload: LocationUpdate,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
loc = db.query(Location).options(joinedload(Location.department)).filter(Location.id == location_id).first()
if loc is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
data = payload.model_dump(exclude_unset=True)
if "department_id" in data and data["department_id"] is not None:
dept = db.query(Department).filter(Department.id == data["department_id"]).first()
if dept is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
if "name" in data and data["name"] is not None:
data["name"] = data["name"].strip()
for k, v in data.items():
setattr(loc, k, v)
db.commit()
db.refresh(loc)
return _loc_out(loc)
@router.delete("/locations/{location_id}", response_model=LocationOut)
def delete_location(
location_id: int,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
loc = db.query(Location).options(joinedload(Location.department)).filter(Location.id == location_id).first()
if loc is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
loc.is_active = False
db.commit()
db.refresh(loc)
return _loc_out(loc)
# ---------------- Categories ----------------
@router.get("/categories", response_model=PaginatedOut[CategoryOut])
def list_categories(
q: Optional[str] = None,
page: int = Query(1, ge=1),
page_size: int = Query(100, ge=0, le=500),
include_inactive: bool = False,
db: Session = Depends(get_db),
_: User = Depends(get_current_user),
):
query = db.query(Category)
if not include_inactive:
query = query.filter(Category.is_active.is_(True))
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(Category.name.ilike(like))
query = query.order_by(Category.name.asc())
items, total = _paginate(query, page, page_size)
return {"items": items, "total": total}
@router.post("/categories", response_model=CategoryOut, status_code=status.HTTP_201_CREATED)
def create_category(
payload: CategoryCreate,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
cat = Category(
name=payload.name.strip(),
description=payload.description,
is_active=payload.is_active,
)
db.add(cat)
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Category with this name already exists.",
)
db.refresh(cat)
return cat
@router.patch("/categories/{category_id}", response_model=CategoryOut)
def update_category(
category_id: int,
payload: CategoryUpdate,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
cat = db.query(Category).filter(Category.id == category_id).first()
if cat is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found.")
data = payload.model_dump(exclude_unset=True)
if "name" in data and data["name"] is not None:
data["name"] = data["name"].strip()
for k, v in data.items():
setattr(cat, k, v)
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Category with this name already exists.",
)
db.refresh(cat)
return cat
@router.delete("/categories/{category_id}", response_model=CategoryOut)
def delete_category(
category_id: int,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
cat = db.query(Category).filter(Category.id == category_id).first()
if cat is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found.")
cat.is_active = False
db.commit()
db.refresh(cat)
return cat
# ---------------- Vendors ----------------
@router.get("/vendors", response_model=PaginatedOut[VendorOut])
def list_vendors(
q: Optional[str] = None,
vendor_type: Optional[str] = None,
page: int = Query(1, ge=1),
page_size: int = Query(100, ge=0, le=500),
include_inactive: bool = False,
db: Session = Depends(get_db),
_: User = Depends(get_current_user),
):
query = db.query(Vendor)
if not include_inactive:
query = query.filter(Vendor.is_active.is_(True))
if vendor_type:
query = query.filter(Vendor.vendor_type == vendor_type)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Vendor.name.ilike(like),
Vendor.contact_person.ilike(like),
Vendor.email.ilike(like),
)
)
query = query.order_by(Vendor.name.asc())
items, total = _paginate(query, page, page_size)
return {"items": items, "total": total}
@router.post("/vendors", response_model=VendorOut, status_code=status.HTTP_201_CREATED)
def create_vendor(
payload: VendorCreate,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
vendor = Vendor(
name=payload.name.strip(),
vendor_type=payload.vendor_type,
contact_person=payload.contact_person,
phone=payload.phone,
email=payload.email,
address=payload.address,
is_active=payload.is_active,
)
db.add(vendor)
db.commit()
db.refresh(vendor)
return vendor
@router.patch("/vendors/{vendor_id}", response_model=VendorOut)
def update_vendor(
vendor_id: int,
payload: VendorUpdate,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
if vendor is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Vendor not found.")
data = payload.model_dump(exclude_unset=True)
if "name" in data and data["name"] is not None:
data["name"] = data["name"].strip()
for k, v in data.items():
setattr(vendor, k, v)
db.commit()
db.refresh(vendor)
return vendor
@router.delete("/vendors/{vendor_id}", response_model=VendorOut)
def delete_vendor(
vendor_id: int,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
if vendor is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Vendor not found.")
vendor.is_active = False
db.commit()
db.refresh(vendor)
return vendor
+43
View File
@@ -0,0 +1,43 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..core.db import get_db
from ..core.deps import require_roles
from ..core.time_utils import effective_today
from ..models.masters import User
from ..schemas.settings import DemoDateIn, DemoDateOut, SettingsListOut, SettingsUpdateIn
from ..services.permissions import Role
from ..services.settings_service import get_all_settings, get_demo_as_of_date, update_settings
router = APIRouter(prefix="/settings", tags=["settings"])
@router.get("", response_model=SettingsListOut)
def list_settings(
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
return {"items": get_all_settings(db)}
@router.put("", response_model=SettingsListOut)
def save_settings(
payload: SettingsUpdateIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin)),
):
items = update_settings(db, payload.values, user_id=current_user.id)
return {"items": items}
@router.post("/demo-date", response_model=DemoDateOut)
def set_demo_date(
payload: DemoDateIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin)),
):
val = payload.demo_as_of_date if payload.demo_as_of_date is not None else ""
update_settings(db, {"demo_as_of_date": val}, user_id=current_user.id)
return {
"demo_as_of_date": get_demo_as_of_date(db),
"effective_today": effective_today(db).isoformat(),
}
+164
View File
@@ -0,0 +1,164 @@
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user, require_roles
from ..core.security import hash_password
from ..models.masters import Department, User
from ..schemas.masters import (
PaginatedOut,
UserCreate,
UserListOut,
UserLookupOut,
UserUpdate,
)
from ..services.permissions import Role
router = APIRouter(prefix="/users", tags=["users"])
def _user_list_out(user: User) -> UserListOut:
return UserListOut(
id=user.id,
name=user.name,
email=user.email,
role=user.role,
department_id=user.department_id,
department_name=user.department.name if user.department else None,
is_active=user.is_active,
)
@router.get("", response_model=PaginatedOut[UserListOut])
def list_users(
q: Optional[str] = None,
role: Optional[str] = None,
page: int = Query(1, ge=1),
page_size: int = Query(100, ge=0, le=500),
include_inactive: bool = False,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
query = db.query(User).options(joinedload(User.department))
if not include_inactive:
query = query.filter(User.is_active.is_(True))
if role:
query = query.filter(User.role == role)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(or_(User.name.ilike(like), User.email.ilike(like)))
query = query.order_by(User.name.asc())
total = query.count()
if page_size > 0:
query = query.offset((page - 1) * page_size).limit(page_size)
items = query.all()
return {"items": [_user_list_out(u) for u in items], "total": total}
@router.get("/lookup", response_model=list[UserLookupOut])
def lookup_users(
db: Session = Depends(get_db),
_: User = Depends(get_current_user),
):
users = (
db.query(User)
.filter(User.is_active.is_(True))
.order_by(User.name.asc())
.all()
)
return users
@router.post("", response_model=UserListOut, status_code=status.HTTP_201_CREATED)
def create_user(
payload: UserCreate,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
if payload.department_id is not None:
dept = db.query(Department).filter(Department.id == payload.department_id).first()
if dept is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
user = User(
name=payload.name.strip(),
email=payload.email.strip().lower(),
password_hash=hash_password(payload.password),
role=payload.role,
department_id=payload.department_id,
is_active=payload.is_active,
)
db.add(user)
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="A user with this email already exists.",
)
user = db.query(User).options(joinedload(User.department)).filter(User.id == user.id).first()
return _user_list_out(user)
@router.patch("/{user_id}", response_model=UserListOut)
def update_user(
user_id: int,
payload: UserUpdate,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
data = payload.model_dump(exclude_unset=True)
if "department_id" in data and data["department_id"] is not None:
dept = db.query(Department).filter(Department.id == data["department_id"]).first()
if dept is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
if "name" in data and data["name"] is not None:
data["name"] = data["name"].strip()
if "email" in data and data["email"] is not None:
data["email"] = data["email"].strip().lower()
password = data.pop("password", None)
if password is not None and password.strip():
if len(password) < 4:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must be at least 4 characters.",
)
user.password_hash = hash_password(password)
for k, v in data.items():
setattr(user, k, v)
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="A user with this email already exists.",
)
db.refresh(user)
user = db.query(User).options(joinedload(User.department)).filter(User.id == user.id).first()
return _user_list_out(user)
@router.delete("/{user_id}", response_model=UserListOut)
def delete_user(
user_id: int,
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
user.is_active = False
db.commit()
db.refresh(user)
return _user_list_out(user)
+49
View File
@@ -0,0 +1,49 @@
from .auth import LoginRequest, TokenResponse, UserOut
from .masters import (
CategoryCreate,
CategoryOut,
CategoryUpdate,
DepartmentCreate,
DepartmentOut,
DepartmentUpdate,
LocationCreate,
LocationOut,
LocationUpdate,
PaginatedOut,
UserCreate,
UserListOut,
UserLookupOut,
UserUpdate,
VendorCreate,
VendorOut,
VendorUpdate,
)
from .settings import DemoDateIn, DemoDateOut, SettingItemOut, SettingsListOut, SettingsUpdateIn
__all__ = [
"LoginRequest",
"TokenResponse",
"UserOut",
"PaginatedOut",
"DepartmentCreate",
"DepartmentUpdate",
"DepartmentOut",
"LocationCreate",
"LocationUpdate",
"LocationOut",
"CategoryCreate",
"CategoryUpdate",
"CategoryOut",
"VendorCreate",
"VendorUpdate",
"VendorOut",
"UserCreate",
"UserUpdate",
"UserListOut",
"UserLookupOut",
"SettingItemOut",
"SettingsListOut",
"SettingsUpdateIn",
"DemoDateIn",
"DemoDateOut",
]
+26
View File
@@ -0,0 +1,26 @@
from typing import Optional
from pydantic import BaseModel, ConfigDict
class LoginRequest(BaseModel):
email: str
password: str
class UserOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
email: str
role: str
department_id: Optional[int] = None
department_name: Optional[str] = None
is_active: bool
demo_as_of_date: Optional[str] = None
class TokenResponse(BaseModel):
access_token: str
token_type: str = "bearer"
user: UserOut
+159
View File
@@ -0,0 +1,159 @@
from typing import Generic, Literal, Optional, TypeVar
from pydantic import BaseModel, ConfigDict, Field
T = TypeVar("T")
VendorType = Literal["supplier", "service_provider", "calibration_agency", "insurer", "oem"]
UserRole = Literal["system_admin", "biomedical", "department_user", "management", "coordinator"]
class PaginatedOut(BaseModel, Generic[T]):
items: list[T]
total: int
# --- Departments ---
class DepartmentCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=150)
code: str = Field(..., min_length=1, max_length=30)
description: Optional[str] = None
is_active: bool = True
class DepartmentUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=150)
code: Optional[str] = Field(None, min_length=1, max_length=30)
description: Optional[str] = None
is_active: Optional[bool] = None
class DepartmentOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
code: str
description: Optional[str] = None
is_active: bool
# --- Locations ---
class LocationCreate(BaseModel):
department_id: int
name: str = Field(..., min_length=1, max_length=150)
floor_wing: Optional[str] = Field(None, max_length=100)
is_active: bool = True
class LocationUpdate(BaseModel):
department_id: Optional[int] = None
name: Optional[str] = Field(None, min_length=1, max_length=150)
floor_wing: Optional[str] = Field(None, max_length=100)
is_active: Optional[bool] = None
class LocationOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
department_id: int
department_name: Optional[str] = None
name: str
floor_wing: Optional[str] = None
is_active: bool
# --- Categories ---
class CategoryCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=150)
description: Optional[str] = None
is_active: bool = True
class CategoryUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=150)
description: Optional[str] = None
is_active: Optional[bool] = None
class CategoryOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
description: Optional[str] = None
is_active: bool
# --- Vendors ---
class VendorCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=200)
vendor_type: VendorType
contact_person: Optional[str] = Field(None, max_length=150)
phone: Optional[str] = Field(None, max_length=50)
email: Optional[str] = Field(None, max_length=150)
address: Optional[str] = None
is_active: bool = True
class VendorUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=200)
vendor_type: Optional[VendorType] = None
contact_person: Optional[str] = Field(None, max_length=150)
phone: Optional[str] = Field(None, max_length=50)
email: Optional[str] = Field(None, max_length=150)
address: Optional[str] = None
is_active: Optional[bool] = None
class VendorOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
vendor_type: str
contact_person: Optional[str] = None
phone: Optional[str] = None
email: Optional[str] = None
address: Optional[str] = None
is_active: bool
# --- Users ---
class UserCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=150)
email: str = Field(..., min_length=3, max_length=200)
password: str = Field(..., min_length=4, max_length=128)
role: UserRole
department_id: Optional[int] = None
is_active: bool = True
class UserUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=150)
email: Optional[str] = Field(None, min_length=3, max_length=200)
password: Optional[str] = Field(None, max_length=128)
role: Optional[UserRole] = None
department_id: Optional[int] = None
is_active: Optional[bool] = None
class UserListOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
email: str
role: str
department_id: Optional[int] = None
department_name: Optional[str] = None
is_active: bool
class UserLookupOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
role: str
department_id: Optional[int] = None
+31
View File
@@ -0,0 +1,31 @@
from typing import Any, Optional
from pydantic import BaseModel
class SettingItemOut(BaseModel):
key: str
value: Any
type: str
label: str
description: str
default: Any
min: Optional[int] = None
max: Optional[int] = None
options: Optional[list[str]] = None
class SettingsListOut(BaseModel):
items: list[SettingItemOut]
class SettingsUpdateIn(BaseModel):
values: dict[str, Any]
class DemoDateIn(BaseModel):
demo_as_of_date: Optional[str] = None
class DemoDateOut(BaseModel):
demo_as_of_date: Optional[str] = None
effective_today: str
View File
+806
View File
@@ -0,0 +1,806 @@
from datetime import date, datetime, time, timedelta, timezone
from pathlib import Path
import random
import time as pytime
from PIL import Image, ImageDraw
from sqlalchemy import text
from sqlalchemy.orm import Session
from ..core.config import settings
from ..core.db import SessionLocal, engine
from ..core.security import hash_password
from ..core.time_utils import KOLKATA
from ..models import (
Asset,
Attachment,
Base,
CalibrationPlan,
CalibrationRecord,
Category,
Complaint,
ComplaintEvent,
Contract,
DemoEquipment,
Department,
DepartmentVisit,
InsurancePolicy,
Location,
PMRecord,
PMSchedule,
User,
Vendor,
Warranty,
)
from ..services.settings_service import ensure_default_settings
def _make_minimal_pdf(title: str) -> bytes:
safe_title = title.replace("(", "").replace(")", "")
stream = f"BT /F1 14 Tf 50 750 Td ({safe_title}) Tj ET".encode("latin-1", errors="ignore")
objects = [
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n",
b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\nendobj\n",
f"4 0 obj\n<< /Length {len(stream)} >>\nstream\n".encode("ascii") + stream + b"\nendstream\nendobj\n",
b"5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n",
]
out = bytearray(b"%PDF-1.4\n")
offsets = [0]
for obj in objects:
offsets.append(len(out))
out.extend(obj)
xref_pos = len(out)
out.extend(f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode("ascii"))
for off in offsets[1:]:
out.extend(f"{off:010d} 00000 n \n".encode("ascii"))
out.extend(
f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode("ascii")
)
return bytes(out)
def _make_placeholder_jpeg(dest: Path, label: str, bg_rgb: tuple[int, int, int]) -> int:
img = Image.new("RGB", (640, 480), color=bg_rgb)
draw = ImageDraw.Draw(img)
draw.rectangle([20, 20, 620, 460], outline=(255, 255, 255), width=3)
draw.text((40, 200), "Poona Hospital & Research Centre", fill=(255, 255, 255))
draw.text((40, 240), label, fill=(240, 240, 240))
img.save(dest, format="JPEG", quality=80)
return dest.stat().st_size
def _ist_to_utc(d: date, hour: int = 10, minute: int = 0) -> datetime:
local_dt = KOLKATA.localize(datetime.combine(d, time(hour, minute)))
return local_dt.astimezone(timezone.utc)
def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]:
rng = random.Random(42)
today = datetime.now(KOLKATA).date()
now_utc = datetime.now(timezone.utc)
# 1. Clear all tables cleanly in reverse dependency order
for table in reversed(Base.metadata.sorted_tables):
db.execute(table.delete())
# Reset SQLite autoincrement counters if sqlite_sequence exists
try:
db.execute(text("DELETE FROM sqlite_sequence"))
except Exception:
pass
db.flush()
# 2. Settings (14 keys)
ensure_default_settings(db)
# 3. Departments (8)
dept_specs = [
("Intensive Care Unit", "ICU", "Medical and surgical intensive care beds"),
("Operation Theatre", "OT", "Main and modular surgical suites"),
("Radiology & Imaging", "RAD", "CT, MRI, Ultrasound, and X-Ray"),
("Cardiology", "CARD", "Cath lab and cardiac diagnostics"),
("Emergency & Trauma", "EMER", "24x7 casualty and trauma care"),
("Pathology & Lab", "LAB", "Clinical biochemistry and hematology"),
("Neonatal ICU", "NICU", "Neonatal intensive care and warmers"),
("Dialysis Unit", "DIAL", "Hemodialysis and RO water treatment"),
]
departments: list[Department] = []
for name, code, desc in dept_specs:
d = Department(name=name, code=code, description=desc, is_active=True)
db.add(d)
departments.append(d)
db.flush()
# 4. Locations (20)
loc_specs = [
(0, "ICU Bay A", "2nd Floor - East Wing"),
(0, "ICU Bay B", "2nd Floor - East Wing"),
(0, "ICU Isolation Room 1", "2nd Floor - East Wing"),
(1, "Modular OT 1", "3rd Floor - Central Block"),
(1, "Modular OT 2", "3rd Floor - Central Block"),
(1, "OT Recovery Suite", "3rd Floor - Central Block"),
(2, "CT Scan Room", "Ground Floor - West Wing"),
(2, "Digital X-Ray Suite", "Ground Floor - West Wing"),
(2, "Ultrasound Room 2", "Ground Floor - West Wing"),
(3, "Cath Lab 1", "4th Floor - Cardiac Block"),
(3, "Echo & TMT Room", "4th Floor - Cardiac Block"),
(4, "Trauma Resuscitation Bay", "Ground Floor - Main Gate"),
(4, "Emergency Observation Ward", "Ground Floor - Main Gate"),
(5, "Biochemistry Analyzer Lab", "1st Floor - Diagnostic Wing"),
(5, "Hematology & Blood Bank", "1st Floor - Diagnostic Wing"),
(6, "NICU Level 3 Bay", "2nd Floor - Maternity Wing"),
(6, "NICU Step-Down Unit", "2nd Floor - Maternity Wing"),
(7, "Dialysis Station 1-6", "1st Floor - Renal Wing"),
(7, "Dialysis Station 7-12", "1st Floor - Renal Wing"),
(7, "RO Water Plant Room", "1st Floor - Renal Wing"),
]
locations: list[Location] = []
locs_by_dept: dict[int, list[Location]] = {d.id: [] for d in departments}
for dept_idx, lname, floor in loc_specs:
dept = departments[dept_idx]
loc = Location(department_id=dept.id, name=lname, floor_wing=floor, is_active=True)
db.add(loc)
locations.append(loc)
locs_by_dept[dept.id].append(loc)
db.flush()
# 5. Categories (8)
cat_specs = [
("Life Support & Ventilators", "ICU ventilators, CPAP/BiPAP, anesthesia systems"),
("Patient Monitoring", "Multipara monitors, pulse oximeters, central stations"),
("Diagnostic Imaging", "X-Ray, C-Arm, ultrasound, CT/MRI auxiliaries"),
("Surgical & OT Equipment", "Electrosurgical cautery, OT tables, OT lights"),
("Laboratory Analyzers", "Biochemistry, hematology, blood gas analyzers"),
("Infusion & Dialysis", "Syringe pumps, infusion pumps, hemodialysis machines"),
("Sterilization & CSSD", "Autoclaves, ETO sterilizers, washer-disinfectors"),
("Emergency & Resuscitation", "Defibrillators, crash carts, suction apparatus"),
]
categories: list[Category] = []
for cname, cdesc in cat_specs:
c = Category(name=cname, description=cdesc, is_active=True)
db.add(c)
categories.append(c)
db.flush()
# 6. Vendors (12)
vendor_specs = [
("Philips Healthcare India", "oem", "Arun Mehta", "+91-20-66201100", "service.west@philips-demo.in", "Pune, MH"),
("GE HealthCare Medical Systems", "oem", "Sanjay Verma", "+91-20-66202200", "support@gehc-demo.in", "Mumbai, MH"),
("Mindray Medical India", "oem", "Rohan Kapoor", "+91-22-40203300", "service@mindray-demo.in", "Mumbai, MH"),
("MedTech Pune Distributors", "supplier", "Prashant Joshi", "+91-9822011223", "sales@medtechpune.in", "Deccan Gymkhana, Pune"),
("Sahyadri Medical Supplies", "supplier", "Manish Patwardhan", "+91-9823044556", "orders@sahyadrimed.in", "Kothrud, Pune"),
("Deccan Bio-Equipments", "supplier", "Kavita Gokhale", "+91-9890077889", "info@deccanbio.in", "Shivajinagar, Pune"),
("Apex Biomedical Services", "service_provider", "Nitin Kulkarni", "+91-9765012345", "amc@apexbiomed.in", "Pimpri, Pune"),
("Precision MedCare Engineering", "service_provider", "Deepak Rao", "+91-9850098765", "ops@precisionmedcare.in", "Hadapsar, Pune"),
("NABL Metrology & CalLabs Pune", "calibration_agency", "Dr. Sunita Deshpande", "+91-20-25441234", "cal@nablcallabs.in", "Bhosari MIDC, Pune"),
("Western India Calibration Lab", "calibration_agency", "Mahesh Pawar", "+91-20-24335678", "qa@wical.in", "Satara Road, Pune"),
("New India Assurance Co.", "insurer", "Smita Kale", "+91-20-26128899", "corporate@nia-demo.in", "MG Road, Pune"),
("Bajaj Allianz General Insurance", "insurer", "Vivek Deshmukh", "+91-20-66026602", "healthassets@bagic-demo.in", "Yerwada, Pune"),
]
vendors: list[Vendor] = []
vendors_by_type: dict[str, list[Vendor]] = {}
for vname, vtype, cp, ph, em, addr in vendor_specs:
v = Vendor(
name=vname,
vendor_type=vtype,
contact_person=cp,
phone=ph,
email=em,
address=addr,
is_active=True,
)
db.add(v)
vendors.append(v)
vendors_by_type.setdefault(vtype, []).append(v)
db.flush()
# 7. Users (11: 5 demo + 6 realistic hospital staff)
demo_pw_hash = hash_password("Demo@123")
user_specs = [
("Dr. Rajesh Kulkarni", "admin@poona.demo", "system_admin", None),
("Suresh Deshmukh", "bio@poona.demo", "biomedical", None),
("Sister Kavita Joshi", "dept@poona.demo", "department_user", departments[0].id), # ICU
("Dr. Anjali Gokhale", "mgmt@poona.demo", "management", None),
("Priya Patwardhan", "coord@poona.demo", "coordinator", None),
("Vikram Shinde", "vikram.shinde@poona.demo", "biomedical", None),
("Sneha Kulkarni", "sneha.kulkarni@poona.demo", "biomedical", None),
("Dr. Amit Bhosale", "dr.amit.bhosale@poona.demo", "department_user", departments[1].id), # OT
("Meera Nair", "meera.nair@poona.demo", "department_user", departments[2].id), # RAD
("Rohit Deshpande", "rohit.deshpande@poona.demo", "department_user", departments[3].id), # CARD
("Neha Chavan", "neha.chavan@poona.demo", "coordinator", None),
]
users: list[User] = []
for uname, uemail, urole, udept in user_specs:
u = User(
name=uname,
email=uemail,
password_hash=demo_pw_hash,
role=urole,
department_id=udept,
is_active=True,
)
db.add(u)
users.append(u)
db.flush()
admin_user = users[0]
bio_users = [users[1], users[5], users[6]]
dept_users = [users[2], users[7], users[8], users[9]]
coord_users = [users[4], users[10]]
# 8. Assets (60)
equipment_catalog = [
("ICU Ventilator Servo-i", 0, 0, True, True, 1850000.0),
("Multipara Patient Monitor MP50", 1, 0, True, True, 320000.0),
("Syringe Infusion Pump SP-500", 5, 0, True, False, 58000.0),
("Biphasic Defibrillator DFM100", 7, 4, True, True, 285000.0),
("Anesthesia Workstation Aespire", 0, 1, True, True, 1650000.0),
("Electrosurgical Cautery Unit", 3, 1, True, False, 240000.0),
("LED Dual-Dome OT Light", 3, 1, False, False, 480000.0),
("Mobile Digital X-Ray Unit", 2, 2, True, True, 2200000.0),
("C-Arm Fluoroscopy System", 2, 1, True, True, 3400000.0),
("Color Doppler Ultrasound", 2, 2, False, True, 2600000.0),
("12-Channel Digital ECG Machine", 1, 3, True, False, 115000.0),
("Echocardiography System Vivid", 2, 3, False, True, 4200000.0),
("Automated Biochemistry Analyzer", 4, 5, True, True, 1450000.0),
("5-Part Hematology Analyzer", 4, 5, True, True, 980000.0),
("ABG Blood Gas Analyzer", 4, 0, True, False, 410000.0),
("Infant Radiant Warmer", 0, 6, True, False, 195000.0),
("Neonatal Phototherapy Unit", 0, 6, False, False, 85000.0),
("Hemodialysis Machine 4008S", 5, 7, True, True, 890000.0),
("High-Pressure Steam Autoclave", 6, 1, True, True, 650000.0),
("Portable Suction Apparatus", 7, 4, False, False, 35000.0),
]
suppliers_and_oems = vendors_by_type["supplier"] + vendors_by_type["oem"]
dept_counters: dict[str, int] = {}
assets: list[Asset] = []
for i in range(60):
base_name, cat_idx, default_dept_idx, req_cal, ins_app, base_val = equipment_catalog[i % len(equipment_catalog)]
dept_idx = default_dept_idx if i < 20 else rng.randrange(len(departments))
dept = departments[dept_idx]
dept_counters[dept.code] = dept_counters.get(dept.code, 0) + 1
asset_code = f"PHRC-{dept.code}-{dept_counters[dept.code]:04d}"
loc = rng.choice(locs_by_dept[dept.id])
supplier = rng.choice(suppliers_and_oems)
years_ago = rng.randint(1, 10)
purchase_date = today - timedelta(days=years_ago * 365 + rng.randint(0, 300))
install_date = purchase_date + timedelta(days=rng.randint(7, 30))
# Status distribution: mostly in_service, a few under_repair / out_of_service / condemned
if i in (5, 19, 31, 44):
status_val = "under_repair"
elif i in (52, 57):
status_val = "out_of_service"
elif i in (58, 59):
status_val = "condemned"
else:
status_val = "in_service"
criticality = "critical" if (cat_idx in (0, 2, 3, 7) or i % 3 == 0) else "non_critical"
# Ensure at least first 20 assets requiring calibration and 25 insurance_applicable
needs_cal = True if i < 22 else req_cal
needs_ins = True if i < 26 else ins_app
a = Asset(
asset_code=asset_code,
serial_no=f"SN-{2016 + (i % 9)}-{10000 + i * 37}",
name=f"{base_name}" if i < 20 else f"{base_name} #{(i // 20) + 1}",
category_id=categories[cat_idx].id,
department_id=dept.id,
location_id=loc.id,
supplier_id=supplier.id,
purchase_value=round(base_val * rng.uniform(0.92, 1.12), 2),
purchase_date=purchase_date,
installation_date=install_date,
status=status_val,
criticality=criticality,
requires_calibration=needs_cal,
insurance_applicable=needs_ins,
remarks="Procured under Poona Hospital capital equipment budget.",
created_by_id=admin_user.id,
updated_by_id=admin_user.id,
)
db.add(a)
assets.append(a)
db.flush()
# 9. Contracts (35 total: 3 expiring <=30d, 1 <=5d, 1 expired, 1 renewed chain w/ is_superseded=True)
service_providers = vendors_by_type["service_provider"] + vendors_by_type["oem"]
contracts: list[Contract] = []
# Renewed chain: old superseded contract (#0) + active renewed contract (#1)
old_c = Contract(
asset_id=assets[0].id,
contract_type="CMC",
provider_id=service_providers[0].id,
start_date=today - timedelta(days=400),
end_date=today - timedelta(days=35),
coverage_period_text="1 Year",
renewed_from_id=None,
is_superseded=True,
remarks="Previous year CMC superseded on renewal.",
created_by_id=coord_users[0].id,
updated_by_id=coord_users[0].id,
)
db.add(old_c)
db.flush()
contracts.append(old_c)
new_c = Contract(
asset_id=assets[0].id,
contract_type="CMC",
provider_id=service_providers[0].id,
start_date=today - timedelta(days=34),
end_date=today + timedelta(days=331),
coverage_period_text="1 Year",
renewed_from_id=old_c.id,
is_superseded=False,
remarks="Renewed annual comprehensive maintenance contract.",
created_by_id=coord_users[0].id,
updated_by_id=coord_users[0].id,
)
db.add(new_c)
contracts.append(new_c)
# 1 expiring <= 5d (idx 2), 3 expiring <= 30d (idx 3, 4, 5), 1 expired (idx 6), rest active > 45d
special_end_offsets = {
2: 3, # <= 5 days
3: 11, # <= 30 days
4: 19, # <= 30 days
5: 27, # <= 30 days
6: -14, # expired
}
for idx in range(2, 35):
asset = assets[idx]
offset = special_end_offsets.get(idx, rng.randint(50, 340))
end_d = today + timedelta(days=offset)
start_d = end_d - timedelta(days=365)
ctype = rng.choice(["AMC", "CMC", "AMC", "OTHER"])
c = Contract(
asset_id=asset.id,
contract_type=ctype,
provider_id=rng.choice(service_providers).id,
start_date=start_d,
end_date=end_d,
coverage_period_text="1 Year",
renewed_from_id=None,
is_superseded=False,
remarks=f"{ctype} maintenance coverage for {asset.asset_code}.",
created_by_id=coord_users[idx % 2].id,
updated_by_id=coord_users[idx % 2].id,
)
db.add(c)
contracts.append(c)
db.flush()
active_contract_by_asset: dict[int, Contract] = {
c.asset_id: c for c in contracts if not c.is_superseded and c.end_date >= today
}
# 10. Warranties (20 total: 4 expiring <= 30d)
for idx in range(20):
asset = assets[idx]
if idx < 4:
end_d = today + timedelta(days=[5, 14, 22, 28][idx])
dur = 24
start_d = end_d - timedelta(days=dur * 30)
else:
dur = rng.choice([12, 24, 36])
end_d = today + timedelta(days=rng.randint(60, 500))
start_d = end_d - timedelta(days=dur * 30)
w = Warranty(
asset_id=asset.id,
duration_months=dur,
start_date=start_d,
end_date=end_d,
provider_id=asset.supplier_id,
remarks="OEM standard warranty.",
created_by_id=coord_users[0].id,
updated_by_id=coord_users[0].id,
)
db.add(w)
db.flush()
# 11. Insurance Policies (25 total: 2 expiring soon)
insurers = vendors_by_type["insurer"]
insured_assets = [a for a in assets if a.insurance_applicable][:25]
for idx, asset in enumerate(insured_assets):
if idx == 0:
end_d = today + timedelta(days=9)
elif idx == 1:
end_d = today + timedelta(days=23)
else:
end_d = today + timedelta(days=rng.randint(45, 330))
start_d = end_d - timedelta(days=365)
pol = InsurancePolicy(
asset_id=asset.id,
insurer_id=insurers[idx % len(insurers)].id,
policy_no=f"PHRC-INS-{today.year}-{1001 + idx}",
start_date=start_d,
end_date=end_d,
coverage_amount=round((asset.purchase_value or 500000.0) * 0.9, 2),
remarks="All-risk biomedical equipment insurance.",
created_by_id=coord_users[idx % 2].id,
updated_by_id=coord_users[idx % 2].id,
)
db.add(pol)
db.flush()
# 12. Calibration Plans (20) + historical completed records + open (upcoming/due/overdue) records
cal_agencies = vendors_by_type["calibration_agency"]
cal_assets = [a for a in assets if a.requires_calibration][:20]
for idx, asset in enumerate(cal_assets):
freq = 6 if idx % 2 == 0 else 12
per_year = 12 // freq
agency = cal_agencies[idx % len(cal_agencies)]
# Make 3 overdue, 4 due within 15 days, 13 upcoming
if idx < 3:
next_due = today - timedelta(days=4 + idx * 5)
elif idx < 7:
next_due = today + timedelta(days=2 + (idx - 3) * 3)
else:
next_due = today + timedelta(days=25 + idx * 7)
plan = CalibrationPlan(
asset_id=asset.id,
frequency_months=freq,
calibrations_per_year=per_year,
agency_id=agency.id,
approved_by_id=bio_users[0].id,
approved_on=today - timedelta(days=400),
next_due_date=next_due,
is_active=True,
created_by_id=bio_users[0].id,
updated_by_id=bio_users[0].id,
)
db.add(plan)
db.flush()
# Historical completed record (1-2 cycles back)
prev_due = next_due - timedelta(days=freq * 30)
if prev_due < today:
db.add(
CalibrationRecord(
asset_id=asset.id,
plan_id=plan.id,
due_date=prev_due,
completed_date=prev_due - timedelta(days=rng.randint(0, 3)),
agency_id=agency.id,
certificate_no=f"CAL-{today.year - 1}-{400 + idx}",
remarks="Calibrated within NABL permissible tolerance.",
status="completed",
created_by_id=bio_users[idx % len(bio_users)].id,
updated_by_id=bio_users[idx % len(bio_users)].id,
)
)
# Current open calibration record (status=None so upcoming/due/overdue is computed dynamically)
db.add(
CalibrationRecord(
asset_id=asset.id,
plan_id=plan.id,
due_date=next_due,
completed_date=None,
agency_id=agency.id,
certificate_no=None,
remarks="Scheduled calibration cycle.",
status=None,
created_by_id=bio_users[0].id,
updated_by_id=bio_users[0].id,
)
)
db.flush()
# 13. PM Schedules (45: 60% in_house=27, 40% outsourced=18) + 6 months records + 4 due this month + 3 overdue
for idx in range(45):
asset = assets[idx]
mode = "in_house" if idx < 27 else "outsourced"
freq = 3 if idx % 3 == 0 else 6
contract = active_contract_by_asset.get(asset.id)
provider_id = contract.provider_id if (mode == "outsourced" and contract) else (
service_providers[idx % len(service_providers)].id if mode == "outsourced" else None
)
# 3 overdue, 4 due this month (within next 12 days), rest upcoming
if idx < 3:
next_planned = today - timedelta(days=3 + idx * 5)
elif idx < 7:
next_planned = today + timedelta(days=1 + (idx - 3) * 3)
else:
next_planned = today + timedelta(days=22 + (idx % 60))
sched = PMSchedule(
asset_id=asset.id,
service_mode=mode,
frequency_months=freq,
responsible_team="In-House Biomedical Team" if mode == "in_house" else None,
provider_id=provider_id,
contract_id=contract.id if (mode == "outsourced" and contract) else None,
next_planned_date=next_planned,
is_active=True,
created_by_id=bio_users[0].id,
updated_by_id=bio_users[0].id,
)
db.add(sched)
db.flush()
# Historical completed PM records over past 6 months
for cycle in (1, 2):
hist_date = today - timedelta(days=cycle * 90 + (idx % 15))
db.add(
PMRecord(
schedule_id=sched.id,
asset_id=asset.id,
planned_date=hist_date,
completed_date=hist_date + timedelta(days=rng.randint(0, 2)),
status="completed",
service_details="Filter cleaning, electrical safety test, and functional verification.",
remarks="Passed all PM checklist points.",
created_by_id=bio_users[idx % len(bio_users)].id,
updated_by_id=bio_users[idx % len(bio_users)].id,
)
)
# Current open PM record (status=None; upcoming/due/overdue computed dynamically)
db.add(
PMRecord(
schedule_id=sched.id,
asset_id=asset.id,
planned_date=next_planned,
completed_date=None,
status=None,
service_details=None,
remarks="Scheduled preventive maintenance.",
created_by_id=bio_users[0].id,
updated_by_id=bio_users[0].id,
)
)
db.flush()
# 14. Complaints (30: 70% non-critical=21, 9 critical; 22 closed, 4 in_progress, 4 open)
# Must include: 1 critical open > 24h, 1 spanning month boundary, 6 spares, 5 CE
complaints: list[Complaint] = []
issue_descriptions = [
"Display flickering intermittently during monitoring",
"Airway pressure sensor alarm triggering falsely",
"Battery backup not holding charge during transport",
"Touchscreen unresponsive on main control panel",
"Power supply fuse blown after voltage fluctuation",
"Flow sensor calibration error on self-test",
"Suction vacuum pressure dropping below threshold",
"ECG lead wire connector loose at patient cable port",
"Temperature probe reading drift observed",
"Cautery foot pedal intermittent contact",
]
for idx in range(30):
asset = assets[(idx * 2) % len(assets)]
priority = "critical" if idx < 9 else "non_critical"
if idx < 22:
call_status = "closed"
elif idx < 26:
call_status = "in_progress"
else:
call_status = "open"
reg_user = dept_users[idx % len(dept_users)]
recv_user = bio_users[idx % len(bio_users)]
assigned_user = bio_users[(idx + 1) % len(bio_users)]
if idx == 26:
# Critical open > 24h (explicit requirement)
priority = "critical"
call_status = "open"
reg_at = now_utc - timedelta(hours=32)
elif idx == 0:
# Spanning month boundary (registered last month, closed this month)
first_of_month = today.replace(day=1)
reg_date = first_of_month - timedelta(days=3)
close_date = first_of_month + timedelta(days=1) if first_of_month + timedelta(days=1) <= today else today
reg_at = _ist_to_utc(reg_date, 18, 30)
closed_at = _ist_to_utc(close_date, 11, 15)
else:
days_back = rng.randint(1, 75) if call_status == "closed" else rng.randint(0, 3)
reg_at = now_utc - timedelta(days=days_back, hours=rng.randint(1, 10))
closed_at = reg_at + timedelta(hours=rng.randint(2, 28))
has_spare = idx in (1, 4, 8, 12, 16, 22)
has_ce = idx in (2, 6, 11, 18, 23)
c_assigned_at = reg_at + timedelta(minutes=25) if call_status in ("in_progress", "closed") else None
c_attended_at = reg_at + timedelta(minutes=65) if call_status in ("in_progress", "closed") else None
c_restored_at = (closed_at - timedelta(minutes=30)) if call_status == "closed" else None
c_closed_at = closed_at if call_status == "closed" else None
comp = Complaint(
complaint_no=f"CMP-{today.year}-{idx + 1:04d}",
asset_id=asset.id,
description=issue_descriptions[idx % len(issue_descriptions)],
breakdown_details=f"Reported by {asset.department.code} nursing/technical staff during routine shift.",
priority=priority,
notes="Logged via Poona AMS helpdesk.",
registered_at=reg_at,
registered_by_id=reg_user.id,
received_by_id=recv_user.id,
assigned_to_id=assigned_user.id if call_status in ("in_progress", "closed") else None,
assigned_at=c_assigned_at,
attended_by_id=assigned_user.id if call_status in ("in_progress", "closed") else None,
attended_at=c_attended_at,
restored_at=c_restored_at,
closed_by_id=assigned_user.id if call_status == "closed" else None,
closed_at=c_closed_at,
call_status=call_status,
closure_remarks="Equipment verified functional and handed back to department." if call_status == "closed" else None,
action_taken="Diagnosed faulty module, replaced worn harness, and ran safety check." if call_status in ("in_progress", "closed") else None,
root_cause="Component aging / power surge wear" if call_status == "closed" else None,
corrective_action="Module replacement and preventive recalibration" if call_status == "closed" else None,
lessons_learned="Verify UPS line conditioning during monthly rounds" if call_status == "closed" else None,
ce_name="Raghavendra Kulkarni (OEM Service)" if has_ce else None,
ce_attended_at=(reg_at + timedelta(hours=4)) if has_ce else None,
ce_action_taken="OEM service engineer inspected PCB assembly and updated firmware." if has_ce else None,
spare_required=has_spare,
spare_details="Power supply module / O2 sensor assembly" if has_spare else None,
spare_cost_estimate=float(rng.choice([4500, 8200, 14500, 22000, 31500])) if has_spare else None,
updated_by_id=assigned_user.id,
)
db.add(comp)
db.flush()
complaints.append(comp)
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="registered",
from_value=None,
to_value="open",
by_user_id=reg_user.id,
at=reg_at,
note="Complaint registered.",
)
)
if call_status in ("in_progress", "closed"):
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="assigned",
from_value="open",
to_value="in_progress",
by_user_id=recv_user.id,
at=c_assigned_at,
note=f"Assigned to {assigned_user.name}.",
)
)
if call_status == "closed":
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="closed",
from_value="in_progress",
to_value="closed",
by_user_id=assigned_user.id,
at=c_closed_at,
note="Restored and closed.",
)
)
db.flush()
# 15. Placeholder uploads (8 JPEGs + 6 PDFs) + Attachment records
target_upload_dir = upload_dir if upload_dir is not None else Path(settings.UPLOAD_DIR)
target_upload_dir.mkdir(parents=True, exist_ok=True)
# Remove previously seeded placeholder files (keep .gitkeep)
for existing_file in target_upload_dir.iterdir():
if existing_file.is_file() and existing_file.name != ".gitkeep":
existing_file.unlink()
palette = [
(30, 64, 175),
(15, 118, 110),
(180, 83, 9),
(109, 40, 217),
]
for j in range(8):
fname = f"seed_photo_{j + 1:02d}.jpg"
fpath = target_upload_dir / fname
size_b = _make_placeholder_jpeg(fpath, f"Equipment Fault Photo #{j + 1}", palette[j % len(palette)])
db.add(
Attachment(
entity_type="complaint",
entity_id=complaints[j].id,
original_name=f"fault_photo_{j + 1}.jpg",
stored_name=fname,
mime_type="image/jpeg",
size_bytes=size_b,
uploaded_by_id=bio_users[j % len(bio_users)].id,
)
)
for p in range(6):
fname = f"seed_doc_{p + 1:02d}.pdf"
fpath = target_upload_dir / fname
pdf_bytes = _make_minimal_pdf(f"Poona Hospital Service / Calibration Report #{p + 1}")
fpath.write_bytes(pdf_bytes)
db.add(
Attachment(
entity_type="asset" if p < 3 else "complaint",
entity_id=assets[p].id if p < 3 else complaints[p + 8].id,
original_name=f"service_report_{p + 1}.pdf",
stored_name=fname,
mime_type="application/pdf",
size_bytes=len(pdf_bytes),
uploaded_by_id=coord_users[p % len(coord_users)].id,
)
)
db.flush()
# 16. Demo Equipment (3 items)
demo_items = [
("Portable Video Laryngoscope", "Airway Management", suppliers_and_oems[0].id, departments[0].id, locs_by_dept[departments[0].id][0].id, today - timedelta(days=10), today + timedelta(days=5), None, "Under clinical trial by ICU consultants."),
("High-Flow Nasal Cannula Unit", "Respiratory Support", suppliers_and_oems[1].id, departments[4].id, locs_by_dept[departments[4].id][0].id, today - timedelta(days=14), today + timedelta(days=2), None, "Evaluation unit due for vendor pickup shortly."),
("Point-of-Care Ultrasound Probe", "Diagnostic Imaging", suppliers_and_oems[2].id, departments[2].id, locs_by_dept[departments[2].id][2].id, today - timedelta(days=30), today - timedelta(days=5), today - timedelta(days=4), "Trial completed and returned to supplier."),
]
for name, eq_type, sup_id, dep_id, loc_id, s_d, exp_d, act_d, rem in demo_items:
db.add(
DemoEquipment(
name=name,
equipment_type=eq_type,
supplier_id=sup_id,
department_id=dep_id,
location_id=loc_id,
start_date=s_d,
expected_return_date=exp_d,
actual_return_date=act_d,
remarks=rem,
created_by_id=coord_users[0].id,
updated_by_id=coord_users[0].id,
)
)
db.flush()
# 17. Department Visits (12 total: 3 linked to complaints, 1 of which linked to 2 complaints)
for v_idx in range(12):
dept = departments[v_idx % len(departments)]
visit = DepartmentVisit(
department_id=dept.id,
visited_by_id=bio_users[v_idx % len(bio_users)].id,
visit_date=today - timedelta(days=v_idx * 4 + 1),
observations=f"Routine biomedical safety & preventive inspection round in {dept.name}.",
created_by_id=bio_users[v_idx % len(bio_users)].id,
updated_by_id=bio_users[v_idx % len(bio_users)].id,
)
dept_assets = [a for a in assets if a.department_id == dept.id][:2]
visit.assets.extend(dept_assets)
if v_idx == 0:
# 1 visit linked to 2 complaints
visit.complaints.extend([complaints[0], complaints[1]])
elif v_idx == 1:
visit.complaints.append(complaints[2])
elif v_idx == 2:
visit.complaints.append(complaints[3])
db.add(visit)
db.commit()
return {
"departments": len(departments),
"locations": len(locations),
"categories": len(categories),
"vendors": len(vendors),
"users": len(users),
"assets": len(assets),
"contracts": len(contracts),
"warranties": 20,
"insurance_policies": len(insured_assets),
"calibration_plans": len(cal_assets),
"pm_schedules": 45,
"complaints": len(complaints),
"demo_equipment": len(demo_items),
"department_visits": 12,
}
def main():
t0 = pytime.perf_counter()
Base.metadata.create_all(bind=engine)
with SessionLocal() as db:
summary = seed_database(db)
elapsed = pytime.perf_counter() - t0
print(f"Seed completed in {elapsed:.2f}s: {summary}")
if __name__ == "__main__":
main()
+104
View File
@@ -0,0 +1,104 @@
from enum import Enum
class Role(str, Enum):
system_admin = "system_admin"
biomedical = "biomedical"
department_user = "department_user"
management = "management"
coordinator = "coordinator"
ALL_ROLES: set[str] = {r.value for r in Role}
RESTRICTED_COMPLAINT_FIELDS: set[str] = {
"action_taken",
"root_cause",
"corrective_action",
"lessons_learned",
"ce_name",
"ce_attended_at",
"ce_action_taken",
"spare_required",
"spare_details",
"spare_cost_estimate",
}
CAPABILITIES: dict[Role, set[str]] = {
Role.system_admin: {
"manage_admin",
"create_edit_assets",
"edit_asset_contracts_only",
"view_assets",
"raise_complaint",
"handle_complaint",
"edit_technical_fields",
"manage_pm",
"view_pm",
"manage_calibration_contracts",
"view_calibration_contracts",
"manage_demo_equipment",
"view_demo_equipment",
"manage_visits",
"view_visits",
"view_all_reports",
"view_dept_reports",
},
Role.biomedical: {
"create_edit_assets",
"view_assets",
"raise_complaint",
"handle_complaint",
"edit_technical_fields",
"manage_pm",
"view_pm",
"manage_calibration_contracts",
"view_calibration_contracts",
"manage_demo_equipment",
"view_demo_equipment",
"manage_visits",
"view_visits",
"view_all_reports",
"view_dept_reports",
},
Role.department_user: {
"view_assets",
"raise_complaint",
"view_pm",
"view_calibration_contracts",
"view_demo_equipment",
"view_dept_reports",
},
Role.management: {
"view_assets",
"view_pm",
"view_calibration_contracts",
"view_demo_equipment",
"view_visits",
"view_all_reports",
"view_dept_reports",
},
Role.coordinator: {
"edit_asset_contracts_only",
"view_assets",
"raise_complaint",
"handle_complaint",
"view_pm",
"manage_calibration_contracts",
"view_calibration_contracts",
"manage_demo_equipment",
"view_demo_equipment",
"view_all_reports",
"view_dept_reports",
},
}
def has_capability(role: Role | str | None, capability: str) -> bool:
if role is None:
return False
try:
role_enum = role if isinstance(role, Role) else Role(role)
except ValueError:
return False
return capability in CAPABILITIES.get(role_enum, set())
+309
View File
@@ -0,0 +1,309 @@
import json
from datetime import date
from typing import Any
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
from ..core.time_utils import utc_now
from ..models.masters import Setting
SETTINGS_SCHEMA: list[dict[str, Any]] = [
{
"key": "demo_as_of_date",
"type": "date_or_empty",
"default": "",
"label": "Demo As-Of Date",
"description": "Optional YYYY-MM-DD override for the system clock (used for testing/demos). Leave empty for real Asia/Kolkata date.",
"min": None,
"max": None,
"options": None,
},
{
"key": "contract_expiry_alert_days",
"type": "int",
"default": 30,
"label": "Contract Expiry Alert Lead Days",
"description": "Days prior to AMC/CMC/OTHER contract end date to generate expiry alerts.",
"min": 1,
"max": 180,
"options": None,
},
{
"key": "contract_critical_alert_days",
"type": "int",
"default": 7,
"label": "Contract Critical Expiry Alert Days",
"description": "Days prior to contract expiry to escalate alert severity to critical (red).",
"min": 1,
"max": 60,
"options": None,
},
{
"key": "warranty_expiry_alert_days",
"type": "int",
"default": 30,
"label": "Warranty Expiry Alert Lead Days",
"description": "Days prior to warranty end date to trigger expiry alerts.",
"min": 1,
"max": 180,
"options": None,
},
{
"key": "insurance_expiry_alert_days",
"type": "int",
"default": 30,
"label": "Insurance Expiry Alert Lead Days",
"description": "Days prior to insurance policy end date to trigger renewal alerts.",
"min": 1,
"max": 180,
"options": None,
},
{
"key": "calibration_due_window_days",
"type": "int",
"default": 15,
"label": "Calibration Due Window (Days)",
"description": "Days before calibration due date when status transitions from upcoming to due.",
"min": 1,
"max": 90,
"options": None,
},
{
"key": "pm_due_window_days",
"type": "int",
"default": 15,
"label": "PM Due Window (Days)",
"description": "Days before planned PM date when status transitions from upcoming to due.",
"min": 1,
"max": 90,
"options": None,
},
{
"key": "critical_complaint_sla_hours",
"type": "int",
"default": 4,
"label": "Critical Complaint Response SLA (Hours)",
"description": "Target hours to attend and restore a critical priority breakdown complaint.",
"min": 1,
"max": 72,
"options": None,
},
{
"key": "non_critical_complaint_sla_hours",
"type": "int",
"default": 24,
"label": "Non-Critical Complaint Response SLA (Hours)",
"description": "Target hours to attend and restore a non-critical priority complaint.",
"min": 1,
"max": 168,
"options": None,
},
{
"key": "escalation_open_complaint_hours",
"type": "int",
"default": 24,
"label": "Open Critical Complaint Escalation (Hours)",
"description": "Hours after registration before an unclosed critical complaint triggers escalation.",
"min": 1,
"max": 168,
"options": None,
},
{
"key": "demo_return_alert_days",
"type": "int",
"default": 3,
"label": "Demo Equipment Return Lead Days",
"description": "Days before expected return date to alert on demo equipment return.",
"min": 0,
"max": 30,
"options": None,
},
{
"key": "require_closure_remarks",
"type": "bool",
"default": True,
"label": "Require Complaint Closure Remarks",
"description": "Require closure remarks before marking a breakdown complaint as closed.",
"min": None,
"max": None,
"options": None,
},
{
"key": "asset_code_prefix",
"type": "str",
"default": "PHRC",
"label": "Asset Code Prefix",
"description": "Default prefix used when formatting hospital asset codes (e.g. PHRC-ICU-0001).",
"min": None,
"max": None,
"options": None,
},
{
"key": "default_pm_mode",
"type": "enum",
"default": "in_house",
"label": "Default PM Service Mode",
"description": "Default preventive maintenance execution mode when creating new schedules.",
"min": None,
"max": None,
"options": ["in_house", "outsourced"],
},
]
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
def validate_setting_value(key: str, value: Any) -> Any:
if key not in SETTINGS_BY_KEY:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Unknown setting key: '{key}'",
)
spec = SETTINGS_BY_KEY[key]
stype = spec["type"]
if stype == "int":
if isinstance(value, bool) or not isinstance(value, int):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Setting '{key}' must be an integer.",
)
if spec["min"] is not None and value < spec["min"]:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Setting '{key}' must be >= {spec['min']}.",
)
if spec["max"] is not None and value > spec["max"]:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Setting '{key}' must be <= {spec['max']}.",
)
return value
if stype == "bool":
if not isinstance(value, bool):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Setting '{key}' must be a boolean.",
)
return value
if stype == "enum":
if not isinstance(value, str) or value not in (spec["options"] or []):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Setting '{key}' must be one of {spec['options']}.",
)
return value
if stype == "str":
if not isinstance(value, str) or not value.strip():
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Setting '{key}' must be a non-empty string.",
)
return value.strip()
if stype == "date_or_empty":
if value is None or value == "":
return ""
if not isinstance(value, str):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Setting '{key}' must be a YYYY-MM-DD date string or empty.",
)
cleaned = value.strip()
if cleaned == "":
return ""
try:
date.fromisoformat(cleaned)
except ValueError:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Setting '{key}' must be a valid YYYY-MM-DD date.",
)
return cleaned
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Unsupported setting type for '{key}'.",
)
def ensure_default_settings(db: Session) -> None:
existing = {row.key for row in db.query(Setting.key).all()}
for spec in SETTINGS_SCHEMA:
if spec["key"] not in existing:
db.add(
Setting(
key=spec["key"],
value_json=json.dumps(spec["default"]),
updated_at=utc_now(),
)
)
db.flush()
def get_setting_value(db: Session, key: str) -> Any:
spec = SETTINGS_BY_KEY.get(key)
row = db.query(Setting).filter(Setting.key == key).first()
if row is None:
return spec["default"] if spec else None
try:
return json.loads(row.value_json)
except (ValueError, TypeError):
return spec["default"] if spec else None
def get_demo_as_of_date(db: Session) -> str | None:
val = get_setting_value(db, "demo_as_of_date")
if isinstance(val, str) and val.strip():
return val.strip()
return None
def get_all_settings(db: Session) -> list[dict[str, Any]]:
rows = {row.key: row for row in db.query(Setting).all()}
items: list[dict[str, Any]] = []
for spec in SETTINGS_SCHEMA:
row = rows.get(spec["key"])
value = spec["default"]
if row is not None:
try:
value = json.loads(row.value_json)
except (ValueError, TypeError):
value = spec["default"]
items.append(
{
"key": spec["key"],
"value": value,
"type": spec["type"],
"label": spec["label"],
"description": spec["description"],
"default": spec["default"],
"min": spec["min"],
"max": spec["max"],
"options": spec["options"],
}
)
return items
def update_settings(db: Session, values: dict[str, Any], user_id: int | None = None) -> list[dict[str, Any]]:
for key, raw_val in values.items():
clean_val = validate_setting_value(key, raw_val)
serialized = json.dumps(clean_val)
row = db.query(Setting).filter(Setting.key == key).first()
if row is None:
row = Setting(
key=key,
value_json=serialized,
updated_at=utc_now(),
updated_by_id=user_id,
)
db.add(row)
else:
row.value_json = serialized
row.updated_at = utc_now()
row.updated_by_id = user_id
db.commit()
return get_all_settings(db)
+1 -1
View File
@@ -4,7 +4,7 @@ sqlalchemy==2.0.36
pydantic==2.10.1
pydantic-settings==2.6.1
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
bcrypt==5.0.0
python-multipart==0.0.12
apscheduler==3.10.4
openpyxl==3.1.5
+389
View File
@@ -0,0 +1,389 @@
from datetime import date, datetime, timezone
from pathlib import Path
import pytest
from app.core.time_utils import KOLKATA, effective_today
from app.models import (
Asset,
Attachment,
CalibrationPlan,
Category,
Complaint,
Contract,
DemoEquipment,
Department,
DepartmentVisit,
InsurancePolicy,
Location,
PMSchedule,
User,
Vendor,
Warranty,
)
from app.seed.seed import seed_database
from app.services.permissions import RESTRICTED_COMPLAINT_FIELDS, Role, has_capability
@pytest.fixture(scope="module", autouse=True)
def seeded_test_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("test_uploads")
seed_database(db, upload_dir=upload_dir)
return upload_dir
def _auth_headers(client, email: str, password: str = "Demo@123") -> dict[str, str]:
res = client.post("/api/auth/login", json={"email": email, "password": password})
assert res.status_code == 200, res.text
token = res.json()["access_token"]
return {"Authorization": f"Bearer {token}"}
def test_login_valid_and_invalid(client, db):
res = client.post("/api/auth/login", json={"email": "admin@poona.demo", "password": "Demo@123"})
assert res.status_code == 200
body = res.json()
assert body["token_type"] == "bearer"
assert body["access_token"]
assert body["user"]["email"] == "admin@poona.demo"
assert body["user"]["role"] == "system_admin"
assert body["user"]["demo_as_of_date"] is None
bad_pw = client.post("/api/auth/login", json={"email": "admin@poona.demo", "password": "wrong"})
assert bad_pw.status_code == 401
bad_email = client.post("/api/auth/login", json={"email": "nobody@poona.demo", "password": "Demo@123"})
assert bad_email.status_code == 401
# Inactive user rejected
user = db.query(User).filter(User.email == "neha.chavan@poona.demo").first()
assert user is not None
user.is_active = False
db.commit()
try:
res_inactive = client.post(
"/api/auth/login",
json={"email": "neha.chavan@poona.demo", "password": "Demo@123"},
)
assert res_inactive.status_code in (401, 403)
finally:
user.is_active = True
db.commit()
def test_auth_me(client):
unauth = client.get("/api/auth/me")
assert unauth.status_code == 401
bad_tok = client.get("/api/auth/me", headers={"Authorization": "Bearer invalid.token.here"})
assert bad_tok.status_code == 401
headers = _auth_headers(client, "dept@poona.demo")
me = client.get("/api/auth/me", headers=headers)
assert me.status_code == 200
data = me.json()
assert data["email"] == "dept@poona.demo"
assert data["role"] == "department_user"
assert data["department_name"] == "Intensive Care Unit"
@pytest.mark.parametrize(
"email",
[
"bio@poona.demo",
"dept@poona.demo",
"mgmt@poona.demo",
"coord@poona.demo",
],
)
def test_non_admin_forbidden_on_admin_endpoints(client, db, email):
headers = _auth_headers(client, email)
dept = db.query(Department).first()
target_user = db.query(User).filter(User.email == "dept@poona.demo").first()
# Masters GET is allowed for authenticated users
assert client.get("/api/departments", headers=headers).status_code == 200
assert client.get("/api/locations", headers=headers).status_code == 200
assert client.get("/api/categories", headers=headers).status_code == 200
assert client.get("/api/vendors", headers=headers).status_code == 200
assert client.get("/api/users/lookup", headers=headers).status_code == 200
# Masters write -> 403
assert (
client.post(
"/api/departments",
headers=headers,
json={"name": "Test Dept", "code": "TST"},
).status_code
== 403
)
assert (
client.patch(
f"/api/departments/{dept.id}",
headers=headers,
json={"description": "hacked"},
).status_code
== 403
)
assert client.delete(f"/api/departments/{dept.id}", headers=headers).status_code == 403
# Users admin endpoints -> 403
assert client.get("/api/users", headers=headers).status_code == 403
assert (
client.post(
"/api/users",
headers=headers,
json={
"name": "Hack",
"email": "hack@poona.demo",
"password": "Password1",
"role": "biomedical",
},
).status_code
== 403
)
assert (
client.patch(
f"/api/users/{target_user.id}",
headers=headers,
json={"name": "Hacked"},
).status_code
== 403
)
assert client.delete(f"/api/users/{target_user.id}", headers=headers).status_code == 403
# Settings endpoints -> 403
assert client.get("/api/settings", headers=headers).status_code == 403
assert (
client.put(
"/api/settings",
headers=headers,
json={"values": {"contract_expiry_alert_days": 45}},
).status_code
== 403
)
assert (
client.post(
"/api/settings/demo-date",
headers=headers,
json={"demo_as_of_date": "2026-06-01"},
).status_code
== 403
)
def test_admin_masters_and_users_crud(client):
headers = _auth_headers(client, "admin@poona.demo")
# Department create, patch, soft-delete
r = client.post(
"/api/departments",
headers=headers,
json={"name": "Physiotherapy", "code": "PHYS", "description": "Rehab unit"},
)
assert r.status_code == 201
dept_id = r.json()["id"]
r_patch = client.patch(
f"/api/departments/{dept_id}",
headers=headers,
json={"description": "Physiotherapy & Rehab"},
)
assert r_patch.status_code == 200
assert r_patch.json()["description"] == "Physiotherapy & Rehab"
r_del = client.delete(f"/api/departments/{dept_id}", headers=headers)
assert r_del.status_code == 200
assert r_del.json()["is_active"] is False
# User create, password update, soft-delete
u_res = client.post(
"/api/users",
headers=headers,
json={
"name": "Temp Staff",
"email": "temp.staff@poona.demo",
"password": "InitPassword1",
"role": "biomedical",
},
)
assert u_res.status_code == 201
uid = u_res.json()["id"]
# Update password
u_patch = client.patch(
f"/api/users/{uid}",
headers=headers,
json={"password": "NewPassword2"},
)
assert u_patch.status_code == 200
login_new = client.post(
"/api/auth/login",
json={"email": "temp.staff@poona.demo", "password": "NewPassword2"},
)
assert login_new.status_code == 200
# Soft delete user
u_del = client.delete(f"/api/users/{uid}", headers=headers)
assert u_del.status_code == 200
assert u_del.json()["is_active"] is False
def test_permissions_matrix_all_roles():
assert "action_taken" in RESTRICTED_COMPLAINT_FIELDS
assert "spare_cost_estimate" in RESTRICTED_COMPLAINT_FIELDS
# system_admin
assert has_capability(Role.system_admin, "manage_admin") is True
assert has_capability(Role.system_admin, "edit_technical_fields") is True
assert has_capability(Role.system_admin, "view_visits") is True
# biomedical
assert has_capability(Role.biomedical, "manage_admin") is False
assert has_capability(Role.biomedical, "create_edit_assets") is True
assert has_capability(Role.biomedical, "edit_technical_fields") is True
assert has_capability(Role.biomedical, "manage_pm") is True
assert has_capability(Role.biomedical, "manage_visits") is True
assert has_capability(Role.biomedical, "view_all_reports") is True
# department_user
assert has_capability(Role.department_user, "manage_admin") is False
assert has_capability(Role.department_user, "view_assets") is True
assert has_capability(Role.department_user, "raise_complaint") is True
assert has_capability(Role.department_user, "handle_complaint") is False
assert has_capability(Role.department_user, "edit_technical_fields") is False
assert has_capability(Role.department_user, "view_visits") is False
assert has_capability(Role.department_user, "view_dept_reports") is True
assert has_capability(Role.department_user, "view_all_reports") is False
# management
assert has_capability(Role.management, "manage_admin") is False
assert has_capability(Role.management, "view_assets") is True
assert has_capability(Role.management, "view_visits") is True
assert has_capability(Role.management, "view_all_reports") is True
assert has_capability(Role.management, "create_edit_assets") is False
assert has_capability(Role.management, "raise_complaint") is False
assert has_capability(Role.management, "edit_technical_fields") is False
# coordinator
assert has_capability(Role.coordinator, "manage_admin") is False
assert has_capability(Role.coordinator, "edit_asset_contracts_only") is True
assert has_capability(Role.coordinator, "handle_complaint") is True
assert has_capability(Role.coordinator, "edit_technical_fields") is False
assert has_capability(Role.coordinator, "manage_calibration_contracts") is True
assert has_capability(Role.coordinator, "manage_demo_equipment") is True
assert has_capability(Role.coordinator, "view_visits") is False
# invalid / None
assert has_capability(None, "view_assets") is False
assert has_capability("unknown_role", "view_assets") is False
def test_settings_validation_and_demo_date(client, db):
headers = _auth_headers(client, "admin@poona.demo")
res = client.get("/api/settings", headers=headers)
assert res.status_code == 200
items = res.json()["items"]
assert len(items) == 14
# Out of range int
bad_range = client.put(
"/api/settings",
headers=headers,
json={"values": {"contract_expiry_alert_days": 999}},
)
assert bad_range.status_code == 422
# Bool passed to int
bad_type = client.put(
"/api/settings",
headers=headers,
json={"values": {"contract_expiry_alert_days": True}},
)
assert bad_type.status_code == 422
# Invalid enum
bad_enum = client.put(
"/api/settings",
headers=headers,
json={"values": {"default_pm_mode": "third_party"}},
)
assert bad_enum.status_code == 422
# Unknown key
bad_key = client.put(
"/api/settings",
headers=headers,
json={"values": {"nonexistent_key": 123}},
)
assert bad_key.status_code == 422
# Valid update
ok_put = client.put(
"/api/settings",
headers=headers,
json={"values": {"contract_expiry_alert_days": 45, "require_closure_remarks": False}},
)
assert ok_put.status_code == 200
updated_map = {item["key"]: item["value"] for item in ok_put.json()["items"]}
assert updated_map["contract_expiry_alert_days"] == 45
assert updated_map["require_closure_remarks"] is False
# Demo date set & reset
set_demo = client.post(
"/api/settings/demo-date",
headers=headers,
json={"demo_as_of_date": "2026-06-15"},
)
assert set_demo.status_code == 200
assert set_demo.json()["demo_as_of_date"] == "2026-06-15"
assert set_demo.json()["effective_today"] == "2026-06-15"
assert effective_today(db) == date(2026, 6, 15)
me_res = client.get("/api/auth/me", headers=headers)
assert me_res.json()["demo_as_of_date"] == "2026-06-15"
# Reset demo date
reset_demo = client.post(
"/api/settings/demo-date",
headers=headers,
json={"demo_as_of_date": None},
)
assert reset_demo.status_code == 200
assert reset_demo.json()["demo_as_of_date"] is None
assert effective_today(db) == datetime.now(KOLKATA).date()
def test_seed_idempotency_and_counts(db, tmp_path):
summary1 = seed_database(db, upload_dir=tmp_path)
summary2 = seed_database(db, upload_dir=tmp_path)
assert summary1 == summary2
assert db.query(Department).count() == 8
assert db.query(Location).count() == 20
assert db.query(Category).count() == 8
assert db.query(Vendor).count() == 12
assert db.query(User).count() == 11
assert db.query(Asset).count() == 60
assert db.query(Contract).count() == 35
assert db.query(Contract).filter(Contract.is_superseded.is_(True)).count() == 1
assert db.query(Warranty).count() == 20
assert db.query(InsurancePolicy).count() == 25
assert db.query(CalibrationPlan).count() == 20
assert db.query(PMSchedule).count() == 45
assert db.query(PMSchedule).filter(PMSchedule.service_mode == "in_house").count() == 27
assert db.query(PMSchedule).filter(PMSchedule.service_mode == "outsourced").count() == 18
assert db.query(Complaint).count() == 30
assert db.query(Complaint).filter(Complaint.call_status == "closed").count() == 22
assert db.query(Complaint).filter(Complaint.call_status == "in_progress").count() == 4
assert db.query(Complaint).filter(Complaint.call_status == "open").count() == 4
assert db.query(Complaint).filter(Complaint.spare_required.is_(True)).count() == 6
assert db.query(Complaint).filter(Complaint.ce_name.is_not(None)).count() == 5
assert db.query(DemoEquipment).count() == 3
assert db.query(DepartmentVisit).count() == 12
assert db.query(Attachment).count() == 14
jpegs = list(Path(tmp_path).glob("*.jpg"))
pdfs = list(Path(tmp_path).glob("*.pdf"))
assert len(jpegs) == 8
assert len(pdfs) == 6
+14 -2
View File
@@ -1,3 +1,15 @@
# Assumptions Log
# Assumptions Log — Poona Hospital AMS
Will be populated with all assumptions during Phase 1.
Items marked "to be confirmed" or left flexible in the proposal are recorded here along with the configurable defaults implemented in Phase 1.
1. **Contract Expiry Alert Thresholds**: Default alert lead time is `30` days (`contract_expiry_alert_days`), with critical (red) escalation at `7` days (`contract_critical_alert_days`). Both are admin-editable in Settings.
2. **Warranty & Insurance Expiry Lead Days**: Default alert window is `30` days prior to end date (`warranty_expiry_alert_days`, `insurance_expiry_alert_days`), configurable by System Admin.
3. **PM & Calibration Due Windows**: Planned PM and Calibration items transition from `upcoming` to `due` at `15` days before `due_date` / `planned_date` (`calibration_due_window_days`, `pm_due_window_days`), and become `overdue` once past the due date. Only `completed` (and `rescheduled` for PM) are persisted in the DB; `upcoming`/`due`/`overdue` are computed at read time against `effective_today()`.
4. **Complaint SLA & Escalation Thresholds**: Default target response/restoration SLA is `4` hours for `critical` priority (`critical_complaint_sla_hours`) and `24` hours for `non_critical` (`non_critical_complaint_sla_hours`), with unclosed critical complaints escalating after `24` hours (`escalation_open_complaint_hours`).
5. **Complaint Closure Remarks**: `require_closure_remarks` defaults to `true` so engineers must document closure notes before closing a breakdown call; configurable in Settings.
6. **Asset Code Format**: Asset codes follow `<asset_code_prefix>-<DEPT_CODE>-<0001>` with default prefix `PHRC` (`asset_code_prefix`), e.g. `PHRC-ICU-0001`.
7. **Default PM Service Mode**: New PM schedules default to `in_house` (`default_pm_mode`, enum `in_house` | `outsourced`).
8. **Demo Equipment Return Alert**: Expected return alerts trigger `3` days before `expected_return_date` (`demo_return_alert_days`), configurable in Settings.
9. **Demo Clock (`demo_as_of_date`)**: System-wide `effective_today()` reads `demo_as_of_date` (`YYYY-MM-DD`) from Settings if non-empty; otherwise uses the real current date in `Asia/Kolkata`.
10. **Soft Deletion for Masters & Users**: Deleting departments, locations, categories, vendors, or users sets `is_active = False` rather than hard-deleting rows so historical asset/complaint/maintenance foreign keys remain intact.
11. **Password Hashing on Python 3.13**: `passlib==1.7.4` is incompatible with `bcrypt>=4.1` on Python 3.13 (`__about__` attribute removed / 72-byte wrap-check error), so `app/core/security.py` uses `bcrypt` (`bcrypt==5.0.0`) directly.
+102 -19
View File
@@ -1,7 +1,12 @@
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { useEffect } from "react";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { AppShell } from "@/components/layout/AppShell";
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
import { LoginPage } from "@/pages/LoginPage";
import { AccessDeniedPage } from "@/pages/AccessDeniedPage";
import { MastersPage } from "@/pages/MastersPage";
import { SettingsPage } from "@/pages/SettingsPage";
import {
DashboardPage,
AssetsPage,
@@ -14,34 +19,112 @@ import {
VisitsPage,
ReportsPage,
NotificationsPage,
SettingsPage,
} from "@/pages/stubs";
import { useAuthStore } from "@/hooks/useAuth";
import { can, type Capability } from "@/lib/permissions";
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 1, staleTime: 30_000 } },
});
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { user, token, hydrating } = useAuthStore();
if (hydrating) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-center space-y-2">
<div className="h-8 w-8 border-4 border-[#1e3a8a] border-t-transparent rounded-full animate-spin mx-auto" />
<p className="text-sm text-gray-500">Loading Poona Hospital AMS...</p>
</div>
</div>
);
}
if (!token || !user) {
return <Navigate to="/login" replace />;
}
return <>{children}</>;
}
function RoleGuard({
capability,
children,
}: {
capability: Capability;
children: React.ReactNode;
}) {
const user = useAuthStore((s) => s.user);
if (!can(user?.role, capability)) {
return <AccessDeniedPage />;
}
return <>{children}</>;
}
function AppRoutes() {
const hydrate = useAuthStore((s) => s.hydrate);
useEffect(() => {
hydrate();
}, [hydrate]);
return (
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route
element={
<ProtectedRoute>
<AppShell />
</ProtectedRoute>
}
>
<Route path="/" element={<DashboardPage />} />
<Route path="/assets" element={<AssetsPage />} />
<Route path="/complaints" element={<ComplaintsPage />} />
<Route path="/pm" element={<PMPage />} />
<Route path="/calibration" element={<CalibrationPage />} />
<Route path="/contracts" element={<ContractsPage />} />
<Route path="/insurance" element={<InsurancePage />} />
<Route path="/demo-equipment" element={<DemoEquipmentPage />} />
<Route
path="/visits"
element={
<RoleGuard capability="view_visits">
<VisitsPage />
</RoleGuard>
}
/>
<Route path="/reports" element={<ReportsPage />} />
<Route path="/notifications" element={<NotificationsPage />} />
<Route
path="/masters"
element={
<RoleGuard capability="manage_admin">
<MastersPage />
</RoleGuard>
}
/>
<Route
path="/settings"
element={
<RoleGuard capability="manage_admin">
<SettingsPage />
</RoleGuard>
}
/>
<Route path="/demo" element={<DataTableDemoPage />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
);
}
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<Routes>
<Route element={<AppShell />}>
<Route path="/" element={<DashboardPage />} />
<Route path="/assets" element={<AssetsPage />} />
<Route path="/complaints" element={<ComplaintsPage />} />
<Route path="/pm" element={<PMPage />} />
<Route path="/calibration" element={<CalibrationPage />} />
<Route path="/contracts" element={<ContractsPage />} />
<Route path="/insurance" element={<InsurancePage />} />
<Route path="/demo-equipment" element={<DemoEquipmentPage />} />
<Route path="/visits" element={<VisitsPage />} />
<Route path="/reports" element={<ReportsPage />} />
<Route path="/notifications" element={<NotificationsPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="/demo" element={<DataTableDemoPage />} />
</Route>
</Routes>
<AppRoutes />
</BrowserRouter>
</QueryClientProvider>
);
+27
View File
@@ -0,0 +1,27 @@
import { api } from "./client";
import type { Role } from "@/lib/permissions";
export interface UserOut {
id: number;
name: string;
email: string;
role: Role;
department_id: number | null;
department_name: string | null;
is_active: boolean;
demo_as_of_date?: string | null;
}
export interface LoginResponse {
access_token: string;
token_type: string;
user: UserOut;
}
export function loginApi(email: string, password: string) {
return api.post<LoginResponse>("/auth/login", { email, password });
}
export function fetchMeApi() {
return api.get<UserOut>("/auth/me");
}
+11 -1
View File
@@ -10,6 +10,12 @@ export class ApiError extends Error {
}
}
let onUnauthorizedCallback: (() => void) | null = null;
export function setUnauthorizedHandler(cb: () => void) {
onUnauthorizedCallback = cb;
}
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const token = sessionStorage.getItem("access_token");
const headers: Record<string, string> = {
@@ -21,6 +27,10 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const res = await fetch(`${BASE_URL}${path}`, { ...options, headers });
if (!res.ok) {
const body = await res.json().catch(() => ({ detail: res.statusText }));
if (res.status === 401 && !path.startsWith("/auth/login")) {
sessionStorage.removeItem("access_token");
onUnauthorizedCallback?.();
}
throw new ApiError(res.status, body.detail ?? res.statusText, body.code);
}
if (res.status === 204) return undefined as T;
@@ -30,7 +40,7 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, data?: unknown) =>
request<T>(path, { method: "POST", body: data ? JSON.stringify(data) : undefined }),
request<T>(path, { method: "POST", body: data !== undefined ? JSON.stringify(data) : undefined }),
patch: <T>(path: string, data: unknown) =>
request<T>(path, { method: "PATCH", body: JSON.stringify(data) }),
put: <T>(path: string, data: unknown) =>
+156
View File
@@ -0,0 +1,156 @@
import { api } from "./client";
import type { Role } from "@/lib/permissions";
export interface PaginatedResponse<T> {
items: T[];
total: number;
}
export interface Department {
id: number;
name: string;
code: string;
description: string | null;
is_active: boolean;
}
export interface LocationItem {
id: number;
department_id: number;
department_name: string | null;
name: string;
floor_wing: string | null;
is_active: boolean;
}
export interface Category {
id: number;
name: string;
description: string | null;
is_active: boolean;
}
export type VendorType =
| "supplier"
| "service_provider"
| "calibration_agency"
| "insurer"
| "oem";
export const VENDOR_TYPE_LABELS: Record<VendorType, string> = {
supplier: "Supplier",
service_provider: "Service Provider",
calibration_agency: "Calibration Agency",
insurer: "Insurer",
oem: "OEM",
};
export interface Vendor {
id: number;
name: string;
vendor_type: VendorType;
contact_person: string | null;
phone: string | null;
email: string | null;
address: string | null;
is_active: boolean;
}
export interface MasterUser {
id: number;
name: string;
email: string;
role: Role;
department_id: number | null;
department_name: string | null;
is_active: boolean;
}
function buildListQuery(includeInactive: boolean) {
const params = new URLSearchParams();
params.set("page_size", "500");
if (includeInactive) params.set("include_inactive", "true");
return `?${params.toString()}`;
}
export const departmentsApi = {
list: (includeInactive = false) =>
api.get<PaginatedResponse<Department>>(`/departments${buildListQuery(includeInactive)}`),
create: (data: { name: string; code: string; description?: string | null }) =>
api.post<Department>("/departments", data),
update: (id: number, data: Partial<{ name: string; code: string; description: string | null; is_active: boolean }>) =>
api.patch<Department>(`/departments/${id}`, data),
remove: (id: number) => api.delete<void>(`/departments/${id}`),
};
export const locationsApi = {
list: (includeInactive = false) =>
api.get<PaginatedResponse<LocationItem>>(`/locations${buildListQuery(includeInactive)}`),
create: (data: { department_id: number; name: string; floor_wing?: string | null }) =>
api.post<LocationItem>("/locations", data),
update: (
id: number,
data: Partial<{ department_id: number; name: string; floor_wing: string | null; is_active: boolean }>
) => api.patch<LocationItem>(`/locations/${id}`, data),
remove: (id: number) => api.delete<void>(`/locations/${id}`),
};
export const categoriesApi = {
list: (includeInactive = false) =>
api.get<PaginatedResponse<Category>>(`/categories${buildListQuery(includeInactive)}`),
create: (data: { name: string; description?: string | null }) =>
api.post<Category>("/categories", data),
update: (id: number, data: Partial<{ name: string; description: string | null; is_active: boolean }>) =>
api.patch<Category>(`/categories/${id}`, data),
remove: (id: number) => api.delete<void>(`/categories/${id}`),
};
export const vendorsApi = {
list: (includeInactive = false) =>
api.get<PaginatedResponse<Vendor>>(`/vendors${buildListQuery(includeInactive)}`),
create: (data: {
name: string;
vendor_type: VendorType;
contact_person?: string | null;
phone?: string | null;
email?: string | null;
address?: string | null;
}) => api.post<Vendor>("/vendors", data),
update: (
id: number,
data: Partial<{
name: string;
vendor_type: VendorType;
contact_person: string | null;
phone: string | null;
email: string | null;
address: string | null;
is_active: boolean;
}>
) => api.patch<Vendor>(`/vendors/${id}`, data),
remove: (id: number) => api.delete<void>(`/vendors/${id}`),
};
export const usersApi = {
list: (includeInactive = false) =>
api.get<PaginatedResponse<MasterUser>>(`/users${buildListQuery(includeInactive)}`),
create: (data: {
name: string;
email: string;
role: Role;
department_id?: number | null;
password: string;
}) => api.post<MasterUser>("/users", data),
update: (
id: number,
data: Partial<{
name: string;
email: string;
role: Role;
department_id: number | null;
password: string;
is_active: boolean;
}>
) => api.patch<MasterUser>(`/users/${id}`, data),
remove: (id: number) => api.delete<void>(`/users/${id}`),
};
+32
View File
@@ -0,0 +1,32 @@
import { api } from "./client";
export type SettingType = "int" | "bool" | "enum" | "str" | "date_or_empty";
export interface SettingItem {
key: string;
value: unknown;
type: SettingType;
label: string;
description: string;
default: unknown;
min?: number | null;
max?: number | null;
options?: string[] | null;
}
export interface SettingsResponse {
items: SettingItem[];
}
export interface DemoDateResponse {
demo_as_of_date: string | null;
effective_today: string;
}
export const settingsApi = {
getAll: () => api.get<SettingsResponse>("/settings"),
updateAll: (values: Record<string, unknown>) =>
api.put<SettingsResponse>("/settings", { values }),
setDemoDate: (demo_as_of_date: string | null) =>
api.post<DemoDateResponse>("/settings/demo-date", { demo_as_of_date }),
};
+67 -15
View File
@@ -11,27 +11,79 @@ import {
Building2,
BarChart3,
Bell,
Database,
Settings,
ChevronRight,
type LucideIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { can, type Capability } from "@/lib/permissions";
import { useAuthStore } from "@/hooks/useAuth";
const NAV_ITEMS = [
{ to: "/", label: "Dashboard", icon: LayoutDashboard, phase: 6 },
{ to: "/assets", label: "Assets", icon: Package, phase: 2 },
{ to: "/complaints", label: "Complaints", icon: AlertCircle, phase: 3 },
{ to: "/pm", label: "Preventive Maintenance", icon: Wrench, phase: 4 },
{ to: "/calibration", label: "Calibration", icon: FlaskConical, phase: 4 },
{ to: "/contracts", label: "Contracts & Warranty", icon: FileText, phase: 5 },
{ to: "/insurance", label: "Insurance", icon: Shield, phase: 5 },
{ to: "/demo-equipment", label: "Demo Equipment", icon: Truck, phase: 5 },
{ to: "/visits", label: "Department Visits", icon: Building2, phase: 5 },
{ to: "/reports", label: "Reports", icon: BarChart3, phase: 7 },
{ to: "/notifications", label: "Notifications", icon: Bell, phase: 6 },
{ to: "/settings", label: "Settings", icon: Settings, phase: 1, adminOnly: true },
interface NavItem {
to: string;
label: string;
icon: LucideIcon;
capability?: Capability;
anyCapabilities?: Capability[];
}
const NAV_ITEMS: NavItem[] = [
{ to: "/", label: "Dashboard", icon: LayoutDashboard },
{ to: "/assets", label: "Assets", icon: Package, capability: "view_assets" },
{ to: "/complaints", label: "Complaints", icon: AlertCircle },
{ to: "/pm", label: "Preventive Maintenance", icon: Wrench, capability: "view_pm" },
{
to: "/calibration",
label: "Calibration",
icon: FlaskConical,
capability: "view_calibration_contracts",
},
{
to: "/contracts",
label: "Contracts & Warranty",
icon: FileText,
capability: "view_calibration_contracts",
},
{
to: "/insurance",
label: "Insurance",
icon: Shield,
capability: "view_calibration_contracts",
},
{
to: "/demo-equipment",
label: "Demo Equipment",
icon: Truck,
capability: "view_demo_equipment",
},
{
to: "/visits",
label: "Department Visits",
icon: Building2,
capability: "view_visits",
},
{
to: "/reports",
label: "Reports",
icon: BarChart3,
anyCapabilities: ["view_all_reports", "view_dept_reports"],
},
{ to: "/notifications", label: "Notifications", icon: Bell },
{ to: "/masters", label: "Masters", icon: Database, capability: "manage_admin" },
{ to: "/settings", label: "Settings", icon: Settings, capability: "manage_admin" },
];
export function Sidebar() {
const user = useAuthStore((s) => s.user);
const role = user?.role;
const visibleItems = NAV_ITEMS.filter((item) => {
if (item.capability) return can(role, item.capability);
if (item.anyCapabilities) return item.anyCapabilities.some((c) => can(role, c));
return true;
});
return (
<aside className="w-56 lg:w-64 shrink-0 min-h-screen bg-[#1e3a8a] text-white flex flex-col">
{/* Logo */}
@@ -50,7 +102,7 @@ export function Sidebar() {
{/* Navigation */}
<nav className="flex-1 px-2 py-4 space-y-0.5 overflow-y-auto">
{NAV_ITEMS.map(({ to, label, icon: Icon }) => (
{visibleItems.map(({ to, label, icon: Icon }) => (
<NavLink
key={to}
to={to}
@@ -73,7 +125,7 @@ export function Sidebar() {
{/* Footer */}
<div className="px-4 py-3 border-t border-blue-700 text-xs text-blue-300">
Phase 0 — Scaffold
Phase 1 — Foundation
</div>
</aside>
);
+132 -12
View File
@@ -1,18 +1,58 @@
import { Search, Bell, ChevronDown, User } from "lucide-react";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { Search, Bell, ChevronDown, User, LogOut, CalendarClock, RotateCcw } from "lucide-react";
import { cn } from "@/lib/utils";
import { formatDate } from "@/lib/format";
import { ROLE_LABELS } from "@/lib/permissions";
import { useAuthStore } from "@/hooks/useAuth";
import { settingsApi } from "@/api/settings";
import { Badge } from "@/components/ui/badge";
interface TopBarProps {
title?: string;
}
export function TopBar({ title }: TopBarProps) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
const [menuOpen, setMenuOpen] = useState(false);
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
const [savingDate, setSavingDate] = useState(false);
useEffect(() => {
setDateInput(demoAsOfDate ?? "");
}, [demoAsOfDate]);
const isAdmin = user?.role === "system_admin";
async function handleDemoDateUpdate(newDate: string | null) {
setSavingDate(true);
try {
const res = await settingsApi.setDemoDate(newDate);
setDemoAsOfDate(res.demo_as_of_date ?? null);
setDateInput(res.demo_as_of_date ?? "");
await queryClient.invalidateQueries();
} finally {
setSavingDate(false);
}
}
function handleSignOut() {
setMenuOpen(false);
logout();
navigate("/login", { replace: true });
}
return (
<header className="h-14 bg-white border-b border-gray-200 flex items-center px-4 gap-4 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">
{/* Page title */}
{title && <h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">{title}</h1>}
{/* Global search placeholder */}
<div className={cn("relative ml-auto", title ? "" : "flex-1 max-w-md")}>
<div className={cn("relative", title ? "" : "flex-1 max-w-xs sm:max-w-sm")}>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
<input
type="text"
@@ -21,20 +61,100 @@ export function TopBar({ title }: TopBarProps) {
/>
</div>
{/* Active Demo Date Pill */}
{demoAsOfDate && (
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-amber-100 text-amber-800 border border-amber-300">
<CalendarClock className="h-3.5 w-3.5" />
Demo Date: {formatDate(demoAsOfDate)}
</span>
)}
{/* Admin Demo Clock Picker */}
{isAdmin && (
<div className="flex items-center gap-1.5 bg-gray-50 border border-gray-200 rounded-md px-2 py-1 text-xs">
<span className="text-gray-500 font-medium hidden md:inline">As of Date:</span>
<input
type="date"
aria-label="As of Date"
value={dateInput}
onChange={(e) => setDateInput(e.target.value)}
className="border border-gray-200 rounded px-1.5 py-0.5 text-xs bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
/>
<button
type="button"
disabled={savingDate || !dateInput}
onClick={() => handleDemoDateUpdate(dateInput || null)}
className="px-2 py-0.5 rounded bg-[#1e3a8a] text-white hover:bg-[#1e3480] disabled:opacity-40"
>
Apply
</button>
{demoAsOfDate && (
<button
type="button"
disabled={savingDate}
onClick={() => handleDemoDateUpdate(null)}
title="Reset to Today"
className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-gray-300 bg-white text-gray-600 hover:bg-gray-100 disabled:opacity-40"
>
<RotateCcw className="h-3 w-3" />
<span className="hidden lg:inline">Reset</span>
</button>
)}
</div>
)}
{/* Notification bell placeholder */}
<button className="relative p-2 rounded-md hover:bg-gray-100 text-gray-500">
<button
type="button"
onClick={() => navigate("/notifications")}
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-500 ml-auto"
aria-label="Notifications"
>
<Bell className="h-5 w-5" />
<span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-red-500" />
</button>
{/* User menu placeholder */}
<button className="flex items-center gap-2 px-3 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700">
<div className="h-7 w-7 rounded-full bg-[#1e3a8a] flex items-center justify-center text-white text-xs font-bold">
<User className="h-4 w-4" />
</div>
<span className="hidden sm:block">Admin</span>
<ChevronDown className="h-4 w-4 text-gray-400" />
</button>
{/* User menu */}
<div className="relative">
<button
type="button"
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"
>
<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" />
</div>
<div className="hidden sm:flex flex-col items-start leading-tight">
<span className="font-medium text-gray-800 text-xs">{user?.name ?? "User"}</span>
<span className="text-[10px] text-gray-500">
{user?.role ? ROLE_LABELS[user.role] : ""}
{user?.department_name ? ` • ${user.department_name}` : ""}
</span>
</div>
<ChevronDown className="h-4 w-4 text-gray-400" />
</button>
{menuOpen && (
<div className="absolute right-0 mt-1 w-60 bg-white border border-gray-200 rounded-md shadow-lg z-30 py-2">
<div className="px-3 py-2 border-b border-gray-100 space-y-1">
<div className="text-sm font-medium text-gray-900 truncate">{user?.name}</div>
<div className="text-xs text-gray-500 truncate">{user?.email}</div>
<div className="flex items-center gap-1.5 flex-wrap pt-0.5">
{user?.role && <Badge variant="info">{ROLE_LABELS[user.role]}</Badge>}
{user?.department_name && <Badge variant="outline">{user.department_name}</Badge>}
</div>
</div>
<button
type="button"
onClick={handleSignOut}
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-red-50 text-left"
>
<LogOut className="h-4 w-4" />
Sign Out
</button>
</div>
)}
</div>
</header>
);
}
+55
View File
@@ -0,0 +1,55 @@
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
interface ModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
description?: string;
children: React.ReactNode;
className?: string;
}
export function Modal({
open,
onOpenChange,
title,
description,
children,
className,
}: ModalProps) {
return (
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="fixed inset-0 z-40 bg-black/40 backdrop-blur-[1px]" />
<DialogPrimitive.Content
className={cn(
"fixed left-1/2 top-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-lg bg-white p-6 shadow-xl border border-gray-200 max-h-[90vh] overflow-y-auto",
className
)}
>
<div className="flex items-start justify-between gap-4 mb-4">
<div>
<DialogPrimitive.Title className="text-lg font-semibold text-gray-900">
{title}
</DialogPrimitive.Title>
{description && (
<DialogPrimitive.Description className="text-sm text-gray-500 mt-0.5">
{description}
</DialogPrimitive.Description>
)}
</div>
<DialogPrimitive.Close
aria-label="Close"
className="rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</DialogPrimitive.Close>
</div>
{children}
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
);
}
+55 -6
View File
@@ -1,21 +1,70 @@
import { create } from "zustand";
import { fetchMeApi, type UserOut } from "@/api/auth";
import { setUnauthorizedHandler } from "@/api/client";
interface AuthState {
user: { id: number; email: string; name: string; role: string } | null;
user: UserOut | null;
token: string | null;
setAuth: (user: AuthState["user"], token: string) => void;
demoAsOfDate: string | null;
hydrating: boolean;
setAuth: (user: UserOut, token: string) => void;
setDemoAsOfDate: (date: string | null) => void;
hydrate: () => Promise<void>;
logout: () => void;
}
export const useAuthStore = create<AuthState>((set) => ({
const initialToken = sessionStorage.getItem("access_token");
export const useAuthStore = create<AuthState>((set, get) => ({
user: null,
token: sessionStorage.getItem("access_token"),
token: initialToken,
demoAsOfDate: null,
hydrating: Boolean(initialToken),
setAuth: (user, token) => {
sessionStorage.setItem("access_token", token);
set({ user, token });
set({
user,
token,
demoAsOfDate: user.demo_as_of_date ?? null,
hydrating: false,
});
},
setDemoAsOfDate: (date) => {
set((state) => ({
demoAsOfDate: date || null,
user: state.user ? { ...state.user, demo_as_of_date: date || null } : null,
}));
},
hydrate: async () => {
const token = get().token ?? sessionStorage.getItem("access_token");
if (!token) {
set({ user: null, token: null, demoAsOfDate: null, hydrating: false });
return;
}
set({ hydrating: true });
try {
const user = await fetchMeApi();
set({
user,
token,
demoAsOfDate: user.demo_as_of_date ?? null,
hydrating: false,
});
} catch {
sessionStorage.removeItem("access_token");
set({ user: null, token: null, demoAsOfDate: null, hydrating: false });
}
},
logout: () => {
sessionStorage.removeItem("access_token");
set({ user: null, token: null });
set({ user: null, token: null, demoAsOfDate: null, hydrating: false });
},
}));
setUnauthorizedHandler(() => {
useAuthStore.getState().logout();
});
+98 -5
View File
@@ -1,4 +1,28 @@
export type Role = "system_admin" | "biomedical" | "department_user" | "management" | "coordinator";
export type Role =
| "system_admin"
| "biomedical"
| "department_user"
| "management"
| "coordinator";
export type Capability =
| "manage_admin"
| "create_edit_assets"
| "edit_asset_contracts_only"
| "view_assets"
| "raise_complaint"
| "handle_complaint"
| "edit_technical_fields"
| "manage_pm"
| "view_pm"
| "manage_calibration_contracts"
| "view_calibration_contracts"
| "manage_demo_equipment"
| "view_demo_equipment"
| "manage_visits"
| "view_visits"
| "view_all_reports"
| "view_dept_reports";
export const ROLE_LABELS: Record<Role, string> = {
system_admin: "System Administrator",
@@ -8,9 +32,78 @@ export const ROLE_LABELS: Record<Role, string> = {
coordinator: "Coordinator",
};
// Full permission matrix will be added in Phase 1
export function can(role: Role | undefined, _capability: string): boolean {
const ROLE_CAPABILITIES: Record<Role, ReadonlySet<Capability>> = {
system_admin: new Set<Capability>([
"manage_admin",
"create_edit_assets",
"edit_asset_contracts_only",
"view_assets",
"raise_complaint",
"handle_complaint",
"edit_technical_fields",
"manage_pm",
"view_pm",
"manage_calibration_contracts",
"view_calibration_contracts",
"manage_demo_equipment",
"view_demo_equipment",
"manage_visits",
"view_visits",
"view_all_reports",
"view_dept_reports",
]),
biomedical: new Set<Capability>([
"create_edit_assets",
"view_assets",
"raise_complaint",
"handle_complaint",
"edit_technical_fields",
"manage_pm",
"view_pm",
"manage_calibration_contracts",
"view_calibration_contracts",
"manage_demo_equipment",
"view_demo_equipment",
"manage_visits",
"view_visits",
"view_all_reports",
"view_dept_reports",
]),
department_user: new Set<Capability>([
"view_assets",
"raise_complaint",
"view_pm",
"view_calibration_contracts",
"view_demo_equipment",
"view_dept_reports",
]),
management: new Set<Capability>([
"view_assets",
"view_pm",
"view_calibration_contracts",
"view_demo_equipment",
"view_visits",
"view_all_reports",
"view_dept_reports",
]),
coordinator: new Set<Capability>([
"edit_asset_contracts_only",
"view_assets",
"raise_complaint",
"handle_complaint",
"view_pm",
"manage_calibration_contracts",
"view_calibration_contracts",
"manage_demo_equipment",
"view_demo_equipment",
"view_all_reports",
"view_dept_reports",
]),
};
export function can(role: Role | undefined | null, capability: Capability | string): boolean {
if (!role) return false;
if (role === "system_admin") return true;
return false; // placeholder
const caps = ROLE_CAPABILITIES[role];
if (!caps) return false;
return caps.has(capability as Capability);
}
+20
View File
@@ -0,0 +1,20 @@
import { Link } from "react-router-dom";
import { ShieldAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
export function AccessDeniedPage() {
return (
<div className="max-w-md mx-auto mt-16 text-center bg-white border border-gray-200 rounded-xl p-8 shadow-sm">
<div className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-red-50 text-red-600 mb-4">
<ShieldAlert className="h-7 w-7" />
</div>
<h2 className="text-xl font-bold text-gray-900 mb-2">Access Denied</h2>
<p className="text-sm text-gray-500 mb-6">
Your role does not have permission to access this page.
</p>
<Link to="/">
<Button variant="default">Return to Dashboard</Button>
</Link>
</div>
);
}
+1 -1
View File
@@ -12,7 +12,7 @@ interface MockAsset {
const MOCK_DATA: MockAsset[] = [
{ code: "PHRC-ICU-0001", name: "Ventilator", department: "ICU", status: "In Service", category: "Life Support" },
{ code: "PHRC-ICU-0002", name: "Patient Monitor", department: "ICU", status: "Under Repair", category: "Monitoring" },
{ code: "PHRC-I CU-0002", name: "Patient Monitor", department: "ICU", status: "Under Repair", category: "Monitoring" },
{ code: "PHRC-OT-0001", name: "Anaesthesia Machine", department: "Operation Theatre", status: "In Service", category: "Life Support" },
{ code: "PHRC-RAD-0001", name: "CT Scanner", department: "Radiology", status: "In Service", category: "Imaging" },
{ code: "PHRC-RAD-0002", name: "X-Ray Unit", department: "Radiology", status: "Out of Service", category: "Imaging" },
+177
View File
@@ -0,0 +1,177 @@
import { useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { AlertCircle, LogIn, ShieldCheck } from "lucide-react";
import { loginApi } from "@/api/auth";
import { ApiError } from "@/api/client";
import { useAuthStore } from "@/hooks/useAuth";
import { Button } from "@/components/ui/button";
const loginSchema = z.object({
email: z.string().email("Enter a valid email address"),
password: z.string().min(1, "Password is required"),
});
type LoginFormValues = z.infer<typeof loginSchema>;
const DEMO_ACCOUNTS = [
{ label: "System Admin", email: "admin@poona.demo", hint: "Full system control" },
{ label: "Biomedical", email: "bio@poona.demo", hint: "Assets, PM, repairs" },
{ label: "Department User (ICU)", email: "dept@poona.demo", hint: "ICU complaints & assets" },
{ label: "Management", email: "mgmt@poona.demo", hint: "Reports & oversight" },
{ label: "Coordinator", email: "coord@poona.demo", hint: "Contracts, demo, calibration" },
];
export function LoginPage() {
const navigate = useNavigate();
const { user, token, setAuth } = useAuthStore();
const [serverError, setServerError] = useState<string | null>(null);
const [quickLoadingEmail, setQuickLoadingEmail] = useState<string | null>(null);
const {
register,
handleSubmit,
setValue,
formState: { errors, isSubmitting },
} = useForm<LoginFormValues>({
resolver: zodResolver(loginSchema),
defaultValues: { email: "", password: "" },
});
if (token && user) {
return <Navigate to="/" replace />;
}
async function doLogin(email: string, password: string) {
setServerError(null);
try {
const res = await loginApi(email, password);
setAuth(res.user, res.access_token);
navigate("/", { replace: true });
} catch (err) {
if (err instanceof ApiError) {
setServerError(err.detail);
} else {
setServerError("Unable to reach server. Please ensure the backend is running.");
}
}
}
async function onSubmit(values: LoginFormValues) {
await doLogin(values.email, values.password);
}
async function handleQuickLogin(email: string) {
setValue("email", email);
setValue("password", "Demo@123");
setQuickLoadingEmail(email);
try {
await doLogin(email, "Demo@123");
} finally {
setQuickLoadingEmail(null);
}
}
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-gray-50 to-indigo-50 flex items-center justify-center p-4">
<div className="w-full max-w-md space-y-5">
<div className="bg-white rounded-xl shadow-md border border-gray-200 p-6 sm:p-8">
{/* Hospital Branding */}
<div className="text-center mb-6">
<img
src="/logo.jpg"
alt="Poona Hospital and Research Centre"
className="h-20 mx-auto object-contain mb-3"
/>
<h1 className="text-xl font-bold text-[#1e3a8a]">
Poona Hospital &amp; Research Centre
</h1>
<p className="text-sm text-gray-500 mt-0.5">
Asset Management &amp; Maintenance System
</p>
</div>
{serverError && (
<div
role="alert"
className="mb-4 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2.5 text-sm text-red-700"
>
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
<span>{serverError}</span>
</div>
)}
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
Email Address
</label>
<input
id="email"
type="email"
autoComplete="email"
placeholder="you@poona.demo"
{...register("email")}
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
{errors.email && (
<p className="text-xs text-red-600 mt-1">{errors.email.message}</p>
)}
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
Password
</label>
<input
id="password"
type="password"
autoComplete="current-password"
placeholder="Enter your password"
{...register("password")}
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
{errors.password && (
<p className="text-xs text-red-600 mt-1">{errors.password.message}</p>
)}
</div>
<Button type="submit" className="w-full" loading={isSubmitting}>
<LogIn className="h-4 w-4 mr-2" />
Sign In
</Button>
</form>
</div>
{/* Quick Demo Login Panel */}
<div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<div className="flex items-center gap-1.5 text-xs font-semibold text-gray-600 uppercase tracking-wide mb-2.5">
<ShieldCheck className="h-4 w-4 text-[#1e3a8a]" />
Quick Demo Login (Password: Demo@123)
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
{DEMO_ACCOUNTS.map((acct) => (
<button
key={acct.email}
type="button"
disabled={isSubmitting || quickLoadingEmail !== null}
onClick={() => handleQuickLogin(acct.email)}
className="text-left px-3 py-2 rounded-md border border-gray-200 hover:border-[#1e3a8a] hover:bg-blue-50/50 transition-colors disabled:opacity-50"
>
<div className="text-xs font-semibold text-gray-800 flex items-center justify-between">
<span>{acct.label}</span>
{quickLoadingEmail === acct.email && (
<span className="text-[10px] text-blue-600">Signing in…</span>
)}
</div>
<div className="text-[11px] text-gray-500 truncate">{acct.email}</div>
</button>
))}
</div>
</div>
</div>
</div>
);
}
+951
View File
@@ -0,0 +1,951 @@
import { useState, useMemo } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import type { ColumnDef } from "@tanstack/react-table";
import { Plus, Pencil, Power, AlertCircle } from "lucide-react";
import { DataTable } from "@/components/DataTable";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Modal } from "@/components/ui/dialog";
import { ApiError } from "@/api/client";
import { ROLE_LABELS, type Role } from "@/lib/permissions";
import {
departmentsApi,
locationsApi,
categoriesApi,
vendorsApi,
usersApi,
VENDOR_TYPE_LABELS,
type Department,
type LocationItem,
type Category,
type Vendor,
type VendorType,
type MasterUser,
} from "@/api/masters";
type TabKey = "departments" | "locations" | "categories" | "vendors" | "users";
const TABS: { key: TabKey; label: string }[] = [
{ key: "departments", label: "Departments" },
{ key: "locations", label: "Locations" },
{ key: "categories", label: "Categories" },
{ key: "vendors", label: "Vendors" },
{ key: "users", label: "Users" },
];
function StatusBadge({ active }: { active: boolean }) {
return <Badge variant={active ? "success" : "outline"}>{active ? "Active" : "Inactive"}</Badge>;
}
function RowActions({
active,
onEdit,
onToggleActive,
busy,
}: {
active: boolean;
onEdit: () => void;
onToggleActive: () => void;
busy?: boolean;
}) {
return (
<div className="flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
<Button variant="outline" size="sm" onClick={onEdit}>
<Pencil className="h-3.5 w-3.5 mr-1" />
Edit
</Button>
<Button
variant={active ? "ghost" : "outline"}
size="sm"
disabled={busy}
onClick={onToggleActive}
className={active ? "text-red-600 hover:bg-red-50" : "text-green-700 hover:bg-green-50"}
>
<Power className="h-3.5 w-3.5 mr-1" />
{active ? "Deactivate" : "Reactivate"}
</Button>
</div>
);
}
function FormErrorBanner({ message }: { message: string | null }) {
if (!message) return null;
return (
<div className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700 mb-3">
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
<span>{message}</span>
</div>
);
}
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";
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
const errCls = "text-xs text-red-600 mt-1";
// --- Department Modal ---
const deptSchema = z.object({
name: z.string().trim().min(1, "Department name is required"),
code: z.string().trim().min(1, "Department code is required").max(20, "Max 20 characters"),
description: z.string().optional(),
});
type DeptForm = z.infer<typeof deptSchema>;
function DepartmentModal({
open,
onClose,
editing,
}: {
open: boolean;
onClose: () => void;
editing: Department | null;
}) {
const qc = useQueryClient();
const [serverError, setServerError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<DeptForm>({
resolver: zodResolver(deptSchema),
values: editing
? { name: editing.name, code: editing.code, description: editing.description ?? "" }
: { name: "", code: "", description: "" },
});
async function onSubmit(values: DeptForm) {
setServerError(null);
const payload = {
name: values.name,
code: values.code.toUpperCase(),
description: values.description?.trim() || null,
};
try {
if (editing) await departmentsApi.update(editing.id, payload);
else await departmentsApi.create(payload);
await qc.invalidateQueries({ queryKey: ["departments"] });
onClose();
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to save department.");
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={editing ? "Edit Department" : "Add Department"}>
<FormErrorBanner message={serverError} />
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<label className={labelCls}>Name *</label>
<input {...register("name")} className={inputCls} placeholder="e.g. Intensive Care Unit" />
{errors.name && <p className={errCls}>{errors.name.message}</p>}
</div>
<div>
<label className={labelCls}>Code *</label>
<input {...register("code")} className={inputCls} placeholder="e.g. ICU" />
{errors.code && <p className={errCls}>{errors.code.message}</p>}
</div>
<div>
<label className={labelCls}>Description</label>
<textarea {...register("description")} rows={2} className={inputCls} />
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
<Button type="submit" loading={isSubmitting}>{editing ? "Save Changes" : "Create"}</Button>
</div>
</form>
</Modal>
);
}
// --- Location Modal ---
const locSchema = z.object({
department_id: z.coerce.number().int().min(1, "Select a department"),
name: z.string().trim().min(1, "Location name is required"),
floor_wing: z.string().optional(),
});
type LocForm = z.infer<typeof locSchema>;
function LocationModal({
open,
onClose,
editing,
departments,
}: {
open: boolean;
onClose: () => void;
editing: LocationItem | null;
departments: Department[];
}) {
const qc = useQueryClient();
const [serverError, setServerError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<LocForm>({
resolver: zodResolver(locSchema),
values: editing
? {
department_id: editing.department_id,
name: editing.name,
floor_wing: editing.floor_wing ?? "",
}
: { department_id: departments[0]?.id ?? 0, name: "", floor_wing: "" },
});
async function onSubmit(values: LocForm) {
setServerError(null);
const payload = {
department_id: values.department_id,
name: values.name,
floor_wing: values.floor_wing?.trim() || null,
};
try {
if (editing) await locationsApi.update(editing.id, payload);
else await locationsApi.create(payload);
await qc.invalidateQueries({ queryKey: ["locations"] });
onClose();
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to save location.");
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={editing ? "Edit Location" : "Add Location"}>
<FormErrorBanner message={serverError} />
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<label className={labelCls}>Department *</label>
<select {...register("department_id")} className={inputCls}>
<option value={0}>Select department...</option>
{departments.map((d) => (
<option key={d.id} value={d.id}>{d.name} ({d.code})</option>
))}
</select>
{errors.department_id && <p className={errCls}>{errors.department_id.message}</p>}
</div>
<div>
<label className={labelCls}>Location Name *</label>
<input {...register("name")} className={inputCls} placeholder="e.g. ICU Bay 1" />
{errors.name && <p className={errCls}>{errors.name.message}</p>}
</div>
<div>
<label className={labelCls}>Floor / Wing</label>
<input {...register("floor_wing")} className={inputCls} placeholder="e.g. 2nd Floor, East Wing" />
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
<Button type="submit" loading={isSubmitting}>{editing ? "Save Changes" : "Create"}</Button>
</div>
</form>
</Modal>
);
}
// --- Category Modal ---
const catSchema = z.object({
name: z.string().trim().min(1, "Category name is required"),
description: z.string().optional(),
});
type CatForm = z.infer<typeof catSchema>;
function CategoryModal({
open,
onClose,
editing,
}: {
open: boolean;
onClose: () => void;
editing: Category | null;
}) {
const qc = useQueryClient();
const [serverError, setServerError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<CatForm>({
resolver: zodResolver(catSchema),
values: editing
? { name: editing.name, description: editing.description ?? "" }
: { name: "", description: "" },
});
async function onSubmit(values: CatForm) {
setServerError(null);
const payload = {
name: values.name,
description: values.description?.trim() || null,
};
try {
if (editing) await categoriesApi.update(editing.id, payload);
else await categoriesApi.create(payload);
await qc.invalidateQueries({ queryKey: ["categories"] });
onClose();
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to save category.");
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={editing ? "Edit Category" : "Add Category"}>
<FormErrorBanner message={serverError} />
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<label className={labelCls}>Name *</label>
<input {...register("name")} className={inputCls} placeholder="e.g. Life Support" />
{errors.name && <p className={errCls}>{errors.name.message}</p>}
</div>
<div>
<label className={labelCls}>Description</label>
<textarea {...register("description")} rows={2} className={inputCls} />
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
<Button type="submit" loading={isSubmitting}>{editing ? "Save Changes" : "Create"}</Button>
</div>
</form>
</Modal>
);
}
// --- Vendor Modal ---
const vendorSchema = z.object({
name: z.string().trim().min(1, "Vendor name is required"),
vendor_type: z.enum(["supplier", "service_provider", "calibration_agency", "insurer", "oem"]),
contact_person: z.string().optional(),
phone: z.string().optional(),
email: z.string().email("Invalid email").or(z.literal("")).optional(),
address: z.string().optional(),
});
type VendorForm = z.infer<typeof vendorSchema>;
function VendorModal({
open,
onClose,
editing,
}: {
open: boolean;
onClose: () => void;
editing: Vendor | null;
}) {
const qc = useQueryClient();
const [serverError, setServerError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<VendorForm>({
resolver: zodResolver(vendorSchema),
values: editing
? {
name: editing.name,
vendor_type: editing.vendor_type,
contact_person: editing.contact_person ?? "",
phone: editing.phone ?? "",
email: editing.email ?? "",
address: editing.address ?? "",
}
: { name: "", vendor_type: "supplier", contact_person: "", phone: "", email: "", address: "" },
});
async function onSubmit(values: VendorForm) {
setServerError(null);
const payload = {
name: values.name,
vendor_type: values.vendor_type,
contact_person: values.contact_person?.trim() || null,
phone: values.phone?.trim() || null,
email: values.email?.trim() || null,
address: values.address?.trim() || null,
};
try {
if (editing) await vendorsApi.update(editing.id, payload);
else await vendorsApi.create(payload);
await qc.invalidateQueries({ queryKey: ["vendors"] });
onClose();
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to save vendor.");
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={editing ? "Edit Vendor" : "Add Vendor"}>
<FormErrorBanner message={serverError} />
<form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
<div>
<label className={labelCls}>Vendor Name *</label>
<input {...register("name")} className={inputCls} />
{errors.name && <p className={errCls}>{errors.name.message}</p>}
</div>
<div>
<label className={labelCls}>Vendor Type *</label>
<select {...register("vendor_type")} className={inputCls}>
{(Object.keys(VENDOR_TYPE_LABELS) as VendorType[]).map((vt) => (
<option key={vt} value={vt}>{VENDOR_TYPE_LABELS[vt]}</option>
))}
</select>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className={labelCls}>Contact Person</label>
<input {...register("contact_person")} className={inputCls} />
</div>
<div>
<label className={labelCls}>Phone</label>
<input {...register("phone")} className={inputCls} />
</div>
</div>
<div>
<label className={labelCls}>Email</label>
<input {...register("email")} type="email" className={inputCls} />
{errors.email && <p className={errCls}>{errors.email.message}</p>}
</div>
<div>
<label className={labelCls}>Address</label>
<textarea {...register("address")} rows={2} className={inputCls} />
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
<Button type="submit" loading={isSubmitting}>{editing ? "Save Changes" : "Create"}</Button>
</div>
</form>
</Modal>
);
}
// --- User Modal ---
function buildUserSchema(isEdit: boolean) {
return z.object({
name: z.string().trim().min(1, "Name is required"),
email: z.string().email("Enter a valid email"),
role: z.enum(["system_admin", "biomedical", "department_user", "management", "coordinator"]),
department_id: z.string().optional(),
password: isEdit
? z.string().refine((v) => v === "" || v.length >= 6, "Password must be at least 6 characters")
: z.string().min(6, "Password must be at least 6 characters"),
});
}
function UserModal({
open,
onClose,
editing,
departments,
}: {
open: boolean;
onClose: () => void;
editing: MasterUser | null;
departments: Department[];
}) {
const qc = useQueryClient();
const [serverError, setServerError] = useState<string | null>(null);
const schema = useMemo(() => buildUserSchema(Boolean(editing)), [editing]);
type UserForm = z.infer<typeof schema>;
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<UserForm>({
resolver: zodResolver(schema),
values: editing
? {
name: editing.name,
email: editing.email,
role: editing.role,
department_id: editing.department_id ? String(editing.department_id) : "",
password: "",
}
: { name: "", email: "", role: "department_user", department_id: "", password: "" },
});
async function onSubmit(values: UserForm) {
setServerError(null);
const deptId = values.department_id ? Number(values.department_id) : null;
try {
if (editing) {
const payload: Parameters<typeof usersApi.update>[1] = {
name: values.name,
email: values.email,
role: values.role,
department_id: deptId,
};
if (values.password) payload.password = values.password;
await usersApi.update(editing.id, payload);
} else {
await usersApi.create({
name: values.name,
email: values.email,
role: values.role,
department_id: deptId,
password: values.password,
});
}
await qc.invalidateQueries({ queryKey: ["users"] });
onClose();
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to save user.");
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={editing ? "Edit User" : "Add User"}>
<FormErrorBanner message={serverError} />
<form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
<div>
<label className={labelCls}>Full Name *</label>
<input {...register("name")} className={inputCls} />
{errors.name && <p className={errCls}>{errors.name.message}</p>}
</div>
<div>
<label className={labelCls}>Email *</label>
<input {...register("email")} type="email" className={inputCls} />
{errors.email && <p className={errCls}>{errors.email.message}</p>}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className={labelCls}>Role *</label>
<select {...register("role")} className={inputCls}>
{(Object.keys(ROLE_LABELS) as Role[]).map((r) => (
<option key={r} value={r}>{ROLE_LABELS[r]}</option>
))}
</select>
</div>
<div>
<label className={labelCls}>Department</label>
<select {...register("department_id")} className={inputCls}>
<option value="">None (Hospital-wide)</option>
{departments.map((d) => (
<option key={d.id} value={String(d.id)}>{d.name}</option>
))}
</select>
</div>
</div>
<div>
<label className={labelCls}>
{editing ? "New Password (leave blank to keep current)" : "Password *"}
</label>
<input {...register("password")} type="password" className={inputCls} />
{errors.password && <p className={errCls}>{errors.password.message}</p>}
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
<Button type="submit" loading={isSubmitting}>{editing ? "Save Changes" : "Create"}</Button>
</div>
</form>
</Modal>
);
}
// --- Main MastersPage ---
export function MastersPage() {
const qc = useQueryClient();
const [activeTab, setActiveTab] = useState<TabKey>("departments");
const [includeInactive, setIncludeInactive] = useState(true);
const [modalOpen, setModalOpen] = useState(false);
const [editingDept, setEditingDept] = useState<Department | null>(null);
const [editingLoc, setEditingLoc] = useState<LocationItem | null>(null);
const [editingCat, setEditingCat] = useState<Category | null>(null);
const [editingVendor, setEditingVendor] = useState<Vendor | null>(null);
const [editingUser, setEditingUser] = useState<MasterUser | null>(null);
const deptsQuery = useQuery({
queryKey: ["departments", includeInactive],
queryFn: () => departmentsApi.list(includeInactive),
});
const activeDeptsQuery = useQuery({
queryKey: ["departments", "active-only"],
queryFn: () => departmentsApi.list(false),
});
const locsQuery = useQuery({
queryKey: ["locations", includeInactive],
queryFn: () => locationsApi.list(includeInactive),
enabled: activeTab === "locations",
});
const catsQuery = useQuery({
queryKey: ["categories", includeInactive],
queryFn: () => categoriesApi.list(includeInactive),
enabled: activeTab === "categories",
});
const vendorsQuery = useQuery({
queryKey: ["vendors", includeInactive],
queryFn: () => vendorsApi.list(includeInactive),
enabled: activeTab === "vendors",
});
const usersQuery = useQuery({
queryKey: ["users", includeInactive],
queryFn: () => usersApi.list(includeInactive),
enabled: activeTab === "users",
});
const toggleMutation = useMutation({
mutationFn: async ({
tab,
id,
currentlyActive,
}: {
tab: TabKey;
id: number;
currentlyActive: boolean;
}) => {
if (tab === "departments") {
return currentlyActive ? departmentsApi.remove(id) : departmentsApi.update(id, { is_active: true });
}
if (tab === "locations") {
return currentlyActive ? locationsApi.remove(id) : locationsApi.update(id, { is_active: true });
}
if (tab === "categories") {
return currentlyActive ? categoriesApi.remove(id) : categoriesApi.update(id, { is_active: true });
}
if (tab === "vendors") {
return currentlyActive ? vendorsApi.remove(id) : vendorsApi.update(id, { is_active: true });
}
return currentlyActive ? usersApi.remove(id) : usersApi.update(id, { is_active: true });
},
onSuccess: (_data, vars) => {
qc.invalidateQueries({ queryKey: [vars.tab] });
},
});
function openCreate() {
setEditingDept(null);
setEditingLoc(null);
setEditingCat(null);
setEditingVendor(null);
setEditingUser(null);
setModalOpen(true);
}
const deptColumns: ColumnDef<Department, unknown>[] = [
{ accessorKey: "code", header: "Code", enableColumnFilter: true },
{ accessorKey: "name", header: "Name", enableColumnFilter: true },
{
accessorKey: "description",
header: "Description",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "is_active",
header: "Status",
cell: ({ getValue }) => <StatusBadge active={Boolean(getValue())} />,
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => (
<RowActions
active={row.original.is_active}
busy={toggleMutation.isPending}
onEdit={() => {
setEditingDept(row.original);
setModalOpen(true);
}}
onToggleActive={() =>
toggleMutation.mutate({ tab: "departments", id: row.original.id, currentlyActive: row.original.is_active })
}
/>
),
},
];
const locColumns: ColumnDef<LocationItem, unknown>[] = [
{ accessorKey: "name", header: "Location Name", enableColumnFilter: true },
{
accessorKey: "department_name",
header: "Department",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "floor_wing",
header: "Floor / Wing",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "is_active",
header: "Status",
cell: ({ getValue }) => <StatusBadge active={Boolean(getValue())} />,
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => (
<RowActions
active={row.original.is_active}
busy={toggleMutation.isPending}
onEdit={() => {
setEditingLoc(row.original);
setModalOpen(true);
}}
onToggleActive={() =>
toggleMutation.mutate({ tab: "locations", id: row.original.id, currentlyActive: row.original.is_active })
}
/>
),
},
];
const catColumns: ColumnDef<Category, unknown>[] = [
{ accessorKey: "name", header: "Category Name", enableColumnFilter: true },
{
accessorKey: "description",
header: "Description",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "is_active",
header: "Status",
cell: ({ getValue }) => <StatusBadge active={Boolean(getValue())} />,
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => (
<RowActions
active={row.original.is_active}
busy={toggleMutation.isPending}
onEdit={() => {
setEditingCat(row.original);
setModalOpen(true);
}}
onToggleActive={() =>
toggleMutation.mutate({ tab: "categories", id: row.original.id, currentlyActive: row.original.is_active })
}
/>
),
},
];
const vendorColumns: ColumnDef<Vendor, unknown>[] = [
{ accessorKey: "name", header: "Vendor Name", enableColumnFilter: true },
{
accessorKey: "vendor_type",
header: "Type",
enableColumnFilter: true,
cell: ({ getValue }) => VENDOR_TYPE_LABELS[getValue() as VendorType] ?? String(getValue()),
},
{
accessorKey: "contact_person",
header: "Contact",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "phone",
header: "Phone",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "email",
header: "Email",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "is_active",
header: "Status",
cell: ({ getValue }) => <StatusBadge active={Boolean(getValue())} />,
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => (
<RowActions
active={row.original.is_active}
busy={toggleMutation.isPending}
onEdit={() => {
setEditingVendor(row.original);
setModalOpen(true);
}}
onToggleActive={() =>
toggleMutation.mutate({ tab: "vendors", id: row.original.id, currentlyActive: row.original.is_active })
}
/>
),
},
];
const userColumns: ColumnDef<MasterUser, unknown>[] = [
{ accessorKey: "name", header: "Name", enableColumnFilter: true },
{ accessorKey: "email", header: "Email", enableColumnFilter: true },
{
accessorKey: "role",
header: "Role",
enableColumnFilter: true,
cell: ({ getValue }) => (
<Badge variant="info">{ROLE_LABELS[getValue() as Role] ?? String(getValue())}</Badge>
),
},
{
accessorKey: "department_name",
header: "Department",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "Hospital-wide",
},
{
accessorKey: "is_active",
header: "Status",
cell: ({ getValue }) => <StatusBadge active={Boolean(getValue())} />,
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => (
<RowActions
active={row.original.is_active}
busy={toggleMutation.isPending}
onEdit={() => {
setEditingUser(row.original);
setModalOpen(true);
}}
onToggleActive={() =>
toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active })
}
/>
),
},
];
const activeDepartments = activeDeptsQuery.data?.items ?? [];
const addLabelMap: Record<TabKey, string> = {
departments: "Add Department",
locations: "Add Location",
categories: "Add Category",
vendors: "Add Vendor",
users: "Add User",
};
return (
<div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-gray-900">Master Lists</h1>
<p className="text-sm text-gray-500 mt-0.5">
Manage departments, locations, equipment categories, vendors, and user accounts.
</p>
</div>
<div className="flex items-center gap-3">
<label className="inline-flex items-center gap-2 text-sm text-gray-600 cursor-pointer">
<input
type="checkbox"
checked={includeInactive}
onChange={(e) => setIncludeInactive(e.target.checked)}
className="rounded border-gray-300"
/>
Show inactive
</label>
<Button onClick={openCreate}>
<Plus className="h-4 w-4 mr-1.5" />
{addLabelMap[activeTab]}
</Button>
</div>
</div>
{/* Tabs */}
<div className="border-b border-gray-200 flex gap-1 overflow-x-auto">
{TABS.map((tab) => (
<button
key={tab.key}
type="button"
onClick={() => setActiveTab(tab.key)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
activeTab === tab.key
? "border-[#1e3a8a] text-[#1e3a8a]"
: "border-transparent text-gray-500 hover:text-gray-800"
}`}
>
{tab.label}
</button>
))}
</div>
{/* Tab Content */}
{activeTab === "departments" && (
<DataTable
data={deptsQuery.data?.items ?? []}
columns={deptColumns}
loading={deptsQuery.isLoading}
globalFilterPlaceholder="Search departments..."
exportFilename="departments"
/>
)}
{activeTab === "locations" && (
<DataTable
data={locsQuery.data?.items ?? []}
columns={locColumns}
loading={locsQuery.isLoading}
globalFilterPlaceholder="Search locations..."
exportFilename="locations"
/>
)}
{activeTab === "categories" && (
<DataTable
data={catsQuery.data?.items ?? []}
columns={catColumns}
loading={catsQuery.isLoading}
globalFilterPlaceholder="Search categories..."
exportFilename="categories"
/>
)}
{activeTab === "vendors" && (
<DataTable
data={vendorsQuery.data?.items ?? []}
columns={vendorColumns}
loading={vendorsQuery.isLoading}
globalFilterPlaceholder="Search vendors..."
exportFilename="vendors"
/>
)}
{activeTab === "users" && (
<DataTable
data={usersQuery.data?.items ?? []}
columns={userColumns}
loading={usersQuery.isLoading}
globalFilterPlaceholder="Search users..."
exportFilename="users"
/>
)}
{/* Modals */}
{modalOpen && activeTab === "departments" && (
<DepartmentModal open={modalOpen} onClose={() => setModalOpen(false)} editing={editingDept} />
)}
{modalOpen && activeTab === "locations" && (
<LocationModal
open={modalOpen}
onClose={() => setModalOpen(false)}
editing={editingLoc}
departments={activeDepartments}
/>
)}
{modalOpen && activeTab === "categories" && (
<CategoryModal open={modalOpen} onClose={() => setModalOpen(false)} editing={editingCat} />
)}
{modalOpen && activeTab === "vendors" && (
<VendorModal open={modalOpen} onClose={() => setModalOpen(false)} editing={editingVendor} />
)}
{modalOpen && activeTab === "users" && (
<UserModal
open={modalOpen}
onClose={() => setModalOpen(false)}
editing={editingUser}
departments={activeDepartments}
/>
)}
</div>
);
}
+226
View File
@@ -0,0 +1,226 @@
import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Save, CheckCircle2, AlertCircle, X } from "lucide-react";
import { settingsApi, type SettingItem } from "@/api/settings";
import { ApiError } from "@/api/client";
import { useAuthStore } from "@/hooks/useAuth";
import { Button } from "@/components/ui/button";
export function SettingsPage() {
const qc = useQueryClient();
const setDemoAsOfDate = useAuthStore((s) => s.setDemoAsOfDate);
const [draft, setDraft] = useState<Record<string, unknown>>({});
const [savedNotice, setSavedNotice] = useState(false);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const { data, isLoading, isError, error } = useQuery({
queryKey: ["settings"],
queryFn: settingsApi.getAll,
});
useEffect(() => {
if (data?.items) {
const next: Record<string, unknown> = {};
for (const item of data.items) {
next[item.key] = item.value ?? "";
}
setDraft(next);
}
}, [data]);
const saveMutation = useMutation({
mutationFn: (values: Record<string, unknown>) => settingsApi.updateAll(values),
onSuccess: async (res) => {
setErrorMsg(null);
setSavedNotice(true);
const demoItem = res.items.find((i) => i.key === "demo_as_of_date");
if (demoItem !== undefined) {
const val = typeof demoItem.value === "string" && demoItem.value ? demoItem.value : null;
setDemoAsOfDate(val);
}
await qc.invalidateQueries({ queryKey: ["settings"] });
await qc.invalidateQueries();
setTimeout(() => setSavedNotice(false), 3500);
},
onError: (err) => {
setSavedNotice(false);
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to save settings.");
},
});
function handleChange(item: SettingItem, raw: unknown) {
setSavedNotice(false);
setDraft((prev) => ({ ...prev, [item.key]: raw }));
}
function handleSave(e: React.FormEvent) {
e.preventDefault();
if (!data?.items) return;
setErrorMsg(null);
const values: Record<string, unknown> = {};
for (const item of data.items) {
const raw = draft[item.key];
if (item.type === "int") {
const num = Number(raw);
if (Number.isNaN(num)) {
setErrorMsg(`"${item.label}" must be a valid integer.`);
return;
}
values[item.key] = Math.trunc(num);
} else if (item.type === "bool") {
values[item.key] = Boolean(raw);
} else if (item.type === "date_or_empty") {
values[item.key] = raw ? String(raw) : "";
} else {
values[item.key] = raw == null ? "" : String(raw);
}
}
saveMutation.mutate(values);
}
if (isLoading) {
return (
<div className="max-w-3xl space-y-4">
<div className="h-8 w-48 bg-gray-200 rounded animate-pulse" />
{[1, 2, 3, 4].map((i) => (
<div key={i} className="h-20 bg-white border border-gray-200 rounded-lg animate-pulse" />
))}
</div>
);
}
if (isError) {
return (
<div className="max-w-3xl rounded-lg bg-red-50 border border-red-200 p-4 text-sm text-red-700">
{error instanceof ApiError ? error.detail : "Failed to load settings."}
</div>
);
}
return (
<form onSubmit={handleSave} className="max-w-3xl space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-gray-900">System Settings</h1>
<p className="text-sm text-gray-500 mt-0.5">
Configure lead days, downtime computation rules, escalation thresholds, and demo clock.
</p>
</div>
<Button type="submit" loading={saveMutation.isPending}>
<Save className="h-4 w-4 mr-1.5" />
Save Settings
</Button>
</div>
{savedNotice && (
<div className="flex items-center gap-2 rounded-md bg-green-50 border border-green-200 px-4 py-2.5 text-sm text-green-800">
<CheckCircle2 className="h-4 w-4 shrink-0" />
Settings saved successfully.
</div>
)}
{errorMsg && (
<div className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-4 py-2.5 text-sm text-red-700">
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
<span>{errorMsg}</span>
</div>
)}
<div className="bg-white rounded-lg border border-gray-200 divide-y divide-gray-100">
{data?.items.map((item) => {
const val = draft[item.key];
return (
<div key={item.key} className="p-4 sm:p-5 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div className="space-y-1 flex-1">
<label htmlFor={`setting-${item.key}`} className="block text-sm font-semibold text-gray-800">
{item.label}
</label>
<p className="text-xs text-gray-500">{item.description}</p>
<p className="text-[11px] text-gray-400">
Default: <code className="bg-gray-100 px-1 rounded">{String(item.default || "empty")}</code>
{item.type === "int" && item.min != null && item.max != null && (
<> • Range: {item.min}–{item.max}</>
)}
</p>
</div>
<div className="sm:w-64 shrink-0">
{item.type === "int" && (
<input
id={`setting-${item.key}`}
type="number"
min={item.min ?? undefined}
max={item.max ?? undefined}
value={val === undefined || val === null ? "" : String(val)}
onChange={(e) => handleChange(item, e.target.value)}
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
)}
{item.type === "bool" && (
<label className="inline-flex items-center gap-2 cursor-pointer">
<input
id={`setting-${item.key}`}
type="checkbox"
checked={Boolean(val)}
onChange={(e) => handleChange(item, e.target.checked)}
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a] focus:ring-blue-500"
/>
<span className="text-sm text-gray-700">{Boolean(val) ? "Enabled" : "Disabled"}</span>
</label>
)}
{item.type === "enum" && (
<select
id={`setting-${item.key}`}
value={String(val ?? "")}
onChange={(e) => handleChange(item, e.target.value)}
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
>
{item.options?.map((opt) => (
<option key={opt} value={opt}>{opt}</option>
))}
</select>
)}
{item.type === "str" && (
<input
id={`setting-${item.key}`}
type="text"
value={String(val ?? "")}
onChange={(e) => handleChange(item, e.target.value)}
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
)}
{item.type === "date_or_empty" && (
<div className="flex items-center gap-1.5">
<input
id={`setting-${item.key}`}
type="date"
value={String(val ?? "")}
onChange={(e) => handleChange(item, e.target.value)}
className="flex-1 px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
{Boolean(val) && (
<button
type="button"
onClick={() => handleChange(item, "")}
title="Clear date"
className="p-1.5 rounded border border-gray-300 text-gray-500 hover:bg-gray-100"
>
<X className="h-4 w-4" />
</button>
)}
</div>
)}
</div>
</div>
);
})}
</div>
</form>
);
}
-3
View File
@@ -70,6 +70,3 @@ export const ReportsPage = () => (
export const NotificationsPage = () => (
<StubPage title="Notifications" phase={6} description="In-app alerts and notification centre." />
);
export const SettingsPage = () => (
<StubPage title="Settings" phase={1} description="Configurable lead days, downtime rules, and system settings." />
);
+67
View File
@@ -0,0 +1,67 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { LoginPage } from "@/pages/LoginPage";
import { useAuthStore } from "@/hooks/useAuth";
import * as authApi from "@/api/auth";
import { ApiError } from "@/api/client";
describe("LoginPage", () => {
beforeEach(() => {
sessionStorage.clear();
useAuthStore.setState({ user: null, token: null, demoAsOfDate: null, hydrating: false });
vi.restoreAllMocks();
});
it("renders branding, form fields, and all 5 Quick Demo Login buttons", () => {
render(
<MemoryRouter>
<LoginPage />
</MemoryRouter>
);
expect(screen.getByAltText("Poona Hospital and Research Centre")).toBeInTheDocument();
expect(screen.getByLabelText("Email Address")).toBeInTheDocument();
expect(screen.getByLabelText("Password")).toBeInTheDocument();
expect(screen.getByRole("button", { name: /Sign In/i })).toBeInTheDocument();
expect(screen.getByText("admin@poona.demo")).toBeInTheDocument();
expect(screen.getByText("bio@poona.demo")).toBeInTheDocument();
expect(screen.getByText("dept@poona.demo")).toBeInTheDocument();
expect(screen.getByText("mgmt@poona.demo")).toBeInTheDocument();
expect(screen.getByText("coord@poona.demo")).toBeInTheDocument();
});
it("shows validation errors when submitting empty credentials", async () => {
render(
<MemoryRouter>
<LoginPage />
</MemoryRouter>
);
fireEvent.click(screen.getByRole("button", { name: /Sign In/i }));
await waitFor(() => {
expect(screen.getByText("Enter a valid email address")).toBeInTheDocument();
expect(screen.getByText("Password is required")).toBeInTheDocument();
});
});
it("displays server error alert when login fails", async () => {
vi.spyOn(authApi, "loginApi").mockRejectedValueOnce(new ApiError(401, "Invalid email or password"));
render(
<MemoryRouter>
<LoginPage />
</MemoryRouter>
);
fireEvent.change(screen.getByLabelText("Email Address"), { target: { value: "admin@poona.demo" } });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "wrong" } });
fireEvent.click(screen.getByRole("button", { name: /Sign In/i }));
await waitFor(() => {
expect(screen.getByRole("alert")).toHaveTextContent("Invalid email or password");
});
});
});
+57
View File
@@ -0,0 +1,57 @@
import { describe, it, expect } from "vitest";
import { can, type Role } from "@/lib/permissions";
describe("permissions.can()", () => {
it("returns false when role is undefined", () => {
expect(can(undefined, "view_assets")).toBe(false);
expect(can(undefined, "manage_admin")).toBe(false);
});
it("enforces manage_admin for system_admin only", () => {
expect(can("system_admin", "manage_admin")).toBe(true);
const nonAdmins: Role[] = ["biomedical", "department_user", "management", "coordinator"];
for (const role of nonAdmins) {
expect(can(role, "manage_admin")).toBe(false);
}
});
it("enforces edit_technical_fields for system_admin and biomedical only", () => {
expect(can("system_admin", "edit_technical_fields")).toBe(true);
expect(can("biomedical", "edit_technical_fields")).toBe(true);
expect(can("department_user", "edit_technical_fields")).toBe(false);
expect(can("management", "edit_technical_fields")).toBe(false);
expect(can("coordinator", "edit_technical_fields")).toBe(false);
});
it("enforces role-specific capabilities across all 5 roles", () => {
// biomedical
expect(can("biomedical", "create_edit_assets")).toBe(true);
expect(can("biomedical", "handle_complaint")).toBe(true);
expect(can("biomedical", "manage_pm")).toBe(true);
expect(can("biomedical", "manage_visits")).toBe(true);
// department_user
expect(can("department_user", "view_assets")).toBe(true);
expect(can("department_user", "raise_complaint")).toBe(true);
expect(can("department_user", "handle_complaint")).toBe(false);
expect(can("department_user", "view_visits")).toBe(false);
expect(can("department_user", "view_all_reports")).toBe(false);
expect(can("department_user", "view_dept_reports")).toBe(true);
// management
expect(can("management", "view_assets")).toBe(true);
expect(can("management", "view_all_reports")).toBe(true);
expect(can("management", "view_visits")).toBe(true);
expect(can("management", "create_edit_assets")).toBe(false);
expect(can("management", "raise_complaint")).toBe(false);
expect(can("management", "handle_complaint")).toBe(false);
// coordinator
expect(can("coordinator", "edit_asset_contracts_only")).toBe(true);
expect(can("coordinator", "create_edit_assets")).toBe(false);
expect(can("coordinator", "handle_complaint")).toBe(true);
expect(can("coordinator", "manage_calibration_contracts")).toBe(true);
expect(can("coordinator", "manage_demo_equipment")).toBe(true);
expect(can("coordinator", "view_visits")).toBe(false);
});
});
+66 -3
View File
@@ -1,12 +1,30 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { Sidebar } from "@/components/layout/Sidebar";
import { DashboardPage } from "@/pages/stubs";
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
import { useAuthStore } from "@/hooks/useAuth";
describe("Phase 0 Frontend Smoke Tests", () => {
it("renders Sidebar with Poona Hospital logo, subtitle, and all 12 navigation links", () => {
describe("Phase 1 Frontend Smoke Tests", () => {
beforeEach(() => {
useAuthStore.setState({
user: {
id: 1,
name: "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("renders Sidebar with Poona Hospital logo, subtitle, and all admin navigation links", () => {
render(
<MemoryRouter>
<Sidebar />
@@ -30,6 +48,7 @@ describe("Phase 0 Frontend Smoke Tests", () => {
"Department Visits",
"Reports",
"Notifications",
"Masters",
"Settings",
];
for (const label of labels) {
@@ -37,6 +56,50 @@ describe("Phase 0 Frontend Smoke Tests", () => {
}
});
it("hides Masters, Settings, and Department Visits for department_user and coordinator", () => {
useAuthStore.setState({
user: {
id: 3,
name: "Dept User",
email: "dept@poona.demo",
role: "department_user",
department_id: 1,
department_name: "ICU",
is_active: true,
},
});
const { rerender } = render(
<MemoryRouter>
<Sidebar />
</MemoryRouter>
);
expect(screen.queryByText("Masters")).not.toBeInTheDocument();
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
expect(screen.getByText("Assets")).toBeInTheDocument();
useAuthStore.setState({
user: {
id: 5,
name: "Coordinator",
email: "coord@poona.demo",
role: "coordinator",
department_id: null,
department_name: null,
is_active: true,
},
});
rerender(
<MemoryRouter>
<Sidebar />
</MemoryRouter>
);
expect(screen.queryByText("Masters")).not.toBeInTheDocument();
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument();
});
it("renders DashboardPage with clickable link to /demo", () => {
render(
<MemoryRouter>
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/client.ts","./src/api/health.ts","./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/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/datatabledemopage.tsx","./src/pages/stubs.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/auth.ts","./src/api/client.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/settings.ts","./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/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}