# Admin Onboarding System - Testing Guide

## Overview

This guide provides comprehensive testing scenarios for the complete admin onboarding system, including invite creation, acceptance, onboarding completion, and email notifications.

---

## Pre-Test Checklist

- [ ] Database migration executed (4 tables created)
- [ ] Email provider configured (SendGrid/Mailgun/SES/SMTP)
- [ ] Environment variables set (EMAIL_API_KEY, EMAIL_FROM_ADDRESS, etc.)
- [ ] Dev server running without TypeScript errors
- [ ] Admin user account created with super_admin role

---

## Test Scenario 1: Admin Invite Creation

### Steps

1. **Navigate to Admin Invite Management**
   - Go to `/admin/invite-management`
   - Verify page loads with "Create New Admin Invite" form

2. **Create Invite**
   - Fill in email: `newadmin@coinkrazy.com`
   - Select role: `moderator`
   - Click "Send Invite"
   - Verify success toast notification

3. **Verify Invite Created**
   - Check "Pending Invites" table
   - Verify invite shows correct email and role
   - Verify invite status is "pending"
   - Verify creation timestamp is recent

4. **Check Email Sent**
   - Check email inbox for `newadmin@coinkrazy.com`
   - Verify email contains:
     - Welcome message
     - Invite link with token
     - Role information
     - Onboarding instructions

### Expected Results

✅ Invite created in database
✅ Email sent successfully
✅ Invite appears in pending list
✅ Invite token is valid and unique

---

## Test Scenario 2: Admin Invite Acceptance

### Steps

1. **Accept Invite**
   - Click invite link in email or navigate to `/admin/accept-invite?token=<token>`
   - Verify page displays role and permissions
   - Click "Accept Invite"

2. **Setup Password**
   - Enter new password (min 12 chars, uppercase, number, special char)
   - Confirm password
   - Click "Continue"
   - Verify password validation works

3. **Complete Device Registration**
   - System auto-detects device info (browser, OS, IP)
   - Click "Register Device"
   - Verify device added to whitelist

4. **Verify Admin Created**
   - Check database for new admin user
   - Verify role matches invite
   - Verify device registered in `admin_device_registrations`
   - Verify invite status changed to "accepted"

### Expected Results

✅ Admin account created with correct role
✅ Password securely stored (hashed)
✅ Device registered and whitelisted
✅ Invite marked as accepted
✅ Confirmation email sent

---

## Test Scenario 3: Admin Onboarding Wizard

### Steps

1. **Login as New Admin**
   - Use credentials created in Scenario 2
   - Verify auto-redirect to `/admin/onboarding-wizard`

2. **Welcome Step**
   - Read welcome message
   - Click "Start Onboarding"
   - Verify progress saved (check database)

3. **Role Assignment Step**
   - Review assigned role and permissions
   - Click "Acknowledge Role"
   - Verify step marked complete

4. **Permission Training Step**
   - Read permission descriptions
   - Review access matrix
   - Click "I Understand Permissions"
   - Verify permissions acknowledged in database

5. **Security Training Step**
   - Complete 4 security topics (read each)
   - Take security quiz (70% required to pass)
   - Answer questions correctly
   - Verify quiz score saved (>= 70%)

6. **Device Registration Step**
   - Review registered device info
   - Verify IP whitelist enabled
   - Click "Device Registered"

7. **Completion Step**
   - Review completion summary
   - Click "Complete Onboarding"
   - Verify redirect to `/admin/profile-setup`

### Expected Results

✅ All steps completed in order
✅ Progress saved to database after each step
✅ Quiz score >= 70%
✅ Device registered and active
✅ Completion timestamp recorded
✅ Admin can now access admin panel

---

## Test Scenario 4: Admin Profile Setup

### Steps

1. **Access Profile Setup**
   - Navigate to `/admin/profile-setup`
   - Verify form loads with empty fields

2. **Fill Profile Information**
   - Upload avatar (optional)
   - Select timezone: "America/Chicago"
   - Select language: "English"
   - Click "Save Profile"

3. **Setup Notifications**
   - Enable in-app notifications
   - Enable email notifications
   - Select notification types:
     - Game Approvals: enabled
     - Fraud Alerts: enabled
     - Payment Issues: enabled
   - Set quiet hours: 10 PM - 8 AM
   - Click "Save Preferences"

