270 lines
12 KiB
Python
270 lines
12 KiB
Python
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# Add backend directory to sys.path
|
|
backend_dir = Path(__file__).resolve().parent.parent
|
|
sys.path.insert(0, str(backend_dir))
|
|
|
|
from sqlalchemy.orm import Session
|
|
from app.database import engine, Base, SessionLocal
|
|
from app.models.user import User, UserRole
|
|
from app.models.department import Department, UserDepartment
|
|
from app.models.dataset import Dataset, DatasetColumn
|
|
from app.models.permission import DatasetPermission, ColumnPermission, RowRule
|
|
from app.core.security import hash_password
|
|
from app.services.ingestion_service import register_dataset_from_csv
|
|
from app.services.permission_service import save_dataset_permission
|
|
from app.services.department_service import add_user_to_department
|
|
from app.schemas.permission import DatasetPermissionCreate, RowRuleCreate
|
|
from app.config import settings
|
|
|
|
DMH_DEPARTMENTS = [
|
|
{"code": "ADMISSION", "name": "Admission & Registration", "desc": "Registration overview, demographics, and patient intake"},
|
|
{"code": "OPD", "name": "Outpatient Department (OPD)", "desc": "Visit performance, clinic consultations, and doctor schedules"},
|
|
{"code": "IPD", "name": "Inpatient Department (IPD)", "desc": "Inpatient admissions, discharges, ward occupancy, and length of stay"},
|
|
{"code": "PHARMACY", "name": "Pharmacy & Dispensary", "desc": "Medication dispensing, inventory stock, and procurement"},
|
|
{"code": "FINANCE", "name": "Finance & Accounts", "desc": "Hospital billing, revenue streams, collections, and outstanding balances"},
|
|
{"code": "INSURANCE", "name": "Insurance & TPA", "desc": "TPA cashless processing, claims submission, settlements, and rejections"},
|
|
{"code": "LABORATORY", "name": "Laboratory & Pathology", "desc": "Clinical pathology, test volumes, turnaround times, and pending samples"},
|
|
{"code": "RADIOLOGY", "name": "Radiology & Imaging", "desc": "CT, MRI, X-ray, Ultrasound volume, and equipment utilization"},
|
|
{"code": "HR", "name": "Human Resources (HR)", "desc": "Hospital workforce, staffing rosters, attendance, and shift analytics"},
|
|
{"code": "BIOMEDICAL", "name": "Biomedical Engineering", "desc": "Medical equipment uptime, maintenance cycles, and breakdown tracking"},
|
|
{"code": "OT", "name": "Operation Theatre (OT)", "desc": "Surgical procedures, OT suite utilization, and elective case turnover"},
|
|
{"code": "MANAGEMENT", "name": "Executive Management", "desc": "Consolidated hospital KPIs, executive overview, and strategic metrics"},
|
|
]
|
|
|
|
|
|
def seed_database():
|
|
print("Initializing database tables...")
|
|
Base.metadata.create_all(bind=engine)
|
|
db: Session = SessionLocal()
|
|
|
|
try:
|
|
# 1. Seed Super Admin
|
|
admin_user = db.query(User).filter(User.username == settings.FIRST_SUPER_ADMIN_USERNAME).first()
|
|
if not admin_user:
|
|
print(f"Creating default Super Admin ({settings.FIRST_SUPER_ADMIN_USERNAME})...")
|
|
admin_user = User(
|
|
username=settings.FIRST_SUPER_ADMIN_USERNAME,
|
|
email=settings.FIRST_SUPER_ADMIN_EMAIL,
|
|
hashed_password=hash_password(settings.FIRST_SUPER_ADMIN_PASSWORD),
|
|
full_name="Hospital Super Administrator",
|
|
role=UserRole.SUPER_ADMIN.value,
|
|
is_active=True
|
|
)
|
|
db.add(admin_user)
|
|
else:
|
|
print("Super Admin user already exists.")
|
|
|
|
# 2. Seed Test Viewer
|
|
viewer_user = db.query(User).filter(User.username == "viewer").first()
|
|
if not viewer_user:
|
|
print("Creating demo Viewer user (viewer)...")
|
|
viewer_user = User(
|
|
username="viewer",
|
|
email="viewer@dmh.org",
|
|
hashed_password=hash_password("Viewer@123456"),
|
|
full_name="Clinical Staff Viewer",
|
|
role=UserRole.VIEWER.value,
|
|
is_active=True
|
|
)
|
|
db.add(viewer_user)
|
|
|
|
# 3. Seed Department Manager
|
|
dept_user = db.query(User).filter(User.username == "dept_manager").first()
|
|
if not dept_user:
|
|
print("Creating demo Department Manager user (dept_manager)...")
|
|
dept_user = User(
|
|
username="dept_manager",
|
|
email="dept_manager@dmh.org",
|
|
hashed_password=hash_password("Manager@123456"),
|
|
full_name="Medicine HOD",
|
|
role=UserRole.DEPARTMENT_MANAGER.value,
|
|
is_active=True
|
|
)
|
|
db.add(dept_user)
|
|
|
|
# 4. Seed Finance User
|
|
fin_user = db.query(User).filter(User.username == "finance_user").first()
|
|
if not fin_user:
|
|
print("Creating demo Finance user (finance_user)...")
|
|
fin_user = User(
|
|
username="finance_user",
|
|
email="finance@dmh.org",
|
|
hashed_password=hash_password("Finance@123456"),
|
|
full_name="Hospital Billing & TPA Analyst",
|
|
role=UserRole.FINANCE.value,
|
|
is_active=True
|
|
)
|
|
db.add(fin_user)
|
|
|
|
db.commit()
|
|
|
|
# 5. Seed 12 DMH Departments
|
|
print("Seeding 12 DMH clinical and administrative departments...")
|
|
dept_map = {}
|
|
for d_info in DMH_DEPARTMENTS:
|
|
existing_dept = db.query(Department).filter(Department.code == d_info["code"]).first()
|
|
if not existing_dept:
|
|
dept_obj = Department(
|
|
code=d_info["code"],
|
|
name=d_info["name"],
|
|
description=d_info["desc"],
|
|
is_active=True
|
|
)
|
|
db.add(dept_obj)
|
|
db.flush()
|
|
dept_map[d_info["code"]] = dept_obj
|
|
else:
|
|
dept_map[d_info["code"]] = existing_dept
|
|
db.commit()
|
|
|
|
# Assign Users to Departments
|
|
print("Assigning users to departments...")
|
|
if "MANAGEMENT" in dept_map and admin_user:
|
|
add_user_to_department(db, dept_map["MANAGEMENT"].id, admin_user.id, is_head=True)
|
|
if "IPD" in dept_map and dept_user:
|
|
add_user_to_department(db, dept_map["IPD"].id, dept_user.id, is_head=True)
|
|
if "OPD" in dept_map and dept_user:
|
|
add_user_to_department(db, dept_map["OPD"].id, dept_user.id, is_head=False)
|
|
if "FINANCE" in dept_map and fin_user:
|
|
add_user_to_department(db, dept_map["FINANCE"].id, fin_user.id, is_head=True)
|
|
if "INSURANCE" in dept_map and fin_user:
|
|
add_user_to_department(db, dept_map["INSURANCE"].id, fin_user.id, is_head=False)
|
|
if "ADMISSION" in dept_map and viewer_user:
|
|
add_user_to_department(db, dept_map["ADMISSION"].id, viewer_user.id, is_head=False)
|
|
|
|
# 6. Seed Admission Dataset
|
|
dataset_name = "Hospital Admissions 2025"
|
|
ds = db.query(Dataset).filter(Dataset.name == dataset_name).first()
|
|
if not ds:
|
|
csv_path = Path(backend_dir).parent / "data" / "admissionData-2025_v1.csv"
|
|
if csv_path.exists():
|
|
print(f"Ingesting {csv_path.name} ({csv_path.stat().st_size / (1024*1024):.1f} MB)...")
|
|
with open(csv_path, "rb") as f:
|
|
content = f.read()
|
|
ds = register_dataset_from_csv(
|
|
db=db,
|
|
file_content=content,
|
|
dataset_name=dataset_name,
|
|
description="Deenanath Mangeshkar Hospital 2025 Inpatient Admission records"
|
|
)
|
|
print(f"Ingested {ds.row_count} rows across {ds.column_count} fields into table '{ds.table_name}'.")
|
|
else:
|
|
print(f"Dataset file {csv_path} not found. Skipping auto-ingestion.")
|
|
else:
|
|
print(f"Dataset '{dataset_name}' already registered ({ds.row_count} rows).")
|
|
|
|
# 6. Seed Role-Based Permissions
|
|
if ds:
|
|
print("Configuring role-based permissions and row rules...")
|
|
# Viewer Role Permission (can view, no export, sensitive columns hidden)
|
|
save_dataset_permission(
|
|
db,
|
|
DatasetPermissionCreate(
|
|
dataset_id=ds.id,
|
|
role=UserRole.VIEWER.value,
|
|
can_view=True,
|
|
can_export=False,
|
|
hidden_column_ids=[],
|
|
row_rules=[]
|
|
)
|
|
)
|
|
|
|
# Department Manager Role Permission (Row rule: MEDICINE only)
|
|
save_dataset_permission(
|
|
db,
|
|
DatasetPermissionCreate(
|
|
dataset_id=ds.id,
|
|
role=UserRole.DEPARTMENT_MANAGER.value,
|
|
can_view=True,
|
|
can_export=True,
|
|
hidden_column_ids=[],
|
|
row_rules=[
|
|
RowRuleCreate(
|
|
column_name="AdmittingDoctorSpecialityName",
|
|
operator="eq",
|
|
rule_value="MEDICINE"
|
|
)
|
|
]
|
|
)
|
|
)
|
|
|
|
# Finance User Role Permission (Row rule: TPA category only)
|
|
save_dataset_permission(
|
|
db,
|
|
DatasetPermissionCreate(
|
|
dataset_id=ds.id,
|
|
role=UserRole.FINANCE.value,
|
|
can_view=True,
|
|
can_export=True,
|
|
hidden_column_ids=[],
|
|
row_rules=[
|
|
RowRuleCreate(
|
|
column_name="PatientCategoryName",
|
|
operator="eq",
|
|
rule_value="TPA"
|
|
)
|
|
]
|
|
)
|
|
)
|
|
# Department-level dataset permissions
|
|
if "IPD" in dept_map:
|
|
save_dataset_permission(
|
|
db,
|
|
DatasetPermissionCreate(
|
|
dataset_id=ds.id,
|
|
department_id=dept_map["IPD"].id,
|
|
can_view=True,
|
|
can_export=True,
|
|
hidden_column_ids=[],
|
|
row_rules=[
|
|
RowRuleCreate(
|
|
column_name="AdmittingDoctorSpecialityName",
|
|
operator="eq",
|
|
rule_value="MEDICINE"
|
|
)
|
|
]
|
|
)
|
|
)
|
|
if "FINANCE" in dept_map:
|
|
save_dataset_permission(
|
|
db,
|
|
DatasetPermissionCreate(
|
|
dataset_id=ds.id,
|
|
department_id=dept_map["FINANCE"].id,
|
|
can_view=True,
|
|
can_export=True,
|
|
hidden_column_ids=[],
|
|
row_rules=[
|
|
RowRuleCreate(
|
|
column_name="PatientCategoryName",
|
|
operator="eq",
|
|
rule_value="TPA"
|
|
)
|
|
]
|
|
)
|
|
)
|
|
if "ADMISSION" in dept_map:
|
|
save_dataset_permission(
|
|
db,
|
|
DatasetPermissionCreate(
|
|
dataset_id=ds.id,
|
|
department_id=dept_map["ADMISSION"].id,
|
|
can_view=True,
|
|
can_export=False,
|
|
hidden_column_ids=[],
|
|
row_rules=[]
|
|
)
|
|
)
|
|
print("Role and Department permissions seeded successfully!")
|
|
|
|
print("Seeding completed successfully!")
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
seed_database()
|