phase-1: data model, auth, permissions, masters, settings, seed
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
@@ -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")
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,3 @@
|
||||
from . import auth, health, masters, settings, users
|
||||
|
||||
__all__ = ["auth", "health", "masters", "settings", "users"]
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -0,0 +1,43 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import require_roles
|
||||
from ..core.time_utils import effective_today
|
||||
from ..models.masters import User
|
||||
from ..schemas.settings import DemoDateIn, DemoDateOut, SettingsListOut, SettingsUpdateIn
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_all_settings, get_demo_as_of_date, update_settings
|
||||
|
||||
router = APIRouter(prefix="/settings", tags=["settings"])
|
||||
|
||||
|
||||
@router.get("", response_model=SettingsListOut)
|
||||
def list_settings(
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
return {"items": get_all_settings(db)}
|
||||
|
||||
|
||||
@router.put("", response_model=SettingsListOut)
|
||||
def save_settings(
|
||||
payload: SettingsUpdateIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
items = update_settings(db, payload.values, user_id=current_user.id)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
@router.post("/demo-date", response_model=DemoDateOut)
|
||||
def set_demo_date(
|
||||
payload: DemoDateIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
val = payload.demo_as_of_date if payload.demo_as_of_date is not None else ""
|
||||
update_settings(db, {"demo_as_of_date": val}, user_id=current_user.id)
|
||||
return {
|
||||
"demo_as_of_date": get_demo_as_of_date(db),
|
||||
"effective_today": effective_today(db).isoformat(),
|
||||
}
|
||||
@@ -0,0 +1,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)
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: str
|
||||
password: str
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
email: str
|
||||
role: str
|
||||
department_id: Optional[int] = None
|
||||
department_name: Optional[str] = None
|
||||
is_active: bool
|
||||
demo_as_of_date: Optional[str] = None
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
user: UserOut
|
||||
@@ -0,0 +1,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
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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())
|
||||
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user