# 🔐 Role-Based Access Control Implementation

## Overview

The application now enforces **strict role-based access control** to completely separate the Sales and Inventory modules. Each user type can ONLY access their designated module(s).

---

## User Roles & Access

### 1. **Admin** (`admin`)
- ✅ Access to **Sales Dashboard** (`/dashboard`)
- ✅ Access to **Inventory Module** (`/inventory`)
- Can see both navigation tabs
- Full access to all features

### 2. **Comercial** (`comercial`)
- ✅ Access to **Sales Dashboard** (`/dashboard`)
- ❌ **Blocked** from Inventory Module
- Only sees Sales tab in navigation
- Can view only their assigned sales data

### 3. **Viewer** (`viewer`)
- ✅ Access to **Sales Dashboard** (`/dashboard`)
- ❌ **Blocked** from Inventory Module
- Only sees Sales tab in navigation
- Can view all sales data (read-only)

### 4. **Warehouse** (`warehouse`)
- ✅ Access to **Inventory Module** (`/inventory`)
- ❌ **Blocked** from Sales Dashboard
- Only sees Inventory tab in navigation
- Can view all inventory data

---

## How It Works

### 1. **Automatic Routing After Login**

When a user logs in successfully, they are **automatically redirected** to their appropriate dashboard:

- **Warehouse users** → `/inventory`
- **All other users** → `/dashboard`

### 2. **Access Control Functions**

Two new functions enforce access:

#### `has_dashboard_access(user_role, user_email)`
- Returns `True` for: `admin`, `comercial`, `viewer`
- Returns `False` for: `warehouse`

#### `has_inventory_access(user_role, user_email)`
- Returns `True` for: `admin`, `warehouse`
- Returns `False` for: `comercial`, `viewer`

### 3. **Access Denied Pages**

If a user tries to access a module they don't have permission for:

- **Warehouse user visits `/dashboard`**:
  - Shows: "🚫 Acesso Negado - Este módulo é para a equipa de vendas"
  - Button: "→ Ir para Inventário"
  
- **Sales user visits `/inventory`**:
  - Shows: "🚫 Acesso Negado - Este módulo é apenas para a equipa de armazém"
  - Button: "→ Ir para Vendas"

### 4. **Navigation Tabs (Role-Based)**

Navigation tabs in `base.html` only show modules the user has access to:

```html
<!-- Sales Tab (visible to: admin, comercial, viewer) -->
{% if user_role in ['admin', 'comercial', 'viewer'] %}
<a href="/dashboard">📊 Vendas</a>
{% endif %}

<!-- Inventory Tab (visible to: admin, warehouse) -->
{% if user_role in ['admin', 'warehouse'] %}
<a href="/inventory">📦 Inventário</a>
{% endif %}
```

---

## Configuration

### Adding Warehouse Team Members

Edit `app.py` lines ~82-87:

```python
WAREHOUSE_EMAILS = {
    "warehouse1@globalerc.com",
    "warehouse2@globalerc.com",
    # Add more warehouse emails here
}
```

Or update `USERS_ROLES` mapping (lines ~89-107):

```python
USERS_ROLES = {
    # ... existing roles ...
    
    # Warehouse team
    "warehouse1@globalerc.com": "warehouse",
    "warehouse2@globalerc.com": "warehouse",
}
```

### Role Priority

The `get_user_role()` function checks in this order:

1. **USERS_ROLES mapping** (explicit role assignment)
2. **ADMIN_EMAILS** set → returns `admin`
3. **COMMERCIAL_EMAILS** set → returns `comercial`
4. **WAREHOUSE_EMAILS** set → returns `warehouse`
5. **Default** → returns `viewer`

---

## Testing Access Control

### Test as Warehouse User

1. Add your test email to `WAREHOUSE_EMAILS`
2. Login with that email
3. ✅ Should redirect to `/inventory` automatically
4. ✅ Should see only "📦 Inventário" tab
5. ❌ Trying to visit `/dashboard` should show "Access Denied" page

### Test as Sales User (Comercial/Viewer)

1. Add your test email to `COMMERCIAL_EMAILS` or let it default to `viewer`
2. Login with that email
3. ✅ Should redirect to `/dashboard` automatically
4. ✅ Should see only "📊 Vendas" tab
5. ❌ Trying to visit `/inventory` should show "Access Denied" page

### Test as Admin

1. Add your test email to `ADMIN_EMAILS`
2. Login with that email
3. ✅ Should redirect to `/dashboard` (default)
4. ✅ Should see both "📊 Vendas" AND "📦 Inventário" tabs
5. ✅ Can access both `/dashboard` and `/inventory` freely

---

## Code Changes Summary

### 1. **app.py Updates**

- **Line 6**: Added `render_template` import
- **Line 14**: Added `json` import
- **Lines 188-208**: Updated `get_user_role()` to check all role sets
- **Lines 1045-1057**: Updated `/` route to redirect warehouse users to inventory
- **Lines 1318-1376**: Added access control to `/dashboard` route
- **Lines 4416-4435**: Created `has_inventory_access()` and `has_dashboard_access()` functions
- **Lines 4437-4478**: Added access control to `/inventory` route

### 2. **templates/base.html Updates**

- **Lines 116-124**: Added role-based navigation tabs (conditional rendering)

---

## Important Notes

### ✅ Complete Separation Achieved

- Warehouse staff **cannot see** sales data (blocked at route level)
- Sales staff **cannot see** inventory data (blocked at route level)
- Navigation tabs only show permitted modules
- Direct URL access is blocked with friendly error pages

### 🔒 Security

- Access control happens **at the route level** (not just UI)
- Even if a user knows the URL, they cannot bypass the check
- Returns HTTP 403 (Forbidden) for unauthorized access

### 📌 Google Sheets Permissions

Remember: **Google Sheets access control is separate**

- Share Sales Sheet (`1ayEGU0h_R7CY55COC1U94-p0rJch109YBGvezjYjHWw`) with sales team emails
- Share Inventory Sheet (`1_r06d4IolTc65P7KLN8XSq2ikG4gf-MG`) with warehouse team emails
- This provides an **additional layer** of data protection

---

## Next Steps

1. **Add Warehouse Emails**: Update `WAREHOUSE_EMAILS` in `app.py` with actual warehouse team emails
2. **Test Each Role**: Login with different role types to verify access control
3. **Update Sheet Permissions**: Configure Google Sheets sharing for additional security
4. **Optional**: Add audit logging to track who accesses which module

---

## Troubleshooting

### Issue: User sees wrong module

**Solution**: Check `get_user_role()` function - email may be in wrong set

### Issue: Navigation tabs not showing

**Solution**: Verify `user_role` is passed to `render_template()` in all routes

### Issue: Access denied for admin

**Solution**: Verify admin email is in `ADMIN_EMAILS` set (case-sensitive)

---

## Related Documentation

- **INVENTORY_SETUP.md** - How to configure inventory module
- **RBAC_IMPLEMENTATION.md** - Legacy RBAC documentation
- **SYSTEM_OVERVIEW.md** - Complete system architecture

---

**Implementation Date**: February 24, 2026  
**Status**: ✅ Complete and Active  
**Tested**: Yes (role-based routing, access control, navigation tabs)
