# RBAC System - Visual Architecture & Quick Reference

## 🏗️ System Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    USER AUTHENTICATION                       │
│              (Login → Email Verification Required)           │
└─────────────────┬───────────────────────────────────────────┘
                  │
                  ▼
        ┌─────────────────────────┐
        │   Get User Role         │
        │ ├─ super_admin          │
        │ ├─ company_admin        │
        │ ├─ cashier              │
        │ ├─ meter_reader         │
        │ └─ customer             │
        └─────────────┬───────────┘
                      │
                      ▼
        ┌─────────────────────────────────┐
        │   CheckRole Middleware          │
        │   Validates Role Authorization  │
        │   ├─ Super admin → All routes   │
        │   ├─ Others → Role-specific     │
        │   └─ 403 on failure             │
        └─────────────┬───────────────────┘
                      │
                      ▼
        ┌──────────────────────────────────┐
        │   Route Handler (Controller)     │
        │   ├─ Load data                   │
        │   ├─ Filter by company_id        │
        │   ├─ Check policies              │
        │   └─ Return view                 │
        └─────────────┬────────────────────┘
                      │
                      ▼
        ┌──────────────────────────────────┐
        │   Render View                    │
        │   ├─ Role-specific dashboard     │
        │   ├─ Filtered data only          │
        │   └─ Log activity                │
        └──────────────────────────────────┘
