# System Admin Management Guide

## Overview

The System Admin management system is a separate control system for managing administrators, account bans, and promo codes within the Beezifi workspace platform. 

### Key Features

- **System Admin Initialization**: Set up the first system admin during application setup
- **Multi-Admin Support**: Add and manage multiple system administrators
- **Account Banning**: Ban or suspend accounts with reasons and optional permanent status
- **Promo Code Management**: Create, distribute, and track promo code batches
- **TOTP 2FA**: Optional two-factor authentication for added security
- **Audit Logging**: Complete audit trail of all system admin actions
- **Separate System**: Isolated from regular organization management

---

## Initial Setup

### 1. Initialize the Database

First, migrate your database to include the new system admin tables:

```bash
mysql -u your_user -p your_database < nexus/database/schema.sql
```

### 2. Create the First System Admin

Run the initialization script:

```bash
cd nexus/backend
node scripts/initSystemAdmin.js
```

Follow the interactive prompts:

```
╔════════════════════════════════════════════════════════════╗
║      System Admin Initialization for Beezifi Workspace      ║
╚════════════════════════════════════════════════════════════╝

Checking for existing system admin...

No system admin found. Creating first system admin...

Enter admin email: admin@example.com
Enter admin username: sysadmin
Enter admin display name: System Administrator
Enter admin password (min 8 characters): ••••••••••••••••
Confirm password: ••••••••••••••••

Creating system admin...

✓ System admin created successfully!

═══════════════════════════════════════════════════════════
Admin Credentials:
  Email:    admin@example.com
  Username: sysadmin
  ID:       550e8400-e29b-41d4-a716-446655440000
═══════════════════════════════════════════════════════════

Next Steps:
  1. Log in to the system admin console using these credentials
  2. Set up TOTP 2FA (optional but recommended)
  3. Add additional system admins as needed
  4. Create promo code batches for billing
  5. Manage account bans and other administrative tasks
```

### 3. Access the System Admin Console

Navigate to `/admin` and log in with your newly created credentials.

---

## System Admin Console

The System Admin Console is a dedicated interface for managing the system. It's accessible only to users with `is_system_admin = TRUE`.

### Dashboard Tab

Overview of key metrics:
- Number of system admins
- Number of banned accounts
- Number of promo code batches
- Recent system activity

### Admins Tab

**View System Admins**
- Lists all current system administrators
- Shows TOTP/2FA status
- Displays creation date

**Add System Admin**
1. Click "+ Add Admin"
2. Enter the user ID to promote
3. Click "Add"
- User must already exist in the system
- User will gain access to the system admin console
- Action is logged for audit purposes

**Remove System Admin**
- Click "Remove" next to any admin
- Confirmation required
- User loses system admin privileges
- User can remain in normal organizations

---

## Account Management

### Ban Account

**To ban an account:**

1. Go to "Accounts" tab
2. Click "🚫 Ban Account"
3. Enter:
   - **User ID**: The UUID of the account to ban
   - **Reason**: Detailed reason for the ban
   - **Type**: Select "Permanent Ban" for permanent suspension

**Ban Effects:**
- Prevents login
- Blocks all API access
- Logged in audit trail
- Can be reversed by unbanning

**Ban Types:**
- **Temporary**: Can be unbanned at any time
- **Permanent**: Indicates a permanent suspension (can still be reversed)

### Unban Account

1. Find the account in "Currently Banned Accounts" list
2. Click "Unban"
3. Enter the reason for unbanning
4. Ban will be removed immediately

**Unban Effects:**
- Account can log in again
- Full API access restored
- Previous ban records maintained for audit
- Unban action logged

### View Ban History

Banned accounts list shows:
- Username and email
- Reason for ban
- Ban type (Temporary/Permanent)
- Admin who performed the ban
- Date of ban action
- Unban status (if applicable)

---

## Promo Code Management

### Create Promo Code Batch

1. Go to "Promo Codes" tab
2. Click "+ Create Batch"
3. Configure:
   - **Batch Name**: Descriptive name (e.g., "Q1 2024 Campaign")
   - **Plan** (optional): Restrict codes to specific plan
     - Leave blank: Works with any plan
     - Select plan: Only those plan types
   - **Duration**: 
     - 6 Months
     - 12 Months
   - **Quantity**: Number of codes to generate (1-10,000)
   - **Expires At** (optional): Automatic expiration date

4. Click "Create Batch"

**Results:**
- Batch created with unique codes
- 12-character codes formatted as XXX-XXX-XXX-XXX
- All codes generated with `is_used = FALSE`
- Codes are single-use

### Promo Code Batch List

View all batches with:
- **Batch Name**
- **Plan Target**: Which plan(s) the codes work with
- **Duration**: Months of service added
- **Total**: Total codes in batch
- **Used**: Number of already-redeemed codes
- **Available**: Number of codes not yet used
- **Created Date**

### View Batch Details

Click "View" on any batch to see:
- All promo codes
- Usage status of each code
- Organization that redeemed each code (if used)
- Redemption date (if used)
- Revocation status

### Revoke Promo Code

1. Find the batch and click "View"
2. Promo codes cannot be individually revoked via UI
3. Contact database administrator to revoke specific codes via:
   ```sql
   UPDATE promo_codes SET is_revoked = TRUE WHERE code = 'XXX-XXX-XXX-XXX';
   ```

---

## System Audit Logs

### View Audit Logs

Audit logs tab shows all system admin actions:

