# Recruiter Showcase Guide: Hoteles Estelar Variable Remuneration System

Welcome to the walkthrough guide for the **Hoteles Estelar Variable Remuneration & Commissions System**. This document outlines how a developer or recruiter can explore the system, understand how it resolves critical enterprise user stories, and verify its production-grade design and architecture.

---

## 1. Project Overview & Tech Stack
The system is built as a highly secure, multi-tenant enterprise app designed to calculate, manage, and audit commercial sales commissions for the Hoteles Estelar franchise.

### Technology Stack
- **Framework**: Next.js (App Router, Turbopack)
- **Database**: PostgreSQL with Prisma ORM
- **Security**: Database-level **Row-Level Security (RLS)** and cryptographic webhook signature validation
- **Automation**: n8n workflows for background calculations and AI-driven compliance auditing
- **Styling**: Vanilla CSS, configured with a high-fidelity dark mode, glassmorphism, and responsive dashboards

---

## 2. Core User Stories & Technical Solutions

### User Story 1: Strict Data Segregation (Row-Level Security)
* **The Solution**: PostgreSQL RLS policies enforce segregation directly in the database. When any query runs, the system dynamically sets the session variables `app.current_user_role` and `app.current_user_id`. Even if a user calls APIs directly or tries to bypass the UI, the database returns `0` rows for other users or hotels.
* **Code Reference**: Check [rls_and_seed.sql](../../prisma/rls_and_seed.sql) to see the SQL policies, and [auth.ts](../../src/lib/auth.ts) to see how session contexts are injected.

### User Story 2: Plan Versioning & Rules Configuration
* **The Solution**: The system implements plan locking. When a plan is in `DRAFT`, rules can be edited. When it is marked `ACTIVE`, it becomes read-only. If an administrator tries to toggle or update an active plan, the system clones the plan, increments the `version` (e.g. `v1` -> `v2`), and sets the old plan's validity end date.
* **Code Reference**: Check plan clone logic in [/api/plans/route.ts](../../src/app/api/plans/route.ts).

### User Story 3: Atomic Bulk Sales Import
* **The Solution**: Excel sheets are parsed and checked against strict validation constraints (non-existent users, negative amounts, invalid periods, incorrect hotel codes). The validation is **atomic**—if even one row fails, the entire transaction is rolled back. The UI presents an inconsistency panel highlighting exactly which cells failed.
* **Code Reference**: View sheet parsing in [/api/sales/import/route.ts](../../src/app/api/sales/import/route.ts).

### User Story 4: Automated Calculations & Retroactive Clawbacks
* **The Solution**: The n8n calculation workflow triggers the settlement engine. The engine queries previous months' sales. If a sale was returned/cancelled, it applies a retroactive delta adjustment (clawback) to the current month's payout.
* **Code Reference**: See settlement computations in [/api/settlements/calculate/route.ts](../../src/app/api/settlements/calculate/route.ts).

### User Story 5: Immutable Auditing Log
* **The Solution**: The `audit_logs` table has database triggers that intercept and block all `UPDATE` and `DELETE` queries. The Admin dashboard features an interactive Audit Logs Explorer displaying side-by-side JSON diff panels showing what changed.
* **Code Reference**: View audit logs logic in [/api/audit-logs/route.ts](../../src/app/api/audit-logs/route.ts).

---

## 3. Step-by-Step Exploration Guide (All 10 Showcase Roles)

You can access the walkthrough version of the app at: **`https://hotels-demo.gaboggamer.online`**

### Step A: The Planner Experience (`director`)
- **Role Purpose**: Represents the commercial planner who configures commissions and rules globally.
1. **Login**: Go to the login screen, enter username **`director`** and password **`password123`**, then click **Iniciar Sesión**.
2. **Plan Creation**: In the top navigation header, click on **Planes** (Plans).
3. **Action**: Click **Nuevo Plan**, enter details (e.g., Name: `Plan Especial Q3 2026`, Code: `EST-Q3-26`, Type: `COMMISSION`, Start/End Dates covering June to August 2026), and click **Guardar**.
4. **Configure Rules**: Find the plan in the table, click the **Reglas** icon, configure tiered commission brackets (e.g. 0% to 90% achievement = 0% rate, 90.01% to 110% achievement = 2.5% rate), and click **Guardar Reglas**.
5. **Activate & Test Versioning**: Return to the plans list. Click the toggle to set the status to **ACTIVO**. Now, click the edit toggle button again. Notice the system blocks direct modification and instead clones the plan to **`v2`** in draft mode while archiving **`v1`** as inactive. This preserves historical calculations.
6. **Assign Quota**: Go to the **Metas** (Goals) tab. Click **Asignar Meta**, select `INDIVIDUAL`, choose `colaborador_mde` for period `2026-06`, set target to `100000`, and click **Guardar Meta**.

