168 lines
6.0 KiB
Python
168 lines
6.0 KiB
Python
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"
|
|
)
|
|
),
|
|
]
|