# 💼 Hoteles Estelar Variable Remuneration System - Standup Showcase Guide

This guide organizes the current capabilities of the **Variable Remuneration, Compensation, and Commissions System** for Hoteles Estelar. Use it to present the implemented features, map them to the corresponding User Stories (US), and run a live demo or automated verification tests.

---

## 1. System Overview & Architecture

The system is built on an enterprise-grade stack designed to replace manual Excel workflows with a secure, auditable, and automated platform.

```mermaid
graph TD
    User([User Browser]) -->|Next.js App Router| App[Next.js API & UI Server]
    App -->|Prisma Client with Context| DB[(PostgreSQL Database)]
    DB -->|PostgreSQL RLS Policies| DB
    App -->|Secure Webhooks x-n8n-signature| n8n[n8n Workflow Engine]
    n8n -->|LLM Anomaly Checks & Translation| n8n
    n8n -->|SMTP Client| Mail[Stalwart SMTP Server]
```

### Key Technical Pillars
* **Next.js & Vanilla CSS Modules**: Clean, responsive, and component-isolated styling.
* **Database-Level Isolation (RLS)**: Context propagated from Next.js sessions to PostgreSQL enforces data segregation at the query level.
* **Audit Immutability**: All write operations write to an `AuditLog` table using an insert-only policy. Password hashes and salary values are redacted automatically.
* **Thin Coordinator n8n Engine**: Integrations and batch calculations run asynchronously in n8n, keeping database connections locked in Next.js and invoking LLM failovers (DeepSeek to Gemini) for semantic anomaly audits.
* **Two-Tier Idempotency**: Excel file imports are checked against client-side transaction keys at the API layer and protected via unique constraints in the DB layer.

---

## 2. Completed Features & User Stories Mapping

| Feature Group | User Story (US) ID | Title / Requirement | Current Implementation Status & Verification |
| :--- | :--- | :--- | :--- |
| **Security & Isolation** | **US-COM-014** | Manage Roles and Permissions | **Completed**. PostgreSQL RLS dynamically filters data based on JWT session context. Bypassed only for `admin` role. Verified in `test-rls.js`. |
| | **US-COM-011** | Record Traceability & Auditing | **Completed**. Immutable, `INSERT-ONLY` audit logging in database with automated logging middleware and password/salary redaction. |
| **Compensation Config** | **US-COM-001** | Create Compensation Plan | **Completed**. UI at `/plans` allows creating, duplicating, and inactivating plans. Enforces temporal versioning for active plans. |
| | **US-COM-002** | Configure Calculation Rules | **Completed**. UI allows setting Percentage, Tiers, Scales, and Cap parameters for calculations. |
| | **US-COM-003** | Configure Commercial Goals | **Completed**. UI at `/goals` configures quotas per period (individual/team/hotel levels). |
| **Integrations & Imports**| **US-COM-004** | Import Results from Excel | **Completed**. UI at `/sales/import` handles XLSX/CSV, checks column formatting, renders localized error reports, and prevents duplicate uploads. |
| | **US-COM-005** | Integration with CRM/PMS | **Completed**. Asynchronous processing via n8n workflow callback (`/api/sales/batch-save`) with signature verification (`x-n8n-signature`). |
| **Settlement Engine** | **US-COM-006** | Calculate Commissions | **Completed**. Core engine processes settlements, applying tiers, rules, caps, and retroactive adjustments/PMS clawback calculations. |
| | **US-COM-007** | Simulate Settlement | **Completed**. UI dashboard at `/sales/simulation` offers dry-run reviews before committing data to the database. |
| **Approvals Flow** | **US-COM-008** | Approve/Reject Settlements | **Completed**. UI panel at `/settlements/approvals` restricts access based on regional leader roles. Rejection requires written comments. |
| | **US-COM-009** | Notify Results | **Completed**. Webhook callbacks in n8n dispatch notification alerts to stakeholders. |
| **Bilingual UI & LLM** | **US-COM-015** | Internationalization & Translation | **Completed**. Client-side locale toggles EN/ES. DB stores bilingual JSON structures for AI audit notes, generated via LangChain nodes. |

---

## 3. Demo Accounts & Credentials

Use these pre-seeded accounts to demonstrate role-based permissions and regional isolation during the standup:

| Username | Password | Role | Hotel Context | Region Context | Area Context |
| :--- | :--- | :--- | :--- | :--- | :--- |
| `admin` | `password123` | Administrator | Estelar Parque 93 | BOG | Sistemas |
| `analista` | `password123` | Financial Analyst | Estelar Parque 93 | BOG | Finanzas |
| `lider_ctg` | `password123` | Commercial Leader | Estelar Cartagena | CAR | Ventas |
| `gerente_mde` | `password123` | Hotel Manager | Estelar Medellin | ANT | Administracion |
| `colaborador_mde` | `password123` | Collaborator | Estelar Medellin | ANT | Ventas |

---

## 4. Step-by-Step Live Demo Walkthrough

Follow this sequence to present a comprehensive, orderly showcase of the program:

### Step 1: Secure Authentication & Role Isolation
1. Navigate to `/login`.
2. Log in as `colaborador_mde`.
3. Try to navigate to `/plans` or `/sales/import`. The UI blocks access, showing an unauthorized banner.
4. Log out, and log in as `admin`. Access is fully restored.

* **Login Screen**
  ![Login Screen](../../prisma/screenshots/01_login_page.png)
* **Unauthorized User View**
  ![Unauthorized User](../../prisma/screenshots-phase4/01_collaborator_unauthorized.png)
* **Admin Dashboard Loaded**
  ![Admin Dashboard](../../prisma/screenshots/03_dashboard_loaded.png)

