# PX360 Onboarding System - Quick Start Guide

## Summary

The Onboarding & Acknowledgement System ensures all new users receive proper training on PX360 before gaining access. Users must complete a guided wizard with learning content, acknowledgement checklist, digital signature, and account activation.

## What Has Been Implemented

### ✅ Completed Components

#### 1. Database Models
- User model extensions (is_provisional, acknowledgement tracking)
- AcknowledgementContent (educational content)
- AcknowledgementChecklistItem (checklist items)
- UserAcknowledgement (acknowledgement records)
- UserProvisionalLog (audit trail)

#### 2. Backend Services
- OnboardingService (create provisional users, validation, progress tracking)
- EmailService (invitations, reminders, notifications)

#### 3. API Endpoints
- Create provisional user
- Resend invitation
- Get onboarding progress
- Get wizard content
- Get checklist items
- Acknowledge items
- Complete wizard and activate account

#### 4. UI Views & Templates
- Welcome page
- Content steps with progress tracking
- Checklist with digital signature canvas
- Account activation with password strength
- Completion page

#### 5. Serializers & Permissions
- All required serializers
- Role-based permissions
- Access control

#### 6. URL Routes
- All wizard routes configured
- Management routes configured
- API routes configured

#### 7. Signals
- Automatic logging of events
- Progress tracking

#### 8. Documentation
- Complete implementation guide
- This quick start guide

## Quick Start Steps

### Step 1: Run Migrations

```bash
python manage.py makemigrations accounts
python manage.py migrate accounts
```

### Step 2: Create Initial Content (Required)

You need to create educational content and checklist items before users can start onboarding. Use the provided management command:

**Via Management Command (Recommended):**
```bash
python manage.py init_onboarding_data
```

This command will create:
- **Generic Content** (for all users):
  - Welcome to PX360 (system overview)
  - Data Privacy & Security policies
  - System Usage Guidelines

- **Role-Specific Content** (if roles exist):
  - PX Admin Responsibilities
  - Hospital Admin Responsibilities
  - Department Manager Responsibilities
  - Physician Responsibilities
  - Staff Responsibilities

- **Checklist Items**: Required acknowledgements for each content section

**Via Django Admin (Custom Content):**
1. Log in as PX Admin
2. Go to `/admin/`
3. Navigate to `Accounts > Acknowledgement Contents`
4. Create custom content as needed
5. Navigate to `Accounts > Acknowledgement Checklist Items`
6. Create checklist items linked to your content

**Via Python Shell (Advanced):**
```bash
python manage.py shell
```

```python
from apps.accounts.models import AcknowledgementContent, AcknowledgementChecklistItem

# Create educational content
content = AcknowledgementContent.objects.create(
    code='system_overview',
    role='all',
    title_en='PX360 System Overview',
    title_ar='نظرة عامة على نظام PX360',
    description_en='Understanding the PX360 system',
    description_ar='فهم نظام PX360',
    content_en='<h1>Welcome to PX360</h1><p>This guide will help you understand the system...</p>',
    content_ar='<h1>مرحباً بك في PX360</h1><p>سيساعدك هذا الدليل على فهم النظام...</p>',
    icon='book',
    color='#007bff',
    order=1,
    is_active=True
)

# Create checklist items
checklist = AcknowledgementChecklistItem.objects.create(
    code='data_privacy',
    role='all',
    text_en='I acknowledge that I have read and understood the Data Privacy Policy',
    text_ar='أقر بأنني قرأت وفهمت سياسة خصوصية البيانات',
    description_en='Commitment to protecting patient data',
    description_ar='الالتزام بحماية بيانات المرضى',
    content=content,
    is_required=True,
    order=1,
    is_active=True
)
```

### Step 3: Create a Provisional User

**Via API:**
```bash
curl -X POST http://localhost:8000/api/accounts/users/onboarding/create-provisional/ \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "new.user@example.com",
    "first_name": "John",
    "last_name": "Doe",
    "roles": ["staff"]
  }'
```

