docs: translate requirements to English, update architecture with n8n and independence, add strict CSS module style guide

This commit is contained in:
Luis Gabriel Ramos Robles 2026-06-11 13:21:03 +00:00
parent 261762030b
commit e3c954cdf7
3 changed files with 371 additions and 185 deletions

View file

@ -1,40 +1,41 @@
# Architecture and System Design
**Sistema de Remuneración Variable, Compensación y Comisiones - Hoteles Estelar**
**Variable Remuneration, Compensation, and Commissions System - Hoteles Estelar**
---
## 1. Technical Stack Selection
To keep resource footprint low on the self-hosted VPS while providing a premium, modern user experience, we recommend a unified **Next.js Full-Stack App Router** architecture.
## 1. Technical Stack
* **Frontend**: Next.js App Router (React + TypeScript).
* **Styling**: Vanilla CSS with a structured design system (CSS variables, dark/light theme tokens, premium layout aesthetics, smooth CSS micro-animations).
* **Styling**: Vanilla CSS utilizing **CSS Modules** (`*.module.css`) for component-level style isolation, paired with a global variables system (`globals.css`) defining the design tokens.
* **Backend**: Next.js API Routes (Node.js runtime).
* **ORM**: Prisma ORM (provides type-safe database queries and automated schema migrations).
* **Database**: PostgreSQL (hosted on the existing `postgres` Docker stack).
* **Excel Processing**: `xlsx` (SheetJS) for high-performance parser logic.
* **Authentication**: NextAuth.js or custom lightweight JWT session cookies.
* **Hosting**: Docker container integrated into the Dockge stack manager, reverse proxied by Caddy with split DNS resolving over WireGuard VPN for security-sensitive areas.
* **ORM**: Prisma ORM (providing type-safe database queries and automated schema migrations).
* **Database**: PostgreSQL (decoupled, configured via environment variables to run on any host/network).
* **Workflow Engine**: **n8n** (external service triggered via API Webhooks). Runs the actual calculation steps, anomaly checks, AI-assisted audits, and notifications. This allows live monitoring of tasks and flexible AI model switching (e.g., swapping OpenAI/Anthropic/Ollama models within n8n nodes without rebuilding the Next.js codebase).
* **Auditing**: Custom Prisma Client Extension that automatically intercepts mutations (`create`, `update`, `delete`) and logs the changes into an `AuditLog` table. This approach is database-agnostic, requires no native OS dependencies, and runs purely inside the runtime.
---
## 2. System Architecture
## 2. Decoupled Network & Environment Independence
The project is structured to run in any isolated Docker environment. All parameters are fed via environment variables:
* `DATABASE_URL`: Connection string for PostgreSQL (e.g. `postgresql://user:pass@host:port/dbname`).
* `N8N_WEBHOOK_URL`: The entry point for the n8n workflow engine.
* `N8N_API_KEY`: Token to authorize callbacks from n8n to the Next.js API.
* `NEXTAUTH_SECRET`: Secret for securing JWT cookies.
### Component Interaction:
```mermaid
graph TD
User([Colaborador / Líder / Admin]) -->|HTTPS| Caddy[Caddy Reverse Proxy]
Caddy -->|Internal Network| NextJS[Next.js Full-Stack App]
User([User Client]) -->|HTTPS| WebApp[Next.js App Router]
subgraph NextJS Container
UI[React Frontend / Vanilla CSS] <--> API[API Routes / Controllers]
Engine[Settlement Engine] <--> API
Parser[Excel Parser] <--> API
subgraph Isolated Network
WebApp -->|Prisma Client| DB[(PostgreSQL)]
WebApp -->|HTTP POST Webhook| n8n[n8n Workflow Engine]
n8n -->|HTTP POST Callback| WebApp
n8n -->|Interact| LLM[AI Model / Provider]
end
API -->|Prisma Client| DB[(PostgreSQL)]
Jobs[Integration CRON Jobs] -->|Fetch Sales| API
External[External PMS / ERP / CRM] -->|API Push / Pull| Jobs
```
---
@ -173,21 +174,27 @@ erDiagram
---
## 4. Key Business Logic: Settlement & Calculation Engine
## 4. Workflows & n8n Integration Model
The engine computes commissions based on the formula:
By offloading calculations and integrations to n8n, we achieve a highly visual, modular, and editable workflow architecture.
$$\text{Achievement \%} = \left( \frac{\text{Sales Amount}}{\text{Goal Amount}} \right) \times 100$$
### 4.1. Sales Data Import Workflow
1. **Trigger**: Next.js calls `POST /api/n8n/import-sales` which forwards the parsed Excel payload to n8n's webhook URL.
2. **n8n Processing**:
- Iterates through sales records.
- Queries Next.js APIs to validate collaborator codes and hotel IDs.
- Cleanses data and identifies duplicates.
- Uses an LLM node (with configurable models: GPT-4, Claude 3.5, Gemini, etc.) to perform semantic anomaly checks (e.g., flag sales values that deviate more than 2.5 standard deviations from the collaborator's monthly average).
3. **Response**: n8n POSTs the sanitized/flagged list back to `POST /api/sales/batch-save` in Next.js to update the database.
### Calculation Flow:
1. **Fetch inputs**: Get sales results, goals, and matching active compensation plan for the collaborator for the period `YYYY-MM`.
2. **Determine Achievement Level**: Check against the plan's `CALCULATION_RULES` (tiers).
3. **Calculate Commission**:
- *Fixed Rate*: $\text{Sales} \times \text{percentage\_rate}$.
- *Tiers/Scales*: Apply rate corresponding to the achievement level tier.
4. **Apply Caps**: If calculated commission exceeds the plan's `max_cap`, set it to `max_cap`.
5. **Add Special Bonuses**: If the collaborator achieves certain thresholds (e.g., >100% meta), add the specific tier's fixed `payout_amount` as a bonus.
6. **Generate Output**: Store as a `SETTLEMENT` entry in `SIMULATED` status.
### 4.2. Settlement Calculation Workflow
1. **Trigger**: Next.js calls n8n to execute the calculation for period `YYYY-MM`.
2. **n8n Processing**:
- Pulls active plans, individual goals, and actual sales from the Next.js API.
- Evaluates the mathematical formulas.
- Evaluates rule scales and applies caps.
- Generates notifications (via email or push notifications) using n8n integrations.
3. **Response**: Updates database records via the Next.js API and completes the task.
---

View file

@ -1,192 +1,192 @@
# Requerimientos y Historias de Usuario
# Requirements and User Stories
**Sistema de Remuneración Variable, Compensación y Comisiones - Hoteles Estelar**
**Variable Remuneration, Compensation, and Commissions System - Hoteles Estelar**
---
## Objetivo General
Implementar una plataforma centralizada para la administración, cálculo, validación y seguimiento de remuneración variable, compensaciones e incentivos comerciales, reemplazando el manejo manual actual realizado en archivos Excel y permitiendo automatizar el proceso de liquidación, aprobación y trazabilidad.
## General Objective
Implement a centralized platform for the administration, calculation, validation, and monitoring of variable remuneration, compensations, and commercial incentives, replacing the current manual management in Excel sheets and enabling automated settlement, approval, and traceability processes.
---
## Alcance Funcional
El sistema se compone de 7 características principales (Features) divididas en 14 Historias de Usuario (HU).
## Functional Scope
The system consists of 7 main features divided into 14 User Stories (US).
### FEATURE 1 — Administración de Planes de Compensación
### FEATURE 1 — Compensation Plan Administration
#### HU-COM-001 — Crear plan de compensación
* **Como:** Administrador del sistema
* **Quiero:** Crear planes de compensación y comisiones
* **Para:** Definir las reglas de remuneración variable.
* **Descripción:**
El sistema deberá permitir configurar planes asociados a:
* Hoteles
* Regiones
* Equipos comerciales
* Cargos
* Campañas
* Temporadas
* Unidades de negocio
* **Criterios de Aceptación:**
* **Escenario 1 (Creación exitosa):** Dado que el administrador ingresa al módulo de compensación, cuando selecciona "Crear plan" y diligencia los campos requeridos, entonces el sistema debe almacenar el plan correctamente.
* **Escenario 2 (Validación de obligatoriedad):** Dado que existen campos obligatorios, cuando el usuario intenta guardar sin completarlos, entonces el sistema debe mostrar mensajes de validación.
* **Campos sugeridos:**
* Nombre del plan, Código, Vigencia, Tipo de compensación, Área, Cargo, Hotel, Región, Tipo de cálculo, Fórmula, Meta, Porcentaje, Topes máximos, Estado.
* **Operaciones (Sub-features):**
* Crear plan, Editar plan, Duplicar plan, Versionamiento, Inactivar plan.
#### US-COM-001 — Create Compensation Plan
* **Role:** System Administrator
* **Goal:** Create compensation and commission plans
* **Benefit:** Define variable remuneration rules.
* **Description:**
The system must allow configuring plans associated with:
* Hotels
* Regions
* Commercial teams
* Roles
* Campaigns
* Seasons
* Business units
* **Acceptance Criteria:**
* **Scenario 1 (Successful creation):** Given that the administrator enters the compensation module, when they select "Create plan" and fill out the required fields, then the system must store the plan correctly.
* **Scenario 2 (Mandatory validation):** Given that mandatory fields exist, when the user tries to save without completing them, then the system must show validation messages.
* **Suggested Fields:**
* Plan Name, Code, Validity/Period, Compensation Type, Area, Role, Hotel, Region, Calculation Type, Formula, Goal/Quota, Percentage, Max Caps, Status.
* **Operations (Sub-features):**
* Create plan, Edit plan, Duplicate plan, Versioning, Inactivate plan.
#### HU-COM-002 — Configurar reglas de cálculo
* **Como:** Administrador
* **Quiero:** Parametrizar reglas de negocio
* **Para:** Automatizar liquidaciones de comisiones e incentivos.
* **Descripción:**
El sistema deberá soportar:
* Cálculos porcentuales
* Escalas y Rangos
* Cumplimiento de metas
* Comisiones fijas y variables
* Bonos especiales
* **Criterios de Aceptación:**
* **Escenario 1 (Configuración de fórmula):** Dado que existe un plan de compensación, cuando el usuario define las reglas, entonces el sistema debe almacenar la configuración.
* **Escenario 2 (Validación de topes):** Dado que existe un tope máximo definido, cuando el cálculo supera el límite, entonces el sistema debe aplicar el tope configurado.
* **Operaciones (Sub-features):**
* Fórmulas dinámicas, Escalas de comisión, Topes máximos, Reglas condicionales, Bonificaciones especiales.
#### US-COM-002 — Configure Calculation Rules
* **Role:** Administrator
* **Goal:** Parametrize business rules
* **Benefit:** Automate commission and incentive settlements.
* **Description:**
The system must support:
* Percentage calculations
* Tiers/Scales and Ranges
* Goal achievements
* Fixed and variable commissions
* Special bonuses
* **Acceptance Criteria:**
* **Scenario 1 (Formula configuration):** Given that a compensation plan exists, when the user defines the rules, then the system must store the configuration.
* **Scenario 2 (Cap validation):** Given that a maximum cap is defined, when the calculation exceeds the limit, then the system must apply the configured cap.
* **Operations (Sub-features):**
* Dynamic formulas, Commission scales, Max caps, Conditional rules, Special bonuses.
#### HU-COM-003 — Configurar metas comerciales
* **Como:** Administrador
* **Quiero:** Configurar metas comerciales
* **Para:** Medir cumplimiento para cálculo de variables.
* **Criterios de Aceptación:**
* **Escenario 1 (Configurar meta):** Dado que existe un colaborador o equipo, cuando el usuario asigna metas, entonces el sistema debe almacenarlas por periodo.
* **Operaciones (Sub-features):**
* Metas mensuales, trimestrales, por hotel, por equipo, individuales.
#### US-COM-003 — Configure Commercial Goals
* **Role:** Administrator
* **Goal:** Configure commercial goals/quotas
* **Benefit:** Measure achievement for variable calculations.
* **Acceptance Criteria:**
* **Scenario 1 (Configure goal):** Given that a collaborator or team exists, when the user assigns goals, then the system must store them by period.
* **Operations (Sub-features):**
* Monthly goals, quarterly goals, per-hotel goals, per-team goals, individual goals.
---
### FEATURE 2 — Carga e Integración de Información
### FEATURE 2 — Data Load & Integration
#### HU-COM-004 — Importar resultados comerciales desde Excel
* **Como:** Usuario
* **Quiero:** Importar resultados comerciales desde Excel
* **Para:** Evitar procesos manuales.
* **Criterios de Aceptación:**
* **Escenario 1 (Importación válida):** Dado que el usuario carga un archivo válido, cuando el sistema procesa la información, entonces debe actualizar resultados automáticamente.
* **Escenario 2 (Archivo inválido):** Dado que el archivo contiene errores, cuando el sistema procesa el archivo, entonces debe mostrar inconsistencias.
* **Operaciones (Sub-features):**
* Importación XLSX/CSV, Validación de columnas, Plantillas de carga.
#### US-COM-004 — Import Commercial Results from Excel
* **Role:** User
* **Goal:** Import commercial results from Excel
* **Benefit:** Avoid manual data-entry processes.
* **Acceptance Criteria:**
* **Scenario 1 (Valid import):** Given that the user uploads a valid file, when the system processes the information, then it must update results automatically.
* **Scenario 2 (Invalid file):** Given that the file contains errors, when the system processes the file, then it must display validation inconsistencies.
* **Operations (Sub-features):**
* XLSX/CSV import, Column validation, Upload templates.
#### HU-COM-005 — Integración automática con sistemas externos
* **Como:** Administrador
* **Quiero:** Integrar automáticamente información de ventas
* **Para:** Automatizar el cálculo de comisiones.
* **Descripción:**
El sistema deberá integrarse con:
* ERP, PMS hotelero, CRM, Sistemas financieros, Plataformas de reservas, Revenue Management.
* **Criterios de Aceptación:**
* **Escenario 1 (Integración exitosa):** Dado que existe una integración configurada, cuando el proceso automático se ejecuta, entonces el sistema debe actualizar la información automáticamente.
* **Escenario 2 (Error de integración):** Dado que existe una falla, cuando el proceso no finaliza correctamente, entonces el sistema debe registrar logs y notificar al administrador.
* **Operaciones (Sub-features):**
* Integraciones API, Jobs automáticos, Logs, Reintentos automáticos.
#### US-COM-005 — Automatic Integration with External Systems
* **Role:** Administrator
* **Goal:** Automatically integrate sales information
* **Benefit:** Automate commission calculation.
* **Description:**
The system must integrate with:
* ERP, Hotel PMS, CRM, Financial systems, Booking platforms, Revenue Management.
* **Acceptance Criteria:**
* **Scenario 1 (Successful integration):** Given that an integration is configured, when the automatic process runs, then the system must update the information automatically.
* **Scenario 2 (Integration error):** Given that a failure occurs, when the process does not finish successfully, then the system must log the errors and notify the administrator.
* **Operations (Sub-features):**
* API integrations, Automated Cron Jobs, Logs, Automatic retries.
---
### FEATURE 3 — Liquidación Automática
### FEATURE 3 — Automated Settlement
#### HU-COM-006 — Calcular comisiones automáticamente
* **Como:** Sistema
* **Quiero:** Calcular automáticamente las comisiones
* **Para:** Reducir errores manuales.
* **Criterios de Aceptación:**
* **Escenario 1 (Cálculo individual):** Dado que existen ventas registradas, cuando el sistema ejecuta la liquidación, entonces debe calcular automáticamente: Comisión individual, Cumplimiento, Bono e Incentivo.
* **Escenario 2 (Cálculo grupal):** Dado que existen reglas grupales, cuando el sistema procesa el cálculo, entonces debe generar comisión grupal automáticamente.
* **Operaciones (Sub-features):**
* Motor de cálculo, Liquidación automática, Cálculos masivos, Simulación de pagos.
#### US-COM-006 — Calculate Commissions Automatically
* **Role:** System
* **Goal:** Automatically calculate commissions
* **Benefit:** Reduce manual errors.
* **Acceptance Criteria:**
* **Scenario 1 (Individual calculation):** Given that registered sales exist, when the system executes the settlement, then it must calculate automatically: Individual commission, Goal achievement percentage, Bonus, and Incentive.
* **Scenario 2 (Group calculation):** Given that group rules exist, when the system processes the calculation, then it must generate the group commission automatically.
* **Operations (Sub-features):**
* Calculation engine, Automatic settlement, Bulk calculations, Payment simulation.
#### HU-COM-007 — Simular liquidación antes de aprobar
* **Como:** Líder Comercial
* **Quiero:** Simular liquidaciones
* **Para:** Validar resultados antes de aprobar pagos.
* **Criterios de Aceptación:**
* **Escenario 1 (Simulación):** Dado que existe un periodo de liquidación, cuando el usuario ejecuta simulación, entonces el sistema debe mostrar resultados preliminares.
* **Operaciones (Sub-features):**
* Simulación, Validación previa, Comparativos, Ajustes antes de cierre.
#### US-COM-007 — Simulate Settlement Before Approval
* **Role:** Commercial Leader
* **Goal:** Simulate settlements
* **Benefit:** Validate results before approving payments.
* **Acceptance Criteria:**
* **Scenario 1 (Simulation):** Given that a settlement period exists, when the user runs the simulation, then the system must show preliminary results.
* **Operations (Sub-features):**
* Simulation, Pre-validation, Comparisons, Adjustments before closing.
---
### FEATURE 4 — Aprobaciones y Flujo de Validación
### FEATURE 4 — Approvals & Validation Flow
#### HU-COM-008 — Aprobar liquidaciones
* **Como:** Líder Comercial
* **Quiero:** Aprobar o rechazar liquidaciones
* **Para:** Validar pagos variables.
* **Criterios de Aceptación:**
* **Escenario 1 (Aprobar):** Dado que existe una liquidación generada, cuando el líder revisa la información, entonces puede aprobarla.
* **Escenario 2 (Rechazar):** Dado que existen inconsistencias, cuando el líder rechaza la liquidación, entonces debe registrar observaciones obligatorias.
* **Operaciones (Sub-features):**
* Flujo de aprobación, Observaciones, Rechazos, Reenvío de liquidación.
#### US-COM-008 — Approve Settlements
* **Role:** Commercial Leader
* **Goal:** Approve or reject settlements
* **Benefit:** Validate variable payments.
* **Acceptance Criteria:**
* **Scenario 1 (Approve):** Given that a settlement has been generated, when the leader reviews the information, then they can approve it.
* **Scenario 2 (Reject):** Given that inconsistencies exist, when the leader rejects the settlement, then they must record mandatory observations/comments.
* **Operations (Sub-features):**
* Approval workflow, Observations/Comments, Rejections, Settlement resubmission.
#### HU-COM-009 — Notificar aprobación o rechazo
* **Como:** Sistema
* **Quiero:** Notificar resultados de aprobación
* **Para:** Informar a los responsables.
* **Criterios de Aceptación:**
* **Escenario 1 (Notificación de aprobación):** Dado que la liquidación fue aprobada, cuando finaliza el proceso, entonces el sistema debe enviar notificación automática.
* **Operaciones (Sub-features):**
* Correos automáticos, Notificaciones push, Historial de notificaciones.
#### US-COM-009 — Notify Approval or Rejection
* **Role:** System
* **Goal:** Notify approval or rejection results
* **Benefit:** Inform responsible stakeholders.
* **Acceptance Criteria:**
* **Scenario 1 (Approval notification):** Given that the settlement was approved, when the process finishes, then the system must send an automatic notification.
* **Operations (Sub-features):**
* Auto-emails, Push notifications, Notification logs.
---
### FEATURE 5 — Consulta y Trazabilidad
### FEATURE 5 — Inquiry & Traceability
#### HU-COM-010 — Consultar histórico de comisiones
* **Como:** Colaborador
* **Quiero:** Consultar mi histórico de pagos variables
* **Para:** Validar liquidaciones realizadas.
* **Criterios de Aceptación:**
* **Escenario 1 (Consulta histórica):** Dado que existen periodos liquidados, cuando el usuario consulta la información, entonces el sistema debe mostrar: Periodo, Meta, Resultado, Comisión, Estado.
* **Operaciones (Sub-features):**
* Histórico de pagos, Filtros, Descarga PDF, Consulta por periodos.
#### US-COM-010 — Consult Commission History
* **Role:** Collaborator
* **Goal:** Consult variable payment history
* **Benefit:** Validate settlements performed.
* **Acceptance Criteria:**
* **Scenario 1 (Historical query):** Given that settled periods exist, when the user queries the information, then the system must display: Period, Goal, Result, Commission, Status.
* **Operations (Sub-features):**
* Payment history, Filters, PDF download, Period queries.
#### HU-COM-011 — Registrar trazabilidad y auditoría
* **Como:** Sistema
* **Quiero:** Registrar cambios y aprobaciones
* **Para:** Mantener trazabilidad histórica.
* **Criterios de Aceptación:**
* **Escenario 1 (Registro automático):** Dado que un usuario modifica reglas o liquidaciones, cuando guarda cambios, entonces el sistema debe registrar: Usuario, Fecha, Hora, Acción, Valor anterior, Valor nuevo.
* **Operaciones (Sub-features):**
* Auditoría, Logs, Histórico, Bitácora.
#### US-COM-011 — Record Traceability and Auditing
* **Role:** System
* **Goal:** Record changes and approvals
* **Benefit:** Maintain historical audit trails.
* **Acceptance Criteria:**
* **Scenario 1 (Automatic recording):** Given that a user modifies rules or settlements, when they save changes, then the system must record: User, Date, Time, Action, Previous value, New value.
* **Operations (Sub-features):**
* Audit trails, Logs, History, Logbook.
---
### FEATURE 6 — Reportes y Analítica
### FEATURE 6 — Reports & Analytics
#### HU-COM-012 — Visualizar dashboard de compensación
* **Como:** Director Comercial
* **Quiero:** Visualizar dashboards de compensación
* **Para:** Analizar desempeño y costos variables.
* **Criterios de Aceptación:**
* **Escenario 1 (Dashboard ejecutivo):** Dado que existen liquidaciones generadas, cuando el usuario consulta el dashboard, entonces el sistema debe mostrar: Comisiones pagadas, Cumplimiento, Ranking comercial, Costos variables, Tendencias.
* **Operaciones (Sub-features):**
* Dashboards, KPIs financieros, Tendencias, Comparativos.
#### US-COM-012 — Visualize Compensation Dashboard
* **Role:** Commercial Director
* **Goal:** View compensation dashboards
* **Benefit:** Analyze performance and variable costs.
* **Acceptance Criteria:**
* **Scenario 1 (Executive Dashboard):** Given that settlements have been generated, when the user views the dashboard, then the system must display: Paid commissions, Goal achievement, Sales ranking, Variable costs, Trends.
* **Operations (Sub-features):**
* Dashboards, Financial KPIs, Trends, Comparisons.
#### HU-COM-013 — Exportar reportes financieros
* **Como:** Usuario Financiero
* **Quiero:** Exportar reportes
* **Para:** Realizar análisis presupuestal y operativo.
* **Criterios de Aceptación:**
* **Escenario 1 (Exportación):** Dado que existen resultados liquidados, cuando el usuario selecciona exportar, entonces el sistema debe generar: PDF, Excel, Consolidados por hotel, Consolidados por región.
* **Operaciones (Sub-features):**
* Exportación PDF, Exportación Excel, Reportes consolidados, Programación automática de reportes.
#### US-COM-013 — Export Financial Reports
* **Role:** Financial User
* **Goal:** Export reports
* **Benefit:** Perform budget and operational analysis.
* **Acceptance Criteria:**
* **Scenario 1 (Export):** Given that settled results exist, when the user selects export, then the system must generate: PDF, Excel, Consolidated reports by hotel, Consolidated reports by region.
* **Operations (Sub-features):**
* PDF export, Excel export, Consolidated reports, Automated report scheduling.
---
### FEATURE 7 — Seguridad y Permisos
### FEATURE 7 — Security & Permissions
#### HU-COM-014 — Gestionar roles y permisos
* **Como:** Administrador
* **Quiero:** Gestionar roles y accesos
* **Para:** Proteger información sensible.
* **Roles sugeridos:**
* Administrador, Director Comercial, Gerente Hotel, Líder Comercial, Analista Financiero, Consulta.
* **Operaciones (Sub-features):**
* Roles, Permisos, Restricción por hotel, Restricción por región, Restricción por área.
#### US-COM-014 — Manage Roles and Permissions
* **Role:** Administrator
* **Goal:** Manage roles and accesses
* **Benefit:** Protect sensitive financial information.
* **Suggested Roles:**
* Administrator, Commercial Director, Hotel Manager, Commercial Leader, Financial Analyst, Inquiry (Consulta).
* **Operations (Sub-features):**
* Roles, Permissions, Restriction by hotel, Restriction by region, Restriction by area.

179
docs/STYLE_GUIDE.md Normal file
View file

@ -0,0 +1,179 @@
# Vanilla CSS & CSS Modules Style Guide
**Variable Remuneration, Compensation, and Commissions System - Hoteles Estelar**
---
This document outlines the strict guidelines for styling the application using **Vanilla CSS** and **CSS Modules**. By sticking to these guidelines, we ensure absolute isolation of component styles, prevent class name collisions, maintain a centralized token system, and support robust theme modifications (light/dark mode).
## 1. Centralized Design Tokens (`globals.css`)
All colors, spacing, typography, transitions, and layout presets must be defined as CSS custom properties (variables) inside `/styles/globals.css`. Global variables are declared in HSL (Hue, Saturation, Lightness) format to allow dynamic opacity control using `alpha-value` mixing.
```css
:root {
/* Color Palette - HSL values for premium dark/light mode */
--primary-h: 220;
--primary-s: 85%;
--primary-l: 57%;
--primary: hsl(var(--primary-h), var(--primary-s), var(--primary-l));
--secondary-h: 260;
--secondary-s: 70%;
--secondary-l: 50%;
--secondary: hsl(var(--secondary-h), var(--secondary-s), var(--secondary-l));
--background-h: 0;
--background-s: 0%;
--background-l: 100%;
--background: hsl(var(--background-h), var(--background-s), var(--background-l));
--foreground-h: 220;
--foreground-s: 40%;
--foreground-l: 10%;
--foreground: hsl(var(--foreground-h), var(--foreground-s), var(--foreground-l));
--card: hsl(0, 0%, 97%);
--border: hsl(220, 20%, 90%);
/* Spacing Grid (8pt Grid System) */
--space-1: 0.25rem; /* 4px */
--space-2: 0.5rem; /* 8px */
--space-3: 0.75rem; /* 12px */
--space-4: 1rem; /* 16px */
--space-6: 1.5rem; /* 24px */
--space-8: 2rem; /* 32px */
--space-12: 3rem; /* 48px */
/* Typography Scale */
--font-sans: 'Inter', system-ui, -apple-system, sans-serif;
--text-xs: 0.75rem;
--text-sm: 0.875rem;
--text-base: 1rem;
--text-lg: 1.125rem;
--text-xl: 1.25rem;
--text-2xl: 1.5rem;
--text-3xl: 1.875rem;
--text-4xl: 2.25rem;
--weight-normal: 400;
--weight-medium: 500;
--weight-semibold: 600;
--weight-bold: 700;
/* Border Radius & Shadow Tokens */
--radius-sm: 0.375rem;
--radius-md: 0.5rem;
--radius-lg: 0.75rem;
--radius-xl: 1rem;
--radius-full: 9999px;
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
--shadow-glow: 0 0 15px 2px hsla(var(--primary-h), var(--primary-s), var(--primary-l), 0.15);
/* Transitions */
--transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1);
--transition-normal: 250ms cubic-bezier(0.4, 0, 0.2, 1);
--transition-slow: 350ms cubic-bezier(0.4, 0, 0.2, 1);
}
/* Dark mode overrides (Activated via html[data-theme='dark'] or media queries) */
[data-theme='dark'] {
--background-h: 220;
--background-s: 40%;
--background-l: 6%;
--background: hsl(var(--background-h), var(--background-s), var(--background-l));
--foreground-h: 220;
--foreground-s: 15%;
--foreground-l: 90%;
--foreground: hsl(var(--foreground-h), var(--foreground-s), var(--foreground-l));
--card: hsl(220, 30%, 11%);
--border: hsl(220, 20%, 18%);
}
```
---
## 2. Component Scoping with CSS Modules
All component-specific styles must live inside a `.module.css` file adjacent to the React component (e.g. `Button.tsx` pairs with `Button.module.css`).
### 2.1. Naming Conventions (Flat Local Names)
Since CSS Modules automatically generate unique identifiers at compile time (e.g., `.container` becomes `.Button_container__u1a2x`), complex BEM class names are not required. Use clear, semantic local names:
* Good: `.container`, `.card`, `.button`, `.badge`
* Avoid: `.button-container-outer`, `.btn-v2`
### 2.2. CSS Modules Usage in React
```tsx
import styles from './Button.module.css';
interface ButtonProps {
variant?: 'primary' | 'secondary';
isActive?: boolean;
}
export function Button({ variant = 'primary', isActive, children }: ButtonProps) {
return (
<button
className={`
${styles.button}
${styles[variant]}
${isActive ? styles.isActive : ''}
`}
>
{children}
</button>
);
}
```
---
## 3. Styling & Layout Guidelines
* **Layout Structure**: Use **CSS Grid** for page structures and multi-column layouts. Use **Flexbox** for alignment inside rows, headers, and buttons. Never use tables or absolute positioning for structural layouts.
* **Sizing & Spacing**: Use `rem` for typography, margin, padding, widths, and heights to ensure relative scaling. Always use variables from the spacing grid (`var(--space-4)`).
* **Responsive Design**: Follow a mobile-first media query approach. Breakpoints are defined in variables and coded as:
```css
.container {
display: grid;
grid-template-columns: 1fr;
gap: var(--space-4);
}
@media (min-width: 768px) {
.container {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 1024px) {
.container {
grid-template-columns: repeat(4, 1fr);
}
}
```
---
## 4. UI Polish & Animations
To deliver a premium visual experience:
* **Micro-interactions**: Every interactive element (buttons, cards, inputs) must have a subtle hover effect using hardware-accelerated properties (`transform`, `opacity`, `background-color`).
```css
.card {
background-color: var(--card);
border: 1px solid var(--border);
transition: transform var(--transition-normal), box-shadow var(--transition-normal);
}
.card:hover {
transform: translateY(-2px);
box-shadow: var(--shadow-lg), var(--shadow-glow);
}
```
* **No Inline Styles**: Inline styles (`style={{ ... }}`) are forbidden unless evaluating dynamically updated values that cannot be declared beforehand (e.g., progress bar percentage `--progress: 73%`).