# Live E2E Demonstration & Role Showcase Guide

**Variable Remuneration, Compensation, and Commissions System - Hoteles Estelar**

---

This guide outlines a comprehensive step-by-step E2E script for presenters. It showcases the application's role-based permissions, database Row-Level Security (RLS) isolation, multilingual language switcher, and n8n background workflow triggers.

---

## 1. System Role Permissions Matrix

The platform is designed with a strict Role-Based Access Control (RBAC) layer mapped to the following permissions:

| User Role | Navigation Access | Can Manage Plans? | Can Assign Goals? | Can Ingest Sales? | Can Run Settlement? | Can Approve/Reject? | Can View Audit Logs? |
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: |
| **`admin`** | All tabs | Yes | Yes | Yes | Yes | Yes (Override) | Yes (diff panel) |
| **`director`** | Plans, Goals, Dashboard | Yes | Yes | No | No | No | No (403 Blocked) |
| **`analyst`** | Plans, Ingest, Calc, Dash | No | No | Yes | Yes | No | No (403 Blocked) |
| **`commercial_leader`** | Plans, Ingest, Approvals | No | No | Yes | No | Yes (Regional) | No (403 Blocked) |
| **`hotel_manager`** | Plans, Goals, Approvals | No | No | No | No | Yes (Regional) | No (403 Blocked) |
| **`auditor`** | Plans, Goals (Read-only) | No | No | No | No | No | No (403 Blocked) |
| **`collaborator`** | History (Personal only) | No | No | No | No | No | No (403 Blocked) |

---

## 2. Seeded Accounts & Credentials

Use these pre-configured accounts (all passwords are set to **`password123`**) to showcase different user views:

1. **System Admin (`admin`)**:
   - Username: `admin`
   - Email: `admin@estelar.com`
   - Hotel Scope: `Estelar Parque de la 93` (Global View)
   - Role: `admin`
2. **Planner / Executive View (`director`)**:
   - Username: `director`
   - Email: `director@estelar.com`
   - Hotel Scope: `Estelar Parque de la 93` (Global view for planning)
   - Role: `director`
3. **Finance Operations View (`analista`)**:
   - Username: `analista`
   - Email: `analista@estelar.com`
   - Hotel Scope: `Estelar Parque de la 93`
   - Role: `analyst`
4. **Hotel Managers (Regional Isolation)**:
   - **Medellin Manager**:
     - Username: `gerente_mde`
     - Email: `gerente.mde@estelar.com`
     - Hotel: `Estelar Medellin` (`EST-MDE`)
     - Role: `hotel_manager`
   - **Cartagena Manager**:
     - Username: `gerente_ctg`
     - Email: `gerente.ctg@estelar.com`
     - Hotel: `Estelar Cartagena` (`EST-CTG`)
     - Role: `hotel_manager`
5. **Commercial Leaders (Regional Isolation)**:
   - **Medellin Leader**:
     - Username: `lider_mde`
     - Email: `lider.mde@estelar.com`
     - Hotel: `Estelar Medellin` (`EST-MDE`)
     - Role: `commercial_leader`
   - **Cartagena Leader**:
     - Username: `lider_ctg`
     - Email: `lider.ctg@estelar.com`
     - Hotel: `Estelar Cartagena` (`EST-CTG`)
     - Role: `commercial_leader`
6. **Collaborators / Sellers (Personal Isolation)**:
   - **Medellin Collaborator**:
     - Username: `colaborador_mde`
     - Email: `colaborador.mde@estelar.com`
     - Hotel: `Estelar Medellin` (`EST-MDE`)
     - Role: `collaborator`
   - **Cartagena Collaborator**:
     - Username: `colaborador_ctg`
     - Email: `colaborador.ctg@estelar.com`
     - Hotel: `Estelar Cartagena` (`EST-CTG`)
     - Role: `collaborator`
7. **Auditor / Guest (`consulta`)**:
   - Username: `consulta`
   - Email: `consulta@estelar.com`
   - Hotel Scope: `Estelar Parque de la 93` (Global View)
   - Role: `auditor`

---

## 3. Step-by-Step E2E Demo Walkthrough Script