### Step B: The Global Finance Operations Experience (`analista`)
- **Role Purpose**: Represents the finance analyst who uploads sales lists and triggers calculation runs globally.
1. **Logout**, then login as **`analista`** (`password123`).
2. **Excel Ingestion**: Go to **Cargar Ventas** (Upload Sales). Drag and drop [demo_sales_data.xlsx](../../public/templates/demo_sales_data.xlsx) into the loading box. Notice the success message listing imported records.
3. **Idempotency Check**: Drag and drop the same file again. The system blocks the upload with a warning: `Error: Código de lote duplicado (Llave de idempotencia ya registrada)`, showing duplicate transaction prevention.
4. **Simulation & Calculation**: Go to the **Simulación** tab. Select period `2026-06`. Uncheck *Modo Simulación* to commit calculations. Click **Calcular Liquidaciones**. Wait 5-10 seconds for the n8n webhook response. The settlements table renders with AI-generated audit observations.

### Step C: The Regional Commercial Leader Experience (`lider_mde` vs `lider_ctg`)
- **Role Purpose**: Demonstrates regional boundaries. Leaders can only load sales for their own hotel.
1. **Logout**, then login as the Medellin Commercial Leader **`lider_mde`** (`password123`).
2. **Regional Ingestion Boundaries**: Go to **Cargar Ventas**. Attempt to upload an Excel file containing Cartagena (`EST-CTG`) records.
3. **Expected Result**: The system rejects the file with a validation error stating that the hotel code `EST-CTG` is outside your permitted Medellin jurisdiction (`EST-MDE`).
4. **Logout**, then login as **`lider_ctg`** (`password123`). Upload a Cartagena sales file; notice it succeeds only for Cartagena.

### Step D: The Collaborator Experience (`colaborador_mde` vs `colaborador_ctg`)
- **Role Purpose**: Shows complete personal data segregation using Row-Level Security.
1. **Logout**, then login as the Medellin Collaborator **`colaborador_mde`** (`password123`).
2. **Personal Data Isolation**: Go to **Historial** and **Metas**. Observe that you only see Medellin (`EST-MDE`) records and sales targets. All other collaborators' data is hidden.
3. **Logout**, then login as the Cartagena Collaborator **`colaborador_ctg`** (`password123`).
4. **Expected Result**: Only Cartagena (`EST-CTG`) records are returned. The database RLS filters the query dynamically based on the session user ID, returning zero results for other hotels.

### Step E: The Regional Manager Experience (`gerente_mde` vs `gerente_ctg`)
- **Role Purpose**: Demonstrates regional segregation in approval workflows.
1. **Logout**, then login as the Medellin Hotel Manager **`gerente_mde`** (`password123`).
2. **Approval Segregation**: Navigate to the **Aprobaciones** (Approvals) tab. You see pending settlements only for Medellin. Click **Rechazar** on the Medellin settlement, enter rejection reason: `"Falta validar soporte físico"`, and submit. The status transitions to `REJECTED`.
3. **Logout**, then login as the Cartagena Hotel Manager **`gerente_ctg`** (`password123`).
4. **Expected Result**: You only see Cartagena pending settlements. Click **Aprobar** on the Cartagena settlement; its status transitions to `APPROVED`, which triggers an audit log.

### Step F: The Read-Only Auditor Compliance Experience (`consulta`)
- **Role Purpose**: Verification of auditing read-only visibility.
1. **Logout**, then login as **`consulta`** (`password123`).
2. **Read-Only Inspection**: Navigate through Plans, Goals, and the Dashboard. Notice that while you can view all data globally across all hotels, all editing, uploading, and approval buttons are completely disabled or hidden.

### Step G: The System Administrator Experience (`admin`)
- **Role Purpose**: Master control view and security log auditing.
1. **Logout**, then login as **`admin`** (`password123`).
2. **Audit Explorer**: Navigate to the **Auditoría** tab. Select any log. The side-by-side JSON diff panel displays the exact changes made. Notice that sensitive fields like `password_hash` are redacted as `[REDACTED]`.
3. **Immutability Check**: Try to edit or delete any log entry. The database trigger blocks the mutation immediately, throwing an error.

---

## 4. Visual Aesthetics & Polish
When presenting this, highlight:
- **Glassmorphism**: Elegant card borders, subtle shadows, and dark translucent backdrops.
- **Micro-animations**: Smooth hover transitions on tables, buttons, and form elements.
- **Dynamic Charts**: Interactive charts that auto-adjust with filters, rendering region comparisons and historic performance trends.
- **Language Switcher**: Dynamically switches the UI and AI-generated text between English and Spanish.
