Files
Data_Visualisation_DMH/docs/IMPLEMENTATION_PLAN.md
T

8.0 KiB
Raw Blame History

DMH Role-Based Data Visualisation Platform — Implementation Plan

Platform Purpose: A governed healthcare analytics platform for hospital admission records (initial dataset: admissionData-2025_v1.csv, 86,099 rows, 19 fields). A super admin controls exactly which data each user or role may see; all other users log in and view interactive charts strictly scoped to their permitted slice. The system is designed to transition seamlessly from flat file uploads to live enterprise databases without code refactoring.


1. Guiding Principles & Architecture

The One Rule That Matters Most

The browser must never receive data the user is not allowed to see. All permission checks, column masking, row filtering, and aggregations happen strictly on the backend. The frontend client sends a declarative JSON chart specification (ChartSpec), never raw SQL. The backend validates every field against a whitelist, injects user/role row rules, runs a parameterized SQLAlchemy Core query, and returns only the aggregated result.

flowchart TD
    Client["Browser / React Client"] -->|"Declarative JSON ChartSpec (No SQL)"| API["FastAPI Gateway"]
    API --> Auth["JWT & RBAC Middleware"]
    Auth --> Perm["Permission & Rule Evaluator"]
    Perm -->|"Inject Row Rules & Check Column Whitelist"| QueryEngine["SQLAlchemy Core Aggregation Engine"]
    QueryEngine -->|"Parameterized Core SQL"| DB[("PostgreSQL / SQLite Database\n(ds_hospital_admissions_2025)")]
    DB -->|"Aggregated Summary Only"| QueryEngine
    QueryEngine -->|"Safe Summary JSON"| Client
    
    subgraph Privacy_Enforcement["Security Boundary"]
        Perm
        QueryEngine
    end

2. Technology Stack

Layer Component Purpose & Implementation
Backend API FastAPI (Python 3.11+) Async REST endpoints, Pydantic v2 request/response validation, dependency injection
Data Engine SQLAlchemy 2.0 Core Whitelisted column expressions, dynamic table binding, parameterized SQL, zero f-string SQL
Migrations Alembic Schema versioning; dynamic data tables (ds_*) excluded via include_object filter
Authentication Argon2-cffi & PyJWT Password hashing resistant to GPU cracking; signed JWT access tokens with 8-hour TTL
Database PostgreSQL 16 (SQLite for Dev/Test) Ingested 86,099 hospital inpatient records across 19 fields
Frontend UI React 18, Vite, TypeScript Type-safe single-page web app with strict compiler checks (noUnusedLocals)
State & Cache TanStack Query v5 Automatic background query caching, query invalidation on filter/role change
Visualisation Apache ECharts (echarts-for-react) Responsive canvas/SVG charts with custom DMH palette, tooltips, and animations
Styling Tailwind CSS & Lucide Icons Clean healthcare SaaS interface, responsive layouts, role badges, simulation toolbar
Deployment Docker Compose & Nginx Reverse proxy, static asset serving, multi-container orchestration

3. Implementation Status Overview

Phase Description Status Test Coverage
Phase 1: Foundation JWT Auth, Argon2 hashing, User CRUD, CSV ingestion engine (86,099 rows), Alembic COMPLETED 15 unit tests passing
Phase 2: Access Control Dataset/Column/Row rules, AND intersection, Super Admin simulation ("Preview As") COMPLETED 4 unit tests passing
Phase 3: Visualisation SQLAlchemy Core aggregation engine, 4 KPI cards, 5 ECharts widgets, dynamic filters COMPLETED 6 unit tests passing
Phase 3.5: Advanced Analytics Average Length of Stay (ALOS), Day-vs-Hour Heatmap, Districts spread, Cross-filtering READY TO BUILD Specs defined
Phase 4: Governance Tamper-evident audit logging, Excel/CSV exports, DPDP Act small-group suppression SCHEDULED Specs defined
Phase 5: Live Database Live DB connectors (Postgres/MySQL), encrypted credentials, caching, Docker Compose SCHEDULED Architecture planned