> [!NOTE]
> Behind the scenes, the Next.js API establishes a transaction context inside PostgreSQL, enforcing Row-Level Security (RLS). Even if a malicious client manually changes the request params, PostgreSQL blocks unauthorized data access.

---

### Step 2: Compensation Plan Config & Version Control
1. As `admin`, navigate to `/plans`. Click **Crear Plan**.
2. Complete the required parameters (Name, Code, Validity Start Date, Plan Type).
3. Set calculation rules (e.g., Tiers and Scales) on the configuration sub-view and click **Guardar Reglas**.
4. Go back to `/plans`. Activate the plan by clicking **Activar**.
5. Edit the active plan. Observe that the system automatically handles **Temporal Versioning**:
   * The original record is marked `INACTIVE` with `validity_end = NOW()`.
   * A new duplicate record is saved with `version = 2` and `status = ACTIVE`.
6. Navigate to `/goals` and assign a commercial goal of `$75,000.00` for collaborator `colaborador_mde` in period `2026-06`.

* **Create Compensation Plan Modal**
  ![Create Modal](../../prisma/screenshots/04_create_modal_open.png)
* **Rules Configuration & Setup**
  ![Rules Populated](../../prisma/screenshots/08_rules_populated.png)
* **Plan Versioning Activation**
  ![Plan Versioned](../../prisma/screenshots/12_plan_versioned.png)
* **Goals Configured Successfully**
  ![Goals Configured](../../prisma/screenshots/15_goal_saved.png)

---

### Step 3: Excel Sales Data Import & Idempotency
1. Navigate to `/sales/import`.
2. Notice the pre-configured **Excel Template Download Button** matching Estelar's expected input columns.
3. Select and upload a corrupted Excel file (containing negative sales, missing headers, or fake users).
4. Review the **Inconsistency Validation Log** rendered on the screen. The errors are translated on the client using the Code + Metadata JSON payload sent by the server.
5. Upload the valid sheet. The progress bar completes, and a success banner confirms the imported row count.
6. Attempt to upload the exact same file. The system checks the `Idempotency-Key` and immediately returns the cached success response without writing redundant entries to the database.

* **Sales Import Interface**
  ![Import View](../../prisma/screenshots-phase4/02_admin_import_view.png)
* **Excel Field Validation Errors Report**
  ![Validation Errors](../../prisma/screenshots-phase4/04_validation_errors_rendered.png)
* **Successful Direct Upload**
  ![Upload Successful](../../prisma/screenshots-phase4/05_valid_upload_success.png)
* **Idempotency Prevention Block**
  ![Idempotency Blocked](../../prisma/screenshots-phase4/06_idempotency_duplicate.png)

---

### Step 4: Settlement Calculations, Simulations & Clawbacks
1. Navigate to `/sales/simulation`.
2. Select period `2026-06` and check **Simulate Only (Dry Run)**.
3. Click **Procesar Liquidaciones**.
4. The dashboard displays the grid: Collaborator, Plan Code, Goal, Confirmed Sales, Achievement Percentage, Commission, Retroactive Adjustments, and Final Payout.
5. Look at the retroactive adjustment column:
   * To demonstrate **Retroactive Adjustments (PMS Clawbacks)**, the engine evaluated sales from previous months (`2026-05`).
   * Because a previous sale was refunded/cancelled, the engine calculated a negative delta and injected it as a pending clawback, reducing the current month's payout.
6. Toggle **Simulate Only** off and run the calculation. The settlements are successfully stored as pending approvals in the DB.

* **Settlement Simulation Screen**
  ![Simulation Results](../../prisma/screenshots-phase5/02_simulation_success.png)
* **PMS Clawback / Retroactive Adjustment Calculations**
  ![Clawback Delta](../../prisma/screenshots-phase5/06_clawback_calculated.png)

---

### Step 5: Commercial Approvals & Bilingual Compliance Logs
1. Log out, and log in as `lider_ctg` (Caribe region leader).
2. Navigate to `/settlements/approvals`.
3. Notice that `lider_ctg` only sees pending settlements for collaborators in the **Caribe** region (Estelar Cartagena). Collaborators from Medellin (Antioquia) are filtered out at the database level by PostgreSQL RLS.
4. Select a settlement and click **Aprobar**.
5. Select another settlement and click **Rechazar**. The UI prompts for a **mandatory rejection reason**. Inputting a reason successfully saves it.
6. Toggle the language switcher in the Header between **Español** and **English**. The entire dashboard updates instantly.
7. Observe the **Bilingual AI Audit Notes** generated by the n8n compliance analysis: the description details are shown in English or Spanish depending on the active user locale.

* **Regional Approvals Dashboard**
  ![Approvals Grid](../../prisma/screenshots-phase5/03_lider_ctg_approvals_view.png)
* **Mandatory Rejection Comment Modal**
  ![Rejection Prompt](../../prisma/screenshots-phase5/04_rejection_modal.png)
* **Rejection State Persisted**
  ![Rejection Finished](../../prisma/screenshots-phase5/05_rejection_done.png)

---

## 5. Automated Verification Suite

To prove the robustness of the implementation during the standup, you can execute the test suites directly. These suites spin up isolated test environments and verify all functionalities.

Run the following commands in the workspace root:

```bash
# 1. Run PostgreSQL RLS isolation & audit immutability checks
rtk pnpm run test:rls

# 2. Run Next.js API & JWT Session RLS validation tests
rtk pnpm run test:auth-rls

# 3. Run E2E Headless Puppeteer UI verification tests (Builds app and tests user flows)
rtk pnpm run test:ui

# 4. Run real n8n Integration Webhook & Anomaly Check tests
rtk pnpm run test:n8n
```

> [!TIP]
> Executing `rtk pnpm run test` runs the complete test catalog sequentially and guarantees zero leaks or calculation failures across all modules.
