﻿# HAD Digital - Developer README

**Version:** 1.0.0  
**Date:** 5 September 2026  
**Author:** Dr Kais Aldabbagh, Polyclinique St Come - Medical Oncology

---

## Quick Start

### Running the Application

**Option 1: Run the .exe (Recommended)**

1. Navigate to: C:\AI Projects\Kais Project\MVP\dist\HAD Digital\
2. Double-click HAD Digital.exe
3. Open your browser to: http://127.0.0.1:8080
4. Login with: dmin / dmin123

**Option 2: Run from Source**

1. Open a terminal
2. Navigate to: C:\AI Projects\Kais Project\MVP\
3. Run: python app.py
4. Open your browser to: http://127.0.0.1:8080
5. Login with: dmin / dmin123

---

## Project Structure

```text
C:\AI Projects\Kais Project\MVP\
├── app.py                    # Main HTTP server (19 API endpoints)
├── database.py               # SQLite database manager
├── user_store.py             # Authentication with scrypt hashing
├── ctcae_engine.py           # CTCAE grading engine
├── alert_engine.py           # Tiered alert routing
├── audit_logger.py           # Immutable audit log
├── seed_demo.py              # Demo data seeder
├── config_manager.py         # Configuration manager
├── config.json               # Application configuration
├── adapters/                 # AI adapter system
│   ├── base.py               # Base adapter interface
│   ├── stub.py               # Stub adapter (offline demo)
│   └── glm.py                # GLM adapter (online AI)
├── static/                   # Frontend files
│   ├── index.html            # Main HTML page
│   ├── app.css               # Styles (29 KB)
│   └── app.js                # Application logic (30 KB)
├── data/                     # Data files
│   ├── had.db                # SQLite database (auto-created)
│   └── ctcae_rules.json      # CTCAE grading rules (14 KB)
├── guidance/                 # Patient guidance
│   └── guidance.json         # Guidance content (24 KB)
└── dist/                     # Distribution files
    └── HAD Digital/          # Built .exe bundle
        ├── HAD Digital.exe   # Standalone executable
        ├── static/           # Frontend files
        ├── data/             # Data files
        └── guidance/         # Guidance files
```

---

## Architecture

### Backend (Python)

The backend is a pure Python HTTP server using the built-in http.server module. No external dependencies are required.

**Key Components:**