**Via Django Admin:**
1. Log in as PX Admin
2. Go to `/admin/`
3. Create a User with `is_provisional=True`
4. Assign appropriate role group

### Step 4: User Completes Onboarding

1. User receives invitation email
2. Clicks the link in the email
3. Goes through wizard steps:
   - **Welcome Page**: Overview of the process
   - **Content Steps**: Read educational content (varies by role)
   - **Checklist**: Review and acknowledge required items
   - **Digital Signature**: Sign acknowledgements
   - **Account Activation**: Create username and password
4. Account is activated and user can log in

### Step 5: Monitor Progress

**Via API:**
```bash
curl -X GET http://localhost:8000/api/accounts/users/onboarding/progress/ \
  -H "Authorization: Bearer USER_TOKEN"
```

**Via UI:**
- PX Admin can access `/accounts/onboarding/provisional/` to see all provisional users
- Click "View Progress" to see detailed progress for each user

## Key Features

### Role-Based Content
Content and checklist items are filtered by user role:
- `px_admin`: PX Administrators
- `hospital_admin`: Hospital Administrators
- `department_manager`: Department Managers
- `staff`: Staff members
- `physician`: Physicians
- `all`: All users

### Digital Signature
- HTML5 Canvas signature capture
- Base64 encoding for storage
- IP address and user agent logging
- Compliance-ready audit trail

### Progress Tracking
- Real-time progress percentage
- Step-by-step completion tracking
- Audit log of all activities
- Detailed progress reports

### Security
- Secure invitation tokens (7-day expiration)
- Role-based access control
- Password strength requirements
- Complete audit trail

## Testing the Flow

### Test as PX Admin
1. Log in as PX Admin
2. Create a provisional user
3. Send invitation
4. Monitor progress

### Test as New User
1. Create a test provisional user
2. Access the onboarding wizard via invitation link
3. Complete all steps
4. Verify account is activated
5. Log in with new credentials

## Important Notes

### Email Configuration
Email functionality requires proper SMTP configuration in `settings.py`:
```python
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'your-smtp-server.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your-email@example.com'
EMAIL_HOST_PASSWORD = 'your-password'
DEFAULT_FROM_EMAIL = 'noreply@px360.com'
```

### Required Setup
Before using the system:
1. **Create content**: At least one AcknowledgementContent record
2. **Create checklist items**: At least one required AcknowledgementChecklistItem
3. **Configure email**: Set up email sending
4. **Create PX Admin role**: Ensure PX Admin role exists

### User Roles
Ensure these groups exist in your database:
- PX Admin
- Hospital Admin
- Department Manager
- Staff
- Physician

## API Endpoints Reference

### Onboarding Endpoints
- `POST /api/accounts/users/onboarding/create-provisional/` - Create provisional user
- `POST /api/accounts/users/{id}/onboarding/resend-invitation/` - Resend invitation
- `GET /api/accounts/users/onboarding/progress/` - Get user progress
- `GET /api/accounts/users/onboarding/content/` - Get wizard content
- `GET /api/accounts/users/onboarding/checklist/` - Get checklist items
- `POST /api/accounts/users/onboarding/acknowledge/` - Acknowledge item
- `POST /api/accounts/users/onboarding/complete/` - Complete wizard
- `GET /api/accounts/users/{id}/onboarding/status/` - Get user status

### UI Endpoints
- `/accounts/onboarding/welcome/` - Welcome page
- `/accounts/onboarding/wizard/step/{step}/` - Content steps
- `/accounts/onboarding/wizard/checklist/` - Checklist
- `/accounts/onboarding/wizard/activation/` - Activation
- `/accounts/onboarding/complete/` - Completion
- `/accounts/onboarding/provisional/` - Provisional user management
- `/accounts/onboarding/provisional/{id}/progress/` - User progress detail

## Troubleshooting

