# Permissions Page Debugging Guide

## Overview
This guide explains the comprehensive logging system added to the permissions page and how to use it to debug issues.

## Console Logging Features

### 1. Page Load Logging
When the permissions page loads, you'll see:
- **Page initialization message** (purple, bold)
- **User information**: Target user and admin user details
- **URL and user agent** information

### 2. Form Analysis
The script logs:
- **Form element**: Action, method, CSRF token presence
- **All checkboxes**: Total count, checked/unchecked counts
- **Individual checkbox details**: Name, ID, checked state, value

### 3. Form Submission Interception
When you submit the form:
- **Submission intercepted** message (orange, bold)
- **Form data summary**: Total fields, checked/unchecked counts, CSRF token
- **All checked permissions**: List of all permissions being submitted
- **Unchecked permissions**: List of permissions not in POST (will use defaults)

### 4. Network Request Monitoring
The script intercepts and logs:
- **Fetch API calls**: URL, method, headers, response status, content type
- **XMLHttpRequest calls**: Method, URL, status, response type, content type
- **JSON parsing**: Attempts to parse JSON and logs errors if parsing fails
- **Response content**: First 200-500 characters of responses

### 5. Error Handling
- **Global error handler**: Catches all JSON parse errors
- **Unhandled promise rejections**: Catches async JSON parse errors
- **Detailed error information**: Error message, filename, line number, stack trace

## How to Use the Logs

### Step 1: Open Browser Console
1. Open the permissions page
2. Press F12 or right-click → Inspect → Console tab
3. Look for messages starting with `[PERMISSIONS PAGE]`

### Step 2: Check Initialization
Look for:
```
[PERMISSIONS PAGE] Initializing...
[PERMISSIONS PAGE] Page loaded: {...}
[PERMISSIONS PAGE] DOM Content Loaded
[PERMISSIONS PAGE] Form found: {...}
[PERMISSIONS PAGE] Found checkboxes: {...}
```

### Step 3: Submit the Form
1. Make your permission changes
2. Click "Save Permissions"
3. Watch the console for:
   - `[PERMISSIONS PAGE] Form submission intercepted`
   - Form data details
   - Network request logs

### Step 4: Check for Errors
Look for red error messages:
- `[PERMISSIONS PAGE] JSON PARSE ERROR DETECTED`
- `[PERMISSIONS PAGE] UNHANDLED PROMISE REJECTION (JSON)`
- `[PERMISSIONS PAGE] XHR JSON parse error`

## Common Issues and Solutions

### Issue 1: No Form Submission Logs
**Symptom**: Form submits but no console logs appear
**Solution**: Check if JavaScript is enabled and console is open

### Issue 2: JSON Parse Error
**Symptom**: Red error message about JSON parsing
**Check**:
1. Look for the XHR/Fetch log that shows the failing request
2. Check the response content (first 200-500 chars)
3. If it's HTML instead of JSON, the endpoint returned an error page
4. Check the URL - it might be wrong (404 = HTML error page)

### Issue 3: No Fields Matched
**Symptom**: `fields_matched: 0` in logs
**Solution**: Check if module code conversion is working:
- Compare checkbox `name` attributes in logs
- Verify they match what the view expects
- Check server logs for field names

### Issue 4: Permissions Not Saving
**Symptom**: Form submits but permissions don't change
**Check**:
1. Server logs for errors
2. Network tab - check response status
3. Console logs for field matching
4. Database to verify if records were created

## Network Tab Analysis

### Check Form Submission
1. Open Network tab
2. Submit the form
3. Look for POST request to the permissions URL
4. Check:
   - **Status**: Should be 200 or 302 (redirect)
   - **Request Payload**: Should include all checkbox fields
   - **Response**: Should be HTML (redirect page) or JSON (if AJAX)

### Check AJAX Calls
1. Filter by XHR/Fetch
2. Look for any requests that return JSON
3. Check if they're getting 404 (returns HTML, causes JSON parse error)

## Server Logs

Check Django server logs for:
```
POST request received: Admin=<id>, User=<id>, Fields count=<n>
Cleared <n> existing permissions for user <id>
Successfully updated permissions: Admin=<id> updated User=<id>, created=<n>, deleted=<n>
```

If you see:
- **No POST request logged**: Form not submitting (check console)
- **Zero fields matched**: Module code mismatch (check field names)
- **Zero permissions created**: All permissions match defaults (this is normal)
- **Error in logs**: Check exception details

## Example Console Output

### Successful Submission
```
[PERMISSIONS PAGE] Initializing...
[PERMISSIONS PAGE] Page loaded: {timestamp: "...", targetUser: {...}, ...}
[PERMISSIONS PAGE] DOM Content Loaded
[PERMISSIONS PAGE] Form found: {action: "", method: "post", hasCSRF: true}
[PERMISSIONS PAGE] Found checkboxes: {total: 150, checked: 75, unchecked: 75}
[PERMISSIONS PAGE] Form submission intercepted
[PERMISSIONS PAGE] Form submission data: {totalFields: 76, checkedCount: 75, ...}
[PERMISSIONS PAGE] Allowing form to submit normally...
```

### Error Case
```
[PERMISSIONS PAGE] XHR opened: {method: "GET", url: "/utils/api/notifications/unread-count/"}
[PERMISSIONS PAGE] XHR load: {status: 404, ...}
[PERMISSIONS PAGE] XHR JSON parse error: {error: "Unexpected token < in JSON at position 0", responseText: "<!DOCTYPE html>..."}
```

## Troubleshooting Checklist

- [ ] Console is open and showing logs
- [ ] Form submission is intercepted (orange message)
- [ ] Field names match expected format (`perm_<module>_<action>`)
- [ ] CSRF token is present
- [ ] Network request shows 200/302 status
- [ ] Server logs show POST request received
- [ ] Server logs show permissions created
- [ ] No JSON parse errors in console
- [ ] No 404 errors for static files

## Additional Notes

- All logs are prefixed with `[PERMISSIONS PAGE]` for easy filtering
- Use browser console filter to show only permission-related logs
- Network interceptors don't prevent requests, just log them
- Error handlers catch both sync and async JSON parse errors
- Form submission is NOT prevented - it still submits normally

