# PX360 Onboarding & Acknowledgement System - Implementation Guide

## Overview

The Onboarding & Acknowledgement System ensures that all new users receive proper training on the PX360 system before accessing it. Users must complete a guided wizard that includes:

1. **Learning Phase**: Review system documentation and procedures
2. **Acknowledgement Phase**: Confirm understanding of key policies and procedures
3. **Activation Phase**: Create username and password with digital signature

## Architecture

### Models

#### 1. User Model Extensions
- `is_provisional`: Boolean flag for provisional user status
- `acknowledgement_completed`: Boolean flag for completion status
- `acknowledgement_completed_at`: Timestamp of completion
- `current_wizard_step`: Track current wizard step
- `wizard_completed_steps`: List of completed step IDs
- `invitation_token`: Unique token for invitation link
- `invitation_expires_at`: Invitation expiration timestamp
- `invitation_sent_at`: Timestamp when invitation was sent

#### 2. AcknowledgementContent
Stores educational content for different roles:
- `code`: Unique identifier
- `role`: Target role (px_admin, hospital_admin, department_manager, staff, physician, all)
- `title_en`, `title_ar`: Title in English and Arabic
- `description_en`, `description_ar`: Short description
- `content_en`, `content_ar`: Full HTML content
- `icon`, `color`: UI customization
- `order`: Display order
- `is_active`: Status flag

#### 3. AcknowledgementChecklistItem
Items users must acknowledge:
- `code`: Unique identifier
- `role`: Target role
- `text_en`, `text_ar`: Item text
- `description_en`, `description_ar`: Additional context
- `content`: Link to related AcknowledgementContent
- `is_required`: Whether this item is mandatory
- `order`: Display order
- `is_active`: Status flag

#### 4. UserAcknowledgement
Records user acknowledgements:
- `user`: Foreign key to User
- `checklist_item`: Foreign key to AcknowledgementChecklistItem
- `is_acknowledged`: Boolean flag
- `acknowledged_at`: Timestamp
- `signature`: Digital signature (base64 encoded)
- `ip_address`: User's IP address
- `user_agent`: Browser information

#### 5. UserProvisionalLog
Audit trail for onboarding events:
- `user`: Foreign key to User
- `event_type`: Event category (created, step_completed, wizard_completed, user_activated, invitation_sent, reminder_sent)
- `description`: Event description
- `metadata`: JSON field for additional data
- `created_at`: Timestamp

### Services

#### OnboardingService
Key methods:
- `create_provisional_user(user_data)`: Create provisional user
- `validate_invitation(token)`: Validate invitation link
- `get_wizard_content(user)`: Get role-specific content
- `get_checklist_items(user)`: Get role-specific checklist
- `acknowledge_item(user, item, signature, request)`: Record acknowledgement
- `complete_wizard(user, username, password, signature, request)`: Complete onboarding
- `get_user_progress_percentage(user)`: Calculate progress

#### EmailService
Email notifications:
- `send_invitation_email(user, request)`: Send invitation
- `send_reminder_email(user, request)`: Send reminder
- `send_completion_notification(user, admins, request)`: Notify admins of completion

### Permissions

- `IsProvisionalUser`: Restrict to provisional users
- `CanManageOnboarding`: PX Admin only
- `CanManageAcknowledgementContent`: PX Admin only
- `CanViewOnboarding`: PX Admin or own user
- `IsOnboardingOwnerOrAdmin`: User can view own, PX Admin can view all

### Serializers

- `ProvisionalUserSerializer`: Create provisional user
- `AcknowledgementContentSerializer`: Content CRUD
- `AcknowledgementChecklistItemSerializer`: Checklist CRUD
- `UserAcknowledgementSerializer`: View acknowledgements
- `WizardProgressSerializer`: Progress tracking
- `AcknowledgeItemSerializer`: Acknowledge item
- `AccountActivationSerializer`: Activate account

### Views & ViewSets