4. **Setup 2FA (Optional)**
   - Click "Enable Two-Factor Authentication"
   - Scan QR code with authenticator app
   - Enter verification code
   - Generate and save backup codes
   - Click "Activate 2FA"

5. **Verify Profile Saved**
   - Check database `admin_profiles` table
   - Verify all fields saved correctly
   - Verify notification preferences stored

### Expected Results

✅ Profile information saved
✅ Notification preferences configured
✅ 2FA enabled (if chosen)
✅ Backup codes generated
✅ Admin ready for production use

---

## Test Scenario 5: Real-Time Alerts & Notifications

### Steps

1. **Login as Different Admin**
   - Open second browser/incognito window
   - Login as different admin user

2. **Trigger Alert Event**
   - From first admin, approve a game
   - Verify alert emitted in backend

3. **Receive Notification**
   - Check second admin's notification bell
   - Verify alert appears in real-time
   - Verify alert type icon correct
   - Verify alert message accurate

4. **Mark Alert as Read**
   - Click alert in notification bell
   - Verify alert marked as read
   - Verify unread count decremented

5. **Check Activity Dashboard**
   - Navigate to `/admin/activity-dashboard`
   - Verify game approval action logged
   - Verify admin name shown
   - Verify timestamp accurate

### Expected Results

✅ Alerts broadcast to connected admins in real-time
✅ Notification bell updates without page refresh
✅ Activity dashboard shows all admin actions
✅ Audit trail complete and accurate

---

## Test Scenario 6: Admin Role-Based Access Control

### Steps

1. **Login as Moderator**
   - Use moderator account from Scenario 2
   - Verify can access allowed sections:
     - Users Management
     - KYC Review
     - Activity Dashboard

2. **Verify Restricted Access**
   - Try to access Finance section
   - Verify access denied message
   - Verify redirect to allowed section

3. **Login as Finance Team**
   - Create new admin with `finance_team` role
   - Verify can access:
     - Payments & Banking
     - Financial Reports
     - Transaction Logs

4. **Verify Role Enforcement**
   - Try to perform admin-only action as moderator
   - Verify permission denied error
   - Verify action not executed

### Expected Results

✅ Role-based access control enforced
✅ Admins only see allowed sections
✅ Unauthorized actions blocked
✅ Proper error messages shown

---

## Test Scenario 7: Email Notifications

### Steps

1. **Verify Welcome Email**
   - Check inbox for welcome email
   - Verify sender: `noreply@coinkrazy.com`
   - Verify subject line professional
   - Verify email contains:
     - Personalized greeting
     - Onboarding link
     - Role information
     - Support contact info

2. **Verify Security Training Email**
   - Check for security training email
   - Verify contains:
     - Security best practices
     - 2FA setup instructions
     - Password policy
     - Device registration info

3. **Verify Completion Email**
   - Complete onboarding wizard
   - Check for completion confirmation email
   - Verify contains:
     - Congratulations message
     - Admin panel access link
     - Quick start guide

4. **Test Email Delivery**
   - Send test email from admin panel
   - Verify email arrives within 5 seconds
   - Verify no spam folder placement
   - Verify email formatting correct

### Expected Results

✅ All emails delivered successfully
✅ Email formatting correct
✅ Links functional
✅ Personalization working
✅ No emails in spam

---

## Test Scenario 8: Database Persistence

### Steps

1. **Verify Onboarding Progress Saved**
   ```sql
   SELECT * FROM admin_onboarding_progress WHERE adminId = <new_admin_id>;
   ```
   - Verify all steps marked complete
   - Verify quiz score saved
   - Verify completion timestamp

2. **Verify Admin Profile Saved**
   ```sql
   SELECT * FROM admin_profiles WHERE adminId = <new_admin_id>;
   ```
   - Verify timezone saved
   - Verify notification preferences
   - Verify 2FA settings

3. **Verify Device Registrations**
   ```sql
   SELECT * FROM admin_device_registrations WHERE adminId = <new_admin_id>;
   ```
   - Verify device info accurate
   - Verify IP address correct
   - Verify browser/OS detected correctly

4. **Verify Analytics Updated**
   ```sql
   SELECT * FROM onboarding_analytics ORDER BY dateRecorded DESC LIMIT 1;
   ```
   - Verify completion count incremented
   - Verify average quiz score calculated
   - Verify step completion rates updated