4. Phase-by-Phase Detailed Plan

Phase 3.5 — Advanced Healthcare Analytics & Cross-Filtering

Goal: Provide clinical and operational metrics requested by hospital leadership.

  1. Average Length of Stay (ALOS) Analysis:
    • Compute (julianday(DischargeDate) - julianday(AdmissionDate)) in SQLite, and EXTRACT(EPOCH FROM DischargeDate - AdmissionDate)/86400 in Postgres.
    • Display overall hospital ALOS (days) in a KPI card.
    • Add "ALOS by Speciality" bar chart to pinpoint long-stay clinical departments.
  2. Day-of-Week vs. Hour-of-Day Admission Heatmap:
    • Aggregated 2D matrix: Day (Monday–Sunday) \times Hour (00:00–23:00).
    • Apache ECharts visual heatmap to visualize peak emergency intake surge times.
  3. Geographic Distribution (District & State):
    • Analysis of regional intake: Pune vs. rural Maharashtra vs. neighboring states.
    • Top 10 districts horizontal bar chart with percentage share.
  4. Interactive Cross-Filtering:
    • Clicking a department in the Speciality chart automatically sets the dashboard filter to that department and triggers re-query for all other widgets.
  5. Chart Image Export:
    • Enable Apache ECharts toolbox (saveAsImage) with high-resolution PNG export.

Phase 4 — Governance, Compliance & Export Engine

Goal: Meet enterprise audit standards and India's Digital Personal Data Protection (DPDP) Act.

  1. Audit Logging System (audit_logs table):
    • Tracks: user_id, action (LOGIN, CHART_QUERY, PERMISSION_CHANGE, EXPORT), resource, query_params (JSON), ip_address, timestamp.
    • Every chart query and simulation execution records an audit entry.
  2. Admin Audit Viewer Screen (/admin/audit-logs):
    • Paginated, filterable table allowing Super Admins to search access history by user, date range, or action type.
  3. Privacy Compliance ($k$-Anonymity / Small-Group Suppression):
    • If an aggregated query group has fewer than 5 patients, automatically mask the count or group into "Other (< 5)" to prevent patient re-identification.
  4. Role-Gated Aggregated Data Exports:
    • Export permitted chart data to CSV and styled .xlsx using openpyxl.
    • Backend enforces can_export == True; unauthorized users receive HTTP 403.
    • Exports include hospital watermark metadata and generation timestamp.

Phase 5 — Live Enterprise Database Connector & Packaging

Goal: Enable real-time database connectivity and production container deployment.

  1. Database Connector Service:
    • Support connecting to external PostgreSQL, MySQL, and SQL Server databases.
    • Store database credentials securely using symmetric encryption (cryptography.fernet).
    • Connection test endpoint (POST /api/v1/connectors/test).
  2. Performance Caching Layer:
    • In-memory / Redis cache for common aggregated chart queries with configurable TTL (e.g., 5 minutes).
    • Invalidation hooks on new dataset upload or permission updates.
  3. Docker Compose & Deployment Hardening:
    • Nginx reverse proxy with gzip compression and cache-control headers.
    • Production Docker containers for Postgres 16, FastAPI backend, and Nginx frontend.

5. Acceptance Verification Matrix

Milestone Key Verification Criteria Target
Phase 1 (Delivered) 86,099 rows ingested, Argon2 JWT login, Super Admin User CRUD PASSED (15 tests)
Phase 2 (Delivered) Dept Manager limited to Medicine (9,770 rows), Finance to TPA (32,056 rows), 403 on mrdNumber PASSED (4 tests)
Phase 3 (Delivered) Live ECharts dashboard, 4 KPIs, 5 visualisations, dynamic building/speciality filters PASSED (6 tests)
Phase 3.5 (Next) ALOS calculated in days, 7x24 heatmap renders, cross-filtering updates widgets Target: Next Turn
Phase 4 Audit entries created on every query, k < 5 suppressed, CSV export gated Target: Phase 4
Phase 5 External PostgreSQL connector connects, Docker Compose boots all 3 containers Target: Phase 5