### User Cannot Access Wizard
- Check `user.is_provisional` is True
- Verify invitation hasn't expired
- Ensure user has at least one role assigned

### Email Not Sending
- Check SMTP configuration in settings.py
- Verify email templates exist
- Check mail server logs

### Progress Not Saving
- Check browser console for API errors
- Verify JWT token is valid
- Check UserAcknowledgement records in database

## Additional Features (Already Implemented)

### ✅ Completed Components

1. **Management Templates**
   - ✅ `templates/accounts/onboarding/provisional_list.html`
   - ✅ `templates/accounts/onboarding/progress_detail.html`
   - ✅ `templates/accounts/onboarding/provisional_create.html`

2. **Wizard Templates**
   - ✅ `templates/accounts/onboarding/welcome.html`
   - ✅ `templates/accounts/onboarding/step_content.html`
   - ✅ `templates/accounts/onboarding/step_checklist.html`
   - ✅ `templates/accounts/onboarding/step_activation.html`
   - ✅ `templates/accounts/onboarding/complete.html`

3. **Email Templates**
   - ✅ `templates/accounts/emails/invitation_email.html` & `.txt`
   - ✅ `templates/accounts/emails/reminder_email.html` & `.txt`
   - ✅ `templates/accounts/emails/completion_notification.html` & `.txt`

4. **OnboardingMiddleware**
   - ✅ `apps/accounts/middleware.py` - Redirects provisional users to wizard
   - ✅ Prevents access until onboarding is complete

5. **Sidebar Integration**
   - ✅ "Onboarding" menu item added for PX Admin
   - ✅ Automatic redirect for provisional users

6. **Data Management**
   - ✅ Management command: `python manage.py init_onboarding_data`
   - ✅ Default content for all roles (generic + role-specific)
   - ✅ Default checklist items for each content section
   - ✅ Bilingual content (English and Arabic)

7. **Documentation**
   - ✅ Complete implementation guide
   - ✅ Quick start guide (this document)
   - ✅ Feature summary
   - ✅ Complete implementation documentation

## Support

For detailed information, see:
- **Implementation Guide**: `docs/ONBOARDING_IMPLEMENTATION_GUIDE.md`
- **Django Admin**: `/admin/` to manage content and users
- **API Documentation**: Available at `/api/docs/` (if configured)

## Summary

The onboarding system is **production-ready** and fully implemented. All features are complete:

✅ Database models with extensions
✅ Backend services and API endpoints
✅ Complete wizard UI and templates
✅ Management UI for PX Admins
✅ Email system (invitation, reminders, notifications)
✅ Permissions and security
✅ URL routing and middleware
✅ Bilingual support (English/Arabic)
✅ Digital signature capture
✅ Progress tracking and audit trail
✅ Management command for initial data
✅ Complete documentation

### To Go Live:

1. **Run migrations** (if not already done):
   ```bash
   python manage.py makemigrations accounts
   python manage.py migrate accounts
   ```

2. **Create initial content** (if not already done):
   ```bash
   python manage.py init_onboarding_data
   ```

3. **Configure email settings** in `settings.py`:
   ```python
   EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
   EMAIL_HOST = 'your-smtp-server.com'
   EMAIL_PORT = 587
   EMAIL_USE_TLS = True
   EMAIL_HOST_USER = 'your-email@example.com'
   EMAIL_HOST_PASSWORD = 'your-password'
   DEFAULT_FROM_EMAIL = 'noreply@px360.com'
   ```

4. **Add middleware to settings.py** (if not already added):
   ```python
   MIDDLEWARE = [
       # ... other middleware ...
       'apps.accounts.middleware.OnboardingMiddleware',
       # ... other middleware ...
   ]
   ```

5. **Start using the system**:
   - Create provisional users via UI or API
   - Users receive invitation emails
   - Users complete onboarding wizard
   - Monitor progress via management interface

---

**Version**: 1.0.0  
**Last Updated**: January 2026  
**Status**: ✅ Production Ready
