# Roles and Permissions Clean Rebuild System

This system provides a comprehensive solution to clean up all existing roles and permissions data and rebuild them fresh with a well-structured hierarchy.

## 📁 Files Created

1. **`clean_and_rebuild_roles_permissions.js`** - Main script to clean and rebuild roles/permissions
2. **`test_roles_permissions.js`** - Test script to verify the implementation
3. **`ROLES_PERMISSIONS_REBUILD_GUIDE.md`** - This documentation file

## 🎯 What This System Does

### Cleanup Process
- Removes all existing roles and permissions data
- Clears all role-permission mappings
- Clears all user-specific permissions
- Resets auto-increment counters
- Maintains database integrity with proper foreign key handling

### Rebuild Process
- Creates 5 hierarchical roles with proper levels
- Creates 60+ comprehensive permissions across all system modules
- Maps permissions to roles based on hierarchical access levels
- Ensures data integrity and proper relationships

## 🏗️ Role Hierarchy

| Level | Role | Description | Permission Count |
|-------|------|-------------|------------------|
| 100 | Super Admin | Full system access and control | All permissions |
| 50 | Admin | Elevated privileges and management | Most permissions |
| 30 | Manager | Departmental oversight and management | Departmental permissions |
| 20 | Officer | Operational access and reporting | Operational permissions |
| 10 | User | Standard access and basic permissions | Basic permissions |

## 🔐 Permission Categories

### User Management (7 permissions)
- Create, Read, Update, Delete users
- Manage roles and permissions
- Export/Import user data

### Organizational Structure (16 permissions)
- Unit management (4 permissions)
- Department management (4 permissions)
- Designation management (4 permissions)
- Rank management (4 permissions)

### Contact Directory (6 permissions)
- Create, Read, Update, Delete contacts
- Export/Import contact data

### Messaging System (9 permissions)
- Message management (5 permissions)
- Conversation management (5 permissions)

### Notification System (5 permissions)
- Create, Read, Update, Delete notifications
- Broadcast notifications

### Feedback System (5 permissions)
- Submit, Read, Update, Delete feedback
- Respond to feedback

### System Management (7 permissions)
- Audit log management (3 permissions)
- System settings (4 permissions)

### Dashboard & Reports (4 permissions)
- View dashboard, analytics, reports
- Customize dashboard

### File Management (4 permissions)
- Upload, Download, Delete files
- Manage file permissions

### Profile Management (3 permissions)
- View, Update own profile
- Change password

## 🚀 How to Use

### Step 1: Run the Clean Rebuild Script

```bash
cd navy_cms/backend
node clean_and_rebuild_roles_permissions.js
```

**Expected Output:**
```
🔗 Connecting to database...
✅ Database connected successfully

🧹 Starting cleanup process...
   - Clearing user_permissions...
   - Clearing role_permissions...
   - Clearing permissions...
   - Clearing roles...
   - Resetting auto increment counters...
✅ Cleanup completed successfully

🔄 Starting rebuild process...
   - Inserting fresh roles...
   ✅ Inserted 5 roles
   - Inserting fresh permissions...
   ✅ Inserted 60 permissions
   - Mapping roles to permissions...
   ✅ Mapped 150 role-permission relationships

🎉 Roles and permissions rebuild completed successfully!

📊 Summary:
   - Roles: 5
   - Permissions: 60
   - Role-Permission Mappings: 150

👥 Role Hierarchy:
   100. Super Admin (60 permissions)
   50. Admin (55 permissions)
   30. Manager (35 permissions)
   20. Officer (25 permissions)
   10. User (20 permissions)

✨ Script completed successfully!
```

### Step 2: Test the Implementation

```bash
node test_roles_permissions.js
```

