# PX360 - Patient Experience 360 Management System

**AlHammadi Group (Saudi Arabia)**

A comprehensive enterprise patient experience management system built with Django 5.0, designed to track, measure, and improve patient satisfaction across multiple touchpoints in the healthcare journey.

## 🎯 Project Overview

PX360 is a complex, event-driven system that:
- Tracks patient journeys through EMS, Inpatient, and OPD pathways
- Automatically sends stage-specific surveys based on integration events
- Manages complaints with SLA tracking and escalation
- Creates and tracks PX actions from negative feedback
- Provides real-time analytics and dashboards
- Supports multi-language (Arabic/English) operations

## 🏗️ Architecture

### Tech Stack
- **Backend**: Python 3.12+ / Django 5.0
- **API**: Django REST Framework with JWT authentication
- **Database**: PostgreSQL 15
- **Task Queue**: Celery + Redis
- **Scheduler**: Celery Beat
- **Documentation**: drf-spectacular (OpenAPI/Swagger)
- **Deployment**: Docker + Docker Compose

### Project Structure

```
px360/
├── config/                 # Project configuration
│   ├── settings/          # Split settings (base/dev/prod)
│   ├── urls.py           # Main URL configuration
│   ├── celery.py         # Celery configuration
│   ├── wsgi.py           # WSGI application
│   └── asgi.py           # ASGI application
├── apps/                  # Business applications
│   ├── core/             # Base models, utilities, health check
│   ├── accounts/         # User authentication & RBAC
│   ├── organizations/    # Hospitals, departments, staff, patients
│   ├── journeys/         # Patient journey templates & instances
│   ├── surveys/          # Survey templates & responses
│   ├── complaints/       # Complaint management
│   ├── feedback/         # General feedback
│   ├── callcenter/       # Call center interactions
│   ├── social/           # Social media monitoring
│   ├── px_action_center/ # Action tracking with SLA
│   ├── analytics/        # KPIs and dashboards
│   ├── physicians/       # Physician ratings
│   ├── projects/         # QI projects
│   ├── integrations/     # External system integrations
│   ├── notifications/    # SMS/WhatsApp/Email delivery
│   └── ai_engine/        # Sentiment analysis
├── templates/            # Django templates
├── static/              # Static files
├── docs/                # Documentation
├── docker/              # Docker configuration files
├── requirements/        # Python dependencies
├── manage.py           # Django management script
├── Dockerfile          # Docker image definition
└── docker-compose.yml  # Multi-container setup
```

## 🚀 Quick Start

### Prerequisites
- Python 3.12+
- Docker & Docker Compose
- PostgreSQL 15 (if running locally)
- Redis 7 (if running locally)

### Installation

1. **Clone the repository**
```bash
git clone <repository-url>
cd PX360
```

2. **Create environment file**
```bash
cp .env.example .env
# Edit .env with your configuration
```

3. **Run with Docker (Recommended)**
```bash
docker-compose up --build
```

This will start:
- Web server (Django) on http://localhost:8000
- PostgreSQL database
- Redis
- Celery worker
- Celery beat scheduler

4. **Access the application**
- API: http://localhost:8000/api/
- Admin: http://localhost:8000/admin/
- API Docs: http://localhost:8000/api/docs/
- Health Check: http://localhost:8000/health/

### Local Development (Without Docker)

1. **Create virtual environment**
```bash
python3 -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
```

2. **Install dependencies**
```bash
pip install -e ".[dev]"
```

3. **Set up database**
```bash
# Make sure PostgreSQL is running
createdb px360
```

4. **Run migrations**
```bash
python manage.py migrate
```

5. **Create superuser**
```bash
python manage.py createsuperuser
```

6. **Run development server**
```bash
python manage.py runserver
```

7. **Run Celery worker (separate terminal)**
```bash
celery -A config worker -l info
```

8. **Run Celery beat (separate terminal)**
```bash
celery -A config beat -l info
```

## 📋 Implementation Status

### ✅ Phase 0: Bootstrap & Infrastructure (COMPLETED)
- [x] Project structure with config/ and apps/
- [x] Split settings (base/dev/prod)
- [x] Django 5.0 + DRF setup
- [x] Celery + Redis configuration
- [x] Docker setup (web, db, redis, celery, celery-beat)
- [x] Health check endpoint
- [x] Environment configuration

### 🔄 Phase 1: Core + Accounts + RBAC + Audit (IN PROGRESS)
- [x] Core base models (UUIDModel, TimeStampedModel, SoftDeleteModel)
- [x] AuditEvent model with generic foreign key
- [x] AuditService for centralized logging
- [x] Custom User model with UUID primary key
- [x] Role model linked to Django Groups
- [ ] JWT authentication endpoints
- [ ] DRF permission classes
- [ ] Management commands for default roles
- [ ] User registration and login audit logging

### 🔄 Phase 2: Organizations (IN PROGRESS)
- [x] Hospital model
- [x] Department model (hierarchical)
- [x] Physician model
- [x] Employee model
- [x] Patient model
- [ ] Admin interfaces
- [ ] DRF API endpoints
- [ ] RBAC enforcement

