# Staff Seed Command Update Documentation ## Overview The `seed_staff` management command has been updated to integrate with the new Staff user account management system. It now uses the `StaffService` for consistent user account creation and adds new features for email delivery. ## What Changed ### 1. Integration with StaffService The command now uses the `StaffService` class for all user account operations: - `StaffService.generate_username()` - For username generation - `StaffService.generate_password()` - For secure password generation - `StaffService.create_user_for_staff()` - For user account creation - `StaffService.get_staff_type_role()` - For proper role assignment - `StaffService.send_credentials_email()` - For credential email delivery ### 2. Staff Email Field The command now sets the `email` field on the Staff model: - Format: `{firstname}.{lastname}@{hospital_code}.sa` - Example: `mohammed.alsalem@almadina.sa` - Handles duplicates by using username as fallback ### 3. New `--send-emails` Flag Added a new command-line flag to send credential emails: ```bash python manage.py seed_staff --create-users --send-emails ``` When enabled: - Generates secure random passwords - Sends credential emails to staff members - Reports success/failure for each email ### 4. Enhanced Error Handling The command now includes comprehensive error handling: - Catches and reports user creation errors - Catches and reports email sending errors - Continues processing even if individual operations fail - Provides clear error messages for debugging ### 5. Role Assignment User accounts are now created with proper roles: - All staff types receive the `staff` role - Role is set using `StaffService.get_staff_type_role()` - Consistent with the rest of the system ## Usage ### Basic Usage (Staff Profiles Only) Create staff profiles without user accounts: ```bash python manage.py seed_staff ``` ### Create Staff with User Accounts Create staff profiles and user accounts: ```bash python manage.py seed_staff --create-users ``` ### Create Staff with User Accounts and Email Delivery Create staff, user accounts, and send credential emails: ```bash python manage.py seed_staff --create-users --send-emails ``` ### Target Specific Hospital Create staff for a specific hospital: ```bash python manage.py seed_staff --hospital-code ALMADINA --create-users ``` ### Custom Counts Specify the number of each staff type: ```bash python manage.py seed_staff \ --physicians 5 \ --nurses 10 \ --admin-staff 3 \ --create-users ``` ### Dry Run Preview what would be created without making changes: ```bash python manage.py seed_staff --dry-run --create-users ``` ### Clear Existing Staff First Delete all existing staff before creating new ones: ```bash python manage.py seed_staff --clear --create-users ``` ## Command-Line Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `--hospital-code` | string | all | Target hospital code | | `--count` | integer | 10 | Number of staff per type | | `--physicians` | integer | 10 | Number of physicians | | `--nurses` | integer | 15 | Number of nurses | | `--admin-staff` | integer | 5 | Number of admin staff | | `--create-users` | flag | False | Create user accounts for staff | | `--send-emails` | flag | False | Send credential emails | | `--clear` | flag | False | Clear existing staff first | | `--dry-run` | flag | False | Preview without making changes | ## Output Examples ### Without User Accounts ``` ============================================================ Staff Data Seeding Command ============================================================ Found 3 hospital(s) to seed staff Configuration: Physicians per hospital: 10 Nurses per hospital: 15 Admin staff per hospital: 5 Total staff per hospital: 30 Create user accounts: False Send credential emails: False Clear existing: False Dry run: False Seeding Physician... Seeding Nurse... Seeding Administrative... ============================================================ Summary: Physicians created: 30 Nurses created: 45 Admin staff created: 15 Total staff created: 90 ============================================================ Staff seeding completed successfully! ``` ### With User Accounts and Emails ``` ============================================================ Staff Data Seeding Command ============================================================ Found 3 hospital(s) to seed staff Configuration: Physicians per hospital: 10 Nurses per hospital: 15 Admin staff per hospital: 5 Total staff per hospital: 30 Create user accounts: True Send credential emails: True Clear existing: False Dry run: False Seeding Physician... ✓ Created user: mohammed.alotaibi (role: staff) ✓ Sent credential email to: mohammed.alotaibi@almadina.sa ✓ Created user: ahmed.aldosari (role: staff) ✓ Sent credential email to: ahmed.aldosari@almadina.sa ... ✓ Created 30 Physician Seeding Nurse... ✓ Created user: fatimah.alharbi (role: staff) ✓ Sent credential email to: fatimah.alharbi@almadina.sa ... ✓ Created 45 Nurse Seeding Administrative... ✓ Created user: abdulrahman.almutairi (role: staff) ✓ Sent credential email to: abdulrahman.almutairi@almadina.sa ... ✓ Created 15 Administrative ============================================================ Summary: Physicians created: 30 Nurses created: 45 Admin staff created: 15 Total staff created: 90 ============================================================ Staff seeding completed successfully! ``` ### With Errors ``` Seeding Physician... ✓ Created user: mohammed.alotaibi (role: staff) ✓ Sent credential email to: mohammed.alotaibi@almadina.sa ⚠ Failed to send email: SMTP server not configured ✗ Failed to create user for Ahmed Aldosari: Email already exists ✓ Created 29 Physician ``` ## Email Requirements For `--send-emails` to work, the following Django email settings must be 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' ``` Optional setting for login URL in emails: ```python SITE_URL = 'https://px360.yourdomain.com' ``` If `SITE_URL` is not configured, it defaults to `http://localhost:8000`. ## Data Generation ### Staff Names - Bilingual (English and Arabic) - Paired to ensure correspondence between languages - Gender-appropriate for staff types: - Nurses: 70% female, 30% male - Physicians: 60% male, 40% female - Admin staff: 60% male, 40% female ### Employee IDs Format: `{TYPE}-{HOSPITAL_CODE}-{RANDOM_NUMBER}` Examples: - Physicians: `DR-ALMADINA-12345` - Nurses: `RN-ALMADINA-23456` - Admin: `ADM-ALMADINA-34567` ### Usernames Format: `{firstname}.{lastname}` (lowercase) Examples: - `mohammed.alotaibi` - `fatimah.alharbi` - `ahmed.aldosari` Duplicate handling: Appends number if username exists: - `mohammed.alotaibi2` - `mohammed.alotaibi3` ### Email Addresses Format: `{username}@{hospital_code}.sa` Examples: - `mohammed.alotaibi@almadina.sa` - `fatimah.alharbi@riyadh.sa` ### Passwords - Length: 12 characters - Characters: Letters, numbers, and special characters - Generated using `secrets` module for cryptographic security - Included in credential email ## Testing ### Test Dry Run ```bash python manage.py seed_staff --dry-run --physicians 1 --nurses 1 ``` ### Test User Account Creation (No Email) ```bash python manage.py seed_staff --physicians 1 --nurses 1 --create-users ``` ### Test Full Workflow ```bash python manage.py seed_staff \ --hospital-code ALMADINA \ --physicians 2 \ --nurses 3 \ --admin-staff 1 \ --create-users \ --send-emails ``` ### Test Error Handling The command handles various error scenarios: - Duplicate usernames - Email conflicts - SMTP server not configured - Missing hospitals or departments ## Best Practices 1. **Use Dry Run First** Always test with `--dry-run` before running the actual command to preview what will be created. 2. **Start Small** Begin with small numbers (e.g., `--physicians 1 --nurses 1`) to verify everything works. 3. **Test Email Configuration** Test email delivery with a single staff member before sending to many: ```bash python manage.py seed_staff --physicians 1 --create-users --send-emails ``` 4. **Backup Data** Use `--clear` with caution as it deletes all existing staff: ```bash python manage.py seed_staff --clear --create-users ``` 5. **Monitor Logs** Check the output for: - ✅ Successful user creations - ⚠ Email sending warnings - ✗ Error messages ## Troubleshooting ### Issue: "SMTP server not configured" **Solution**: Configure email settings in `config/settings/base.py` ### Issue: "Email already exists" **Solution**: The command automatically handles this by using username as email fallback ### Issue: "Username already exists" **Solution**: The command automatically appends a number to make the username unique ### Issue: "No hospitals found" **Solution**: Create hospitals first using the hospital seed command or manually ### Issue: "No departments found" **Solution**: This is a warning. Staff will be created without departments. Create departments if needed. ## Migration Notes If you're upgrading from an older version: 1. **Email Field Migration** The Staff model already has the `email` field, so no migration is needed. 2. **User Account Creation** Existing staff without user accounts can have accounts created via: - UI: Staff Detail page → "Create User Account" button - API: `POST /api/organizations/staff/{id}/create_user_account/` - Admin: Select staff → "Create user accounts" action 3. **Backward Compatibility** The command is fully backward compatible. Running without flags creates staff profiles only. ## Related Documentation - [Staff User Account Implementation](STAFF_USER_ACCOUNT_IMPLEMENTATION.md) - [Organization Model](ORGANIZATION_MODEL.md) - [API Endpoints](API_ENDPOINTS.md) ## Future Enhancements Potential improvements for future versions: 1. **CSV Import** - Import staff from CSV files - Support bulk upload with user account creation 2. **Department Assignment** - Better department matching logic - Auto-assign based on specialization 3. **Email Templates** - Customizable email templates per hospital - Multi-language email support 4. **Progress Tracking** - Real-time progress updates for large batches - Percentage complete indicator 5. **Audit Logging** - Log all seed command executions - Track who ran the command and when ## Support For issues or questions: 1. Check the troubleshooting section above 2. Review the Staff User Account Implementation documentation 3. Check Django logs for detailed error messages 4. Ensure all dependencies are installed and configured correctly