1. **app.py** - Main HTTP server with 19 API endpoints
2. **database.py** - SQLite database manager with WAL mode
3. **user_store.py** - Authentication with scrypt password hashing
4. **ctcae_engine.py** - CTCAE grading engine with rule-based logic
5. **alert_engine.py** - Tiered alert routing (routine/urgent/emergency)
6. **audit_logger.py** - Immutable audit trail
7. **config_manager.py** - Configuration with environment variable overrides
8. **adapters/** - Pluggable AI adapter system

**Design Principles:**

- Zero external dependencies (pure Python standard library)
- SQLite for zero-config database
- Session-based authentication with HttpOnly cookies
- Role-based access control for 8 user roles
- Immutable audit trail for all clinical actions

### Frontend (HTML/CSS/JS)

The frontend is a single-page application (SPA) using vanilla HTML, CSS, and JavaScript. No framework dependencies.

**Key Features:**

- Mobile-first responsive design
- Large touch targets for patient usability
- Role-based navigation (different views for different roles)
- Real-time alerts and notifications
- Structured symptom reporting with CTCAE domains

### Database (SQLite)

The database uses SQLite with WAL (Write-Ahead Logging) mode for better concurrency and data integrity.

**Key Tables:**

- users - User accounts with role-based access
- patients - Patient demographics and medical info
- episodes - Care episodes (HAD stays)
- 	reatment_plans - Treatment protocols and schedules
- 	oxicity_reports - Patient and clinician symptom reports
- 	oxicity_grades - CTCAE grades (auto-assigned and confirmed)
- lerts - Clinical alerts (routine/urgent/emergency)
- messages - Care team messages
- 	imeline_events - Care coordination timeline
- udit_log - Immutable audit trail

---

## API Endpoints

### Authentication

| Method | Path | Description |
|--------|------|-------------|
| POST | /api/login | Login with username/password |
| POST | /api/logout | Logout and destroy session |
| GET | /api/whoami | Get current user info |

### Patients

| Method | Path | Description |
|--------|------|-------------|
| GET | /api/patients | List patients (role-filtered) |
| GET | /api/patients/{id} | Get patient details |

### Toxicity Reports

| Method | Path | Description |
|--------|------|-------------|
| POST | /api/reports | Submit toxicity report |
| GET | /api/reports | List reports |

### CTCAE Grades

| Method | Path | Description |
|--------|------|-------------|
| GET | /api/grades | List CTCAE grades |
| GET | /api/symptoms | List CTCAE symptom terms |

### Alerts

| Method | Path | Description |
|--------|------|-------------|
| GET | /api/alerts | List alerts |
| POST | /api/alerts/{id}/acknowledge | Acknowledge alert |

### Timeline

| Method | Path | Description |
|--------|------|-------------|
| GET | /api/timeline | Get care timeline |

### Treatment Plan

| Method | Path | Description |
|--------|------|-------------|
| GET | /api/treatment-plan | Get treatment plan |

### Messages

| Method | Path | Description |
|--------|------|-------------|
| POST | /api/messages | Send message |
| GET | /api/messages | List messages |

### Export

| Method | Path | Description |
|--------|------|-------------|
| GET | /api/export/summary | Export toxicity summary |

### Guidance

| Method | Path | Description |
|--------|------|-------------|
| GET | /api/guidance | Get patient guidance |

### Audit

| Method | Path | Description |
|--------|------|-------------|
| GET | /api/audit-log | Get audit trail |

### AI Chat

| Method | Path | Description |
|--------|------|-------------|
| POST | /api/chat | AI chat (stub adapter) |

---

## Configuration

### config.json

```json
{
  "app_name": "HAD Digital MVP",
  "version": "1.0.0",
  "host": "127.0.0.1",
  "port": 8080,
  "debug": false,
  "database": {
    "path": "data/had.db",
    "wal_mode": true
  },
  "session": {
    "cookie_name": "HAD_SESSION",
    "max_age_seconds": 86400
  },
  "ai": {
    "adapter": "stub"
  }
}
```

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| HAD_HOST | Server host | 127.0.0.1 |
| HAD_PORT | Server port | 8080 |
| HAD_DEBUG | Debug mode | false |
| HAD_DB_PATH | Database path | data/had.db |
| HAD_SESSION_SECRET | Session secret | (auto-generated) |
| HAD_AI_ADAPTER | AI adapter | stub |
| GLM_API_KEY | GLM API key | (none) |

---

## Demo Users

| Username | Password | Role | Display Name |
|----------|----------|------|--------------|
| admin | admin123 | admin | Marie Dupont |
| dr.martin | demo123 | oncologist | Dr Martin |
| inf.moret | demo123 | had_nurse | Nurse Moret |
| nurse.leroy | demo123 | community_nurse | Nurse Leroy |
| dr.thomas | demo123 | gp | Dr Thomas |
| pharm.garcia | demo123 | pharmacist | Pharmacist Garcia |
| patient.durand | demo123 | patient | Marie Durand |
| caregiver.durand | demo123 | caregiver | Pierre Durand |

---

## Building the .exe

### Prerequisites

- Python 3.13+
- PyInstaller (pip install pyinstaller)

### Build Command

```bash
cd "C:\AI Projects\Kais Project\MVP"
python -m PyInstaller --noconfirm --clean --onedir --name "HAD Digital" --add-data "static;static" --add-data "data;data" --add-data "guidance;guidance" --add-data "adapters;adapters" --hidden-import adapters --hidden-import adapters.stub --hidden-import adapters.glm --hidden-import adapters.base app.py
```

### Output

The built .exe is in: C:\AI Projects\Kais Project\MVP\dist\HAD Digital\

---

## Documentation

| Document | Path | Description |
|----------|------|-------------|
| API Contract | 03_Architecture/API_Contract.md | Full API documentation |
| Database Schema | 03_Architecture/Database_Schema.md | Database tables and relationships |
| Escalation Protocol | 02_Requirements/Escalation_Protocol.md | Clinical escalation rules |
| Role Permissions | 02_Requirements/Role_Permissions.md | Access control matrix |
| CTCAE Terms | 02_Requirements/CTCAE_Term_Subset.md | Prioritized CTCAE terms |
| User Stories | 02_Requirements/User_Stories.md | 23 user stories with acceptance criteria |
| MVP Plan | MVP_PLAN.md | Project planning document |
| Execution Plan | MVP_EXECUTION_PLAN.md | Full execution plan |
| Specification | HAD_Digital_Specifications.docx | Original specification |

---

## Development Notes

### What's Built

- ✅ All 19 API endpoints
- ✅ SQLite database with 10 tables
- ✅ Authentication with scrypt hashing
- ✅ CTCAE grading engine (12 terms)
- ✅ Tiered alert routing (3 tiers)
- ✅ Patient guidance content (French)
- ✅ Role-based access control (8 roles)
- ✅ Mobile-first responsive UI
- ✅ Standalone .exe (18 MB)
- ✅ Demo data (3 patients)

### What's Not Built (Future Phases)

- ❌ Multi-factor authentication
- ❌ SMS/phone notifications
- ❌ Offline mode with sync
- ❌ Full CTCAE v5.0 (790+ terms)
- ❌ Lab value integration
- ❌ Connected device integration
- ❌ Mon Espace Sante interoperability
- ❌ HL7 FHIR integration
- ❌ Predictive risk scoring

---

## Support

For questions or issues, contact:

- **Clinical Lead:** Dr Kais Aldabbagh, Polyclinique St Come - Medical Oncology
- **Technical Lead:** [Your Name]

---

## License

This project is proprietary. See the specification document for intellectual property details.