### Expected Results

✅ All data persisted correctly
✅ Database queries return expected results
✅ Analytics updated in real-time
✅ No data loss or corruption

---

## Performance Testing

### Load Testing

1. **Create Multiple Invites**
   - Create 10 admin invites simultaneously
   - Verify all created successfully
   - Verify response time < 2 seconds each

2. **Concurrent Onboarding**
   - Have 5 admins complete onboarding simultaneously
   - Verify no conflicts or data corruption
   - Verify database handles concurrent writes

3. **Alert Broadcasting**
   - Emit 100 alerts rapidly
   - Verify all delivered to connected admins
   - Verify no alerts lost

### Expected Results

✅ System handles concurrent operations
✅ Response times acceptable (< 2s)
✅ No data corruption under load
✅ Database connections pooled efficiently

---

## Security Testing

### Steps

1. **Invalid Token Handling**
   - Try to accept invite with invalid token
   - Verify error message shown
   - Verify no account created

2. **Expired Token Handling**
   - Create invite, wait 24 hours
   - Try to accept expired invite
   - Verify error message
   - Verify can request new invite

3. **Password Validation**
   - Try weak password (< 12 chars)
   - Verify validation error
   - Try password without uppercase
   - Verify validation error

4. **IP Whitelist Enforcement**
   - Login from registered device
   - Verify access granted
   - Try login from different IP
   - Verify access denied (if IP whitelist enabled)

5. **2FA Bypass Prevention**
   - Enable 2FA for admin
   - Try login without 2FA code
   - Verify access denied
   - Try with invalid 2FA code
   - Verify access denied

### Expected Results

✅ Invalid tokens rejected
✅ Expired tokens handled gracefully
✅ Password validation enforced
✅ IP whitelist working
✅ 2FA cannot be bypassed

---

## Rollback Testing

### Steps

1. **Test Checkpoint Rollback**
   - Save checkpoint before onboarding
   - Complete onboarding
   - Rollback to previous checkpoint
   - Verify onboarding progress cleared
   - Verify can start fresh

2. **Test Data Integrity After Rollback**
   - Verify no orphaned records
   - Verify foreign keys intact
   - Verify indexes still present

### Expected Results

✅ Rollback completes successfully
✅ Data integrity maintained
✅ System ready for fresh onboarding

---

## Troubleshooting

### Issue: Email Not Sent

**Solution:**
1. Verify EMAIL_API_KEY set correctly
2. Check email provider dashboard for errors
3. Verify sender email whitelisted
4. Check spam folder
5. Review server logs for errors

### Issue: Onboarding Progress Not Saved

**Solution:**
1. Verify database migration executed
2. Check database connection string
3. Verify tables created with correct schema
4. Check for database errors in logs
5. Verify user has database write permissions

### Issue: Role-Based Access Not Working

**Solution:**
1. Verify admin role assigned correctly
2. Check role-based guard component
3. Verify tRPC procedures checking role
4. Review permission matrix configuration
5. Check browser console for errors

### Issue: 2FA Not Working

**Solution:**
1. Verify authenticator app time synchronized
2. Check backup codes saved correctly
3. Verify 2FA secret stored in database
4. Check TOTP library configuration
5. Review 2FA setup logs

---

## Sign-Off Checklist

- [ ] All 8 test scenarios completed successfully
- [ ] Performance testing passed
- [ ] Security testing passed
- [ ] Database persistence verified
- [ ] Email notifications working
- [ ] Real-time alerts functioning
- [ ] Role-based access control enforced
- [ ] No critical bugs found
- [ ] Documentation complete
- [ ] Ready for production deployment

---

## Next Steps

1. **Deploy to Production**
   - Execute database migration on production database
   - Configure email provider with production keys
   - Deploy code to production environment

2. **Monitor System**
   - Watch error logs for issues
   - Monitor email delivery rates
   - Track admin onboarding completion rates

3. **Gather Feedback**
   - Collect admin feedback on UX
   - Identify pain points
   - Plan improvements for next iteration

4. **Optimize Performance**
   - Analyze database query performance
   - Optimize slow queries
   - Add caching where beneficial

---

**Last Updated:** April 13, 2026
**Version:** 1.0
**Status:** Ready for Testing
