# Staff User Account Management Implementation

## Overview
This document describes the implementation of optional user account creation and management for Staff members in the PX360 system.

## Features Implemented

### 1. Optional One-to-One User Relation
- **Status**: ✅ Already exists in Staff model
- The Staff model already has an optional one-to-one relation to the User model via the `user` field
- Allows staff profiles to be linked to user accounts for login access

### 2. Staff CRUD Operations
- **Status**: ✅ Complete
- Full CRUD operations for Staff members via:
  - REST API endpoints (`/api/organizations/staff/`)
  - UI views (List, Detail, Create, Update)
  - Django Admin interface

### 3. User Account Creation for Staff
- **Status**: ✅ Complete
- Ability to create user accounts for staff members
- Auto-generated username format: `first.last` (lowercase)
- Auto-generated secure random passwords (12 characters)
- Automatic email delivery of credentials

### 4. User Account Management
- **Status**: ✅ Complete
- **Create User Account**: Create a new user account for staff member
- **Link User Account**: Link an existing user account to a staff member
- **Unlink User Account**: Remove user account association
- **Send Invitation Email**: Resend credentials with new password

## Implementation Details

### Files Created/Modified

#### Backend Files

1. **`apps/organizations/services.py`** (NEW)
   - `StaffService` class with methods:
     - `generate_username(staff)` - Generate unique username
     - `generate_password()` - Generate secure password
     - `create_user_for_staff(staff, role, request)` - Create user account
     - `link_user_to_staff(staff, user_id, request)` - Link existing user
     - `unlink_user_from_staff(staff, request)` - Unlink user account
     - `send_credentials_email(staff, password, request)` - Send credentials email
     - `get_staff_type_role(staff_type)` - Map staff type to role

2. **`apps/organizations/serializers.py`** (MODIFIED)
   - Added `has_user_account` field to StaffSerializer
   - Added write-only fields: `create_user`, `user_username`, `user_password`, `send_email`
   - Enhanced `create()` method to support optional user account creation
   - Enhanced `update()` method to support optional user account creation

3. **`apps/organizations/views.py`** (MODIFIED)
   - Added custom actions to StaffViewSet:
     - `create_user_account` - POST `/api/organizations/staff/{id}/create_user_account/`
     - `link_user` - POST `/api/organizations/staff/{id}/link_user/`
     - `unlink_user` - POST `/api/organizations/staff/{id}/unlink_user/`
     - `send_invitation` - POST `/api/organizations/staff/{id}/send_invitation/`

4. **`apps/organizations/admin.py`** (MODIFIED)
   - Added `has_user_account` column to list display
   - Added admin actions:
     - `create_user_accounts` - Bulk create user accounts
     - `send_credentials_emails` - Bulk send credential emails

5. **`apps/organizations/forms.py`** (NEW)
   - `StaffForm` for creating and updating staff
   - Includes RBAC filtering for hospitals and departments
   - Validates unique employee IDs
   - Cleans and normalizes email addresses

6. **`apps/organizations/ui_views.py`** (MODIFIED)
   - `staff_detail(pk)` - Display staff details with user account status
   - `staff_create(request)` - Create new staff with optional user account
   - `staff_update(request, pk)` - Update staff with optional user account creation

7. **`apps/organizations/urls.py`** (MODIFIED)
   - Added URL patterns:
     - `/staff/create/` - Create staff
     - `/staff/<uuid:pk>/` - Staff detail
     - `/staff/<uuid:pk>/edit/` - Update staff

#### Frontend Files

8. **`templates/organizations/staff_list.html`** (NEW)
   - Staff list with filtering and search
   - User account status indicators
   - Actions for creating/sending/unlinking user accounts
   - Pagination support
   - Confirmation modals for user account actions

9. **`templates/organizations/staff_detail.html`** (NEW)
   - Detailed staff profile view
   - User account status display
   - User account management actions
   - Confirmation modals

10. **`templates/organizations/staff_form.html`** (NEW)
    - Staff creation/editing form
    - Optional user account creation checkbox
    - Tips and guidance for users

11. **`templates/organizations/emails/staff_credentials.html`** (NEW)
    - Professional email template for credentials
    - Contains username, password, and login URL
    - Security notice about password change
    - Responsive design

12. **`templates/layouts/partials/sidebar.html`** (MODIFIED)
    - Added "Staff" menu item with icon
    - Positioned between "Physicians" and "Complaints"

## User Account Creation Process

### Username Generation
- Format: `first.last` (all lowercase)
- Example: John Smith → `john.smith`
- Duplicate handling: Appends number if duplicate exists
  - `john.smith2`, `john.smith3`, etc.

### Password Generation
- Length: 12 characters
- Characters: Letters, numbers, and special characters
- Generated using `secrets` module for cryptographic security

### Role Assignment
- All staff types receive the `staff` role by default
- Can be modified by admins if needed
- Mapping: physician → staff, nurse → staff, admin → staff, other → staff