### ⏳ Phase 3: Journeys + Event Intake (PENDING)
- [ ] JourneyType enum (EMS/Inpatient/OPD)
- [ ] PatientJourneyTemplate & StageTemplate models
- [ ] PatientJourneyInstance & StageInstance models
- [ ] InboundEvent model for integration events
- [ ] Event processing Celery task
- [ ] API endpoint to receive events
- [ ] Stage completion logic

### ⏳ Phase 4: Surveys + Delivery (PENDING)
- [ ] SurveyTemplate & SurveyQuestion models
- [ ] SurveyInstance & SurveyResponse models
- [ ] Bilingual survey support (AR/EN)
- [ ] Signed token URL generation
- [ ] Survey submission endpoint
- [ ] Automatic survey creation on stage completion
- [ ] Notification delivery (SMS/WhatsApp/Email stubs)

### ⏳ Phase 5: Complaints + Resolution Satisfaction (PENDING)
- [ ] Complaint model with SLA tracking
- [ ] Complaint workflow (open → resolved → closed)
- [ ] ComplaintAttachment & ComplaintUpdate models
- [ ] Inquiry model
- [ ] Resolution satisfaction survey trigger
- [ ] API endpoints

### ⏳ Phase 6: PX Action Center (PENDING)
- [ ] PXAction model with SLA configuration
- [ ] Automatic action creation triggers
- [ ] SLA reminder Celery tasks
- [ ] Escalation logic
- [ ] Approval workflow
- [ ] Evidence attachment

### ⏳ Phase 7: Call Center + Social + AI Engine (PENDING)
- [ ] Call center interaction models
- [ ] Social media mention models
- [ ] AI sentiment analysis (stubbed)
- [ ] Sentiment-driven action creation

### ⏳ Phase 8: Analytics + Dashboards (PENDING)
- [ ] KPI models and aggregation
- [ ] Physician monthly ratings
- [ ] QI project models
- [ ] PX Command Center dashboard
- [ ] Department/physician leaderboards

### ⏳ Comprehensive UI (PENDING)
- [ ] Bootstrap 5 base templates
- [ ] PX Command Center dashboard
- [ ] Complaints console
- [ ] PX Action Center board
- [ ] Journey template builder
- [ ] Survey control center
- [ ] Public survey forms

## 🔑 Key Features

### Event-Driven Architecture
- Integration events from HIS/Lab/Radiology/Pharmacy trigger journey stage completions
- Stage completions automatically send stage-specific surveys
- Negative feedback automatically creates PX actions

### SLA Management
- Configurable SLA thresholds by priority/severity
- Automatic reminders before due date
- Automatic escalation when overdue
- Audit trail of all SLA events

### Multi-Language Support
- Arabic and English throughout the system
- Bilingual survey templates
- RTL-ready UI components

### RBAC (Role-Based Access Control)
- PX Admin: Full system access
- Hospital Admin: Hospital-level access
- Department Manager: Department-level access
- PX Coordinator: Action management
- Physician/Nurse/Staff: Limited access
- Viewer: Read-only access

## 📚 API Documentation

Once the server is running, access the interactive API documentation:
- **Swagger UI**: http://localhost:8000/api/docs/
- **ReDoc**: http://localhost:8000/api/redoc/
- **OpenAPI Schema**: http://localhost:8000/api/schema/

## 🧪 Testing

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=apps --cov-report=html

# Run specific app tests
pytest apps/core/tests/
```

## 🔧 Management Commands

```bash
# Create default roles and groups
python manage.py create_default_roles

# Create sample data for testing
python manage.py create_sample_data

# Process pending integration events
python manage.py process_events

# Calculate KPIs
python manage.py calculate_kpis
```

## 📊 Celery Tasks

### Periodic Tasks (Celery Beat)
- **process-integration-events**: Every 1 minute
- **check-overdue-complaints**: Every 15 minutes
- **check-overdue-actions**: Every 15 minutes
- **send-sla-reminders**: Every hour
- **calculate-daily-kpis**: Daily at 1 AM
- **calculate-physician-ratings**: Monthly on 1st at 2 AM

## 🔒 Security

- JWT authentication for API access
- RBAC enforced at view and API level
- Audit logging for all critical operations
- HTTPS enforced in production
- CSRF protection enabled
- SQL injection protection via ORM
- XSS protection via template escaping

## 🌍 Deployment

### Production Checklist
- [ ] Set `DEBUG=False` in .env
- [ ] Configure `SECRET_KEY` with strong random value
- [ ] Set `ALLOWED_HOSTS` to your domain
- [ ] Configure production database
- [ ] Set up Redis for production
- [ ] Configure email backend (SMTP)
- [ ] Set up SMS/WhatsApp providers
- [ ] Configure static file serving (WhiteNoise/CDN)
- [ ] Set up SSL certificates
- [ ] Configure backup strategy
- [ ] Set up monitoring and logging
- [ ] Configure firewall rules

### Environment Variables

See `.env.example` for all available configuration options.

## 📝 License

Proprietary - AlHammadi Group

## 👥 Team

- **Client**: AlHammadi Group, Saudi Arabia
- **Project**: PX360 Patient Experience Management System

## 📞 Support

For issues and questions, please contact the development team.

---

**Note**: This is a work in progress. The system is being built incrementally following the 8-phase implementation plan outlined in the requirements document.
