Initial commit: Role-based data visualisation platform for DMH hospital admissions (Phases 1-3)
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
# Environment Configuration Example
|
||||
PROJECT_NAME="DMH Role-Based Data Visualisation Platform"
|
||||
ENV=development
|
||||
DEBUG=True
|
||||
|
||||
# Database Configuration
|
||||
# For production PostgreSQL: postgresql://postgres:postgres@localhost:5432/dmh_visualisation
|
||||
# Default fallback for development/testing: sqlite:///./dmh_platform.db
|
||||
DATABASE_URL=sqlite:///./dmh_platform.db
|
||||
|
||||
# JWT & Security
|
||||
SECRET_KEY=change-this-in-production-to-a-super-secret-random-key-dmh-2025
|
||||
ALGORITHM=HS256
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=480
|
||||
|
||||
# CORS
|
||||
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173,http://127.0.0.1:5173
|
||||
|
||||
# Initial Super Admin (automatically seeded on first boot)
|
||||
FIRST_SUPER_ADMIN_EMAIL=admin@dmh.org
|
||||
FIRST_SUPER_ADMIN_USERNAME=admin
|
||||
FIRST_SUPER_ADMIN_PASSWORD=Admin@123456
|
||||
@@ -0,0 +1,19 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
libpq-dev \
|
||||
curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["sh", "-c", "python scripts/seed.py && uvicorn app.main:app --host 0.0.0.0 --port 8000"]
|
||||
@@ -0,0 +1,117 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
# Use forward slashes (/) also on windows to provide an os agnostic path
|
||||
script_location = alembic
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the python>=3.9 or backports.zoneinfo library.
|
||||
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
|
||||
# string value is passed to ZoneInfo()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to alembic/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
|
||||
|
||||
# version path separator; As mentioned above, this is the character used to split
|
||||
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||
# Valid values for version_path_separator are:
|
||||
#
|
||||
# version_path_separator = :
|
||||
# version_path_separator = ;
|
||||
# version_path_separator = space
|
||||
# version_path_separator = newline
|
||||
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in each "version_locations" directory
|
||||
# new in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
sqlalchemy.url = driver://user:pass@localhost/dbname
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = %(here)s/.venv/bin/ruff
|
||||
# ruff.options = --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
@@ -0,0 +1,96 @@
|
||||
import os
|
||||
import sys
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
# Append app path to sys.path
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
||||
|
||||
from app.config import settings
|
||||
from app.database import Base
|
||||
import app.models # load models
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# Set database url from application settings
|
||||
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def include_object(object, name, type_, reflected, compare_to):
|
||||
"""Exclude dynamic dataset tables (prefixed with 'ds_') from migrations."""
|
||||
if type_ == "table" and name.startswith("ds_"):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
include_object=include_object,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
include_object=include_object,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Initial schema: users, datasets, dataset_columns
|
||||
|
||||
Revision ID: 1f35b45a7c20
|
||||
Revises:
|
||||
Create Date: 2026-11-24 15:58:54.746778
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '1f35b45a7c20'
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
'users',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.String(length=50), nullable=False),
|
||||
sa.Column('email', sa.String(length=100), nullable=False),
|
||||
sa.Column('hashed_password', sa.String(length=255), nullable=False),
|
||||
sa.Column('full_name', sa.String(length=100), nullable=True),
|
||||
sa.Column('role', sa.String(length=30), nullable=False),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
|
||||
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
|
||||
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
|
||||
|
||||
op.create_table(
|
||||
'datasets',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=100), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('source_type', sa.String(length=30), nullable=False),
|
||||
sa.Column('table_name', sa.String(length=100), nullable=False),
|
||||
sa.Column('row_count', sa.Integer(), nullable=False),
|
||||
sa.Column('column_count', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('table_name')
|
||||
)
|
||||
op.create_index(op.f('ix_datasets_id'), 'datasets', ['id'], unique=False)
|
||||
|
||||
op.create_table(
|
||||
'dataset_columns',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('dataset_id', sa.Integer(), nullable=False),
|
||||
sa.Column('column_name', sa.String(length=100), nullable=False),
|
||||
sa.Column('display_name', sa.String(length=100), nullable=False),
|
||||
sa.Column('data_type', sa.String(length=30), nullable=False),
|
||||
sa.Column('is_sensitive', sa.Boolean(), nullable=False),
|
||||
sa.Column('is_identifier', sa.Boolean(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['dataset_id'], ['datasets.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_dataset_columns_dataset_id'), 'dataset_columns', ['dataset_id'], unique=False)
|
||||
op.create_index(op.f('ix_dataset_columns_id'), 'dataset_columns', ['id'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index(op.f('ix_dataset_columns_id'), table_name='dataset_columns')
|
||||
op.drop_index(op.f('ix_dataset_columns_dataset_id'), table_name='dataset_columns')
|
||||
op.drop_table('dataset_columns')
|
||||
op.drop_index(op.f('ix_datasets_id'), table_name='datasets')
|
||||
op.drop_table('datasets')
|
||||
op.drop_index(op.f('ix_users_username'), table_name='users')
|
||||
op.drop_index(op.f('ix_users_id'), table_name='users')
|
||||
op.drop_index(op.f('ix_users_email'), table_name='users')
|
||||
op.drop_table('users')
|
||||
@@ -0,0 +1,48 @@
|
||||
from typing import Generator, Optional
|
||||
from fastapi import Depends, Header
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import SessionLocal, get_db
|
||||
from app.models.user import User, UserRole
|
||||
from app.core.security import decode_access_token
|
||||
from app.core.exceptions import AuthException, ForbiddenException
|
||||
|
||||
|
||||
def get_current_user(
|
||||
authorization: Optional[str] = Header(None),
|
||||
db: Session = Depends(get_db)
|
||||
) -> User:
|
||||
"""Extracts and verifies JWT bearer token from Authorization header."""
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise AuthException("Missing or malformed Authorization header")
|
||||
|
||||
token = authorization.split("Bearer ")[1].strip()
|
||||
payload = decode_access_token(token)
|
||||
if not payload:
|
||||
raise AuthException("Token is invalid or expired")
|
||||
|
||||
user_id_str = payload.get("sub")
|
||||
if not user_id_str:
|
||||
raise AuthException("Token payload missing subject identifier")
|
||||
|
||||
try:
|
||||
user_id = int(user_id_str)
|
||||
except ValueError:
|
||||
raise AuthException("Invalid user identifier in token")
|
||||
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise AuthException("User associated with token does not exist")
|
||||
|
||||
if not user.is_active:
|
||||
raise ForbiddenException("User account is deactivated")
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def require_super_admin(
|
||||
current_user: User = Depends(get_current_user)
|
||||
) -> User:
|
||||
"""Ensures that the authenticated user possesses the super_admin role."""
|
||||
if current_user.role != UserRole.SUPER_ADMIN.value:
|
||||
raise ForbiddenException("Super admin privileges required")
|
||||
return current_user
|
||||
@@ -0,0 +1,14 @@
|
||||
from fastapi import APIRouter
|
||||
from app.api.v1.auth import router as auth_router
|
||||
from app.api.v1.users import router as users_router
|
||||
from app.api.v1.datasets import router as datasets_router
|
||||
from app.api.v1.permissions import router as permissions_router
|
||||
from app.api.v1.charts import router as charts_router
|
||||
|
||||
router = APIRouter(prefix="/v1")
|
||||
|
||||
router.include_router(auth_router)
|
||||
router.include_router(users_router)
|
||||
router.include_router(datasets_router)
|
||||
router.include_router(permissions_router)
|
||||
router.include_router(charts_router)
|
||||
@@ -0,0 +1,27 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models.user import User
|
||||
from app.schemas.auth import LoginRequest, TokenResponse, UserSummary
|
||||
from app.services.auth_service import login_user
|
||||
from app.api.deps import get_current_user
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Authentication"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
def login(request: LoginRequest, db: Session = Depends(get_db)):
|
||||
"""Logs in with username or email and returns a signed JWT access token."""
|
||||
return login_user(db, request.username_or_email, request.password)
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserSummary)
|
||||
def get_me(current_user: User = Depends(get_current_user)):
|
||||
"""Retrieves profile and role details of the current authenticated user."""
|
||||
return current_user
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(current_user: User = Depends(get_current_user)):
|
||||
"""Client logout acknowledgment endpoint."""
|
||||
return {"message": "Successfully logged out"}
|
||||
@@ -0,0 +1,167 @@
|
||||
from typing import List, Optional, Dict
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import Table, MetaData, select, func, and_
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models.user import User
|
||||
from app.models.dataset import Dataset
|
||||
from app.schemas.chart import (
|
||||
ChartSpec, ChartResult, DashboardWidget, FilterOptionsResponse, FilterOptionItem
|
||||
)
|
||||
from app.services import chart_service
|
||||
from app.services.permission_service import get_effective_permissions
|
||||
from app.api.deps import get_current_user
|
||||
|
||||
router = APIRouter(prefix="/charts", tags=["Charts & Visualisations"])
|
||||
|
||||
|
||||
@router.post("/query", response_model=ChartResult)
|
||||
def query_chart_data(
|
||||
spec: ChartSpec,
|
||||
preview_user_id: Optional[int] = Query(None),
|
||||
preview_role: Optional[str] = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""
|
||||
Executes a secure aggregated chart query.
|
||||
Enforces dataset grants, column masking, and row-level filter rules on the backend.
|
||||
"""
|
||||
return chart_service.execute_chart_query(
|
||||
db=db,
|
||||
user=current_user,
|
||||
spec=spec,
|
||||
preview_user_id=preview_user_id,
|
||||
preview_role=preview_role
|
||||
)
|
||||
|
||||
|
||||
@router.get("/filter-options/{dataset_id}", response_model=FilterOptionsResponse)
|
||||
def get_filter_options(
|
||||
dataset_id: int,
|
||||
preview_user_id: Optional[int] = Query(None),
|
||||
preview_role: Optional[str] = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""
|
||||
Returns distinct filter options (BuildingName, Speciality, AdmissionType, etc.)
|
||||
filtered according to the user's active permissions.
|
||||
"""
|
||||
eff = get_effective_permissions(db, current_user, dataset_id, preview_user_id, preview_role)
|
||||
dataset = db.query(Dataset).filter(Dataset.id == dataset_id).first()
|
||||
if not dataset or not eff.can_view:
|
||||
return FilterOptionsResponse(options={})
|
||||
|
||||
bind = db.get_bind()
|
||||
table = Table(dataset.table_name, MetaData(), autoload_with=bind)
|
||||
target_cols = ["BuildingName", "AdmittingDoctorSpecialityName", "AdmissionType", "Gender", "PatientCategoryName"]
|
||||
allowed = [c for c in target_cols if c in eff.allowed_columns and c in table.c]
|
||||
|
||||
result: Dict[str, List[FilterOptionItem]] = {}
|
||||
for col_name in allowed:
|
||||
q = select(table.c[col_name], func.count().label("cnt")).group_by(table.c[col_name])
|
||||
# Apply row rules if any
|
||||
conditions = []
|
||||
for rule in eff.row_rules:
|
||||
if rule.column_name in table.c:
|
||||
conditions.append(chart_service.build_filter_clause(
|
||||
table,
|
||||
chart_service.ChartFilter(column=rule.column_name, operator=rule.operator, value=rule.rule_value)
|
||||
))
|
||||
if conditions:
|
||||
q = q.where(and_(*conditions))
|
||||
|
||||
q = q.order_by(func.count().desc()).limit(20)
|
||||
rows = db.execute(q).fetchall()
|
||||
items = []
|
||||
for val, count in rows:
|
||||
if val is not None and str(val).strip():
|
||||
items.append(FilterOptionItem(value=str(val), label=str(val), count=count))
|
||||
result[col_name] = items
|
||||
|
||||
return FilterOptionsResponse(options=result)
|
||||
|
||||
|
||||
@router.get("/dashboards/default/{dataset_id}", response_model=List[DashboardWidget])
|
||||
def get_default_dashboard_widgets(dataset_id: int):
|
||||
"""Returns the hospital admission core dashboard specification."""
|
||||
return [
|
||||
DashboardWidget(
|
||||
id="kpi-total-admissions",
|
||||
title="Total Admissions",
|
||||
description="Overall patient intake count",
|
||||
width="third",
|
||||
chart_spec=ChartSpec(
|
||||
dataset_id=dataset_id,
|
||||
chart_type="kpi",
|
||||
dimension="srNo",
|
||||
aggregation="count"
|
||||
)
|
||||
),
|
||||
DashboardWidget(
|
||||
id="chart-speciality-admissions",
|
||||
title="Admissions by Medical Speciality",
|
||||
description="Top clinical departments admitting patients",
|
||||
width="half",
|
||||
chart_spec=ChartSpec(
|
||||
dataset_id=dataset_id,
|
||||
chart_type="bar",
|
||||
dimension="AdmittingDoctorSpecialityName",
|
||||
aggregation="count",
|
||||
limit=10,
|
||||
order="desc"
|
||||
)
|
||||
),
|
||||
DashboardWidget(
|
||||
id="chart-building-admissions",
|
||||
title="Admissions by Hospital Building",
|
||||
description="Distribution between DMHRC, DMHSS, etc.",
|
||||
width="half",
|
||||
chart_spec=ChartSpec(
|
||||
dataset_id=dataset_id,
|
||||
chart_type="donut",
|
||||
dimension="BuildingName",
|
||||
aggregation="count"
|
||||
)
|
||||
),
|
||||
DashboardWidget(
|
||||
id="chart-monthly-trend",
|
||||
title="Admissions Trend (Monthly)",
|
||||
description="Seasonal inpatient admission volumes",
|
||||
width="half",
|
||||
chart_spec=ChartSpec(
|
||||
dataset_id=dataset_id,
|
||||
chart_type="area",
|
||||
dimension="AdmissionDate",
|
||||
time_bucket="month",
|
||||
aggregation="count",
|
||||
order="asc"
|
||||
)
|
||||
),
|
||||
DashboardWidget(
|
||||
id="chart-admission-type",
|
||||
title="Admission Categories",
|
||||
description="Emergency vs. Walk-in breakdown",
|
||||
width="half",
|
||||
chart_spec=ChartSpec(
|
||||
dataset_id=dataset_id,
|
||||
chart_type="pie",
|
||||
dimension="AdmissionType",
|
||||
aggregation="count"
|
||||
)
|
||||
),
|
||||
DashboardWidget(
|
||||
id="chart-demographics-gender-category",
|
||||
title="Patient Demographics: Gender & Category",
|
||||
description="GNL vs TPA insurance by gender",
|
||||
width="full",
|
||||
chart_spec=ChartSpec(
|
||||
dataset_id=dataset_id,
|
||||
chart_type="stacked_bar",
|
||||
dimension="PatientCategoryName",
|
||||
secondary_dimension="Gender",
|
||||
aggregation="count"
|
||||
)
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,72 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, UploadFile, File, Form, status
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models.user import User
|
||||
from app.schemas.dataset import (
|
||||
DatasetResponse, DatasetUploadResponse, ColumnResponse, ColumnUpdate
|
||||
)
|
||||
from app.services import ingestion_service
|
||||
from app.api.deps import require_super_admin, get_current_user
|
||||
|
||||
router = APIRouter(prefix="/datasets", tags=["Datasets & Ingestion"])
|
||||
|
||||
|
||||
@router.post("/upload", response_model=DatasetUploadResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def upload_dataset_csv(
|
||||
file: UploadFile = File(...),
|
||||
name: str = Form(...),
|
||||
description: str = Form(""),
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_super_admin)
|
||||
):
|
||||
"""Uploads and ingests a CSV dataset, building a typed schema table. Super Admin only."""
|
||||
content = await file.read()
|
||||
dataset = ingestion_service.register_dataset_from_csv(
|
||||
db=db,
|
||||
file_content=content,
|
||||
dataset_name=name,
|
||||
description=description
|
||||
)
|
||||
return DatasetUploadResponse(
|
||||
message=f"Dataset '{dataset.name}' registered successfully with {dataset.row_count} rows.",
|
||||
dataset=dataset
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=List[DatasetResponse])
|
||||
def list_datasets(
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user)
|
||||
):
|
||||
"""Lists all available registered datasets."""
|
||||
return ingestion_service.get_all_datasets(db)
|
||||
|
||||
|
||||
@router.get("/{dataset_id}", response_model=DatasetResponse)
|
||||
def get_dataset(
|
||||
dataset_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user)
|
||||
):
|
||||
"""Gets dataset details including columns and types."""
|
||||
return ingestion_service.get_dataset_by_id(db, dataset_id)
|
||||
|
||||
|
||||
@router.patch("/{dataset_id}/columns/{column_id}", response_model=ColumnResponse)
|
||||
def update_column(
|
||||
dataset_id: int,
|
||||
column_id: int,
|
||||
column_in: ColumnUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_super_admin)
|
||||
):
|
||||
"""Updates column display name, sensitivity, and identifier flags. Super Admin only."""
|
||||
return ingestion_service.update_column_metadata(
|
||||
db=db,
|
||||
dataset_id=dataset_id,
|
||||
column_id=column_id,
|
||||
display_name=column_in.display_name,
|
||||
is_sensitive=column_in.is_sensitive,
|
||||
is_identifier=column_in.is_identifier
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Depends, Query, status
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models.user import User
|
||||
from app.models.permission import DatasetPermission
|
||||
from app.schemas.permission import (
|
||||
DatasetPermissionCreate, DatasetPermissionResponse, EffectivePermissions
|
||||
)
|
||||
from app.services import permission_service
|
||||
from app.api.deps import require_super_admin, get_current_user
|
||||
|
||||
router = APIRouter(prefix="/permissions", tags=["Access Control & Permissions"])
|
||||
|
||||
|
||||
@router.post("", response_model=DatasetPermissionResponse, status_code=status.HTTP_200_OK)
|
||||
def set_dataset_permission(
|
||||
perm_in: DatasetPermissionCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_super_admin)
|
||||
):
|
||||
"""Sets dataset, column, and row-level rules for a user or role. Super Admin only."""
|
||||
return permission_service.save_dataset_permission(db, perm_in)
|
||||
|
||||
|
||||
@router.get("/users/{user_id}", response_model=List[DatasetPermissionResponse])
|
||||
def get_user_permissions(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_super_admin)
|
||||
):
|
||||
"""Retrieves all permissions configured for a specific user. Super Admin only."""
|
||||
return db.query(DatasetPermission).filter(DatasetPermission.user_id == user_id).all()
|
||||
|
||||
|
||||
@router.get("/roles/{role}", response_model=List[DatasetPermissionResponse])
|
||||
def get_role_permissions(
|
||||
role: str,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_super_admin)
|
||||
):
|
||||
"""Retrieves all permissions configured for a specific role. Super Admin only."""
|
||||
return db.query(DatasetPermission).filter(DatasetPermission.role == role).all()
|
||||
|
||||
|
||||
@router.get("/effective/{dataset_id}", response_model=EffectivePermissions)
|
||||
def get_effective_user_permissions(
|
||||
dataset_id: int,
|
||||
preview_user_id: Optional[int] = Query(None),
|
||||
preview_role: Optional[str] = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Computes the effective (intersected) allowed columns and row rules for current user."""
|
||||
return permission_service.get_effective_permissions(
|
||||
db=db,
|
||||
user=current_user,
|
||||
dataset_id=dataset_id,
|
||||
preview_user_id=preview_user_id,
|
||||
preview_role=preview_role
|
||||
)
|
||||
@@ -0,0 +1,90 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models.user import User, UserRole
|
||||
from app.schemas.user import UserCreate, UserUpdate, UserResponse, RoleResponse
|
||||
from app.services import user_service
|
||||
from app.api.deps import require_super_admin, get_current_user
|
||||
|
||||
router = APIRouter(tags=["User Management"])
|
||||
|
||||
|
||||
@router.get("/roles", response_model=List[RoleResponse])
|
||||
def list_roles(_: User = Depends(get_current_user)):
|
||||
"""Returns available role descriptions in the platform."""
|
||||
return [
|
||||
RoleResponse(
|
||||
role=UserRole.SUPER_ADMIN.value,
|
||||
label="Super Admin",
|
||||
description="Full control over data connections, permissions, users, and dashboards"
|
||||
),
|
||||
RoleResponse(
|
||||
role=UserRole.VIEWER.value,
|
||||
label="Viewer (Standard User)",
|
||||
description="Accesses only explicitly granted datasets, dashboards, and charts"
|
||||
),
|
||||
RoleResponse(
|
||||
role=UserRole.DEPARTMENT_MANAGER.value,
|
||||
label="Department Manager",
|
||||
description="Manages and views department-scoped clinical and operational data"
|
||||
),
|
||||
RoleResponse(
|
||||
role=UserRole.FINANCE.value,
|
||||
label="Finance User",
|
||||
description="Analyzes payer mix, corporate claims, and insurance policies"
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@router.get("/users", response_model=List[UserResponse])
|
||||
def get_users(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_super_admin)
|
||||
):
|
||||
"""Lists all users. Restricted to Super Admin."""
|
||||
return user_service.get_users(db, skip=skip, limit=limit)
|
||||
|
||||
|
||||
@router.post("/users", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_user(
|
||||
user_in: UserCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_super_admin)
|
||||
):
|
||||
"""Creates a new user. Restricted to Super Admin."""
|
||||
return user_service.create_user(db, user_in)
|
||||
|
||||
|
||||
@router.get("/users/{user_id}", response_model=UserResponse)
|
||||
def get_user_by_id(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_super_admin)
|
||||
):
|
||||
"""Gets user details by ID. Restricted to Super Admin."""
|
||||
return user_service.get_user_by_id(db, user_id)
|
||||
|
||||
|
||||
@router.put("/users/{user_id}", response_model=UserResponse)
|
||||
def update_user(
|
||||
user_id: int,
|
||||
user_in: UserUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_super_admin)
|
||||
):
|
||||
"""Updates user information, roles, or status. Restricted to Super Admin."""
|
||||
return user_service.update_user(db, user_id, user_in)
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_super_admin)
|
||||
):
|
||||
"""Deletes a user account. Restricted to Super Admin."""
|
||||
user_service.delete_user(db, user_id)
|
||||
return None
|
||||
@@ -0,0 +1,37 @@
|
||||
import os
|
||||
from typing import List
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
PROJECT_NAME: str = "DMH Role-Based Data Visualisation Platform"
|
||||
ENV: str = "development"
|
||||
DEBUG: bool = True
|
||||
|
||||
# Database
|
||||
DATABASE_URL: str = "sqlite:///./dmh_platform.db"
|
||||
|
||||
# Security
|
||||
SECRET_KEY: str = "dmh-data-vis-secret-key-super-secure-2025"
|
||||
ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 480 # 8 hours
|
||||
|
||||
# CORS
|
||||
ALLOWED_ORIGINS: str = "http://localhost:3000,http://localhost:5173,http://127.0.0.1:5173"
|
||||
|
||||
# Initial Super Admin
|
||||
FIRST_SUPER_ADMIN_EMAIL: str = "admin@dmh.org"
|
||||
FIRST_SUPER_ADMIN_USERNAME: str = "admin"
|
||||
FIRST_SUPER_ADMIN_PASSWORD: str = "Admin@123456"
|
||||
|
||||
@property
|
||||
def cors_origins(self) -> List[str]:
|
||||
return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",") if origin.strip()]
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
env_file_encoding = "utf-8"
|
||||
extra = "ignore"
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,42 @@
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
|
||||
class AuthException(HTTPException):
|
||||
def __init__(self, detail: str = "Could not validate credentials"):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=detail,
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
|
||||
class ForbiddenException(HTTPException):
|
||||
def __init__(self, detail: str = "Access forbidden: insufficient permissions"):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=detail
|
||||
)
|
||||
|
||||
|
||||
class NotFoundException(HTTPException):
|
||||
def __init__(self, detail: str = "Resource not found"):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=detail
|
||||
)
|
||||
|
||||
|
||||
class ConflictException(HTTPException):
|
||||
def __init__(self, detail: str = "Resource already exists"):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=detail
|
||||
)
|
||||
|
||||
|
||||
class ValidationException(HTTPException):
|
||||
def __init__(self, detail: str = "Invalid query or parameters"):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=detail
|
||||
)
|
||||
@@ -0,0 +1,43 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, Optional
|
||||
import jwt
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, InvalidHashError
|
||||
from app.config import settings
|
||||
|
||||
ph = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Hashes a plain password using argon2-cffi."""
|
||||
return ph.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verifies a plain password against an argon2 hash."""
|
||||
try:
|
||||
return ph.verify(hashed_password, plain_password)
|
||||
except (VerifyMismatchError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
|
||||
"""Creates a signed JWT token with PyJWT."""
|
||||
to_encode = data.copy()
|
||||
if expires_delta:
|
||||
expire = datetime.now(timezone.utc) + expires_delta
|
||||
else:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
|
||||
to_encode.update({"exp": expire, "iat": datetime.now(timezone.utc)})
|
||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
"""Decodes and validates a JWT token using PyJWT."""
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
return payload
|
||||
except (jwt.PyJWTError, Exception):
|
||||
return None
|
||||
@@ -0,0 +1,29 @@
|
||||
from sqlalchemy import create_engine, MetaData
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
from app.config import settings
|
||||
|
||||
# Configure SQLite or PostgreSQL connect_args
|
||||
connect_args = {}
|
||||
if settings.DATABASE_URL.startswith("sqlite"):
|
||||
connect_args = {"check_same_thread": False}
|
||||
|
||||
engine = create_engine(
|
||||
settings.DATABASE_URL,
|
||||
connect_args=connect_args,
|
||||
pool_pre_ping=True
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# Shared metadata for SQLAlchemy Core & ORM
|
||||
metadata = MetaData()
|
||||
Base = declarative_base(metadata=metadata)
|
||||
|
||||
|
||||
def get_db():
|
||||
"""Dependency that yields a database session for requests."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,47 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.config import settings
|
||||
from app.database import engine, Base
|
||||
from app.api.v1 import router as api_v1_router
|
||||
# Import all models to ensure they are registered with Base.metadata
|
||||
import app.models
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Create DB schema tables if they do not exist
|
||||
Base.metadata.create_all(bind=engine)
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title=settings.PROJECT_NAME,
|
||||
description="Backend API for Role-Based Hospital Admission Data Visualisation Platform",
|
||||
version="1.0.0",
|
||||
lifespan=lifespan,
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc"
|
||||
)
|
||||
|
||||
# CORS Middleware
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# API routes
|
||||
app.include_router(api_v1_router, prefix="/api")
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health_check():
|
||||
"""Service health check endpoint."""
|
||||
return {
|
||||
"status": "healthy",
|
||||
"service": settings.PROJECT_NAME,
|
||||
"environment": settings.ENV
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
from app.models.user import User, UserRole
|
||||
from app.models.dataset import Dataset, DatasetColumn
|
||||
from app.models.permission import DatasetPermission, ColumnPermission, RowRule
|
||||
|
||||
__all__ = [
|
||||
"User", "UserRole", "Dataset", "DatasetColumn",
|
||||
"DatasetPermission", "ColumnPermission", "RowRule"
|
||||
]
|
||||
@@ -0,0 +1,35 @@
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class Dataset(Base):
|
||||
__tablename__ = "datasets"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
source_type = Column(String(30), default="file", nullable=False) # 'file' or 'database'
|
||||
table_name = Column(String(100), unique=True, nullable=False)
|
||||
row_count = Column(Integer, default=0, nullable=False)
|
||||
column_count = Column(Integer, default=0, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
|
||||
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)
|
||||
|
||||
columns = relationship("DatasetColumn", back_populates="dataset", cascade="all, delete-orphan", order_by="DatasetColumn.id")
|
||||
|
||||
|
||||
class DatasetColumn(Base):
|
||||
__tablename__ = "dataset_columns"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
dataset_id = Column(Integer, ForeignKey("datasets.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
column_name = Column(String(100), nullable=False)
|
||||
display_name = Column(String(100), nullable=False)
|
||||
data_type = Column(String(30), nullable=False) # 'string', 'integer', 'float', 'datetime', 'boolean'
|
||||
is_sensitive = Column(Boolean, default=False, nullable=False)
|
||||
is_identifier = Column(Boolean, default=False, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
|
||||
|
||||
dataset = relationship("Dataset", back_populates="columns")
|
||||
@@ -0,0 +1,46 @@
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class DatasetPermission(Base):
|
||||
__tablename__ = "dataset_permissions"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=True, index=True)
|
||||
role = Column(String(30), nullable=True, index=True) # e.g. 'viewer', 'department_manager', 'finance'
|
||||
dataset_id = Column(Integer, ForeignKey("datasets.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
can_view = Column(Boolean, default=True, nullable=False)
|
||||
can_export = Column(Boolean, default=False, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
|
||||
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)
|
||||
|
||||
user = relationship("User")
|
||||
dataset = relationship("Dataset")
|
||||
column_permissions = relationship("ColumnPermission", back_populates="dataset_permission", cascade="all, delete-orphan")
|
||||
row_rules = relationship("RowRule", back_populates="dataset_permission", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class ColumnPermission(Base):
|
||||
__tablename__ = "column_permissions"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
dataset_permission_id = Column(Integer, ForeignKey("dataset_permissions.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
column_id = Column(Integer, ForeignKey("dataset_columns.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
is_hidden = Column(Boolean, default=False, nullable=False)
|
||||
|
||||
dataset_permission = relationship("DatasetPermission", back_populates="column_permissions")
|
||||
column = relationship("DatasetColumn")
|
||||
|
||||
|
||||
class RowRule(Base):
|
||||
__tablename__ = "row_rules"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
dataset_permission_id = Column(Integer, ForeignKey("dataset_permissions.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
column_name = Column(String(100), nullable=False)
|
||||
operator = Column(String(20), default="eq", nullable=False) # 'eq', 'ne', 'in', 'gt', 'lt', 'gte', 'lte'
|
||||
rule_value = Column(Text, nullable=False) # e.g. "DMHRC" or comma-separated / JSON values
|
||||
|
||||
dataset_permission = relationship("DatasetPermission", back_populates="row_rules")
|
||||
@@ -0,0 +1,28 @@
|
||||
import enum
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Enum
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class UserRole(str, enum.Enum):
|
||||
SUPER_ADMIN = "super_admin"
|
||||
VIEWER = "viewer"
|
||||
DEPARTMENT_MANAGER = "department_manager"
|
||||
FINANCE = "finance"
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
username = Column(String(50), unique=True, index=True, nullable=False)
|
||||
email = Column(String(100), unique=True, index=True, nullable=False)
|
||||
hashed_password = Column(String(255), nullable=False)
|
||||
full_name = Column(String(100), nullable=True)
|
||||
role = Column(String(30), default=UserRole.VIEWER.value, nullable=False)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
|
||||
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)
|
||||
|
||||
def is_super_admin(self) -> bool:
|
||||
return self.role == UserRole.SUPER_ADMIN.value
|
||||
@@ -0,0 +1,9 @@
|
||||
from app.schemas.auth import LoginRequest, TokenResponse, UserSummary, TokenData
|
||||
from app.schemas.user import UserCreate, UserUpdate, UserResponse, RoleResponse
|
||||
from app.schemas.dataset import ColumnResponse, ColumnUpdate, DatasetResponse, DatasetUploadResponse
|
||||
|
||||
__all__ = [
|
||||
"LoginRequest", "TokenResponse", "UserSummary", "TokenData",
|
||||
"UserCreate", "UserUpdate", "UserResponse", "RoleResponse",
|
||||
"ColumnResponse", "ColumnUpdate", "DatasetResponse", "DatasetUploadResponse"
|
||||
]
|
||||
@@ -0,0 +1,32 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username_or_email: str
|
||||
password: str
|
||||
|
||||
|
||||
class UserSummary(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
email: str
|
||||
full_name: Optional[str] = None
|
||||
role: str
|
||||
is_active: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_in: int
|
||||
user: UserSummary
|
||||
|
||||
|
||||
class TokenData(BaseModel):
|
||||
sub: str # user id as str
|
||||
username: str
|
||||
role: str
|
||||
@@ -0,0 +1,51 @@
|
||||
from typing import List, Optional, Any, Dict, Union
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ChartFilter(BaseModel):
|
||||
column: str
|
||||
operator: str = "eq" # 'eq', 'ne', 'in', 'gt', 'lt', 'gte', 'lte', 'between'
|
||||
value: Union[str, int, float, List[Union[str, int, float]]]
|
||||
|
||||
|
||||
class ChartSpec(BaseModel):
|
||||
dataset_id: int
|
||||
chart_type: str = "bar" # 'bar', 'stacked_bar', 'line', 'area', 'pie', 'donut', 'heatmap', 'kpi', 'table'
|
||||
dimension: Optional[str] = None
|
||||
measure: Optional[str] = "*"
|
||||
aggregation: str = "count" # 'count', 'sum', 'avg', 'min', 'max'
|
||||
secondary_dimension: Optional[str] = None
|
||||
filters: List[ChartFilter] = Field(default_factory=list)
|
||||
time_bucket: Optional[str] = None # 'day', 'month', 'year'
|
||||
limit: Optional[int] = 50
|
||||
order: Optional[str] = "desc" # 'asc', 'desc'
|
||||
|
||||
|
||||
class ChartResult(BaseModel):
|
||||
chart_type: str
|
||||
title: Optional[str] = None
|
||||
categories: List[str] = Field(default_factory=list)
|
||||
series: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
data: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
kpi_value: Optional[Union[int, float, str]] = None
|
||||
kpi_subtext: Optional[str] = None
|
||||
total_records: int = 0
|
||||
applied_rules_count: int = 0
|
||||
|
||||
|
||||
class FilterOptionItem(BaseModel):
|
||||
value: str
|
||||
label: str
|
||||
count: Optional[int] = None
|
||||
|
||||
|
||||
class FilterOptionsResponse(BaseModel):
|
||||
options: Dict[str, List[FilterOptionItem]]
|
||||
|
||||
|
||||
class DashboardWidget(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
description: Optional[str] = None
|
||||
width: str = "half" # 'full', 'half', 'third'
|
||||
chart_spec: ChartSpec
|
||||
@@ -0,0 +1,44 @@
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ColumnResponse(BaseModel):
|
||||
id: int
|
||||
dataset_id: int
|
||||
column_name: str
|
||||
display_name: str
|
||||
data_type: str
|
||||
is_sensitive: bool
|
||||
is_identifier: bool
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class ColumnUpdate(BaseModel):
|
||||
display_name: Optional[str] = None
|
||||
is_sensitive: Optional[bool] = None
|
||||
is_identifier: Optional[bool] = None
|
||||
|
||||
|
||||
class DatasetResponse(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
source_type: str
|
||||
table_name: str
|
||||
row_count: int
|
||||
column_count: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
columns: Optional[List[ColumnResponse]] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class DatasetUploadResponse(BaseModel):
|
||||
message: str
|
||||
dataset: DatasetResponse
|
||||
@@ -0,0 +1,68 @@
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class RowRuleCreate(BaseModel):
|
||||
column_name: str
|
||||
operator: str = "eq" # 'eq', 'ne', 'in', 'gt', 'lt', 'gte', 'lte'
|
||||
rule_value: str
|
||||
|
||||
|
||||
class RowRuleResponse(BaseModel):
|
||||
id: int
|
||||
column_name: str
|
||||
operator: str
|
||||
rule_value: str
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class ColumnPermissionItem(BaseModel):
|
||||
column_id: int
|
||||
is_hidden: bool = False
|
||||
|
||||
|
||||
class ColumnPermissionResponse(BaseModel):
|
||||
id: int
|
||||
column_id: int
|
||||
is_hidden: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class DatasetPermissionCreate(BaseModel):
|
||||
dataset_id: int
|
||||
user_id: Optional[int] = None
|
||||
role: Optional[str] = None
|
||||
can_view: bool = True
|
||||
can_export: bool = False
|
||||
hidden_column_ids: List[int] = Field(default_factory=list)
|
||||
row_rules: List[RowRuleCreate] = Field(default_factory=list)
|
||||
|
||||
|
||||
class DatasetPermissionResponse(BaseModel):
|
||||
id: int
|
||||
dataset_id: int
|
||||
user_id: Optional[int] = None
|
||||
role: Optional[str] = None
|
||||
can_view: bool
|
||||
can_export: bool
|
||||
column_permissions: List[ColumnPermissionResponse] = Field(default_factory=list)
|
||||
row_rules: List[RowRuleResponse] = Field(default_factory=list)
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class EffectivePermissions(BaseModel):
|
||||
dataset_id: int
|
||||
can_view: bool
|
||||
can_export: bool
|
||||
allowed_columns: List[str]
|
||||
hidden_columns: List[str]
|
||||
row_rules: List[RowRuleResponse]
|
||||
@@ -0,0 +1,40 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
|
||||
|
||||
class UserCreate(BaseModel):
|
||||
username: str = Field(..., min_length=3, max_length=50)
|
||||
email: EmailStr
|
||||
password: str = Field(..., min_length=6)
|
||||
full_name: Optional[str] = None
|
||||
role: str = "viewer"
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
email: Optional[EmailStr] = None
|
||||
password: Optional[str] = Field(None, min_length=6)
|
||||
full_name: Optional[str] = None
|
||||
role: Optional[str] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
email: str
|
||||
full_name: Optional[str] = None
|
||||
role: str
|
||||
is_active: bool
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class RoleResponse(BaseModel):
|
||||
role: str
|
||||
label: str
|
||||
description: str
|
||||
@@ -0,0 +1,45 @@
|
||||
from typing import Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.user import User
|
||||
from app.core.security import verify_password, create_access_token
|
||||
from app.core.exceptions import AuthException, ForbiddenException
|
||||
from app.schemas.auth import TokenResponse, UserSummary
|
||||
from app.config import settings
|
||||
|
||||
|
||||
def authenticate_user(db: Session, username_or_email: str, password: str) -> Optional[User]:
|
||||
"""Finds user by username or email and verifies argon2 password hash."""
|
||||
user = db.query(User).filter(
|
||||
(User.username == username_or_email) | (User.email == username_or_email)
|
||||
).first()
|
||||
|
||||
if not user:
|
||||
return None
|
||||
if not verify_password(password, user.hashed_password):
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def login_user(db: Session, username_or_email: str, password: str) -> TokenResponse:
|
||||
"""Authenticates credentials and generates signed JWT token."""
|
||||
user = authenticate_user(db, username_or_email, password)
|
||||
if not user:
|
||||
raise AuthException("Incorrect username or password")
|
||||
|
||||
if not user.is_active:
|
||||
raise ForbiddenException("User account is inactive. Please contact your administrator.")
|
||||
|
||||
token = create_access_token(
|
||||
data={
|
||||
"sub": str(user.id),
|
||||
"username": user.username,
|
||||
"role": user.role,
|
||||
}
|
||||
)
|
||||
|
||||
return TokenResponse(
|
||||
access_token=token,
|
||||
token_type="Bearer",
|
||||
expires_in=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
|
||||
user=UserSummary.model_validate(user)
|
||||
)
|
||||
@@ -0,0 +1,255 @@
|
||||
from datetime import datetime
|
||||
from typing import List, Dict, Any, Optional
|
||||
from sqlalchemy import (
|
||||
Table, MetaData, select, func, and_, or_, text, Column
|
||||
)
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.user import User
|
||||
from app.models.dataset import Dataset, DatasetColumn
|
||||
from app.schemas.chart import ChartSpec, ChartResult, ChartFilter
|
||||
from app.services.permission_service import get_effective_permissions
|
||||
from app.core.exceptions import NotFoundException, ForbiddenException, ValidationException
|
||||
|
||||
|
||||
def get_column_expression(table: Table, col_name: str, time_bucket: Optional[str] = None, dialect_name: str = "sqlite") -> Any:
|
||||
"""Returns a safe SQLAlchemy Core column expression with optional time bucketing."""
|
||||
if col_name not in table.c:
|
||||
raise ValidationException(f"Column '{col_name}' does not exist on table")
|
||||
|
||||
col = table.c[col_name]
|
||||
if time_bucket:
|
||||
if dialect_name == "postgresql":
|
||||
if time_bucket == "month":
|
||||
return func.to_char(col, "YYYY-MM").label("time_bucket")
|
||||
elif time_bucket == "day":
|
||||
return func.to_char(col, "YYYY-MM-DD").label("time_bucket")
|
||||
elif time_bucket == "year":
|
||||
return func.to_char(col, "YYYY").label("time_bucket")
|
||||
else:
|
||||
# SQLite fallback
|
||||
if time_bucket == "month":
|
||||
return func.strftime("%Y-%m", col).label("time_bucket")
|
||||
elif time_bucket == "day":
|
||||
return func.strftime("%Y-%m-%d", col).label("time_bucket")
|
||||
elif time_bucket == "year":
|
||||
return func.strftime("%Y", col).label("time_bucket")
|
||||
|
||||
return col
|
||||
|
||||
|
||||
def build_filter_clause(table: Table, filt: ChartFilter) -> Any:
|
||||
"""Builds a parameterized filter condition using SQLAlchemy Core whitelisted columns."""
|
||||
if filt.column not in table.c:
|
||||
raise ValidationException(f"Filter column '{filt.column}' is not a valid dataset column")
|
||||
|
||||
col = table.c[filt.column]
|
||||
op = filt.operator.lower()
|
||||
val = filt.value
|
||||
|
||||
if op == "eq":
|
||||
return col == val
|
||||
elif op == "ne":
|
||||
return col != val
|
||||
elif op == "gt":
|
||||
return col > val
|
||||
elif op == "gte":
|
||||
return col >= val
|
||||
elif op == "lt":
|
||||
return col < val
|
||||
elif op == "lte":
|
||||
return col <= val
|
||||
elif op == "in":
|
||||
if isinstance(val, list):
|
||||
return col.in_(val)
|
||||
else:
|
||||
return col.in_([v.strip() for v in str(val).split(",") if v.strip()])
|
||||
elif op == "between" and isinstance(val, list) and len(val) == 2:
|
||||
return and_(col >= val[0], col <= val[1])
|
||||
else:
|
||||
return col == val
|
||||
|
||||
|
||||
def execute_chart_query(
|
||||
db: Session,
|
||||
user: User,
|
||||
spec: ChartSpec,
|
||||
preview_user_id: Optional[int] = None,
|
||||
preview_role: Optional[str] = None
|
||||
) -> ChartResult:
|
||||
"""
|
||||
Validates permissions, whitelists columns, injects row rules,
|
||||
and executes an aggregated query using SQLAlchemy Core with bound parameters.
|
||||
"""
|
||||
# 1. Dataset verification
|
||||
dataset = db.query(Dataset).filter(Dataset.id == spec.dataset_id).first()
|
||||
if not dataset:
|
||||
raise NotFoundException(f"Dataset with ID {spec.dataset_id} not found")
|
||||
|
||||
# 2. Permission Evaluation
|
||||
eff_perms = get_effective_permissions(
|
||||
db=db,
|
||||
user=user,
|
||||
dataset_id=spec.dataset_id,
|
||||
preview_user_id=preview_user_id,
|
||||
preview_role=preview_role
|
||||
)
|
||||
|
||||
if not eff_perms.can_view:
|
||||
raise ForbiddenException("Access denied: You do not have permission to view this dataset")
|
||||
|
||||
# 3. Whitelist column checks
|
||||
allowed_cols = set(eff_perms.allowed_columns)
|
||||
if spec.dimension and spec.dimension not in allowed_cols:
|
||||
raise ForbiddenException(f"Access to dimension column '{spec.dimension}' is restricted")
|
||||
|
||||
if spec.measure and spec.measure != "*" and spec.measure not in allowed_cols:
|
||||
raise ForbiddenException(f"Access to measure column '{spec.measure}' is restricted")
|
||||
|
||||
if spec.secondary_dimension and spec.secondary_dimension not in allowed_cols:
|
||||
raise ForbiddenException(f"Access to secondary dimension '{spec.secondary_dimension}' is restricted")
|
||||
|
||||
for f in spec.filters:
|
||||
if f.column not in allowed_cols:
|
||||
raise ForbiddenException(f"Filtering on restricted column '{f.column}' is forbidden")
|
||||
|
||||
# 4. Reflect dynamic table
|
||||
bind = db.get_bind()
|
||||
dialect_name = bind.dialect.name
|
||||
meta = MetaData()
|
||||
table = Table(dataset.table_name, meta, autoload_with=bind)
|
||||
|
||||
# 5. Build WHERE conditions (Row rules + User filters)
|
||||
where_conditions = []
|
||||
|
||||
# Inject enforced row rules (AND intersection)
|
||||
for rule in eff_perms.row_rules:
|
||||
if rule.column_name in table.c:
|
||||
rule_filt = ChartFilter(
|
||||
column=rule.column_name,
|
||||
operator=rule.operator,
|
||||
value=rule.rule_value
|
||||
)
|
||||
where_conditions.append(build_filter_clause(table, rule_filt))
|
||||
|
||||
# Inject client filters
|
||||
for f in spec.filters:
|
||||
where_conditions.append(build_filter_clause(table, f))
|
||||
|
||||
where_clause = and_(*where_conditions) if where_conditions else None
|
||||
|
||||
# 6. Aggregation function
|
||||
agg_op = spec.aggregation.lower()
|
||||
if agg_op == "sum" and spec.measure and spec.measure != "*":
|
||||
agg_metric = func.sum(table.c[spec.measure]).label("metric_value")
|
||||
elif agg_op == "avg" and spec.measure and spec.measure != "*":
|
||||
agg_metric = func.avg(table.c[spec.measure]).label("metric_value")
|
||||
elif agg_op == "min" and spec.measure and spec.measure != "*":
|
||||
agg_metric = func.min(table.c[spec.measure]).label("metric_value")
|
||||
elif agg_op == "max" and spec.measure and spec.measure != "*":
|
||||
agg_metric = func.max(table.c[spec.measure]).label("metric_value")
|
||||
else:
|
||||
agg_metric = func.count().label("metric_value")
|
||||
|
||||
# 7. Chart-specific query building
|
||||
if spec.chart_type == "kpi":
|
||||
# Total metric query
|
||||
q = select(agg_metric).select_from(table)
|
||||
if where_clause is not None:
|
||||
q = q.where(where_clause)
|
||||
scalar_val = db.execute(q).scalar() or 0
|
||||
formatted_val = round(float(scalar_val), 1) if isinstance(scalar_val, float) else scalar_val
|
||||
return ChartResult(
|
||||
chart_type="kpi",
|
||||
title=spec.dimension or "Total",
|
||||
kpi_value=formatted_val,
|
||||
kpi_subtext=f"Aggregated {agg_op.upper()} on {dataset.name}",
|
||||
total_records=int(scalar_val) if isinstance(scalar_val, (int, float)) else 0,
|
||||
applied_rules_count=len(eff_perms.row_rules)
|
||||
)
|
||||
|
||||
# Dimensional Query
|
||||
dim_expr = get_column_expression(table, spec.dimension, spec.time_bucket, dialect_name)
|
||||
select_items = [dim_expr.label("dim_label"), agg_metric]
|
||||
group_items = [dim_expr]
|
||||
|
||||
if spec.secondary_dimension:
|
||||
sec_dim = table.c[spec.secondary_dimension].label("sec_dim_label")
|
||||
select_items.append(sec_dim)
|
||||
group_items.append(sec_dim)
|
||||
|
||||
query = select(*select_items).group_by(*group_items)
|
||||
if where_clause is not None:
|
||||
query = query.where(where_clause)
|
||||
|
||||
# Ordering
|
||||
if spec.order == "asc":
|
||||
query = query.order_by(agg_metric.asc())
|
||||
else:
|
||||
query = query.order_by(agg_metric.desc())
|
||||
|
||||
if spec.limit:
|
||||
query = query.limit(spec.limit)
|
||||
|
||||
rows = db.execute(query).fetchall()
|
||||
|
||||
# 8. Shape Data for ECharts
|
||||
categories: List[str] = []
|
||||
series_data: List[Dict[str, Any]] = []
|
||||
raw_aggregated: List[Dict[str, Any]] = []
|
||||
total_recs = 0
|
||||
|
||||
if not spec.secondary_dimension:
|
||||
values = []
|
||||
for r in rows:
|
||||
label = str(r[0]) if r[0] is not None else "(Blank)"
|
||||
val = round(float(r[1]), 2) if isinstance(r[1], float) else (r[1] or 0)
|
||||
categories.append(label)
|
||||
values.append(val)
|
||||
raw_aggregated.append({"name": label, "value": val})
|
||||
total_recs += (val if isinstance(val, int) else 1)
|
||||
|
||||
series_data.append({
|
||||
"name": spec.dimension or "Count",
|
||||
"type": "pie" if spec.chart_type in ("pie", "donut") else ("line" if spec.chart_type in ("line", "area") else "bar"),
|
||||
"data": values
|
||||
})
|
||||
else:
|
||||
# Grouped / Stacked query
|
||||
distinct_categories = []
|
||||
distinct_sec = []
|
||||
matrix: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
for r in rows:
|
||||
dim_lbl = str(r[0]) if r[0] is not None else "(Blank)"
|
||||
sec_lbl = str(r[2]) if r[2] is not None else "(Blank)"
|
||||
val = round(float(r[1]), 2) if isinstance(r[1], float) else (r[1] or 0)
|
||||
|
||||
if dim_lbl not in distinct_categories:
|
||||
distinct_categories.append(dim_lbl)
|
||||
if sec_lbl not in distinct_sec:
|
||||
distinct_sec.append(sec_lbl)
|
||||
|
||||
if sec_lbl not in matrix:
|
||||
matrix[sec_lbl] = {}
|
||||
matrix[sec_lbl][dim_lbl] = val
|
||||
raw_aggregated.append({"dimension": dim_lbl, "secondary": sec_lbl, "value": val})
|
||||
|
||||
categories = distinct_categories
|
||||
for s in distinct_sec:
|
||||
s_data = [matrix.get(s, {}).get(cat, 0) for cat in categories]
|
||||
series_data.append({
|
||||
"name": s,
|
||||
"type": "bar",
|
||||
"stack": "total" if spec.chart_type == "stacked_bar" else None,
|
||||
"data": s_data
|
||||
})
|
||||
|
||||
return ChartResult(
|
||||
chart_type=spec.chart_type,
|
||||
title=f"{dataset.name} by {spec.dimension}",
|
||||
categories=categories,
|
||||
series=series_data,
|
||||
data=raw_aggregated,
|
||||
total_records=total_recs,
|
||||
applied_rules_count=len(eff_perms.row_rules)
|
||||
)
|
||||
@@ -0,0 +1,223 @@
|
||||
import csv
|
||||
import io
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import List, Dict, Any, Tuple
|
||||
from sqlalchemy import (
|
||||
Table, Column, Integer, String, DateTime, MetaData, select, func, inspect, text
|
||||
)
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.dataset import Dataset, DatasetColumn
|
||||
from app.core.exceptions import ConflictException, NotFoundException, ValidationException
|
||||
|
||||
|
||||
SENSITIVE_FIELD_NAMES = {"mrdnumber", "admittingdoctorname", "doctorname", "patientname"}
|
||||
IDENTIFIER_FIELD_NAMES = {"srno", "mrdnumber", "patientid", "id"}
|
||||
|
||||
|
||||
def clean_table_name(name: str) -> str:
|
||||
"""Generates a safe SQL table name."""
|
||||
clean = re.sub(r"[^a-zA-Z0-9_]", "_", name.lower()).strip("_")
|
||||
return f"ds_{clean}"
|
||||
|
||||
|
||||
def parse_datetime_value(val: str) -> Any:
|
||||
"""Parses DD-MM-YYYY HH:MM into a Python datetime object."""
|
||||
if not val or not val.strip():
|
||||
return None
|
||||
val = val.strip()
|
||||
# Primary format: DD-MM-YYYY HH:MM
|
||||
for fmt in ("%d-%m-%Y %H:%M", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d", "%d/%m/%Y %H:%M"):
|
||||
try:
|
||||
return datetime.strptime(val, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def parse_int_value(val: str) -> Any:
|
||||
"""Parses integer or returns None."""
|
||||
if not val or not val.strip():
|
||||
return None
|
||||
try:
|
||||
return int(val.strip())
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def register_dataset_from_csv(
|
||||
db: Session,
|
||||
file_content: bytes,
|
||||
dataset_name: str,
|
||||
description: str = ""
|
||||
) -> Dataset:
|
||||
"""
|
||||
Ingests CSV data (specifically tuned for hospital admission data),
|
||||
creates a dedicated table via SQLAlchemy Core, inserts data in chunks,
|
||||
and registers dataset and column metadata.
|
||||
"""
|
||||
bind = db.get_bind()
|
||||
|
||||
# Decode CSV content
|
||||
text_data = file_content.decode("utf-8-sig", errors="replace")
|
||||
csv_reader = csv.DictReader(io.StringIO(text_data))
|
||||
fieldnames = csv_reader.fieldnames or []
|
||||
|
||||
if not fieldnames:
|
||||
raise ValidationException("CSV file contains no headers or columns")
|
||||
|
||||
table_name = clean_table_name(dataset_name)
|
||||
|
||||
# Check if dataset name already exists
|
||||
existing_ds = db.query(Dataset).filter(
|
||||
(Dataset.name == dataset_name) | (Dataset.table_name == table_name)
|
||||
).first()
|
||||
if existing_ds:
|
||||
db.delete(existing_ds)
|
||||
db.commit()
|
||||
|
||||
# Drop table if exists on this bind
|
||||
try:
|
||||
db.execute(text(f'DROP TABLE IF EXISTS "{table_name}"'))
|
||||
db.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Read rows and infer schema
|
||||
rows = list(csv_reader)
|
||||
total_rows = len(rows)
|
||||
|
||||
# Define columns using SQLAlchemy Core with fresh MetaData
|
||||
table_meta = MetaData()
|
||||
cols = []
|
||||
col_metadata = []
|
||||
|
||||
for f in fieldnames:
|
||||
col_lower = f.lower()
|
||||
is_sensitive = col_lower in SENSITIVE_FIELD_NAMES
|
||||
is_identifier = col_lower in IDENTIFIER_FIELD_NAMES
|
||||
|
||||
# Determine column data type
|
||||
if col_lower == "srno":
|
||||
data_type = "integer"
|
||||
sa_col = Column(f, Integer, primary_key=True)
|
||||
elif "date" in col_lower:
|
||||
data_type = "datetime"
|
||||
sa_col = Column(f, DateTime, nullable=True)
|
||||
elif col_lower == "age":
|
||||
data_type = "integer"
|
||||
sa_col = Column(f, Integer, nullable=True)
|
||||
else:
|
||||
data_type = "string"
|
||||
sa_col = Column(f, String(255), nullable=True)
|
||||
|
||||
cols.append(sa_col)
|
||||
col_metadata.append({
|
||||
"column_name": f,
|
||||
"display_name": f.replace("_", " ").title() if "_" in f else f,
|
||||
"data_type": data_type,
|
||||
"is_sensitive": is_sensitive,
|
||||
"is_identifier": is_identifier
|
||||
})
|
||||
|
||||
# Dynamically create table with SQLAlchemy Core
|
||||
dynamic_table = Table(table_name, table_meta, *cols, extend_existing=True)
|
||||
dynamic_table.create(bind=bind, checkfirst=True)
|
||||
|
||||
# Prepare batch records
|
||||
prepared_records = []
|
||||
for r in rows:
|
||||
row_dict = {}
|
||||
for f in fieldnames:
|
||||
col_lower = f.lower()
|
||||
val = r.get(f)
|
||||
if val is not None:
|
||||
val = val.strip()
|
||||
if val == "":
|
||||
val = None
|
||||
|
||||
if col_lower == "srno":
|
||||
row_dict[f] = parse_int_value(val)
|
||||
elif "date" in col_lower:
|
||||
row_dict[f] = parse_datetime_value(val)
|
||||
elif col_lower == "age":
|
||||
row_dict[f] = parse_int_value(val)
|
||||
else:
|
||||
row_dict[f] = val
|
||||
prepared_records.append(row_dict)
|
||||
|
||||
# Bulk insert in batches of 5000 using SQLAlchemy Core
|
||||
batch_size = 5000
|
||||
for i in range(0, len(prepared_records), batch_size):
|
||||
batch = prepared_records[i : i + batch_size]
|
||||
db.execute(dynamic_table.insert(), batch)
|
||||
db.commit()
|
||||
|
||||
# Save Dataset record
|
||||
dataset = Dataset(
|
||||
name=dataset_name,
|
||||
description=description,
|
||||
source_type="file",
|
||||
table_name=table_name,
|
||||
row_count=total_rows,
|
||||
column_count=len(fieldnames)
|
||||
)
|
||||
db.add(dataset)
|
||||
db.flush()
|
||||
|
||||
# Save DatasetColumn records
|
||||
for cm in col_metadata:
|
||||
db_col = DatasetColumn(
|
||||
dataset_id=dataset.id,
|
||||
column_name=cm["column_name"],
|
||||
display_name=cm["display_name"],
|
||||
data_type=cm["data_type"],
|
||||
is_sensitive=cm["is_sensitive"],
|
||||
is_identifier=cm["is_identifier"]
|
||||
)
|
||||
db.add(db_col)
|
||||
|
||||
db.commit()
|
||||
db.refresh(dataset)
|
||||
return dataset
|
||||
|
||||
|
||||
def get_all_datasets(db: Session) -> List[Dataset]:
|
||||
"""Returns all registered datasets with columns."""
|
||||
return db.query(Dataset).order_by(Dataset.created_at.desc()).all()
|
||||
|
||||
|
||||
def get_dataset_by_id(db: Session, dataset_id: int) -> Dataset:
|
||||
"""Gets dataset details or raises 404."""
|
||||
ds = db.query(Dataset).filter(Dataset.id == dataset_id).first()
|
||||
if not ds:
|
||||
raise NotFoundException(f"Dataset with ID {dataset_id} not found")
|
||||
return ds
|
||||
|
||||
|
||||
def update_column_metadata(
|
||||
db: Session,
|
||||
dataset_id: int,
|
||||
column_id: int,
|
||||
display_name: str = None,
|
||||
is_sensitive: bool = None,
|
||||
is_identifier: bool = None
|
||||
) -> DatasetColumn:
|
||||
"""Updates display name, sensitivity, and identifier flags for a column."""
|
||||
col = db.query(DatasetColumn).filter(
|
||||
DatasetColumn.id == column_id,
|
||||
DatasetColumn.dataset_id == dataset_id
|
||||
).first()
|
||||
if not col:
|
||||
raise NotFoundException(f"Column ID {column_id} for Dataset ID {dataset_id} not found")
|
||||
|
||||
if display_name is not None:
|
||||
col.display_name = display_name
|
||||
if is_sensitive is not None:
|
||||
col.is_sensitive = is_sensitive
|
||||
if is_identifier is not None:
|
||||
col.is_identifier = is_identifier
|
||||
|
||||
db.commit()
|
||||
db.refresh(col)
|
||||
return col
|
||||
@@ -0,0 +1,193 @@
|
||||
from typing import List, Optional, Set
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.user import User, UserRole
|
||||
from app.models.dataset import Dataset, DatasetColumn
|
||||
from app.models.permission import DatasetPermission, ColumnPermission, RowRule
|
||||
from app.schemas.permission import (
|
||||
DatasetPermissionCreate, EffectivePermissions, RowRuleResponse
|
||||
)
|
||||
from app.core.exceptions import NotFoundException, ValidationException
|
||||
|
||||
|
||||
def save_dataset_permission(db: Session, perm_in: DatasetPermissionCreate) -> DatasetPermission:
|
||||
"""Creates or updates permission rules for a user or role on a dataset."""
|
||||
dataset = db.query(Dataset).filter(Dataset.id == perm_in.dataset_id).first()
|
||||
if not dataset:
|
||||
raise NotFoundException(f"Dataset with ID {perm_in.dataset_id} not found")
|
||||
|
||||
if not perm_in.user_id and not perm_in.role:
|
||||
raise ValidationException("Either user_id or role must be specified")
|
||||
|
||||
# Find existing permission
|
||||
query = db.query(DatasetPermission).filter(DatasetPermission.dataset_id == perm_in.dataset_id)
|
||||
if perm_in.user_id:
|
||||
query = query.filter(DatasetPermission.user_id == perm_in.user_id)
|
||||
else:
|
||||
query = query.filter(DatasetPermission.role == perm_in.role)
|
||||
|
||||
existing = query.first()
|
||||
if existing:
|
||||
existing.can_view = perm_in.can_view
|
||||
existing.can_export = perm_in.can_export
|
||||
# Clear previous column permissions & row rules to replace
|
||||
db.query(ColumnPermission).filter(ColumnPermission.dataset_permission_id == existing.id).delete()
|
||||
db.query(RowRule).filter(RowRule.dataset_permission_id == existing.id).delete()
|
||||
perm_record = existing
|
||||
else:
|
||||
perm_record = DatasetPermission(
|
||||
dataset_id=perm_in.dataset_id,
|
||||
user_id=perm_in.user_id,
|
||||
role=perm_in.role,
|
||||
can_view=perm_in.can_view,
|
||||
can_export=perm_in.can_export,
|
||||
)
|
||||
db.add(perm_record)
|
||||
db.flush()
|
||||
|
||||
# Add hidden columns
|
||||
for col_id in perm_in.hidden_column_ids:
|
||||
col = db.query(DatasetColumn).filter(
|
||||
DatasetColumn.id == col_id,
|
||||
DatasetColumn.dataset_id == perm_in.dataset_id
|
||||
).first()
|
||||
if col:
|
||||
col_perm = ColumnPermission(
|
||||
dataset_permission_id=perm_record.id,
|
||||
column_id=col.id,
|
||||
is_hidden=True
|
||||
)
|
||||
db.add(col_perm)
|
||||
|
||||
# Add row rules
|
||||
for r in perm_in.row_rules:
|
||||
# Validate column name exists in dataset
|
||||
col_exists = db.query(DatasetColumn).filter(
|
||||
DatasetColumn.dataset_id == perm_in.dataset_id,
|
||||
DatasetColumn.column_name == r.column_name
|
||||
).first()
|
||||
if not col_exists:
|
||||
raise ValidationException(f"Column '{r.column_name}' does not exist in dataset")
|
||||
|
||||
row_rule = RowRule(
|
||||
dataset_permission_id=perm_record.id,
|
||||
column_name=r.column_name,
|
||||
operator=r.operator,
|
||||
rule_value=r.rule_value
|
||||
)
|
||||
db.add(row_rule)
|
||||
|
||||
db.commit()
|
||||
db.refresh(perm_record)
|
||||
return perm_record
|
||||
|
||||
|
||||
def get_effective_permissions(
|
||||
db: Session,
|
||||
user: User,
|
||||
dataset_id: int,
|
||||
preview_user_id: Optional[int] = None,
|
||||
preview_role: Optional[str] = None
|
||||
) -> EffectivePermissions:
|
||||
"""
|
||||
Computes effective dataset, column and row-level permissions for a user.
|
||||
If the requesting user is a Super Admin and provides preview_user_id or preview_role,
|
||||
permissions are evaluated for that target entity.
|
||||
"""
|
||||
# Resolve target user / role for preview
|
||||
target_role = user.role
|
||||
target_user_id = user.id
|
||||
|
||||
if user.is_super_admin():
|
||||
if preview_user_id:
|
||||
target_user = db.query(User).filter(User.id == preview_user_id).first()
|
||||
if target_user:
|
||||
target_user_id = target_user.id
|
||||
target_role = target_user.role
|
||||
elif preview_role:
|
||||
target_role = preview_role
|
||||
target_user_id = None
|
||||
else:
|
||||
# Unrestricted Super Admin
|
||||
all_cols = db.query(DatasetColumn).filter(DatasetColumn.dataset_id == dataset_id).all()
|
||||
return EffectivePermissions(
|
||||
dataset_id=dataset_id,
|
||||
can_view=True,
|
||||
can_export=True,
|
||||
allowed_columns=[c.column_name for c in all_cols],
|
||||
hidden_columns=[],
|
||||
row_rules=[]
|
||||
)
|
||||
|
||||
# Fetch all columns for this dataset
|
||||
all_columns = db.query(DatasetColumn).filter(DatasetColumn.dataset_id == dataset_id).all()
|
||||
col_dict = {c.id: c.column_name for c in all_columns}
|
||||
sensitive_cols = {c.column_name for c in all_columns if c.is_sensitive}
|
||||
|
||||
# Fetch permissions by user_id and by role
|
||||
perms: List[DatasetPermission] = []
|
||||
if target_user_id:
|
||||
user_perm = db.query(DatasetPermission).filter(
|
||||
DatasetPermission.dataset_id == dataset_id,
|
||||
DatasetPermission.user_id == target_user_id
|
||||
).first()
|
||||
if user_perm:
|
||||
perms.append(user_perm)
|
||||
|
||||
if target_role:
|
||||
role_perm = db.query(DatasetPermission).filter(
|
||||
DatasetPermission.dataset_id == dataset_id,
|
||||
DatasetPermission.role == target_role
|
||||
).first()
|
||||
if role_perm:
|
||||
perms.append(role_perm)
|
||||
|
||||
# If no permissions found, default to view=False
|
||||
if not perms:
|
||||
return EffectivePermissions(
|
||||
dataset_id=dataset_id,
|
||||
can_view=False,
|
||||
can_export=False,
|
||||
allowed_columns=[],
|
||||
hidden_columns=[c.column_name for c in all_columns],
|
||||
row_rules=[]
|
||||
)
|
||||
|
||||
# Intersection logic:
|
||||
# can_view is True if any granted permission allows view
|
||||
can_view = any(p.can_view for p in perms)
|
||||
can_export = any(p.can_export for p in perms)
|
||||
|
||||
# Hidden columns: combine all explicitly hidden column permissions + sensitive columns by default
|
||||
hidden_col_names: Set[str] = set()
|
||||
for p in perms:
|
||||
for cp in p.column_permissions:
|
||||
if cp.is_hidden and cp.column_id in col_dict:
|
||||
hidden_col_names.add(col_dict[cp.column_id])
|
||||
|
||||
# Add sensitive columns unless role is super_admin
|
||||
if target_role != UserRole.SUPER_ADMIN.value:
|
||||
hidden_col_names.update(sensitive_cols)
|
||||
|
||||
allowed_columns = [c.column_name for c in all_columns if c.column_name not in hidden_col_names]
|
||||
|
||||
# Combine row rules across all applicable permissions (AND intersection)
|
||||
combined_row_rules = []
|
||||
for p in perms:
|
||||
for r in p.row_rules:
|
||||
combined_row_rules.append(
|
||||
RowRuleResponse(
|
||||
id=r.id,
|
||||
column_name=r.column_name,
|
||||
operator=r.operator,
|
||||
rule_value=r.rule_value
|
||||
)
|
||||
)
|
||||
|
||||
return EffectivePermissions(
|
||||
dataset_id=dataset_id,
|
||||
can_view=can_view,
|
||||
can_export=can_export,
|
||||
allowed_columns=allowed_columns,
|
||||
hidden_columns=list(hidden_col_names),
|
||||
row_rules=combined_row_rules
|
||||
)
|
||||
@@ -0,0 +1,85 @@
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.user import User, UserRole
|
||||
from app.schemas.user import UserCreate, UserUpdate
|
||||
from app.core.security import hash_password
|
||||
from app.core.exceptions import ConflictException, NotFoundException, ValidationException
|
||||
|
||||
|
||||
def get_users(db: Session, skip: int = 0, limit: int = 100) -> List[User]:
|
||||
"""Retrieves paginated list of users."""
|
||||
return db.query(User).offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
def get_user_by_id(db: Session, user_id: int) -> User:
|
||||
"""Retrieves single user by primary key or raises 404."""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise NotFoundException(f"User with ID {user_id} not found")
|
||||
return user
|
||||
|
||||
|
||||
def create_user(db: Session, user_in: UserCreate) -> User:
|
||||
"""Validates uniqueness and creates a new user."""
|
||||
# Check if username exists
|
||||
if db.query(User).filter(User.username == user_in.username).first():
|
||||
raise ConflictException(f"Username '{user_in.username}' already registered")
|
||||
|
||||
# Check if email exists
|
||||
if db.query(User).filter(User.email == user_in.email).first():
|
||||
raise ConflictException(f"Email '{user_in.email}' already registered")
|
||||
|
||||
# Validate role
|
||||
valid_roles = [r.value for r in UserRole]
|
||||
if user_in.role not in valid_roles:
|
||||
raise ValidationException(f"Invalid role '{user_in.role}'. Allowed: {', '.join(valid_roles)}")
|
||||
|
||||
db_user = User(
|
||||
username=user_in.username,
|
||||
email=user_in.email,
|
||||
hashed_password=hash_password(user_in.password),
|
||||
full_name=user_in.full_name,
|
||||
role=user_in.role,
|
||||
is_active=user_in.is_active
|
||||
)
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
||||
|
||||
def update_user(db: Session, user_id: int, user_in: UserUpdate) -> User:
|
||||
"""Updates user fields with validation."""
|
||||
user = get_user_by_id(db, user_id)
|
||||
|
||||
if user_in.email and user_in.email != user.email:
|
||||
if db.query(User).filter(User.email == user_in.email, User.id != user_id).first():
|
||||
raise ConflictException(f"Email '{user_in.email}' already in use by another user")
|
||||
user.email = user_in.email
|
||||
|
||||
if user_in.password:
|
||||
user.hashed_password = hash_password(user_in.password)
|
||||
|
||||
if user_in.full_name is not None:
|
||||
user.full_name = user_in.full_name
|
||||
|
||||
if user_in.role is not None:
|
||||
valid_roles = [r.value for r in UserRole]
|
||||
if user_in.role not in valid_roles:
|
||||
raise ValidationException(f"Invalid role '{user_in.role}'. Allowed: {', '.join(valid_roles)}")
|
||||
user.role = user_in.role
|
||||
|
||||
if user_in.is_active is not None:
|
||||
user.is_active = user_in.is_active
|
||||
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def delete_user(db: Session, user_id: int) -> bool:
|
||||
"""Deletes a user record."""
|
||||
user = get_user_by_id(db, user_id)
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
return True
|
||||
@@ -0,0 +1,8 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
python_files = test_*.py
|
||||
python_classes = Test*
|
||||
python_functions = test_*
|
||||
addopts = -v --tb=short
|
||||
filterwarnings =
|
||||
ignore::DeprecationWarning
|
||||
@@ -0,0 +1,14 @@
|
||||
fastapi>=0.110.0
|
||||
uvicorn[standard]>=0.28.0
|
||||
sqlalchemy>=2.0.28
|
||||
pydantic>=2.6.4
|
||||
pydantic-settings>=2.2.1
|
||||
argon2-cffi>=23.1.0
|
||||
pyjwt>=2.8.0
|
||||
python-multipart>=0.0.9
|
||||
psycopg2-binary>=2.9.9
|
||||
alembic>=1.13.1
|
||||
pytest>=8.0.0
|
||||
pytest-asyncio>=0.23.5
|
||||
httpx>=0.27.0
|
||||
python-dotenv>=1.0.1
|
||||
@@ -0,0 +1,295 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
||||
from reportlab.platypus import (
|
||||
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, KeepTogether, HRFlowable
|
||||
)
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
|
||||
class NumberedCanvas(canvas.Canvas):
|
||||
"""Two-pass canvas to dynamically compute and print 'Page X of Y'."""
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._saved_page_states = []
|
||||
|
||||
def showPage(self):
|
||||
self._saved_page_states.append(dict(self.__dict__))
|
||||
self._startPage()
|
||||
|
||||
def save(self):
|
||||
num_pages = len(self._saved_page_states)
|
||||
for state in self._saved_page_states:
|
||||
self.__dict__.update(state)
|
||||
self.draw_page_number(num_pages)
|
||||
canvas.Canvas.showPage(self)
|
||||
canvas.Canvas.save(self)
|
||||
|
||||
def draw_page_number(self, page_count):
|
||||
self.saveState()
|
||||
self.setFont("Helvetica", 8)
|
||||
self.setFillColor(colors.HexColor("#64748B"))
|
||||
|
||||
# Header (on pages > 1)
|
||||
if self._pageNumber > 1:
|
||||
self.drawString(36, 810, "DMH Hospital Data Visualisation Platform — System Documentation")
|
||||
self.setStrokeColor(colors.HexColor("#E2E8F0"))
|
||||
self.setLineWidth(0.5)
|
||||
self.line(36, 804, 559, 804)
|
||||
|
||||
# Footer
|
||||
page_str = f"Page {self._pageNumber} of {page_count}"
|
||||
self.drawRightString(559, 25, page_str)
|
||||
self.drawString(36, 25, "Confidential — Deenanath Mangeshkar Hospital (DMH)")
|
||||
self.setStrokeColor(colors.HexColor("#E2E8F0"))
|
||||
self.setLineWidth(0.5)
|
||||
self.line(36, 35, 559, 35)
|
||||
|
||||
self.restoreState()
|
||||
|
||||
|
||||
def build_pdf(output_path: str):
|
||||
doc = SimpleDocTemplate(
|
||||
output_path,
|
||||
pagesize=A4,
|
||||
leftMargin=36,
|
||||
rightMargin=36,
|
||||
topMargin=46,
|
||||
bottomMargin=46
|
||||
)
|
||||
|
||||
styles = getSampleStyleSheet()
|
||||
|
||||
# Custom palette
|
||||
c_primary = colors.HexColor("#1E3A8A") # Navy Blue
|
||||
c_secondary = colors.HexColor("#0284C7") # Hospital Sky Blue
|
||||
c_dark = colors.HexColor("#0F172A") # Slate Dark
|
||||
c_text = colors.HexColor("#334155") # Body text
|
||||
c_light = colors.HexColor("#F8FAFC") # Table BG
|
||||
c_border = colors.HexColor("#CBD5E1") # Border
|
||||
c_success = colors.HexColor("#16A34A") # Green
|
||||
c_warning = colors.HexColor("#D97706") # Amber
|
||||
|
||||
# Typography styles
|
||||
styles.add(ParagraphStyle('DocTitle', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=22, leading=26, textColor=c_primary, spaceAfter=4))
|
||||
styles.add(ParagraphStyle('DocSubtitle', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=11, leading=14, textColor=c_secondary, spaceAfter=12))
|
||||
styles.add(ParagraphStyle('SectionHeading', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=13, leading=16, textColor=c_primary, spaceBefore=12, spaceAfter=6, keepWithNext=True))
|
||||
styles.add(ParagraphStyle('SubSectionHeading', parent=styles['Heading3'], fontName='Helvetica-Bold', fontSize=10.5, leading=13, textColor=c_dark, spaceBefore=8, spaceAfter=4, keepWithNext=True))
|
||||
styles.add(ParagraphStyle('BodyCustom', parent=styles['Normal'], fontName='Helvetica', fontSize=8.5, leading=12, textColor=c_text, spaceAfter=5))
|
||||
styles.add(ParagraphStyle('BodyBold', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=8.5, leading=12, textColor=c_dark, spaceAfter=5))
|
||||
styles.add(ParagraphStyle('Callout', parent=styles['Normal'], fontName='Helvetica-Oblique', fontSize=8.5, leading=12, textColor=colors.HexColor("#1E293B"), spaceBefore=4, spaceAfter=6))
|
||||
styles.add(ParagraphStyle('TableHeader', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=8, leading=10, textColor=colors.white, alignment=1))
|
||||
styles.add(ParagraphStyle('TableCell', parent=styles['Normal'], fontName='Helvetica', fontSize=7.8, leading=10, textColor=c_dark))
|
||||
styles.add(ParagraphStyle('TableCellBold', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=7.8, leading=10, textColor=c_dark))
|
||||
styles.add(ParagraphStyle('BadgeSuccess', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=7.5, leading=9, textColor=c_success, alignment=1))
|
||||
styles.add(ParagraphStyle('BadgePending', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=7.5, leading=9, textColor=c_warning, alignment=1))
|
||||
|
||||
story = []
|
||||
|
||||
# 1. Title Banner
|
||||
story.append(Paragraph("DMH Role-Based Data Visualisation Platform", styles['DocTitle']))
|
||||
story.append(Paragraph("System Architecture, Delivered Modules & Comprehensive Project Roadmap", styles['DocSubtitle']))
|
||||
story.append(HRFlowable(width="100%", thickness=1.5, color=c_secondary, spaceBefore=0, spaceAfter=10))
|
||||
|
||||
# Meta Info Table
|
||||
meta_data = [
|
||||
[Paragraph("<b>Target Organisation:</b> Deenanath Mangeshkar Hospital (DMH), Pune", styles['TableCell']),
|
||||
Paragraph("<b>Date:</b> 24 November 2026", styles['TableCell'])],
|
||||
[Paragraph("<b>Initial Dataset:</b> admissionData-2025_v1.csv (86,099 rows, 19 fields)", styles['TableCell']),
|
||||
Paragraph("<b>Status:</b> Phases 1–3 Complete (25/25 Tests Passing)", styles['TableCell'])],
|
||||
[Paragraph("<b>Tech Stack:</b> FastAPI, SQLAlchemy 2.0 Core, React 18, Apache ECharts", styles['TableCell']),
|
||||
Paragraph("<b>Lead:</b> AI Engineering Team", styles['TableCell'])]
|
||||
]
|
||||
meta_table = Table(meta_data, colWidths=[270, 253])
|
||||
meta_table.setStyle(TableStyle([
|
||||
('BACKGROUND', (0,0), (-1,-1), c_light),
|
||||
('BOX', (0,0), (-1,-1), 0.5, c_border),
|
||||
('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
|
||||
('TOPPADDING', (0,0), (-1,-1), 4),
|
||||
('BOTTOMPADDING', (0,0), (-1,-1), 4),
|
||||
]))
|
||||
story.append(meta_table)
|
||||
story.append(Spacer(1, 10))
|
||||
|
||||
# 2. Executive Summary
|
||||
story.append(Paragraph("1. Executive Summary & Background", styles['SectionHeading']))
|
||||
p1 = ("Healthcare organisations manage high-volume operational and clinical records. Historically, this data is either "
|
||||
"circulated via raw spreadsheets (causing privacy risks, version confusion, and non-compliance) or locked behind one-off "
|
||||
"manual reports built by developers (which are expensive and slow). "
|
||||
"This platform provides a governed, self-service visualization hub where a <b>Super Admin</b> configures exact permissions, "
|
||||
"and departmental users log in to see interactive charts limited strictly to their permitted data.")
|
||||
story.append(Paragraph(p1, styles['BodyCustom']))
|
||||
|
||||
# 3. The One Rule That Matters Most
|
||||
story.append(Paragraph("2. The One Rule That Matters Most (Zero Data Leakage)", styles['SectionHeading']))
|
||||
rule_box_data = [[
|
||||
Paragraph("<b>THE CRUCIAL SECURITY RULE:</b><br/>"
|
||||
"The browser must never receive data the user is not allowed to see. All permission checks, column masking, "
|
||||
"and aggregations happen on the backend. The frontend client sends a declarative JSON chart specification, "
|
||||
"never SQL. The backend validates it against a strict whitelist, applies user/role row-level rules, runs an "
|
||||
"aggregated query via SQLAlchemy Core with bound parameters, and returns only the mathematical summary result.",
|
||||
styles['Callout'])
|
||||
]]
|
||||
rule_table = Table(rule_box_data, colWidths=[523])
|
||||
rule_table.setStyle(TableStyle([
|
||||
('BACKGROUND', (0,0), (-1,-1), colors.HexColor("#EFF6FF")),
|
||||
('BOX', (0,0), (-1,-1), 1, c_secondary),
|
||||
('TOPPADDING', (0,0), (-1,-1), 6),
|
||||
('BOTTOMPADDING', (0,0), (-1,-1), 6),
|
||||
('LEFTPADDING', (0,0), (-1,-1), 10),
|
||||
('RIGHTPADDING', (0,0), (-1,-1), 10),
|
||||
]))
|
||||
story.append(rule_table)
|
||||
story.append(Spacer(1, 8))
|
||||
|
||||
# 4. Tech Stack Table
|
||||
story.append(Paragraph("3. Technology Stack & Architectural Decisions", styles['SectionHeading']))
|
||||
tech_data = [
|
||||
[Paragraph("Layer", styles['TableHeader']), Paragraph("Technology", styles['TableHeader']), Paragraph("Architectural Rationale & Implementation", styles['TableHeader'])],
|
||||
[Paragraph("Backend API", styles['TableCellBold']), Paragraph("FastAPI (Python 3.11+)", styles['TableCell']), Paragraph("Async endpoints, Pydantic v2 data validation, OpenAPI autodoc", styles['TableCell'])],
|
||||
[Paragraph("Data Engine", styles['TableCellBold']), Paragraph("SQLAlchemy 2.0 Core", styles['TableCell']), Paragraph("Dynamic typed table reflections, parameter binding, whitelisting (Zero f-string SQL)", styles['TableCell'])],
|
||||
[Paragraph("Migrations", styles['TableCellBold']), Paragraph("Alembic", styles['TableCell']), Paragraph("System schema versioning; dynamic data tables (ds_*) excluded cleanly", styles['TableCell'])],
|
||||
[Paragraph("Auth & Crypto", styles['TableCellBold']), Paragraph("Argon2-cffi + PyJWT", styles['TableCell']), Paragraph("GPU-resistant password hashing; 8-hour stateless signed JWT tokens", styles['TableCell'])],
|
||||
[Paragraph("Database", styles['TableCellBold']), Paragraph("PostgreSQL 16 / SQLite", styles['TableCell']), Paragraph("Postgres for production; zero-dependency SQLite for fast isolated unit tests", styles['TableCell'])],
|
||||
[Paragraph("Frontend UI", styles['TableCellBold']), Paragraph("React 18 + TypeScript + Vite", styles['TableCell']), Paragraph("Type-safe SPA with strict compilation checks (no unused locals/params)", styles['TableCell'])],
|
||||
[Paragraph("Visualisations", styles['TableCellBold']), Paragraph("Apache ECharts (React)", styles['TableCell']), Paragraph("High-performance canvas/SVG charts with responsive resize and custom DMH palette", styles['TableCell'])],
|
||||
[Paragraph("Deployment", styles['TableCellBold']), Paragraph("Docker Compose + Nginx", styles['TableCell']), Paragraph("Reverse proxy, asset compression, multi-container orchestration", styles['TableCell'])]
|
||||
]
|
||||
tech_table = Table(tech_data, colWidths=[80, 130, 313])
|
||||
tech_table.setStyle(TableStyle([
|
||||
('BACKGROUND', (0,0), (-1,0), c_primary),
|
||||
('BOX', (0,0), (-1,-1), 0.5, c_border),
|
||||
('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
|
||||
('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, c_light]),
|
||||
('TOPPADDING', (0,0), (-1,-1), 3.5),
|
||||
('BOTTOMPADDING', (0,0), (-1,-1), 3.5),
|
||||
]))
|
||||
story.append(tech_table)
|
||||
story.append(Spacer(1, 10))
|
||||
|
||||
# 5. What Has Been Developed (Phases 1-3)
|
||||
story.append(Paragraph("4. Modules Currently Developed & Verified (Phases 1, 2 & 3)", styles['SectionHeading']))
|
||||
|
||||
story.append(Paragraph("A. Authentication & User Management (Phase 1)", styles['SubSectionHeading']))
|
||||
story.append(Paragraph("• Implemented Argon2id password hashing and PyJWT token generation.<br/>"
|
||||
"• Established 4-role RBAC hierarchy: Super Admin, Viewer, Department Manager, and Finance User.<br/>"
|
||||
"• Built Super Admin user management CRUD (/api/v1/users) with full 403 Forbidden enforcement for non-admin requests.", styles['BodyCustom']))
|
||||
|
||||
story.append(Paragraph("B. Data Ingestion & Schema Registration (Phase 1)", styles['SubSectionHeading']))
|
||||
story.append(Paragraph("• Ingested all <b>86,099 rows and 19 fields</b> from <code>admissionData-2025_v1.csv</code> into <code>ds_hospital_admissions_2025</code>.<br/>"
|
||||
"• Robust parsing of <code>DD-MM-YYYY HH:MM</code> timestamps into real database <code>DATETIME</code> types.<br/>"
|
||||
"• Automatic sensitive column tagging: direct patient identifiers (<code>mrdNumber</code>) and doctor names flagged as sensitive by default; <code>bedNumber</code> handled as text.", styles['BodyCustom']))
|
||||
|
||||
story.append(Paragraph("C. Access Control Matrix & Rule Intersection (Phase 2)", styles['SubSectionHeading']))
|
||||
story.append(Paragraph("• Three-tiered access control: Dataset grants, Column masking, and Row-level filter rules.<br/>"
|
||||
"• Mathematical AND-rule intersection: users inherit all applicable role and user-specific constraints.<br/>"
|
||||
"• Super Admin <b>'Preview As' Simulation Tool</b>: Allows administrators to simulate restricted roles (Medicine only, TPA only) with instant live UI re-rendering.", styles['BodyCustom']))
|
||||
|
||||
story.append(Paragraph("D. Declarative Query & Aggregation Engine (Phase 3)", styles['SubSectionHeading']))
|
||||
story.append(Paragraph("• Accepts client JSON <code>ChartSpec</code>, verifies whitelist, injects parameterized WHERE clauses.<br/>"
|
||||
"• Rejects restricted dimensions/measures with HTTP 403. Executes aggregations (COUNT, SUM, AVG) via SQLAlchemy Core.", styles['BodyCustom']))
|
||||
|
||||
story.append(Paragraph("E. Interactive Apache ECharts Dashboard (Phase 3)", styles['SubSectionHeading']))
|
||||
story.append(Paragraph("• <b>4 Executive KPIs:</b> Total Admissions, Average Patient Age, Active Clinical Specialities, Hospital Wings.<br/>"
|
||||
"• <b>5 Core Charts:</b> Admissions by Medical Speciality (Bar), Hospital Building Breakdown (Donut), Monthly Volume Trend (Area), Admission Categories (Pie), and Patient Payer Mix & Demographics (Stacked Bar).<br/>"
|
||||
"• <b>Dynamic Filter Bar:</b> Permission-scoped dropdowns for Building, Speciality, and Admission Type.", styles['BodyCustom']))
|
||||
story.append(Spacer(1, 8))
|
||||
|
||||
# 6. Live Ingested Dataset Verification Table
|
||||
story.append(Paragraph("5. Live Dataset Verification Metrics (86,099 Records)", styles['SectionHeading']))
|
||||
verif_data = [
|
||||
[Paragraph("Role / Persona", styles['TableHeader']), Paragraph("Enforced Access Boundaries", styles['TableHeader']), Paragraph("Verified Output Metric", styles['TableHeader']), Paragraph("Status", styles['TableHeader'])],
|
||||
[Paragraph("Super Admin", styles['TableCellBold']), Paragraph("Unrestricted hospital-wide access", styles['TableCell']), Paragraph("<b>86,099</b> admissions across all 19 columns", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
|
||||
[Paragraph("Top Specialities", styles['TableCellBold']), Paragraph("Hospital rankings (Unrestricted)", styles['TableCell']), Paragraph("Oncology: 18,536 | Medicine: 9,770 | Eye: 5,366", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
|
||||
[Paragraph("Department Manager", styles['TableCellBold']), Paragraph("Row rule: Speciality = 'MEDICINE'", styles['TableCell']), Paragraph("<b>9,770</b> admissions (Non-Medicine rows excluded)", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
|
||||
[Paragraph("Finance User", styles['TableCellBold']), Paragraph("Row rule: PatientCategory = 'TPA'", styles['TableCell']), Paragraph("<b>32,056</b> claims (Cash/GNL rows excluded)", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
|
||||
[Paragraph("Restricted Viewer", styles['TableCellBold']), Paragraph("Column masking (mrdNumber, Doctor)", styles['TableCell']), Paragraph("HTTP 403 Forbidden on sensitive fields", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
|
||||
[Paragraph("Automated Tests", styles['TableCellBold']), Paragraph("Pytest test suite (backend/tests)", styles['TableCell']), Paragraph("<b>25/25 unit tests passing</b> (7.27 seconds)", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
|
||||
]
|
||||
verif_table = Table(verif_data, colWidths=[95, 145, 203, 80])
|
||||
verif_table.setStyle(TableStyle([
|
||||
('BACKGROUND', (0,0), (-1,0), c_primary),
|
||||
('BOX', (0,0), (-1,-1), 0.5, c_border),
|
||||
('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
|
||||
('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, c_light]),
|
||||
('TOPPADDING', (0,0), (-1,-1), 3),
|
||||
('BOTTOMPADDING', (0,0), (-1,-1), 3),
|
||||
]))
|
||||
story.append(verif_table)
|
||||
story.append(Spacer(1, 10))
|
||||
|
||||
# 7. What is Remaining (Roadmap)
|
||||
story.append(Paragraph("6. Remaining Roadmap & Planned Enhancements", styles['SectionHeading']))
|
||||
|
||||
plan_data = [
|
||||
[Paragraph("Phase", styles['TableHeader']), Paragraph("Module Title", styles['TableHeader']), Paragraph("Scope & Planned Functionality", styles['TableHeader']), Paragraph("Status", styles['TableHeader'])],
|
||||
[Paragraph("Phase 3.5", styles['TableCellBold']),
|
||||
Paragraph("Advanced Healthcare Analytics & Cross-Filtering", styles['TableCell']),
|
||||
Paragraph("• <b>Average Length of Stay (ALOS):</b> Days calculation per department.<br/>"
|
||||
"• <b>24x7 Day-vs-Hour Surge Heatmap:</b> Emergency surge hours visualization.<br/>"
|
||||
"• <b>Geographic Breakdown:</b> In-state vs out-of-state and district spread.<br/>"
|
||||
"• <b>Cross-Filtering:</b> Click-to-filter across all dashboard widgets.<br/>"
|
||||
"• <b>Image Exports:</b> High-resolution PNG/SVG chart export via ECharts.", styles['TableCell']),
|
||||
Paragraph("READY TO BUILD", styles['BadgePending'])],
|
||||
|
||||
[Paragraph("Phase 4", styles['TableCellBold']),
|
||||
Paragraph("Governance, Compliance & Export Engine", styles['TableCell']),
|
||||
Paragraph("• <b>Tamper-Evident Audit Logging:</b> Log user logins, queries, permission edits.<br/>"
|
||||
"• <b>Admin Audit Viewer:</b> Searchable audit trail (/admin/audit-logs).<br/>"
|
||||
"• <b>India DPDP Act Compliance:</b> Small-group suppression (k < 5 patients).<br/>"
|
||||
"• <b>Role-Gated Data Exports:</b> Watermarked Excel/CSV export gated by can_export.", styles['TableCell']),
|
||||
Paragraph("SCHEDULED", styles['BadgePending'])],
|
||||
|
||||
[Paragraph("Phase 5", styles['TableCellBold']),
|
||||
Paragraph("Live Enterprise Connectors & Deployment", styles['TableCell']),
|
||||
Paragraph("• <b>External Database Connectors:</b> Direct PostgreSQL, MySQL, SQL Server.<br/>"
|
||||
"• <b>Encrypted Credentials:</b> Symmetric Fernet encryption for connection strings.<br/>"
|
||||
"• <b>Aggregation Caching:</b> Redis / In-memory caching for sub-50ms query responses.<br/>"
|
||||
"• <b>Docker Compose Hardening:</b> Production Nginx reverse proxy & containers.", styles['TableCell']),
|
||||
Paragraph("SCHEDULED", styles['BadgePending'])],
|
||||
]
|
||||
plan_table = Table(plan_data, colWidths=[65, 125, 253, 80])
|
||||
plan_table.setStyle(TableStyle([
|
||||
('BACKGROUND', (0,0), (-1,0), c_primary),
|
||||
('BOX', (0,0), (-1,-1), 0.5, c_border),
|
||||
('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
|
||||
('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, c_light]),
|
||||
('TOPPADDING', (0,0), (-1,-1), 4),
|
||||
('BOTTOMPADDING', (0,0), (-1,-1), 4),
|
||||
]))
|
||||
story.append(plan_table)
|
||||
story.append(Spacer(1, 10))
|
||||
|
||||
# 8. Demo Credentials & How to Run
|
||||
story.append(Paragraph("7. Execution Guide & Demo Accounts", styles['SectionHeading']))
|
||||
creds_data = [
|
||||
[Paragraph("Role", styles['TableHeader']), Paragraph("Username", styles['TableHeader']), Paragraph("Password", styles['TableHeader']), Paragraph("Enforced Data Scope", styles['TableHeader'])],
|
||||
[Paragraph("Super Admin", styles['TableCellBold']), Paragraph("admin", styles['TableCell']), Paragraph("Admin@123456", styles['TableCell']), Paragraph("Unrestricted hospital-wide access (86,099 rows)", styles['TableCell'])],
|
||||
[Paragraph("Staff Viewer", styles['TableCellBold']), Paragraph("viewer", styles['TableCell']), Paragraph("Viewer@123456", styles['TableCell']), Paragraph("General view; sensitive doctor and MRN masked", styles['TableCell'])],
|
||||
[Paragraph("Dept Manager", styles['TableCellBold']), Paragraph("dept_manager", styles['TableCell']), Paragraph("Manager@123456", styles['TableCell']), Paragraph("Medicine department admissions only (9,770 rows)", styles['TableCell'])],
|
||||
[Paragraph("Finance Analyst", styles['TableCellBold']), Paragraph("finance_user", styles['TableCell']), Paragraph("Finance@123456", styles['TableCell']), Paragraph("TPA insurance claims only (32,056 rows)", styles['TableCell'])],
|
||||
]
|
||||
creds_table = Table(creds_data, colWidths=[90, 80, 95, 258])
|
||||
creds_table.setStyle(TableStyle([
|
||||
('BACKGROUND', (0,0), (-1,0), c_primary),
|
||||
('BOX', (0,0), (-1,-1), 0.5, c_border),
|
||||
('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
|
||||
('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, c_light]),
|
||||
('TOPPADDING', (0,0), (-1,-1), 3),
|
||||
('BOTTOMPADDING', (0,0), (-1,-1), 3),
|
||||
]))
|
||||
story.append(creds_table)
|
||||
|
||||
# Build PDF with custom numbered canvas
|
||||
doc.build(story, canvasmaker=NumberedCanvas)
|
||||
print(f"PDF successfully built at: {output_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
out_dir = Path(__file__).resolve().parent.parent.parent / "docs"
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
out_file = str(out_dir / "DMH_Role_Based_Data_Visualisation_Platform_Documentation.pdf")
|
||||
build_pdf(out_file)
|
||||
@@ -0,0 +1,169 @@
|
||||
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.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.schemas.permission import DatasetPermissionCreate, RowRuleCreate
|
||||
from app.config import settings
|
||||
|
||||
|
||||
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 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"
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
print("Role permissions seeded successfully!")
|
||||
|
||||
print("Seeding completed successfully!")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
seed_database()
|
||||
@@ -0,0 +1,101 @@
|
||||
import pytest
|
||||
from typing import Generator
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.database import Base, get_db
|
||||
from app.main import app
|
||||
from app.models.user import User, UserRole
|
||||
from app.core.security import hash_password, create_access_token
|
||||
|
||||
# In-memory SQLite database for fast isolated unit tests
|
||||
TEST_DATABASE_URL = "sqlite:///:memory:"
|
||||
|
||||
test_engine = create_engine(
|
||||
TEST_DATABASE_URL,
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def setup_test_db():
|
||||
Base.metadata.create_all(bind=test_engine)
|
||||
yield
|
||||
Base.metadata.drop_all(bind=test_engine)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session() -> Generator:
|
||||
connection = test_engine.connect()
|
||||
transaction = connection.begin()
|
||||
session = TestingSessionLocal(bind=connection)
|
||||
|
||||
yield session
|
||||
|
||||
session.close()
|
||||
transaction.rollback()
|
||||
connection.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(db_session) -> Generator:
|
||||
def override_get_db():
|
||||
try:
|
||||
yield db_session
|
||||
finally:
|
||||
pass
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_user(db_session) -> User:
|
||||
user = db_session.query(User).filter(User.username == "test_admin").first()
|
||||
if not user:
|
||||
user = User(
|
||||
username="test_admin",
|
||||
email="admin@test.com",
|
||||
hashed_password=hash_password("AdminPass123!"),
|
||||
full_name="Test Administrator",
|
||||
role=UserRole.SUPER_ADMIN.value,
|
||||
is_active=True
|
||||
)
|
||||
db_session.add(user)
|
||||
db_session.commit()
|
||||
db_session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def viewer_user(db_session) -> User:
|
||||
user = db_session.query(User).filter(User.username == "test_viewer").first()
|
||||
if not user:
|
||||
user = User(
|
||||
username="test_viewer",
|
||||
email="viewer@test.com",
|
||||
hashed_password=hash_password("ViewerPass123!"),
|
||||
full_name="Test Regular Viewer",
|
||||
role=UserRole.VIEWER.value,
|
||||
is_active=True
|
||||
)
|
||||
db_session.add(user)
|
||||
db_session.commit()
|
||||
db_session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_token(admin_user) -> str:
|
||||
return create_access_token(data={"sub": str(admin_user.id), "username": admin_user.username, "role": admin_user.role})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def viewer_token(viewer_user) -> str:
|
||||
return create_access_token(data={"sub": str(viewer_user.id), "username": viewer_user.username, "role": viewer_user.role})
|
||||
@@ -0,0 +1,53 @@
|
||||
def test_login_success(client, admin_user):
|
||||
response = client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"username_or_email": "test_admin", "password": "AdminPass123!"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "access_token" in data
|
||||
assert data["token_type"] == "Bearer"
|
||||
assert data["user"]["username"] == "test_admin"
|
||||
assert data["user"]["role"] == "super_admin"
|
||||
|
||||
|
||||
def test_login_invalid_password(client, admin_user):
|
||||
response = client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"username_or_email": "test_admin", "password": "WrongPassword!"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert "Incorrect username or password" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_login_nonexistent_user(client):
|
||||
response = client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"username_or_email": "nonexistent_user", "password": "any_password"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_get_current_user_me(client, admin_token):
|
||||
response = client.get(
|
||||
"/api/v1/auth/me",
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["username"] == "test_admin"
|
||||
assert data["email"] == "admin@test.com"
|
||||
|
||||
|
||||
def test_get_current_user_unauthorized(client):
|
||||
response = client.get("/api/v1/auth/me")
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_logout(client, admin_token):
|
||||
response = client.post(
|
||||
"/api/v1/auth/logout",
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["message"] == "Successfully logged out"
|
||||
@@ -0,0 +1,154 @@
|
||||
import io
|
||||
import pytest
|
||||
|
||||
|
||||
SAMPLE_CSV = """srNo,mrdNumber,Gender,Age,PatientCategoryName,District,State,Country,Nationality,AdmissionDate,DischargeDate,bedNumber,BedLocation,BuildingName,AdmittingDoctorName,AdmittingDoctorSpecialityName,CorporateCompanyName,PolicyName,AdmissionType
|
||||
1,1001,Male,45,GNL,Pune,Maharashtra,India,Indian,01-01-2025 10:00,03-01-2025 12:00,101,Wing A,DMHRC,Dr. Jane Doe,MEDICINE,,,Emergency
|
||||
2,1002,Female,32,TPA,Mumbai,Maharashtra,India,Indian,02-01-2025 11:30,05-01-2025 16:45,202,Wing B,DMHSS,Dr. John Smith,CARDIOLOGY,Care Health,TPA,Walk-in
|
||||
3,1003,Male,60,TPA,Pune,Maharashtra,India,Indian,03-01-2025 09:15,04-01-2025 14:00,303,Wing C,DMHRC,Dr. Alice Brown,MEDICINE,Star Health,TPA,Emergency
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admission_dataset(client, admin_token):
|
||||
csv_file = io.BytesIO(SAMPLE_CSV.encode("utf-8"))
|
||||
upload_res = client.post(
|
||||
"/api/v1/datasets/upload",
|
||||
data={"name": "Admissions Query Test", "description": "For query tests"},
|
||||
files={"file": ("query_test.csv", csv_file, "text/csv")},
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert upload_res.status_code == 201
|
||||
ds = upload_res.json()["dataset"]
|
||||
|
||||
# Configure role permission for viewer with row rule: BuildingName == 'DMHRC'
|
||||
client.post(
|
||||
"/api/v1/permissions",
|
||||
json={
|
||||
"dataset_id": ds["id"],
|
||||
"role": "viewer",
|
||||
"can_view": True,
|
||||
"hidden_column_ids": [],
|
||||
"row_rules": [
|
||||
{
|
||||
"column_name": "BuildingName",
|
||||
"operator": "eq",
|
||||
"rule_value": "DMHRC"
|
||||
}
|
||||
]
|
||||
},
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
return ds
|
||||
|
||||
|
||||
def test_admin_queries_chart_successfully(client, admin_token, admission_dataset):
|
||||
query_payload = {
|
||||
"dataset_id": admission_dataset["id"],
|
||||
"chart_type": "bar",
|
||||
"dimension": "AdmittingDoctorSpecialityName",
|
||||
"measure": "*",
|
||||
"aggregation": "count"
|
||||
}
|
||||
response = client.post(
|
||||
"/api/v1/charts/query",
|
||||
json=query_payload,
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
res = response.json()
|
||||
assert res["chart_type"] == "bar"
|
||||
assert "MEDICINE" in res["categories"]
|
||||
assert "CARDIOLOGY" in res["categories"]
|
||||
assert res["total_records"] == 3
|
||||
|
||||
|
||||
def test_viewer_row_rules_enforced(client, viewer_token, admission_dataset):
|
||||
# Viewer is restricted to DMHRC only (rows 1 and 3, total 2 rows)
|
||||
query_payload = {
|
||||
"dataset_id": admission_dataset["id"],
|
||||
"chart_type": "bar",
|
||||
"dimension": "BuildingName",
|
||||
"measure": "*",
|
||||
"aggregation": "count"
|
||||
}
|
||||
response = client.post(
|
||||
"/api/v1/charts/query",
|
||||
json=query_payload,
|
||||
headers={"Authorization": f"Bearer {viewer_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
res = response.json()
|
||||
assert res["categories"] == ["DMHRC"]
|
||||
assert res["total_records"] == 2
|
||||
assert "DMHSS" not in res["categories"]
|
||||
|
||||
|
||||
def test_querying_restricted_sensitive_column_fails(client, viewer_token, admission_dataset):
|
||||
# mrdNumber is sensitive by default, viewer cannot query it
|
||||
query_payload = {
|
||||
"dataset_id": admission_dataset["id"],
|
||||
"chart_type": "bar",
|
||||
"dimension": "mrdNumber",
|
||||
"measure": "*",
|
||||
"aggregation": "count"
|
||||
}
|
||||
response = client.post(
|
||||
"/api/v1/charts/query",
|
||||
json=query_payload,
|
||||
headers={"Authorization": f"Bearer {viewer_token}"}
|
||||
)
|
||||
assert response.status_code == 403
|
||||
assert "restricted" in response.json()["detail"].lower()
|
||||
|
||||
|
||||
def test_kpi_query(client, admin_token, admission_dataset):
|
||||
query_payload = {
|
||||
"dataset_id": admission_dataset["id"],
|
||||
"chart_type": "kpi",
|
||||
"dimension": "srNo",
|
||||
"measure": "*",
|
||||
"aggregation": "count"
|
||||
}
|
||||
response = client.post(
|
||||
"/api/v1/charts/query",
|
||||
json=query_payload,
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
res = response.json()
|
||||
assert res["kpi_value"] == 3
|
||||
|
||||
|
||||
def test_stacked_bar_query(client, admin_token, admission_dataset):
|
||||
query_payload = {
|
||||
"dataset_id": admission_dataset["id"],
|
||||
"chart_type": "stacked_bar",
|
||||
"dimension": "PatientCategoryName",
|
||||
"secondary_dimension": "Gender",
|
||||
"measure": "*",
|
||||
"aggregation": "count"
|
||||
}
|
||||
response = client.post(
|
||||
"/api/v1/charts/query",
|
||||
json=query_payload,
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
res = response.json()
|
||||
assert len(res["series"]) >= 2
|
||||
series_names = [s["name"] for s in res["series"]]
|
||||
assert "Male" in series_names or "Female" in series_names
|
||||
|
||||
|
||||
def test_filter_options_endpoint(client, viewer_token, admission_dataset):
|
||||
response = client.get(
|
||||
f"/api/v1/charts/filter-options/{admission_dataset['id']}",
|
||||
headers={"Authorization": f"Bearer {viewer_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
opts = response.json()["options"]
|
||||
# Viewer row rule restricts to DMHRC
|
||||
buildings = [b["value"] for b in opts.get("BuildingName", [])]
|
||||
assert "DMHRC" in buildings
|
||||
assert "DMHSS" not in buildings
|
||||
@@ -0,0 +1,78 @@
|
||||
import io
|
||||
|
||||
|
||||
SAMPLE_CSV_DATA = """srNo,mrdNumber,Gender,Age,PatientCategoryName,District,State,Country,Nationality,AdmissionDate,DischargeDate,bedNumber,BedLocation,BuildingName,AdmittingDoctorName,AdmittingDoctorSpecialityName,CorporateCompanyName,PolicyName,AdmissionType
|
||||
1,1001,Male,45,GNL,Pune,Maharashtra,India,Indian,01-01-2025 10:00,03-01-2025 12:00,101,Wing A,DMHRC,Dr. Jane Doe,CARDIOLOGY,,,Emergency
|
||||
2,1002,Female,32,TPA,Mumbai,Maharashtra,India,Indian,02-01-2025 11:30,05-01-2025 16:45,202,Wing B,DMHSS,Dr. John Smith,NEUROLOGY,Care Health,TPA,Walk-in
|
||||
"""
|
||||
|
||||
|
||||
def test_viewer_cannot_upload_dataset(client, viewer_token):
|
||||
csv_file = io.BytesIO(SAMPLE_CSV_DATA.encode("utf-8"))
|
||||
response = client.post(
|
||||
"/api/v1/datasets/upload",
|
||||
data={"name": "Test Sample Dataset", "description": "Test only"},
|
||||
files={"file": ("sample.csv", csv_file, "text/csv")},
|
||||
headers={"Authorization": f"Bearer {viewer_token}"}
|
||||
)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_admin_uploads_dataset_successfully(client, admin_token):
|
||||
csv_file = io.BytesIO(SAMPLE_CSV_DATA.encode("utf-8"))
|
||||
response = client.post(
|
||||
"/api/v1/datasets/upload",
|
||||
data={"name": "Hospital Admissions Test", "description": "Test admissions"},
|
||||
files={"file": ("sample.csv", csv_file, "text/csv")},
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 201
|
||||
result = response.json()
|
||||
assert "registered successfully" in result["message"]
|
||||
dataset = result["dataset"]
|
||||
assert dataset["row_count"] == 2
|
||||
assert dataset["column_count"] == 19
|
||||
|
||||
# Check column metadata
|
||||
columns = dataset["columns"]
|
||||
assert len(columns) == 19
|
||||
|
||||
# Check sensitive flags
|
||||
col_map = {c["column_name"]: c for c in columns}
|
||||
assert col_map["mrdNumber"]["is_sensitive"] is True
|
||||
assert col_map["mrdNumber"]["is_identifier"] is True
|
||||
assert col_map["AdmittingDoctorName"]["is_sensitive"] is True
|
||||
assert col_map["Gender"]["is_sensitive"] is False
|
||||
|
||||
|
||||
def test_admin_updates_column_metadata(client, admin_token):
|
||||
# First upload a dataset for this test
|
||||
csv_file = io.BytesIO(SAMPLE_CSV_DATA.encode("utf-8"))
|
||||
upload_res = client.post(
|
||||
"/api/v1/datasets/upload",
|
||||
data={"name": "Hospital Admissions Test 2", "description": "Test admissions 2"},
|
||||
files={"file": ("sample2.csv", csv_file, "text/csv")},
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert upload_res.status_code == 201
|
||||
ds_id = upload_res.json()["dataset"]["id"]
|
||||
|
||||
# Fetch full dataset with columns
|
||||
detail_res = client.get(
|
||||
f"/api/v1/datasets/{ds_id}",
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert detail_res.status_code == 200
|
||||
columns = detail_res.json()["columns"]
|
||||
gender_col = next(c for c in columns if c["column_name"] == "Gender")
|
||||
|
||||
# Update Gender column to sensitive
|
||||
patch_res = client.patch(
|
||||
f"/api/v1/datasets/{ds_id}/columns/{gender_col['id']}",
|
||||
json={"display_name": "Patient Gender", "is_sensitive": True},
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert patch_res.status_code == 200
|
||||
updated_col = patch_res.json()
|
||||
assert updated_col["display_name"] == "Patient Gender"
|
||||
assert updated_col["is_sensitive"] is True
|
||||
@@ -0,0 +1,119 @@
|
||||
import pytest
|
||||
from app.models.dataset import Dataset, DatasetColumn
|
||||
from app.models.user import UserRole
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_dataset(db_session):
|
||||
ds = db_session.query(Dataset).filter(Dataset.name == "Perm Test Dataset").first()
|
||||
if not ds:
|
||||
ds = Dataset(
|
||||
name="Perm Test Dataset",
|
||||
source_type="file",
|
||||
table_name="ds_perm_test",
|
||||
row_count=100,
|
||||
column_count=3
|
||||
)
|
||||
db_session.add(ds)
|
||||
db_session.flush()
|
||||
|
||||
c1 = DatasetColumn(dataset_id=ds.id, column_name="id", display_name="ID", data_type="integer", is_sensitive=False, is_identifier=True)
|
||||
c2 = DatasetColumn(dataset_id=ds.id, column_name="doctor", display_name="Doctor", data_type="string", is_sensitive=True, is_identifier=False)
|
||||
c3 = DatasetColumn(dataset_id=ds.id, column_name="department", display_name="Department", data_type="string", is_sensitive=False, is_identifier=False)
|
||||
db_session.add_all([c1, c2, c3])
|
||||
db_session.commit()
|
||||
db_session.refresh(ds)
|
||||
return ds
|
||||
|
||||
|
||||
def test_viewer_cannot_set_permissions(client, viewer_token, sample_dataset):
|
||||
payload = {
|
||||
"dataset_id": sample_dataset.id,
|
||||
"role": "viewer",
|
||||
"can_view": True,
|
||||
"hidden_column_ids": [],
|
||||
"row_rules": []
|
||||
}
|
||||
response = client.post(
|
||||
"/api/v1/permissions",
|
||||
json=payload,
|
||||
headers={"Authorization": f"Bearer {viewer_token}"}
|
||||
)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_admin_sets_permissions(client, admin_token, sample_dataset):
|
||||
payload = {
|
||||
"dataset_id": sample_dataset.id,
|
||||
"role": "viewer",
|
||||
"can_view": True,
|
||||
"can_export": False,
|
||||
"hidden_column_ids": [sample_dataset.columns[2].id], # hide department
|
||||
"row_rules": [
|
||||
{
|
||||
"column_name": "department",
|
||||
"operator": "eq",
|
||||
"rule_value": "CARDIOLOGY"
|
||||
}
|
||||
]
|
||||
}
|
||||
response = client.post(
|
||||
"/api/v1/permissions",
|
||||
json=payload,
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["can_view"] is True
|
||||
assert len(data["column_permissions"]) == 1
|
||||
assert len(data["row_rules"]) == 1
|
||||
assert data["row_rules"][0]["rule_value"] == "CARDIOLOGY"
|
||||
|
||||
|
||||
def test_get_effective_permissions_super_admin(client, admin_token, sample_dataset):
|
||||
response = client.get(
|
||||
f"/api/v1/permissions/effective/{sample_dataset.id}",
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
eff = response.json()
|
||||
assert eff["can_view"] is True
|
||||
assert eff["can_export"] is True
|
||||
# Admin has all columns allowed, none hidden
|
||||
assert "doctor" in eff["allowed_columns"]
|
||||
assert len(eff["row_rules"]) == 0
|
||||
|
||||
|
||||
def test_get_effective_permissions_with_preview_role(client, admin_token, sample_dataset):
|
||||
# Set permission for viewer role first
|
||||
client.post(
|
||||
"/api/v1/permissions",
|
||||
json={
|
||||
"dataset_id": sample_dataset.id,
|
||||
"role": "viewer",
|
||||
"can_view": True,
|
||||
"can_export": False,
|
||||
"hidden_column_ids": [sample_dataset.columns[2].id],
|
||||
"row_rules": [
|
||||
{
|
||||
"column_name": "department",
|
||||
"operator": "eq",
|
||||
"rule_value": "CARDIOLOGY"
|
||||
}
|
||||
]
|
||||
},
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
|
||||
# Preview as viewer role
|
||||
response = client.get(
|
||||
f"/api/v1/permissions/effective/{sample_dataset.id}?preview_role=viewer",
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
eff = response.json()
|
||||
# Sensitive column doctor is hidden for non-admin
|
||||
assert "doctor" in eff["hidden_columns"]
|
||||
assert "department" in eff["hidden_columns"]
|
||||
assert len(eff["row_rules"]) == 1
|
||||
assert eff["row_rules"][0]["rule_value"] == "CARDIOLOGY"
|
||||
@@ -0,0 +1,83 @@
|
||||
def test_admin_can_list_users(client, admin_token):
|
||||
response = client.get(
|
||||
"/api/v1/users",
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
users = response.json()
|
||||
assert isinstance(users, list)
|
||||
assert len(users) >= 1
|
||||
|
||||
|
||||
def test_viewer_cannot_list_users(client, viewer_token):
|
||||
response = client.get(
|
||||
"/api/v1/users",
|
||||
headers={"Authorization": f"Bearer {viewer_token}"}
|
||||
)
|
||||
assert response.status_code == 403
|
||||
assert "Super admin privileges required" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_admin_creates_user(client, admin_token):
|
||||
new_user_payload = {
|
||||
"username": "new_clinical_user",
|
||||
"email": "clinical@dmh.org",
|
||||
"password": "Password123!",
|
||||
"full_name": "Dr. Sarah",
|
||||
"role": "viewer",
|
||||
"is_active": True
|
||||
}
|
||||
response = client.post(
|
||||
"/api/v1/users",
|
||||
json=new_user_payload,
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 201
|
||||
created = response.json()
|
||||
assert created["username"] == "new_clinical_user"
|
||||
assert created["email"] == "clinical@dmh.org"
|
||||
assert created["role"] == "viewer"
|
||||
|
||||
|
||||
def test_cannot_create_duplicate_username(client, admin_token, admin_user):
|
||||
payload = {
|
||||
"username": admin_user.username,
|
||||
"email": "another_email@dmh.org",
|
||||
"password": "Password123!",
|
||||
"role": "viewer"
|
||||
}
|
||||
response = client.post(
|
||||
"/api/v1/users",
|
||||
json=payload,
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 409
|
||||
|
||||
|
||||
def test_admin_updates_user(client, admin_token, viewer_user):
|
||||
update_payload = {
|
||||
"full_name": "Updated Name",
|
||||
"role": "department_manager"
|
||||
}
|
||||
response = client.put(
|
||||
f"/api/v1/users/{viewer_user.id}",
|
||||
json=update_payload,
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
updated = response.json()
|
||||
assert updated["full_name"] == "Updated Name"
|
||||
assert updated["role"] == "department_manager"
|
||||
|
||||
|
||||
def test_list_roles(client, viewer_token):
|
||||
response = client.get(
|
||||
"/api/v1/roles",
|
||||
headers={"Authorization": f"Bearer {viewer_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
roles = response.json()
|
||||
assert len(roles) >= 4
|
||||
role_names = [r["role"] for r in roles]
|
||||
assert "super_admin" in role_names
|
||||
assert "viewer" in role_names
|
||||
Reference in New Issue
Block a user