# 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)
> **As a** sales collaborator,  
> **I want** to see only my own sales, goals, and commission settlements,  
> **So that** I cannot view or tamper with other team members' financial information.
* **The Solution**: PostgreSQL RLS policies enforce segregation directly in the database. When any query runs, the system dynamically sets the session variable `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
> **As an** administrator or commercial analyst,  
> **I want** to create commission plans and rules, and ensure that editing active plans creates a new version instead of changing history,  
> **So that** historical calculations remain auditable and unchanged.
* **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
> **As a** commercial leader,  
> **I want** to import Excel files containing monthly sales results,  
> **So that** sales are automatically processed and verified, returning clear validation errors if the file is inconsistent.
* **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
> **As a** finance analyst,  
> **I want** commission calculations to run automatically via n8n and adjust for returned or cancelled sales from previous months,  
> **So that** payouts are correct and negative adjustments are deducted.
* **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
> **As an** external auditor,  
> **I want** to see a complete history of all user logins, plan modifications, and approvals,  
> **So that** I can verify that logs cannot be edited or deleted by anyone.
* **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

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

### Step A: The Collaborator Experience (Zero-Trust Boundaries & Multi-Hotel Segregation)
1. **Login** as the Medellin collaborator:
   - **Username**: `colaborador_mde`
   - **Password**: `password123`
2. **Observe**: The dashboard page loads. You can see your own metrics (sales amount, goals, achievement percentage) for `Estelar Medellin (EST-MDE)`.
3. **Verify Segregation**: Navigate to the **Historial** and **Metas** tabs. You will only see records associated with `colaborador_mde`. You cannot see any other collaborator's goals or payouts.
4. **Test Cross-Hotel Isolation**:
   - Log out and log in as the Cartagena collaborator:
     - **Username**: `colaborador_ctg`
     - **Password**: `password123`
   - **Observe**: You now only see data for `Estelar Cartagena (EST-CTG)`. The database restricts your session so that you have absolutely zero exposure to Medellin (`EST-MDE`) records, despite sharing the same collaborator role.
5. **Try to Bypass**: Notice there is no "Cargar Ventas" (Upload Sales) or "Planes" (Plans) link in the header. The UI actively hides admin-level controls.

### Step B: The Regional Manager & Leader Experience (Approval Segregation)
1. **Log out** and **Login** as the Medellin Hotel Manager:
   - **Username**: `gerente_mde`
   - **Password**: `password123`
2. **Observe**: The manager sees dashboard metrics summarizing total sales for `Estelar Medellin (EST-MDE)`.
3. **Approval Segregation**: Navigate to the **Aprobaciones** (Approvals) tab. You will see pending settlements for June 2026. Note that you can only see collaborators belonging to `EST-MDE` (like `colaborador_mde`).
4. **Verify Cross-Hotel Isolation**:
   - Log out and log in as the Cartagena Hotel Manager:
     - **Username**: `gerente_ctg`
     - **Password**: `password123`
   - **Observe**: The dashboard and the **Aprobaciones** tab now show only data for `Estelar Cartagena (EST-CTG)`. You cannot view, approve, or reject settlements for Medellin or Bogota.
5. **Leader Level Separation**:
   - Log out and log in as the Medellin Commercial Leader:
     - **Username**: `lider_mde`
     - **Password**: `password123`
   - **Observe**: The commercial leader has read access to their hotel's records and can upload sales only for `EST-MDE`, but has zero access to Cartagena (`EST-CTG`) or Bogota (`EST-P93`) data.
6. **Action Flow**: Under a manager account, approve or reject a pending settlement. Approve transitions status to `APPROVED` and writes an immutable audit log. Reject requires entering a rejection reason (e.g. `"Falta validar soporte físico"`) and transitions status to `REJECTED`.

### Step C: The Administrator Experience (Plans & Auditing)
1. **Log out** and **Login** as the System Admin:
   - **Username**: `admin`
   - **Password**: `password123`
2. **Global View**: The Admin sees all metrics across all regions/hotels on the dashboard.
3. **Plan Versioning**: Navigate to the **Planes** tab.
   - Click on **Nuevo Plan** to open the creation modal.
   - Create a draft plan named `Plan Piloto Q3` with code `PLAN-Q3` and validity dates.
   - Click the "Reglas" icon next to it and configure tiered commission brackets (e.g. 0% rate up to 90% achievement, 2% rate up to 100% achievement).
   - Toggle the status to **ACTIVO**.
   - Click toggle **AGAIN** on the active plan. You will see the version increment to `v2` and the old version status set to `INACTIVO`.
4. **Audit Logs Explorer**: Navigate to the **Auditoría** tab.
   - Click on any log row (e.g. `APPROVE` or `CREATE`).
   - The side-by-side JSON diff panel appears, displaying the precise changes made in that transaction.
   - Try to delete or modify a log entry; the database returns an error, preventing tampering.

---

## 4. Visual Aesthetics & Polish
When presenting this to a recruiter, be sure to 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.