### Step 1: Manage Compensation Plans & Rules (Planner View)
* **Objective**: Show how plans are created, configured, and automatically version-controlled when active.
* **User**: **`director`** (Planner / Executive View)
* **Action Details**:
  1. Open the browser and navigate to the application URL.
  2. Login with username **`director`** and password **`password123`**.
  3. In the top navigation header, click on the **Planes** (Plans) tab.
  4. Click the **Nuevo Plan** button to launch the creation modal.
  5. Fill in the modal form fields:
     - **Name**: `Plan Especial Q3 2026`
     - **Code**: `EST-Q3-26`
     - **Type**: Select `COMMISSION` from the dropdown.
     - **Start/End Dates**: Select a validity range covering `2026-06-01` to `2026-08-31`.
  6. Click **Guardar Plan** to submit.
  7. Locate the new plan in the table. Click the **Reglas** icon next to its name.
  8. In the rules drawer/view, add two brackets:
     - Tier 1: `0% - 90%` achievement range = `0%` commission rate. Click **Agregar Tramo**.
     - Tier 2: `90.01% - 110%` achievement range = `2.5%` commission rate. Click **Agregar Tramo**.
  9. Click **Guardar Reglas** to persist rules.
  10. Return to the plans list and click the status switch toggle to activate the plan. Observe that the status immediately changes to `ACTIVE`.
  11. Now, click the edit toggle button again on the active plan.
  12. **Expected System Behavior**: The system blocks direct inline changes to active rules. Instead, it clones the entire plan, incrementing its version to `v2` in draft state, while setting `v1` to inactive. This prevents retroactive calculations from being manipulated.

### Step 2: Assign Quotas and Goals (Planner View)
* **Objective**: Define sales targets for sellers.
* **User**: **`director`** (Planner / Executive View)
* **Action Details**:
  1. Still logged in as **`director`**, click the **Metas** (Goals) link in the navigation header.
  2. Click **Asignar Meta** (Assign Goal) to open the goal configuration modal.
  3. Fill in the form:
     - **Target Type**: Select `INDIVIDUAL`.
     - **Collaborator**: Select `colaborador_mde` from the user dropdown.
     - **Period**: Enter `2026-06`.
     - **Target Sales Amount**: Enter `100000`.
  4. Click **Guardar Meta**.
  5. **Expected System Behavior**: A success toast appears. The goal is stored, automatically bounded to the collaborator's hotel scope (`EST-MDE`), laying the groundwork for regional RLS segregation.