#### API ViewSets
- `AcknowledgementContentViewSet`: Manage content
- `AcknowledgementChecklistItemViewSet`: Manage checklist items
- `UserAcknowledgementViewSet`: View acknowledgements (read-only)

#### UserViewSet Actions
- `onboarding_create_provisional`: Create provisional user
- `onboarding_resend_invitation`: Resend invitation
- `onboarding_progress`: Get user progress
- `onboarding_content`: Get wizard content
- `onboarding_checklist`: Get checklist items
- `onboarding_acknowledge`: Acknowledge item
- `onboarding_complete`: Complete wizard and activate

#### UI Views
- `onboarding_welcome`: Welcome page
- `onboarding_step_content`: Content step
- `onboarding_step_checklist`: Checklist step
- `onboarding_step_activation`: Activation step
- `onboarding_complete`: Completion page
- `provisional_user_list`: Manage provisional users
- `provisional_user_progress`: View user progress
- `acknowledgement_content_list`: Manage content
- `acknowledgement_checklist_list`: Manage checklist items

## User Flow

### 1. Admin Creates Provisional User
```
Admin → Provisional Users List → Create User → Select Role → Send Invitation
```

### 2. User Receives Invitation
```
Email → Click Link → Welcome Page → Start Wizard
```

### 3. Wizard Flow
```
Step 1: Review Content (multiple steps based on role)
  ↓
Step 2: Review and Acknowledge Checklist Items
  ↓
Step 3: Digital Signature
  ↓
Step 4: Create Username & Password
  ↓
Completion: Account Activated
```

### 4. Admin Monitors Progress
```
Admin → Provisional Users → View Progress → See Acknowledgements
```

## URL Routes

### API 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 progress
- `GET /api/accounts/users/onboarding/content/` - Get content
- `GET /api/accounts/users/onboarding/checklist/` - Get checklist
- `POST /api/accounts/users/onboarding/acknowledge/` - Acknowledge item
- `POST /api/accounts/users/onboarding/complete/` - Complete wizard
- `GET /api/accounts/users/{id}/onboarding/status/` - Get 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 list
- `/accounts/onboarding/provisional/{id}/progress/` - User progress
- `/accounts/onboarding/content/` - Content management
- `/accounts/onboarding/checklist-items/` - Checklist management

## Templates

### Wizard Templates
- `welcome.html` - Welcome page with overview
- `step_content.html` - Content review step with progress sidebar
- `step_checklist.html` - Checklist with digital signature canvas
- `step_activation.html` - Account activation with password strength indicator
- `complete.html` - Success page with next steps

### Management Templates (To Be Created)
- `provisional_list.html` - List and create provisional users
- `progress_detail.html` - View detailed progress for a user
- `content_list.html` - Manage educational content
- `checklist_list.html` - Manage checklist items

### Email Templates (To Be Created)
- `invitation_email.html` - Invitation email
- `reminder_email.html` - Reminder email
- `completion_notification.html` - Admin notification

## Signals

### post_save - User
- `log_provisional_user_creation`: Log when provisional user is created
- `check_onboarding_completion`: Check if all required items are completed
- `log_account_activation`: Log when account is activated

### post_save - UserAcknowledgement
- `log_acknowledgement`: Log when item is acknowledged

## Database Migrations

Run these migrations to create the onboarding tables:

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

## Setup Instructions

### 1. Create Initial Content

Create role-specific educational content:

```python
# Example: PX Admin content
AcknowledgementContent.objects.create(
    code='px_admin_overview',
    role='px_admin',
    title_en='PX360 System Overview',
    title_ar='نظرة عامة على نظام PX360',
    description_en='Understanding the PX360 system architecture and features',
    description_ar='فهم بنية وميزات نظام PX360',
    content_en='<p>Detailed HTML content...</p>',
    content_ar='<p>محتوى HTML مفصل...</p>',
    icon='cogs',
    color='#007bff',
    order=1,
    is_active=True
)
```

### 2. Create Checklist Items

Create acknowledgement checklist items:

```python
# Example: Required acknowledgement
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='الالتزام بحماية بيانات المرضى',
    is_required=True,
    order=1,
    is_active=True
)
```

### 3. Create Provisional User

As a PX Admin:

```python
# Via API
POST /api/accounts/users/onboarding/create-provisional/
{
    "email": "new.user@example.com",
    "first_name": "John",
    "last_name": "Doe",
    "roles": ["staff"]
}

# Via UI
Navigate to /accounts/onboarding/provisional/ and fill the form
```

### 4. User Completes Onboarding

1. User clicks invitation link
2. Goes through wizard steps
3. Acknowledges all required items
4. Provides digital signature
5. Creates username and password
6. Account is activated

### 5. Monitor Progress

```python
# Get user progress
GET /api/accounts/users/onboarding/progress/

# View detailed progress
GET /accounts/onboarding/provisional/{user_id}/progress/
```

## Customization

### Role-Specific Content

Content and checklist items can be assigned to specific roles:
- `px_admin`: PX Administrators
- `hospital_admin`: Hospital Administrators
- `department_manager`: Department Managers
- `staff`: Staff members
- `physician`: Physicians
- `all`: All users

### Digital Signature

The system uses HTML5 Canvas for digital signature capture. Signature is stored as base64-encoded image in the UserAcknowledgement model.

### Email Templates

Customize email templates in `templates/accounts/emails/`:
- `invitation_email.html`: Invitation email
- `reminder_email.html`: Reminder email
- `completion_notification.html`: Admin notification

## Security Considerations

1. **Invitation Links**: Single-use tokens with expiration (default 7 days)
2. **Digital Signatures**: Capture IP address and user agent
3. **Audit Trail**: All onboarding events are logged
4. **Role-Based Access**: Content and checklist items filtered by role
5. **Password Requirements**: Minimum 8 characters with strength indicator

## Compliance Features

1. **Audit Trail**: Complete log of all onboarding activities
2. **Digital Signatures**: Legally-binding acknowledgements
3. **Timestamp Records**: Exact time of each acknowledgement
4. **IP Address Logging**: Track user location
5. **Content Versioning**: Track which version of content was acknowledged

## Monitoring and Reporting

### User Progress
```python
from apps.accounts.models import User, UserAcknowledgement

# Get all provisional users
provisional_users = User.objects.filter(is_provisional=True)

# Get completed users
completed_users = User.objects.filter(
    is_provisional=False,
    acknowledgement_completed=True
)

# Get user progress
user = User.objects.get(id=user_id)
progress = user.get_onboarding_progress_percentage()
```

### Acknowledgement Reports
```python
# Get all acknowledgements for a user
acknowledgements = UserAcknowledgement.objects.filter(user=user)

# Get acknowledgements for a specific item
item_acknowledgements = UserAcknowledgement.objects.filter(
    checklist_item=item
)

# Get acknowledgement statistics
total_users = User.objects.filter(is_active=True).count()
total_acknowledged = UserAcknowledgement.objects.filter(
    is_acknowledged=True
).values('user').distinct().count()
```

## Troubleshooting

### User Cannot Access Wizard
- Check if user is provisional: `user.is_provisional`
- Check if invitation is expired: `user.invitation_expires_at`
- Verify user has at least one role assigned

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

### Email Not Sending
- Verify email configuration in settings.py
- Check mail server logs
- Verify email template exists

## Future Enhancements

1. **Content Localization**: Add more language support
2. **Video Integration**: Add video content to learning materials
3. **Quiz Mode**: Add quizzes to verify understanding
4. **Certificate Generation**: Generate completion certificates
5. **Bulk Import**: Import multiple provisional users at once
6. **Reminders**: Automatic reminder emails for inactive users
7. **Analytics Dashboard**: Visual progress tracking
8. **Content Versioning**: Track content changes and updates

## Support

For issues or questions:
1. Check this documentation
2. Review audit logs in `UserProvisionalLog`
3. Check Django logs for errors
4. Contact system administrator

---

**Last Updated**: January 2026
**Version**: 1.0.0
