# DMH Role-Based Data Visualisation Platform — System Documentation **Author / Engineering Lead:** AI Engineering Team **Client / Organisation:** Deenanath Mangeshkar Hospital (DMH), Pune **Current Date:** 24 November 2026 **Initial Dataset:** `admissionData-2025_v1.csv` (86,099 inpatient records, 19 fields) **System Status:** Phases 1–3 Complete & Verified (25/25 Tests Passing); Phases 3.5–5 Planned --- ## 1. Executive Summary & Problem Context Healthcare organisations manage large, highly sensitive operational datasets. Historically, these datasets are consumed in one of two suboptimal ways: 1. **Uncontrolled Spreadsheets**: Raw CSV or Excel exports containing sensitive patient-level data are circulated via email or shared drives, resulting in data staleness and compliance violations. 2. **Rigid, Expensive Ad-Hoc Reports**: Each department requests custom reports from developers, creating engineering bottlenecks and lack of self-service agility. In hospital environments, access must be strictly role-governed: * **Department Managers** (e.g., Medicine, Oncology, Cardiology) should only see operational data for their respective departments. * **Finance & Billing Analysts** need access to payer mix, corporate insurance claims (TPA), and policy categories, but should not access clinical medical notes. * **Hospital Executive Leadership** requires an aggregate, hospital-wide view across all buildings and specialties. * **Patient Privacy**: Direct identifiers (Medical Record Numbers `mrdNumber`, Doctor Identifiers) must be strictly masked by default. ### The Problem Statement Build a web-based, role-governed healthcare visualization platform that enables a **Super Admin** to connect data sources, configure exact column masking and row-level access rules per user or role, and deliver interactive charts (pie, bar, line, area, KPI cards, heatmaps) that are **strictly confined to permitted data slices**. The platform must ingest flat files initially and transition to live client databases without architectural rework. --- ## 2. "The One Rule That Matters Most" > **The browser must never receive data the user is not allowed to see.** * **No Client-Side Filtering**: Hiding chart elements, blurring table cells, or filtering arrays in the browser is prohibited. A user inspecting network traffic (DevTools) must never see unpermitted rows or columns. * **No Client-Supplied SQL**: The frontend sends a declarative JSON chart specification (`ChartSpec`), never SQL. * **Server-Side Enforcement**: All column whitelisting, row-rule injection, and mathematical aggregations occur exclusively on the backend. * **Zero SQL Injection**: Queries are built via SQLAlchemy 2.0 Core using bound parameters and schema-whitelisted column objects. String concatenation or f-strings for SQL are strictly prohibited. * **Zero Raw Records to Browser**: Only aggregated data points (e.g., `{"name": "MEDICINE", "value": 9770}`) are returned to the client. ```mermaid flowchart TD subgraph Frontend["Frontend Layer (React 18 + Vite)"] UI["Dashboard / ECharts"] FilterBar["Interactive Filter Bar"] UI -->|"1. User triggers filter / chart view"| Client Client["JSON ChartSpec\n(dimension, aggregation, filters)"] end subgraph BackendGateway["FastAPI Gateway"] AuthMid["2. JWT Bearer Auth & Role Check"] PermEngine["3. Permission Evaluator\n- Whitelist Columns\n- Intersect Row Rules"] end subgraph CoreEngine["Data Layer (SQLAlchemy 2.0 Core)"] Builder["4. Dynamic Query Builder\n(Bound Parameters Only)"] DB[("Database\nds_hospital_admissions_2025\n(86,099 rows)")] end Client -->|"POST /api/v1/charts/query"| AuthMid AuthMid --> PermEngine PermEngine -->|"Allowed Column Objects & Injected WHERE clauses"| Builder Builder -->|"SELECT dim, count() WHERE role_rule = val GROUP BY dim"| DB DB -->|"Aggregated counts only (No raw rows)"| Builder Builder -->|"JSON ChartResult"| UI ``` --- ## 3. Technology Stack | Layer | Technology | Architectural Purpose | |---|---|---| | **Backend API** | Python 3.11 / 3.13 + FastAPI | Asynchronous REST endpoints, OpenAPI documentation, Pydantic v2 validation | | **Data Engine** | SQLAlchemy 2.0 Core | Dynamic schema generation, parameterized SQL compilation, column whitelisting | | **Migrations** | Alembic | System table migrations; dynamic data tables (`ds_*`) excluded via custom filter | | **Security & Auth** | `argon2-cffi` + `PyJWT` | Password hashing resistant to GPU cracking; signed JWT access tokens (8h TTL) | | **Primary Database** | PostgreSQL 16 (SQLite for Dev/Test) | Relational storage for metadata and dynamic data tables | | **Frontend Framework**| React 18 + TypeScript + Vite | Type-safe single-page web app with strict compilation rules (`noUnusedLocals`) | | **State & Networking**| TanStack Query v5 | Automatic query caching, background re-fetching, cache invalidation | | **Visualisation** | Apache ECharts (`echarts-for-react`)| Production-grade, high-performance canvas/SVG charts with DMH healthcare palette | | **Styling & UI** | Tailwind CSS + Lucide Icons | Responsive layout, modern healthcare SaaS aesthetics, simulation toolbar | | **Packaging** | Docker Compose + Nginx | Reverse proxy, static asset serving, multi-container deployment | --- ## 4. What Has Been Developed (Phases 1–3 Complete) ### Module 1: Authentication & User Management (Phase 1) * **Argon2 Password Hashing**: Passwords stored as irreversible Argon2id hashes. * **JWT Token Security**: Stateless bearer tokens signed with `HS256`, containing user ID, username, and active role. * **Role Hierarchy**: 4 system roles defined (`super_admin`, `viewer`, `department_manager`, `finance`). * **Super Admin User Console**: * `GET /api/v1/users`: List registered users with roles and status. * `POST /api/v1/users`: Create new users with role assignments and password policies. * `PUT /api/v1/users/{id}`: Modify user profile, change roles, activate/deactivate accounts. * `DELETE /api/v1/users/{id}`: Safely remove user accounts. * Non-super admins attempting to access these endpoints receive **HTTP 403 Forbidden**. ### Module 2: High-Performance Data Ingestion Engine (Phase 1) * **Generic Ingestion Pipeline**: Ingests flat CSV files via `POST /api/v1/datasets/upload`. * **Hospital Admission Parser**: * Accurately parses `DD-MM-YYYY HH:MM` timestamps (e.g. `01-01-2025 00:06`) into ISO `DATETIME` columns. * Handles empty strings / cash patient blanks cleanly. * Treats `bedNumber` as text. * **Dynamic Table Creation**: Builds dynamic tables (`ds_hospital_admissions_2025`) using SQLAlchemy Core `Table` constructs. * **Batch Ingestion**: Uses chunked bulk inserts (5,000 rows/batch) to ingest all **86,099 rows and 19 columns** in under 5 seconds. * **Automatic Column Classification**: Automatically identifies and marks sensitive fields (`mrdNumber`, `AdmittingDoctorName`) as `is_sensitive=True`. ### Module 3: Access Control Matrix & Rule Intersection (Phase 2) * **Three Levels of Access Control**: 1. **Dataset Grants**: Defines whether a user or role can view or export a specific dataset (`can_view`, `can_export`). 2. **Column Masking**: Explicit list of hidden columns. Sensitive columns are masked for non-super admins by default. 3. **Row-Level Rules**: Parameterized rules (e.g. `BuildingName = 'DMHRC'`, `AdmittingDoctorSpecialityName = 'MEDICINE'`, `PatientCategoryName = 'TPA'`). * **AND-Rule Intersection**: If multiple permissions apply to a user (user-specific + role-based), the system applies the strict mathematical intersection (all row filters combined with `AND`; columns hidden if hidden in either). * **Super Admin "Preview As" Simulation Tool**: Super Admins can simulate restricted user views (`viewer`, `department_manager`, `finance`) directly in the header to audit exactly what each role sees. ### Module 4: SQLAlchemy Core Aggregation Engine (Phase 3) * **Declarative Specification**: Frontend sends a typed `ChartSpec`: ```json { "dataset_id": 1, "chart_type": "bar", "dimension": "AdmittingDoctorSpecialityName", "measure": "*", "aggregation": "count", "filters": [{"column": "BuildingName", "operator": "eq", "value": "DMHRC"}], "limit": 10 } ``` * **Security Validation**: * Verifies dataset access rights. * Rejects queries requesting restricted dimensions, measures, or filter columns with **HTTP 403**. * Dynamically binds row rules to the SQLAlchemy query. * Compiles parameterized SQL with bound parameters. * **Performance Aggregation**: Returns only grouped aggregations. Raw rows are never transmitted across the network. ### Module 5: Interactive Apache ECharts Dashboard (Phase 3) * **4 Executive KPI Cards**: Total Admissions, Average Patient Age, Active Clinical Specialities, Hospital Wings. * **Admissions by Medical Speciality**: Ranked horizontal/vertical bar chart showing department volumes. * **Admissions by Hospital Building**: Donut chart displaying facility distribution (`DMHRC`, `DMHSS`). * **Monthly Admission Trend**: Smooth area chart tracking inpatient intake throughout 2025. * **Admission Categories**: Pie chart of Emergency vs. Walk-in admissions. * **Demographics & Payer Mix**: Multi-series stacked bar chart combining insurance categories (`GNL` vs `TPA`) across genders. * **Permission-Scoped Filter Bar**: Dropdown filters for Building, Speciality, and Admission Type that only display values permitted under the active user's permissions. --- ## 5. Live Verification Metrics on the Ingested Dataset The platform was seeded and tested directly against the full `admissionData-2025_v1.csv` dataset. The verified query outputs: | Scenario / Role | Enforced Rules | Verified Aggregated Result | Security Verification | |---|---|---|---| | **Super Admin (Unrestricted)** | None (full access) | **86,099 Total Admissions** | All 19 columns accessible | | **Top Specialities (Admin)** | None | Oncology: 18,536
Medicine: 9,770
Ophthalmology: 5,366
OB/GYN: 5,264
Nephrology: 5,044 | Verified exact row counts | | **Department Manager** | `Speciality = 'MEDICINE'` | **9,770 Admissions** | Non-Medicine rows excluded by server | | **Finance User** | `PatientCategory = 'TPA'` | **32,056 Admissions** | Cash / GNL rows excluded by server | | **Restricted Viewer** | Sensitive masking | `mrdNumber` query rejected | **HTTP 403 Forbidden** | ### Automated Test Suite Status * **Backend Pytest**: **25 out of 25 unit tests passing** (7.27 seconds execution time). * `test_auth.py`: 6/6 tests passing (login, invalid creds, token expiration, profile endpoint). * `test_users.py`: 6/6 tests passing (RBAC boundaries, user CRUD, duplicate checks). * `test_datasets.py`: 3/3 tests passing (upload, column typing, sensitive flagging). * `test_permissions.py`: 4/4 tests passing (permission CRUD, effective permissions, preview-as). * `test_charts.py`: 6/6 tests passing (KPI queries, stacked bars, row rules, 403 column rejection, filter options). * **Frontend Production Build**: Vite compiled **2,134 modules** into `dist/` with **zero TypeScript errors**. --- ## 6. What Is Remaining to Develop (Roadmap) ### Phase 3.5 — Advanced Healthcare Analytics & Cross-Filtering (Next Step) 1. **Average Length of Stay (ALOS) Analysis**: - Compute `DischargeDate - AdmissionDate` in days across SQLite and PostgreSQL. - Display overall hospital ALOS KPI card plus a department-level ALOS ranking chart. 2. **Day-of-Week vs. Hour-of-Day Admission Surge Heatmap**: - 2D matrix ($7 \text{ days} \times 24 \text{ hours}$) showing peak emergency admission hours to assist hospital bed allocation. 3. **Geographic Distribution (District & State)**: - In-state (Pune, Satara, Solapur, Ahmednagar) vs. out-of-state patient volume breakdown. 4. **Interactive Cross-Filtering**: - Clicking a department in the Speciality chart automatically filters all other charts to that department. 5. **Chart Image Export**: - High-resolution PNG/SVG export via the ECharts toolbox. ### Phase 4 — Governance, Compliance & Export Engine 1. **Tamper-Evident Audit Logging**: - `audit_logs` table tracking: `user_id`, `action` (`LOGIN`, `CHART_QUERY`, `PERMISSION_CHANGE`, `EXPORT`), `resource`, `query_params`, `ip_address`, and `timestamp`. 2. **Admin Audit Trail Viewer Screen (`/admin/audit-logs`)**: - Searchable, filterable audit log interface for compliance officers. 3. **India DPDP Act Compliance ($k$-Anonymity / Small-Group Suppression)**: - Automatically suppress or lump groups with $< 5$ patients into `"Other (< 5)"` to eliminate patient re-identification risks. 4. **Role-Gated Data Exports**: - Export permitted chart data to CSV and formatted `.xlsx` (via `openpyxl`), strictly gated by the `can_export` flag. ### Phase 5 — Live Enterprise Database Connector & Production Deployment 1. **External Database Connector Wizard**: - Connect directly to external PostgreSQL, MySQL, and Microsoft SQL Server databases. - Encrypt database connection strings at rest using symmetric encryption (`cryptography.fernet`). 2. **Scheduled Refresh & Caching**: - In-memory / Redis query caching for high-concurrency performance ($< 50\text{ms}$ response times). 3. **Production Packaging**: - Multi-container Docker Compose configuration (`postgres`, `backend`, `frontend` behind Nginx). --- ## 7. Project File Structure Reference ``` DMH-Data-visualisation/ ├── backend/ │ ├── alembic/ # Alembic database migrations │ ├── app/ │ │ ├── api/v1/ # auth, users, datasets, permissions, charts │ │ ├── core/ # security (argon2, pyjwt), custom exceptions │ │ ├── models/ # User, Dataset, DatasetColumn, DatasetPermission, RowRule │ │ ├── schemas/ # Pydantic v2 schemas │ │ ├── services/ # Ingestion, Permissions, Chart aggregation engine │ │ ├── config.py # Pydantic settings │ │ ├── database.py # SQLAlchemy 2.0 Core engine & Session │ │ └── main.py # FastAPI application │ ├── scripts/seed.py # Database seeder (86,099 rows + roles) │ ├── tests/ # 25 automated pytest tests │ ├── Dockerfile │ └── requirements.txt ├── frontend/ │ ├── src/ │ │ ├── api/ # client, auth, users, datasets, permissions, charts │ │ ├── components/charts/ # EChartRenderer, DashboardFilters, PreviewAsBanner │ │ ├── pages/ # LoginPage, DashboardPage, AdminUsers, AdminDatasets, AdminPermissions │ │ ├── context/ # AuthContext │ │ └── types/ # TypeScript types │ ├── Dockerfile │ ├── nginx.conf │ └── package.json ├── data/admissionData-2025_v1.csv # 86,099 records ├── docs/ # Implementation plan, acceptance reports ├── docker-compose.yml └── README.md ``` --- ## 8. Developer Quick-Start Guide ### Backend Execution ```powershell cd backend .venv\Scripts\activate python scripts/seed.py uvicorn app.main:app --reload --port 8000 ``` Swagger UI: `http://localhost:8000/docs` ### Frontend Execution ```powershell cd frontend npm run dev ``` Web App: `http://localhost:5173` ### Pre-Configured Demo Accounts | Role | Username | Password | Access Scope | |---|---|---|---| | **Super Admin** | `admin` | `Admin@123456` | Unrestricted full hospital access. | | **Clinical Staff Viewer** | `viewer` | `Viewer@123456` | General view; sensitive columns masked. | | **Department Manager** | `dept_manager` | `Manager@123456` | Row rule: **Medicine** department only (9,770 rows). | | **Finance / Billing** | `finance_user` | `Finance@123456` | Row rule: **TPA** insurance only (32,056 rows). |