**Logged Information:**
- **Admin**: Username of who performed the action
- **Action**: Action type (ADMIN_ADD, ACCOUNT_BAN, PROMO_BATCH_CREATE, etc.)
- **Resource**: Type of resource affected
- **Target User**: User ID affected (if applicable)
- **IP Address**: Source of the request
- **Timestamp**: When the action occurred

**Action Types:**
- `SYSTEM_INIT`: System admin initialization
- `ADMIN_ADD`: Promote user to system admin
- `ADMIN_REMOVE`: Remove system admin privileges
- `ACCOUNT_BAN`: Ban an account
- `ACCOUNT_UNBAN`: Unban an account
- `PROMO_BATCH_CREATE`: Create promo code batch
- `PROMO_CODE_REVOKE`: Revoke a promo code

### Audit Log Retention

- All logs preserved indefinitely
- Immutable once created
- Includes IP addresses for security tracking
- User agent information captured

---

## API Reference

### System Admin Endpoints

#### Initialize System (Public)

```http
GET /api/system-admin/check
```

Check if system admin exists:

```json
{
  "success": true,
  "exists": true,
  "message": "System admin exists"
}
```

#### Create First Admin (Public)

```http
POST /api/system-admin/init
Content-Type: application/json

{
  "email": "admin@example.com",
  "username": "sysadmin",
  "password": "securepassword",
  "displayName": "System Administrator"
}
```

#### Add System Admin

```http
POST /api/system-admin/add-admin
Authorization: Bearer {token}
Content-Type: application/json

{
  "userId": "550e8400-e29b-41d4-a716-446655440000"
}
```

#### List System Admins

```http
GET /api/system-admin/admins
Authorization: Bearer {token}
```

Response:

```json
{
  "success": true,
  "data": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "email": "admin@example.com",
      "username": "sysadmin",
      "display_name": "System Administrator",
      "totp_enabled": false,
      "created_at": "2024-04-28T10:00:00Z"
    }
  ]
}
```

#### Ban Account

```http
POST /api/system-admin/ban-account
Authorization: Bearer {token}
Content-Type: application/json

{
  "userId": "550e8400-e29b-41d4-a716-446655440001",
  "reason": "Violation of terms of service",
  "isPermanent": false
}
```

#### Unban Account

```http
POST /api/system-admin/unban-account
Authorization: Bearer {token}
Content-Type: application/json

{
  "userId": "550e8400-e29b-41d4-a716-446655440001",
  "reason": "Appeal approved"
}
```

#### Get Ban Status

```http
GET /api/system-admin/ban-status/:userId
```

Response:

```json
{
  "success": true,
  "isBanned": true,
  "ban": {
    "id": "550e8400-e29b-41d4-a716-446655440002",
    "user_id": "550e8400-e29b-41d4-a716-446655440001",
    "reason": "Violation of terms",
    "is_permanent": false,
    "banned_at": "2024-04-28T10:00:00Z",
    "unbanned_at": null,
    "banned_by_name": "sysadmin"
  }
}
```

#### Create Promo Batch

```http
POST /api/system-admin/promo-batches
Authorization: Bearer {token}
Content-Type: application/json

{
  "name": "Q1 Campaign",
  "plan": "growth",
  "durationMonths": 12,
  "quantity": 100,
  "expiresAt": "2024-12-31T23:59:59Z"
}
```

Response:

```json
{
  "success": true,
  "message": "Promo batch created successfully",
  "batch": {
    "id": "550e8400-e29b-41d4-a716-446655440003",
    "name": "Q1 Campaign",
    "plan": "growth",
    "durationMonths": 12,
    "quantity": 100,
    "codes": [
      "ABC-DEF-GHI-JKL",
      "MNO-PQR-STU-VWX",
      "..."
    ]
  }
}
```

#### Get System Admin Logs

```http
GET /api/system-admin/logs?limit=100&offset=0
Authorization: Bearer {token}
```

---

## Security Best Practices

1. **Strong Passwords**: All system admin passwords should be at least 8 characters
2. **Enable TOTP 2FA**: Set up optional but recommended two-factor authentication
3. **Limit Admin Count**: Keep number of admins to minimum necessary
4. **Regular Audits**: Review system admin logs regularly
5. **Secure Access**: Only access admin console from secure networks
6. **Account Monitoring**: Watch for unusual admin activity in logs
7. **Backup Codes**: Generate and store backup authentication codes

---

## Troubleshooting

### No System Admin Exists
- Run `node scripts/initSystemAdmin.js` to create the first admin
- Ensure database migrations have been applied

### Cannot Log In
- Verify email and password
- Check if account is banned: `/api/system-admin/ban-status/:userId`
- Ensure `is_system_admin = TRUE` in database

### Promo Codes Not Generating
- Check database connection
- Verify batch quantity is within limits (1-10,000)
- Check for database errors in server logs

### Audit Logs Missing
- Logs are created for all actions automatically
- Check database `system_admin_logs` table
- Verify admin user has `is_system_admin = TRUE`

---

## Database Schema Reference

### banned_accounts
```sql
id, user_id, banned_by, reason, is_permanent, 
banned_at, unbanned_at, unbanned_by, unban_reason, 
created_at, updated_at
```

### system_admin_logs
```sql
id, admin_id, action, resource_type, resource_id, 
target_user_id, details, ip_address, user_agent, created_at
```

### system_admin_sessions
```sql
id, admin_id, session_token, ip_address, user_agent, 
totp_verified, expires_at, last_activity, created_at
```

---

## Support

For issues or questions about the System Admin system:
1. Check audit logs for recent actions
2. Review server logs for errors
3. Verify database integrity
4. Contact system administrator
