# Custom Role Management Guide

## Overview

Sistem RBAC sekarang mendukung pembuatan, pengeditan, dan penghapusan **custom roles** untuk memenuhi kebutuhan bisnis yang spesifik.

## Features

### 1. Create Custom Role
- **Path:** Master → Roles → Create New Role
- **URL:** `/role/create`
- **Requirements:**
  - Role name: lowercase dengan underscore (e.g., `branch_manager`, `supervisor`, `auditor`)
  - Description: Deskripsi lengkap role (max 255 karakter)
- **Auto-features:**
  - BranchAccessRule applied automatically
  - Ready for permission assignment

### 2. Update Custom Role
- **Path:** Master → Roles → [Role Name] → Update
- **URL:** `/role/update?name=role_name`
- **Editable:**
  - Description only
- **Non-editable:**
  - Role name (cannot be changed after creation)

### 3. Delete Custom Role
- **Path:** Master → Roles → [Role Name] → Delete
- **URL:** `/role/delete?name=role_name`
- **Safety Checks:**
  - ✅ Prevent deletion of system roles
  - ✅ Prevent deletion if users are assigned to this role
  - ✅ Prevent deletion if other roles inherit from this role
  - ✅ Confirmation dialog required

### 4. Manage Permissions
- **Path:** Master → Roles → [Role Name] → Manage Permissions
- **URL:** `/role/manage-permissions?name=role_name`
- **Features:**
  - Checkbox interface grouped by category
  - Add/remove permissions dynamically
  - Works for both system and custom roles

---

## System vs Custom Roles

### System Roles (Protected)
Cannot be deleted, but permissions can be modified:
- `super_admin` - Super Administrator (Level 1)
- `branch_admin` - Branch Administrator (Level 2)
- `branch_staff` - Branch Staff (Level 3)
- `cashier` - Cashier
- `waiter` - Waiter
- `kitchen` - Kitchen Staff

**Label:** Red/Yellow/Blue badge with "System"

### Custom Roles (Fully Editable)
Can be created, updated, and deleted:
- Examples: `branch_manager`, `supervisor`, `auditor`, `warehouse_staff`, etc.

**Label:** Green badge with "Custom"

---

## Use Cases

### Example 1: Branch Manager Role
```
Name: branch_manager
Description: Branch Manager with additional reporting access

Permissions:
- All branch_admin permissions
- Additional: viewAllBranches, viewReportFinance
```

### Example 2: Warehouse Staff Role
```
Name: warehouse_staff
Description: Warehouse operations and inventory management

Permissions:
- viewInventory, updateInventory, adjustInventory
- viewTransfer, createTransfer, updateTransfer
- viewStockReport, viewStokMovement
- manageWarehouse
```

### Example 3: Accounting Role
```
Name: accounting
Description: Accounting and financial reporting access

Permissions:
- viewReportFinance, exportReports
- viewPurchaseInvoice, viewPurchasePayment
- viewReservationInvoice, viewReservationPayment
- viewDashboardPayable, viewDashboardProfit
```

---

## Workflow: Creating a New Custom Role

1. **Navigate to Roles**
   - Go to Master → Roles
   - Click "Create New Role" button

2. **Fill Role Details**
   - Name: `branch_manager` (lowercase, underscore)
   - Description: "Branch Manager with enhanced access"
   - Click "Create Role"

3. **Assign Permissions**
   - Click "Manage Permissions" button
   - Select desired permissions from grouped categories
   - Click "Save Permissions"

4. **Assign to Users**
   - Go to Master → Role Assignments
   - Select user
   - Assign the new custom role
   - Auto-revokes previous role

5. **Test Access**
   - Login as assigned user
   - Verify menu visibility matches permissions
   - Test controller access

---

## Best Practices

### Naming Convention
✅ **Good:**
- `branch_manager`
- `warehouse_supervisor`
- `accounting_staff`
- `audit_team`

❌ **Bad:**
- `BranchManager` (not lowercase)
- `branch manager` (has space)
- `branch-manager` (use underscore, not hyphen)
- `Manager` (too generic)

### Description Guidelines
- Be specific about the role's purpose
- Mention key responsibilities
- Max 255 characters
- Examples:
  - "Branch Manager with full operational control and reporting access"
  - "Warehouse Supervisor managing inventory and stock transfers"
  - "Accounting staff with financial reporting and invoice management"

### Permission Assignment Strategy
1. **Start with minimum permissions needed**
2. **Group related permissions together**
3. **Test thoroughly before production**
4. **Document custom role purposes**
5. **Regular audit of unused roles**

---

## API Reference

### RoleController Actions

#### Create
```php
POST /role/create
Parameters:
  - name: string (required, lowercase_underscore)
  - description: string (required, max 255)
Returns: Redirect to /role/view?name={name}
```

#### Update
```php
POST /role/update?name={role_name}
Parameters:
  - description: string (required, max 255)
Returns: Redirect to /role/view?name={name}
```

#### Delete
```php
POST /role/delete?name={role_name}
Safety checks:
  - Not a system role
  - No users assigned
  - No child roles depending on it
Returns: Redirect to /role/index
```

---

## Troubleshooting

### Error: "Role name must be lowercase with underscores"
**Solution:** Use format like `branch_manager`, not `branchManager` or `Branch Manager`

### Error: "Role already exists"
**Solution:** Choose a different role name. Role names must be unique.

### Error: "Cannot delete role. X user(s) are assigned"
**Solution:** 
1. Go to Role Assignments
2. Reassign users to different roles
3. Then delete the custom role

### Error: "Cannot delete role. It is inherited by: ..."
**Solution:**
1. Remove inheritance from parent roles first
2. Then delete the custom role

### Custom role not appearing in Role Assignment dropdown
**Solution:** Refresh the page. New roles are immediately available after creation.

---

## Security Considerations

1. **System Role Protection**
   - Built-in roles cannot be deleted
   - Prevents accidental system breakage
   - Permissions can still be modified

2. **User Assignment Check**
   - Cannot delete roles with active users
   - Forces proper user reassignment
   - Maintains audit trail

3. **Hierarchy Validation**
   - Cannot delete parent roles with dependencies
   - Ensures role hierarchy integrity
   - Prevents orphaned permissions

4. **Permission Inheritance**
   - Custom roles can inherit from any role
   - Build complex hierarchies as needed
   - Maintain clear documentation

---

## Migration from Jabatan System

Old `jabatan` values can be mapped to custom roles:

```php
// Console migration already handles system roles
// For custom business roles:

JABATAN_SUPERVISOR → custom role: supervisor
JABATAN_MANAGER → custom role: branch_manager
JABATAN_WAREHOUSE → custom role: warehouse_staff
```

Run after creating custom roles:
```bash
php yii rbac/migrate-users
```

---

## Summary

✅ **Create** unlimited custom roles  
✅ **Update** role descriptions anytime  
✅ **Delete** unused custom roles safely  
✅ **Manage** permissions flexibly  
✅ **Protect** system roles from deletion  
✅ **Assign** to users via UI or console  

The RBAC system is now fully customizable while maintaining safety and integrity!
