# Database Fix: User Permissions Table

## Problem

You're encountering this error:
```
OperationalError: (1054, "Unknown column 'user_permissions.module' in 'field list'")
```

This happens when the database table structure doesn't match the Django model definition.

## Quick Fix

### Option 1: Quick Fix Script (Recommended)
```bash
python fix_permissions_db.py
```

### Option 2: Production Fix Script
```bash
# Test first
python production_database_fix.py --dry-run

# Apply fix
python production_database_fix.py
```

### Option 3: Manual Django Command
```bash
python manage.py shell
```
Then run:
```python
from django.db import connection
cursor = connection.cursor()
cursor.execute("""
    ALTER TABLE user_permissions 
    MODIFY COLUMN module VARCHAR(50) NOT NULL
""")
```

## What the Fix Does

1. **Checks** if the `user_permissions` table exists
2. **Creates** the table if it doesn't exist
3. **Adds** missing columns if they're missing
4. **Updates** column types (e.g., module VARCHAR(20) → VARCHAR(50))
5. **Runs** Django migrations to sync everything
6. **Verifies** the fix worked

## Files Created

- `fix_permissions_db.py` - Quick fix script
- `production_database_fix.py` - Comprehensive production fix
- `fix_user_permissions_database.py` - Alternative fix script

## After the Fix

The user permissions page should work correctly:
- Navigate to Staff Management → Select User → User Permissions
- You should be able to check/uncheck permissions without errors
- The permission-based navigation system will work as expected

## Troubleshooting

If you still get errors:

1. **Check Django migrations**:
   ```bash
   python manage.py migrate users
   ```

2. **Verify table structure**:
   ```bash
   python manage.py shell
   ```
   ```python
   from django.db import connection
   cursor = connection.cursor()
   cursor.execute("DESCRIBE user_permissions")
   print(cursor.fetchall())
   ```

3. **Check for foreign key issues**:
   - Ensure the `users` table exists
   - Verify user IDs are consistent

## Production Notes

- The fix scripts create backups automatically
- All changes are logged for audit purposes
- Use `--dry-run` to test before applying changes
- The fix is safe to run multiple times

---

**The fix resolves the database schema mismatch and allows the permission-based navigation system to work correctly.**