```

---

## 👥 Role Hierarchy & Permissions

```
┌─────────────────────────────────────────────────────────────┐
│ 🔴 SUPER ADMIN (Global Access)                              │
├─────────────────────────────────────────────────────────────┤
│ ✅ View all companies                                        │
│ ✅ Manage all users                                          │
│ ✅ System settings                                           │
│ ✅ All company resources (filtered view)                     │
│ ✅ Activity logs                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│ 🟠 COMPANY ADMIN (Company Level)                             │
├─────────────────────────────────────────────────────────────┤
│ ✅ Manage clients                                            │
│ ✅ Create & manage billings                                  │
│ ✅ Record & manage payments                                  │
│ ✅ Meter reading management                                  │
│ ✅ Staff management                                          │
│ ✅ Company settings & profile                                │
│ ✅ Activity logs (own company)                               │
│ ❌ Cannot access system settings or other companies          │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│ 🟡 CASHIER (Payment Focus)                                   │
├─────────────────────────────────────────────────────────────┤
│ ✅ View billings                                             │
│ ✅ Record payments                                           │
│ ✅ View/manage clients (for disconnection)                   │
│ ✅ View applications                                         │
│ ❌ Cannot create/edit clients                                │
│ ❌ Cannot create/delete billings                             │
│ ❌ Cannot access company settings                            │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│ 🟢 METER READER (Operations)                                 │
├─────────────────────────────────────────────────────────────┤
│ ✅ Record meter readings                                     │
│ ✅ View own recordings                                       │
│ ✅ View clients (for meter purposes)                         │
│ ❌ Cannot access billing or payments                         │
│ ❌ Cannot manage any settings                                │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│ 🔵 CUSTOMER (Personal Only)                                  │
├─────────────────────────────────────────────────────────────┤
│ ✅ View own billings                                         │
│ ✅ View own payment history                                  │
│ ❌ Cannot access admin features                              │
│ ❌ Cannot manage any resources                               │
└─────────────────────────────────────────────────────────────┘
```

---

## 🗺️ Route Map by Role

```
                           PUBLIC ROUTES
                           ✓ /home
                           ✓ /apply/{slug}
                           ✓ /application/{ref}
                           ✓ /receipt/{id}
                                │
                                ▼
                    ┌──────────────────────┐
                    │   AUTHENTICATED      │
                    │   Routes             │
                    │ ✓ /dashboard         │
                    │ ✓ /profile           │
                    └──────────────────────┘
                           │
            ┌──────────────┼──────────────┐
            │              │              │
            ▼              ▼              ▼
      SUPER ADMIN   COMPANY ADMIN    CASHIER
      ───────────   ────────────     ──────────
      /companies    /clients         /clients
      /currencies   /billings        /billings
      /users        /payments        /payments
      /admin/settings /meter-readings /applications
                    /tiers
                    /staff
                    /company/*
            │              │              │
            ▼              ▼              ▼
      METER READER       CUSTOMER
      ───────────────    ────────────
      /record-meter      /my-billings
      /my-meter-readings /my-payments
```

---

## 🔐 Data Isolation by Role

```
DATABASE
│
├── Companies [All companies in system]
│   │
│   ├── Company A
│   │   ├── Users [All users in Company A]
│   │   │   ├── super_admin_1      → Can see: ALL
│   │   │   ├── company_admin_1    → Can see: Company A only
│   │   │   ├── cashier_1          → Can see: Company A only
│   │   │   └── meter_reader_1     → Can see: Company A only
│   │   │
│   │   └── Clients [Company A's clients]
│   │       ├── Client 1
│   │       │   └── Billings [Company A's billings]
│   │       │       └── Payments
│   │       └── Client 2
│   │           └── Billings
│   │               └── Payments
│   │
│   └── Company B [Similar structure]
│       ├── Users
│       ├── Clients
│       └── Data
│
└── Note: super_admin can filter by company_id
         company_admin/cashier MUST belong to company
         Data is automatically filtered per controller
```

---

## 🎯 Access Decision Tree

```
User Requests Route
        │
        ├─ Is user authenticated?
        │  ├─ NO → Redirect to login
        │  └─ YES → Continue
        │
        ├─ Is email verified?
        │  ├─ NO → Redirect to verification
        │  └─ YES → Continue
        │
        ├─ Is role allowed for this route?
        │  ├─ NO → Return 403 Forbidden
        │  └─ YES → Continue
        │
        ├─ Is data owned by user's company?
        │  ├─ NO → Return 403 Forbidden
        │  └─ YES → Continue
        │
        └─ Grant access & log activity
           │
           └─ Render view with filtered data
```

---

## 📊 Dashboard Distribution

```
User Login
    │
    ├─ Super Admin Role?
    │  └─→ SUPER ADMIN DASHBOARD
    │     ├─ Total Companies
    │     ├─ Total Users
    │     ├─ System Activity
    │     └─ All Statistics
    │
    ├─ Company Admin Role?
    │  └─→ COMPANY ADMIN DASHBOARD
    │     ├─ Company Statistics
    │     ├─ Client Count
    │     ├─ Billing Status
    │     └─ Revenue Overview
    │
    ├─ Cashier Role?
    │  └─→ CASHIER DASHBOARD
    │     ├─ Payment Collections
    │     ├─ Daily Revenue
    │     ├─ Pending Payments
    │     └─ Recent Transactions
    │
    ├─ Meter Reader Role?
    │  └─→ METER READER DASHBOARD
    │     ├─ Meter Reading Stats
    │     ├─ Clients to Read
    │     └─ Recent Readings
    │
    └─ Customer Role?
       └─→ CUSTOMER DASHBOARD
          ├─ My Billings
          ├─ My Payment Status
          └─ Outstanding Balance
```

---

## 🔄 Authorization Flow Examples

### Example 1: Super Admin Creating a Billing
```
1. User (super_admin) → GET /billings/create
2. Middleware: Is role "super_admin"?
   ✅ YES → Continue
3. Controller: Load create form
4. User submits form → POST /billings
5. Middleware: Is role "super_admin"?
   ✅ YES → Continue
6. Controller: Create billing (no company filter needed)
7. Log: "Billing created by Super Admin"
8. Redirect to /billings/{id}
```

### Example 2: Company Admin Viewing Billings
```
1. User (company_admin, Company A) → GET /billings
2. Middleware: Is role "company_admin"?
   ✅ YES → Continue
3. Controller: Query billings
   WHERE company_id = user->company->id (Company A)
4. View renders: Only Company A's billings
5. Log: "Billings viewed by Company Admin for Company A"
```

### Example 3: Cashier Accessing Restricted Route
```
1. User (cashier) → GET /company/settings
2. Middleware: Is role "cashier"?
   ❌ NO → Cashier not allowed
3. Abort: 403 Forbidden
4. Log: "Access DENIED - Cashier tried to access company/settings"
5. User sees: 403 error page
```

### Example 4: Cashier from Different Company
```
1. User (cashier, Company A) → GET /billings/1
   (Billing 1 belongs to Company B)
2. Middleware: Is role "cashier"?
   ✅ YES → Continue
3. Controller: Load Billing 1
   Check: billing->company_id == user->company->id?
   ❌ Company B ≠ Company A
4. Abort: 403 Forbidden
5. Log: "Cashier from Company A tried to access Company B data"
```

---

## 🚦 Status Codes Reference

| Code | Meaning | When You See It |
|------|---------|---|
| **200** | Success | Page loaded successfully |
| **302** | Redirect | Login redirect, etc. |
| **403** | Forbidden | Unauthorized role or data |
| **404** | Not Found | Resource doesn't exist |
| **500** | Server Error | Programming error, check logs |

---

## 📋 Quick Checklist

### For Each Role:
- [ ] Can access own dashboard
- [ ] Can access authorized routes
- [ ] Cannot access unauthorized routes (403)
- [ ] Sees only own company's data (if applicable)
- [ ] Actions are logged

### For System:
- [ ] Email verification working
- [ ] Middleware enforcing roles
- [ ] Activity logs recording
- [ ] 403 errors on unauthorized access
- [ ] Performance acceptable

---

## 📂 Configuration Files

### Routes Configuration
**File:** `routes/web.php`
- Lines 26-36: Authenticated routes
- Lines 38-45: Super admin routes
- Lines 47-83: Company-level resources
- Lines 85-87: Company admin routes
- Lines 89-91: Cashier routes
- Lines 93-96: Meter reader routes
- Lines 98-101: Customer routes

### Middleware Configuration
**File:** `app/Http/Middleware/CheckRole.php`
- Takes role parameter: `check.role:super_admin`
- Supports multiple: `check.role:role1,role2`
- Logs all attempts
- Aborts with 403 if unauthorized

### Controller Configuration
**File:** `app/Http/Controllers/DashboardController.php`
- `index()` - Routes to role-specific dashboard
- `superAdminDashboard()` - System overview
- `companyAdminDashboard()` - Company stats
- `cashierDashboard()` - Payment stats
- `meterReaderDashboard()` - Meter ops
- `customerDashboard()` - Personal billing

---

## 🎓 Key Concepts

### **Multi-Tenancy**
- One system serves multiple companies
- Data isolation by company_id
- Each company admin sees only their data

### **Role-Based Access Control (RBAC)**
- Access determined by user's role
- Clear permission boundaries
- Easy to manage and audit

### **Authorization**
- Multiple layers: middleware → controller → policy → view
- Fail-safe: deny by default, allow explicitly
- Logged for audit trail

### **Activity Logging**
- Every action recorded
- User identification
- Before/after values
- Searchable and exportable

---

## ✅ Verification Checklist

Run these after deployment:

```bash
# 1. Check middleware is loaded
grep -r "check.role" routes/

# 2. Verify role methods exist
grep -r "isSuperAdmin\|isCompanyAdmin\|isCashier" app/Models/

# 3. Test activity logging
Visit /logs → Should see recent entries

# 4. Check error logging
tail storage/logs/laravel.log | grep "CheckRole"

# 5. Verify database structure
SELECT * FROM roles;
SELECT role_id, company_id FROM users WHERE id = 1;
```

---

## 📞 Quick Support

| Issue | Solution |
|-------|----------|
| 403 Error | Check role in user record, verify middleware config |
| Wrong data showing | Check company_id filter in controller |
| Dashboard not loading | Verify role has dashboard method & view file |
| Logs not recording | Check ActivityLog model and migrations |
| Routes not working | Run `php artisan route:clear` |

---

## 🎯 Success Metrics

After implementation:
- ✅ Users can only access their role's routes
- ✅ Users see only their company's data
- ✅ All actions are logged with user info
- ✅ System responds quickly (<200ms per request)
- ✅ No data leakage between companies
- ✅ Clear 403 errors for unauthorized access

---

**This is your visual reference guide for the RBAC system!** 📊

For detailed information, see the other RBAC documentation files.