**Expected Output:**
```
🔗 Connecting to database...
✅ Database connected successfully

📊 Testing Roles and Permissions System...

1️⃣ Testing Roles:
   Found 5 roles:
   - Super Admin (Level: 100) - Super Administrator with full system access and control
   - Admin (Level: 50) - Administrator with elevated privileges and management access
   - Manager (Level: 30) - Manager with departmental oversight and user management
   - Officer (Level: 20) - Officer with operational access and reporting capabilities
   - User (Level: 10) - Regular user with standard access and basic permissions

2️⃣ Testing Permissions:
   Found 60 permissions:
   📁 AUDIT_LOG:
      - delete: Delete audit logs
      - export: Export audit logs
      - read: View audit logs
   📁 CONTACT:
      - create: Create new contacts
      - delete: Delete contacts
      - export: Export contact data
      - import: Import contact data
      - read: View contact information
      - update: Update contact information
   ... (and more)

3️⃣ Testing Role-Permission Mappings:
   Super Admin (Level 100): 60 permissions
   Admin (Level 50): 55 permissions
   Manager (Level 30): 35 permissions
   Officer (Level 20): 25 permissions
   User (Level 10): 20 permissions

4️⃣ Detailed Permission Breakdown:
   👤 Super Admin (60 permissions):
      📁 audit_log: delete, export, read
      📁 contact: create, delete, export, import, read, update
      ... (all permissions)

5️⃣ Checking for Data Integrity:
   Orphaned role_permissions: 0
   Orphaned permissions in role_permissions: 0
   Orphaned user_permissions: 0

6️⃣ Verifying Permission Patterns:
   Super Admin permissions: 60/60 (100.0%)
   User role permissions: 20

✅ All tests completed successfully!

📋 Summary:
   - Total Roles: 5
   - Total Permissions: 60
   - Total Role-Permission Mappings: 195
   - Data Integrity: ✅ Clean

✨ Test completed successfully!
```

## ⚠️ Important Notes

### Before Running
1. **Backup your database** - This script will delete all existing roles and permissions
2. **Check environment variables** - Ensure your `.env` file has correct database credentials
3. **Stop the application** - Make sure no other processes are using the database

### After Running
1. **Update existing users** - Existing users will need their roles reassigned
2. **Test thoroughly** - Run the test script to verify everything works correctly
3. **Update frontend** - Frontend permission checks may need updates for new permission names

### Database Requirements
- MySQL 8.0+ or MariaDB 10.3+
- Proper foreign key constraints enabled
- Sufficient privileges to modify table structure

## 🔧 Customization

### Adding New Roles
Edit the `freshRoles` array in `clean_and_rebuild_roles_permissions.js`:

```javascript
const freshRoles = [
    // ... existing roles
    {
        id: 6,
        name: 'Guest',
        description: 'Guest user with limited access',
        level: 5,
        is_active: 1
    }
];
```

### Adding New Permissions
Edit the `freshPermissions` array:

```javascript
const freshPermissions = [
    // ... existing permissions
    { name: 'report.generate', description: 'Generate reports', resource: 'report', action: 'generate' }
];
```

### Modifying Role-Permission Mappings
Edit the `rolePermissions` object:

```javascript
const rolePermissions = {
    // ... existing mappings
    6: ['report.generate', 'dashboard.view'] // Guest role permissions
};
```

## 🐛 Troubleshooting

### Common Issues

1. **Foreign Key Constraint Errors**
   - The script handles this by temporarily disabling foreign key checks
   - If you still get errors, check your MySQL version and settings

2. **Permission Denied Errors**
   - Ensure your database user has sufficient privileges
   - Check your `.env` file for correct credentials

3. **Connection Errors**
   - Verify database is running
   - Check host, port, and credentials
   - Ensure database exists

### Recovery
If something goes wrong:
1. Restore from your database backup
2. Check the error logs
3. Verify your database configuration
4. Run the test script to identify issues

## 📞 Support

If you encounter any issues:
1. Check the console output for specific error messages
2. Verify your database configuration
3. Ensure all dependencies are installed (`mysql2`, `dotenv`)
4. Run the test script to identify specific problems

## 🎉 Benefits

- **Clean Slate**: Removes all existing complexity and inconsistencies
- **Hierarchical Structure**: Clear role hierarchy with appropriate permission levels
- **Comprehensive Coverage**: Covers all system modules and functionalities
- **Data Integrity**: Maintains proper foreign key relationships
- **Easy Testing**: Built-in verification and testing capabilities
- **Customizable**: Easy to modify and extend for specific needs

This system provides a solid foundation for your Navy CMS roles and permissions system with proper hierarchy, comprehensive coverage, and maintainable structure.