### Email Delivery
- Credentials are sent automatically when user account is created
- Email includes:
  - Username
  - Password
  - Email address
  - Login URL
- Staff member is advised to change password after first login

## API Endpoints

### Staff Management
- `GET /api/organizations/staff/` - List staff (with filters)
- `POST /api/organizations/staff/` - Create staff (with optional user account)
- `GET /api/organizations/staff/{id}/` - Get staff details
- `PUT/PATCH /api/organizations/staff/{id}/` - Update staff
- `DELETE /api/organizations/staff/{id}/` - Delete staff

### User Account Actions
- `POST /api/organizations/staff/{id}/create_user_account/` - Create user account
- `POST /api/organizations/staff/{id}/link_user/` - Link existing user
- `POST /api/organizations/staff/{id}/unlink_user/` - Unlink user account
- `POST /api/organizations/staff/{id}/send_invitation/` - Send invitation email

## Permissions

### Staff Viewing
- PX Admins: Can view all staff
- Hospital Admins: Can view staff in their hospital
- Department Managers: Can view staff in their department
- Others: Can view staff in their hospital

### User Account Creation/Management
- PX Admins: Can create/link/unlink user accounts for all staff
- Hospital Admins: Can create/link/unlink user accounts for staff in their hospital only
- Other roles: No permission to manage user accounts

## UI Views

### Staff List (`/staff/`)
- Filter by hospital, status, staff type
- Search by name, ID, license, job title
- User account status indicators (Yes/No)
- Quick actions for user account management
- Pagination support

### Staff Detail (`/staff/{id}/`)
- Complete staff profile
- User account status and details
- User account management actions
- Related information (hospital, department, etc.)

### Staff Create (`/staff/create/`)
- Staff information form
- Optional user account creation checkbox
- Hospital/department filtering based on user role
- Email address required for user account creation

### Staff Edit (`/staff/{id}/edit/`)
- Update staff information
- Optional user account creation (if not already created)

## Email Configuration

### Required Settings
Ensure the following settings are configured in `config/settings/base.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@domain.com'
EMAIL_HOST_PASSWORD = 'your-password'
DEFAULT_FROM_EMAIL = 'noreply@px360.local'
```

## Usage Examples

### Creating Staff with User Account via API
```bash
curl -X POST http://localhost:8000/api/organizations/staff/ \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <token>" \
  -d '{
    "first_name": "John",
    "last_name": "Smith",
    "staff_type": "physician",
    "job_title": "Cardiologist",
    "employee_id": "EMP001",
    "email": "john.smith@example.com",
    "hospital": "<hospital-uuid>",
    "department": "<department-uuid>",
    "status": "active",
    "create_user": true,
    "send_email": true
  }'
```

### Creating User Account for Existing Staff via API
```bash
curl -X POST http://localhost:8000/api/organizations/staff/<staff-id>/create_user_account/ \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <token>" \
  -d '{}'
```

## Audit Logging

All user account management actions are logged:
- User creation events
- User linking/unlinking events
- Email sending events
- Includes metadata: staff ID, staff name, role, etc.

## Testing Recommendations

1. **Test User Account Creation**
   - Create staff with email
   - Create user account
   - Verify email delivery
   - Test login with credentials

2. **Test User Account Linking**
   - Create existing user
   - Link to staff member
   - Verify association

3. **Test Permissions**
   - Test PX Admin can manage all staff
   - Test Hospital Admin can only manage hospital staff
   - Test other roles cannot manage user accounts

4. **Test Email Delivery**
   - Verify email template rendering
   - Test with different email addresses
   - Verify login URL is correct

5. **Test Edge Cases**
   - Duplicate usernames
   - Staff without email
   - Staff already has user account
   - Invalid email addresses

## Security Considerations

1. **Password Security**
   - Strong random password generation
   - Passwords are hashed before storage
   - Staff advised to change password after first login

2. **Access Control**
   - RBAC enforced at all levels
   - Hospital Admins restricted to their hospital
   - API endpoints have permission checks

3. **Email Security**
   - Email sent via secure connection (TLS)
   - Password included in email (required for first login)
   - Security notice encourages password change

4. **Audit Trail**
   - All actions logged
   - Includes user, timestamp, and metadata
   - Can be reviewed for security audits

## Future Enhancements

Potential improvements for future versions:

1. **Two-Factor Authentication**
   - Add 2FA option for staff accounts

2. **Password Policies**
   - Enforce password complexity rules
   - Password expiration policies

3. **Bulk User Account Creation**
   - CSV import for bulk staff with user accounts
   - Background job for email sending

4. **User Account Status Management**
   - Ability to deactivate user accounts without unlinking
   - Temporarily suspend access

5. **Password Reset Flow**
   - Integration with existing password reset system
   - Staff-initiated password reset

## Conclusion

The Staff User Account Management feature is fully implemented and ready for use. Staff members can now be given login access to the PX360 system with automatic credential delivery via email. The implementation includes proper RBAC, audit logging, and a user-friendly interface for managing staff user accounts.