### Step 3: Excel Sales File Ingestion (Finance Operations View)
* **Objective**: Ingest monthly sales results with header validations, idempotency check, and transactional rollbacks.
* **User**: **`analista`** (Finance Operations View)
* **Action Details**:
  1. Click the **Cerrar Sesión** button in the top right.
  2. Login with username **`analista`** and password **`password123`**.
  3. Click the **Cargar Ventas** (Upload Sales) tab in the header.
  4. Drag and drop the template spreadsheet: [demo_sales_data.xlsx](file:///home/gabogg/Proyects/semillero-special-hotel/public/templates/demo_sales_data.xlsx) into the file drop target zone, or click the zone to upload it via file selector.
  5. **Expected System Behavior**: The system parses the spreadsheet, performing atomic validations (user existence check, positive numeric checks, regional validations). Once successful, a green success banner appears: `Carga exitosa`.
  6. **Idempotency Test**: Select and drop the *same file again* immediately.
  7. **Expected System Behavior**: The UI highlights a red error block: `Error: Código de lote duplicado (Llave de idempotencia ya registrada)`. The system has blocked the ingestion and rolled back the transaction to prevent double payout calculation.

### Step 4: Regional Leader Ingestion Validation (Regional Isolation)
* **Objective**: Show that regional boundaries block leaders from loading sales for other hotels.
* **User**: **`lider_mde`** (Medellin Commercial Leader)
* **Action Details**:
  1. Logout, then login as the Medellin Commercial Leader **`lider_mde`** and password **`password123`**.
  2. Navigate to **Cargar Ventas** (Upload Sales).
  3. Attempt to upload a custom Excel file containing rows with the Cartagena hotel code (`EST-CTG`).
  4. **Expected System Behavior**: The upload fails with a red warning stating: `Error de Validación: El código de hotel EST-CTG no coincide con su jurisdicción permitida (EST-MDE)`. The transaction is rolled back, demonstrating multi-tenant regional ingestion security.
  5. Logout, then login as **`lider_ctg`** (`password123`). Go to **Cargar Ventas** and upload a valid file containing Cartagena `EST-CTG` rows. The upload completes successfully.

### Step 5: Run Settlement Calculation & AI Anomaly Detection (Finance Operations View)
* **Objective**: Trigger n8n webhook calculation runs and review the generated AI audit observations.
* **User**: **`analista`** (Finance Operations View)
* **Action Details**:
  1. Logout, and login again as **`analista`** (`password123`).
  2. Click on **Liquidación** (Settlement) in the top navigation.
  3. Select period **`2026-06`**.
  4. **Crucial**: Ensure the **Modo Simulación** (Simulation Mode) checkbox is UNCHECKED to persist the calculation.
  5. Click **Calcular Liquidaciones** (Calculate Settlements).
  6. **Expected System Behavior**: A loading indicator appears while the application calls the n8n webhook backend. Wait 5-10 seconds. The webhook triggers the settlement computation workflows. The UI refreshes:
     - **`colaborador_mde`**: Payout is calculated.
     - **`colaborador_ctg`**: Payout calculated. If any sale amount exceeds normal parameters, a warning icon appears under the AI Audit column. Click the icon to view the audit observations: `Warning: Anomalous high sale detected`.

### Step 6: Collaborator Personal Segregation (Row-Level Security)
* **Objective**: Verify that sellers have access only to their personal goals and history.
* **Users**: **`colaborador_mde`** (Medellin Collaborator) vs **`colaborador_ctg`** (Cartagena Collaborator)
* **Action Details**:
  1. Logout, then login as **`colaborador_mde`** (`password123`).
  2. Navigate to **Historial** (History) and **Metas** (Goals). Verify you can see only your personal Medellin records.
  3. Logout, then login as **`colaborador_ctg`** (`password123`).
  4. Navigate to **Historial** and **Metas**.
  5. **Expected System Behavior**: The tables display only Cartagena records. Even if a user attempts to fetch Medellin records via direct API requests, the PostgreSQL RLS policy filters the query dynamically based on the session ID, returning zero results.

### Step 7: Regional Manager Approvals (Regional Segregation)
* **Objective**: Perform commercial leader/manager sign-off with regional isolation.
* **Users**: **`gerente_mde`** (Medellin Manager) vs **`gerente_ctg`** (Cartagena Manager)
* **Action Details**:
  1. Logout, then login as **`gerente_mde`** (`password123`).
  2. Navigate to **Aprobaciones** (Approvals). Notice that only the pending Medellin settlement is visible.
  3. Click **Rechazar** (Reject) on the Medellin settlement. In the rejection modal, enter: `"Falta validar soporte físico"` and click submit. The status transitions to `REJECTED`.
  4. Logout, then login as **`gerente_ctg`** (`password123`).
  5. Navigate to **Aprobaciones**. Notice that only the Cartagena settlement is visible.
  6. Click **Aprobar** (Approve) on the Cartagena settlement. The status changes to `APPROVED` and generates an audit log.

### Step 8: Read-Only Auditor Compliance (Read-only Compliance View)
* **Objective**: Verify that auditors can view all data globally but cannot edit or approve anything.
* **User**: **`consulta`** (Auditor / Guest)
* **Action Details**:
  1. Logout, then login as **`consulta`** (`password123`).
  2. Navigate through **Planes**, **Metas**, and the **Tablero** (Dashboard).
  3. **Expected System Behavior**: The auditor can see plans and goals for all three regions (Bogota, Medellin, Cartagena) on the tables. However, all "Nuevo Plan", "Asignar Meta", "Aprobar", or "Cargar Ventas" buttons are completely hidden or disabled, ensuring read-only compliance.

### Step 9: Executive Dashboard (Executive View)
* **Objective**: Showcase executive visual trends.
* **User**: **`director`** or **`analista`**
* **Action Details**:
  1. Logout, then login as **`director`** (`password123`).
  2. Navigate to **Dashboard** (Tablero).
  3. **Expected System Behavior**: The dashboard renders KPI cards showing total payouts, average achievement percentage, and budget cap bars. Recharts interactive SVG charts display monthly sales trends and comparative performance between the Medellin, Bogota, and Cartagena hotels.

### Step 10: System Audit Logs & JSON Diff (System Admin View)
* **Objective**: Inspect security mutations and redaction details.
* **User**: **`admin`** (System Admin View)
* **Action Details**:
  1. Logout, then login as **`admin`** (`password123`).
  2. Navigate to **Audit Logs** (Auditoría).
  3. Select any log row. The side-by-side JSON panel displays the exact snapshot of the database fields before and after the action.
  4. **Expected System Behavior**: Sensitive fields like `password_hash` or base salaries are redacted as `[REDACTED]`.
  5. **Immutability Check**: Try to edit or delete any log entry. The database trigger blocks the mutation immediately, throwing an error.

---

## 4. Financial Reports Exporting (US-COM-013)

To test consolidations, run these API endpoints directly in your browser:
* **Consolidated Excel Sheet**: `/api/reports/export/excel?period=2026-06` (Downloads a multi-sheet spreadsheet).
* **Consolidated PDF HTML print view**: `/api/reports/export/pdf?period=2026-06` (Generates printable tabular views with signature sign-off lines).
