docs: translate requirements to English, update architecture with n8n and independence, add strict CSS module style guide
This commit is contained in:
parent
261762030b
commit
e3c954cdf7
3 changed files with 371 additions and 185 deletions
|
|
@ -1,40 +1,41 @@
|
||||||
# Architecture and System Design
|
# 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
|
## 1. Technical Stack
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
* **Frontend**: Next.js App Router (React + TypeScript).
|
* **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).
|
* **Backend**: Next.js API Routes (Node.js runtime).
|
||||||
* **ORM**: Prisma ORM (provides type-safe database queries and automated schema migrations).
|
* **ORM**: Prisma ORM (providing type-safe database queries and automated schema migrations).
|
||||||
* **Database**: PostgreSQL (hosted on the existing `postgres` Docker stack).
|
* **Database**: PostgreSQL (decoupled, configured via environment variables to run on any host/network).
|
||||||
* **Excel Processing**: `xlsx` (SheetJS) for high-performance parser logic.
|
* **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).
|
||||||
* **Authentication**: NextAuth.js or custom lightweight JWT session cookies.
|
* **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.
|
||||||
* **Hosting**: Docker container integrated into the Dockge stack manager, reverse proxied by Caddy with split DNS resolving over WireGuard VPN for security-sensitive areas.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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
|
```mermaid
|
||||||
graph TD
|
graph TD
|
||||||
User([Colaborador / Líder / Admin]) -->|HTTPS| Caddy[Caddy Reverse Proxy]
|
User([User Client]) -->|HTTPS| WebApp[Next.js App Router]
|
||||||
Caddy -->|Internal Network| NextJS[Next.js Full-Stack App]
|
|
||||||
|
|
||||||
subgraph NextJS Container
|
subgraph Isolated Network
|
||||||
UI[React Frontend / Vanilla CSS] <--> API[API Routes / Controllers]
|
WebApp -->|Prisma Client| DB[(PostgreSQL)]
|
||||||
Engine[Settlement Engine] <--> API
|
WebApp -->|HTTP POST Webhook| n8n[n8n Workflow Engine]
|
||||||
Parser[Excel Parser] <--> API
|
n8n -->|HTTP POST Callback| WebApp
|
||||||
|
n8n -->|Interact| LLM[AI Model / Provider]
|
||||||
end
|
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:
|
### 4.2. Settlement Calculation Workflow
|
||||||
1. **Fetch inputs**: Get sales results, goals, and matching active compensation plan for the collaborator for the period `YYYY-MM`.
|
1. **Trigger**: Next.js calls n8n to execute the calculation for period `YYYY-MM`.
|
||||||
2. **Determine Achievement Level**: Check against the plan's `CALCULATION_RULES` (tiers).
|
2. **n8n Processing**:
|
||||||
3. **Calculate Commission**:
|
- Pulls active plans, individual goals, and actual sales from the Next.js API.
|
||||||
- *Fixed Rate*: $\text{Sales} \times \text{percentage\_rate}$.
|
- Evaluates the mathematical formulas.
|
||||||
- *Tiers/Scales*: Apply rate corresponding to the achievement level tier.
|
- Evaluates rule scales and applies caps.
|
||||||
4. **Apply Caps**: If calculated commission exceeds the plan's `max_cap`, set it to `max_cap`.
|
- Generates notifications (via email or push notifications) using n8n integrations.
|
||||||
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.
|
3. **Response**: Updates database records via the Next.js API and completes the task.
|
||||||
6. **Generate Output**: Store as a `SETTLEMENT` entry in `SIMULATED` status.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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
|
## General Objective
|
||||||
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.
|
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
|
## Functional Scope
|
||||||
El sistema se compone de 7 características principales (Features) divididas en 14 Historias de Usuario (HU).
|
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
|
#### US-COM-001 — Create Compensation Plan
|
||||||
* **Como:** Administrador del sistema
|
* **Role:** System Administrator
|
||||||
* **Quiero:** Crear planes de compensación y comisiones
|
* **Goal:** Create compensation and commission plans
|
||||||
* **Para:** Definir las reglas de remuneración variable.
|
* **Benefit:** Define variable remuneration rules.
|
||||||
* **Descripción:**
|
* **Description:**
|
||||||
El sistema deberá permitir configurar planes asociados a:
|
The system must allow configuring plans associated with:
|
||||||
* Hoteles
|
* Hotels
|
||||||
* Regiones
|
* Regions
|
||||||
* Equipos comerciales
|
* Commercial teams
|
||||||
* Cargos
|
* Roles
|
||||||
* Campañas
|
* Campaigns
|
||||||
* Temporadas
|
* Seasons
|
||||||
* Unidades de negocio
|
* Business units
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **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.
|
||||||
* **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.
|
* **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.
|
||||||
* **Campos sugeridos:**
|
* **Suggested Fields:**
|
||||||
* 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.
|
* Plan Name, Code, Validity/Period, Compensation Type, Area, Role, Hotel, Region, Calculation Type, Formula, Goal/Quota, Percentage, Max Caps, Status.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Crear plan, Editar plan, Duplicar plan, Versionamiento, Inactivar plan.
|
* Create plan, Edit plan, Duplicate plan, Versioning, Inactivate plan.
|
||||||
|
|
||||||
#### HU-COM-002 — Configurar reglas de cálculo
|
#### US-COM-002 — Configure Calculation Rules
|
||||||
* **Como:** Administrador
|
* **Role:** Administrator
|
||||||
* **Quiero:** Parametrizar reglas de negocio
|
* **Goal:** Parametrize business rules
|
||||||
* **Para:** Automatizar liquidaciones de comisiones e incentivos.
|
* **Benefit:** Automate commission and incentive settlements.
|
||||||
* **Descripción:**
|
* **Description:**
|
||||||
El sistema deberá soportar:
|
The system must support:
|
||||||
* Cálculos porcentuales
|
* Percentage calculations
|
||||||
* Escalas y Rangos
|
* Tiers/Scales and Ranges
|
||||||
* Cumplimiento de metas
|
* Goal achievements
|
||||||
* Comisiones fijas y variables
|
* Fixed and variable commissions
|
||||||
* Bonos especiales
|
* Special bonuses
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **Scenario 1 (Formula configuration):** Given that a compensation plan exists, when the user defines the rules, then the system must store the configuration.
|
||||||
* **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.
|
* **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.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Fórmulas dinámicas, Escalas de comisión, Topes máximos, Reglas condicionales, Bonificaciones especiales.
|
* Dynamic formulas, Commission scales, Max caps, Conditional rules, Special bonuses.
|
||||||
|
|
||||||
#### HU-COM-003 — Configurar metas comerciales
|
#### US-COM-003 — Configure Commercial Goals
|
||||||
* **Como:** Administrador
|
* **Role:** Administrator
|
||||||
* **Quiero:** Configurar metas comerciales
|
* **Goal:** Configure commercial goals/quotas
|
||||||
* **Para:** Medir cumplimiento para cálculo de variables.
|
* **Benefit:** Measure achievement for variable calculations.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **Escenario 1 (Configurar meta):** Dado que existe un colaborador o equipo, cuando el usuario asigna metas, entonces el sistema debe almacenarlas por periodo.
|
* **Scenario 1 (Configure goal):** Given that a collaborator or team exists, when the user assigns goals, then the system must store them by period.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Metas mensuales, trimestrales, por hotel, por equipo, individuales.
|
* 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
|
#### US-COM-004 — Import Commercial Results from Excel
|
||||||
* **Como:** Usuario
|
* **Role:** User
|
||||||
* **Quiero:** Importar resultados comerciales desde Excel
|
* **Goal:** Import commercial results from Excel
|
||||||
* **Para:** Evitar procesos manuales.
|
* **Benefit:** Avoid manual data-entry processes.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **Scenario 1 (Valid import):** Given that the user uploads a valid file, when the system processes the information, then it must update results automatically.
|
||||||
* **Escenario 2 (Archivo inválido):** Dado que el archivo contiene errores, cuando el sistema procesa el archivo, entonces debe mostrar inconsistencias.
|
* **Scenario 2 (Invalid file):** Given that the file contains errors, when the system processes the file, then it must display validation inconsistencies.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Importación XLSX/CSV, Validación de columnas, Plantillas de carga.
|
* XLSX/CSV import, Column validation, Upload templates.
|
||||||
|
|
||||||
#### HU-COM-005 — Integración automática con sistemas externos
|
#### US-COM-005 — Automatic Integration with External Systems
|
||||||
* **Como:** Administrador
|
* **Role:** Administrator
|
||||||
* **Quiero:** Integrar automáticamente información de ventas
|
* **Goal:** Automatically integrate sales information
|
||||||
* **Para:** Automatizar el cálculo de comisiones.
|
* **Benefit:** Automate commission calculation.
|
||||||
* **Descripción:**
|
* **Description:**
|
||||||
El sistema deberá integrarse con:
|
The system must integrate with:
|
||||||
* ERP, PMS hotelero, CRM, Sistemas financieros, Plataformas de reservas, Revenue Management.
|
* ERP, Hotel PMS, CRM, Financial systems, Booking platforms, Revenue Management.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **Scenario 1 (Successful integration):** Given that an integration is configured, when the automatic process runs, then the system must update the information automatically.
|
||||||
* **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.
|
* **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.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Integraciones API, Jobs automáticos, Logs, Reintentos automáticos.
|
* 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
|
#### US-COM-006 — Calculate Commissions Automatically
|
||||||
* **Como:** Sistema
|
* **Role:** System
|
||||||
* **Quiero:** Calcular automáticamente las comisiones
|
* **Goal:** Automatically calculate commissions
|
||||||
* **Para:** Reducir errores manuales.
|
* **Benefit:** Reduce manual errors.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **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.
|
||||||
* **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.
|
* **Scenario 2 (Group calculation):** Given that group rules exist, when the system processes the calculation, then it must generate the group commission automatically.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Motor de cálculo, Liquidación automática, Cálculos masivos, Simulación de pagos.
|
* Calculation engine, Automatic settlement, Bulk calculations, Payment simulation.
|
||||||
|
|
||||||
#### HU-COM-007 — Simular liquidación antes de aprobar
|
#### US-COM-007 — Simulate Settlement Before Approval
|
||||||
* **Como:** Líder Comercial
|
* **Role:** Commercial Leader
|
||||||
* **Quiero:** Simular liquidaciones
|
* **Goal:** Simulate settlements
|
||||||
* **Para:** Validar resultados antes de aprobar pagos.
|
* **Benefit:** Validate results before approving payments.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **Scenario 1 (Simulation):** Given that a settlement period exists, when the user runs the simulation, then the system must show preliminary results.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Simulación, Validación previa, Comparativos, Ajustes antes de cierre.
|
* 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
|
#### US-COM-008 — Approve Settlements
|
||||||
* **Como:** Líder Comercial
|
* **Role:** Commercial Leader
|
||||||
* **Quiero:** Aprobar o rechazar liquidaciones
|
* **Goal:** Approve or reject settlements
|
||||||
* **Para:** Validar pagos variables.
|
* **Benefit:** Validate variable payments.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **Escenario 1 (Aprobar):** Dado que existe una liquidación generada, cuando el líder revisa la información, entonces puede aprobarla.
|
* **Scenario 1 (Approve):** Given that a settlement has been generated, when the leader reviews the information, then they can approve it.
|
||||||
* **Escenario 2 (Rechazar):** Dado que existen inconsistencias, cuando el líder rechaza la liquidación, entonces debe registrar observaciones obligatorias.
|
* **Scenario 2 (Reject):** Given that inconsistencies exist, when the leader rejects the settlement, then they must record mandatory observations/comments.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Flujo de aprobación, Observaciones, Rechazos, Reenvío de liquidación.
|
* Approval workflow, Observations/Comments, Rejections, Settlement resubmission.
|
||||||
|
|
||||||
#### HU-COM-009 — Notificar aprobación o rechazo
|
#### US-COM-009 — Notify Approval or Rejection
|
||||||
* **Como:** Sistema
|
* **Role:** System
|
||||||
* **Quiero:** Notificar resultados de aprobación
|
* **Goal:** Notify approval or rejection results
|
||||||
* **Para:** Informar a los responsables.
|
* **Benefit:** Inform responsible stakeholders.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **Scenario 1 (Approval notification):** Given that the settlement was approved, when the process finishes, then the system must send an automatic notification.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Correos automáticos, Notificaciones push, Historial de notificaciones.
|
* Auto-emails, Push notifications, Notification logs.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### FEATURE 5 — Consulta y Trazabilidad
|
### FEATURE 5 — Inquiry & Traceability
|
||||||
|
|
||||||
#### HU-COM-010 — Consultar histórico de comisiones
|
#### US-COM-010 — Consult Commission History
|
||||||
* **Como:** Colaborador
|
* **Role:** Collaborator
|
||||||
* **Quiero:** Consultar mi histórico de pagos variables
|
* **Goal:** Consult variable payment history
|
||||||
* **Para:** Validar liquidaciones realizadas.
|
* **Benefit:** Validate settlements performed.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **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.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Histórico de pagos, Filtros, Descarga PDF, Consulta por periodos.
|
* Payment history, Filters, PDF download, Period queries.
|
||||||
|
|
||||||
#### HU-COM-011 — Registrar trazabilidad y auditoría
|
#### US-COM-011 — Record Traceability and Auditing
|
||||||
* **Como:** Sistema
|
* **Role:** System
|
||||||
* **Quiero:** Registrar cambios y aprobaciones
|
* **Goal:** Record changes and approvals
|
||||||
* **Para:** Mantener trazabilidad histórica.
|
* **Benefit:** Maintain historical audit trails.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **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.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Auditoría, Logs, Histórico, Bitácora.
|
* Audit trails, Logs, History, Logbook.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### FEATURE 6 — Reportes y Analítica
|
### FEATURE 6 — Reports & Analytics
|
||||||
|
|
||||||
#### HU-COM-012 — Visualizar dashboard de compensación
|
#### US-COM-012 — Visualize Compensation Dashboard
|
||||||
* **Como:** Director Comercial
|
* **Role:** Commercial Director
|
||||||
* **Quiero:** Visualizar dashboards de compensación
|
* **Goal:** View compensation dashboards
|
||||||
* **Para:** Analizar desempeño y costos variables.
|
* **Benefit:** Analyze performance and variable costs.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **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.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Dashboards, KPIs financieros, Tendencias, Comparativos.
|
* Dashboards, Financial KPIs, Trends, Comparisons.
|
||||||
|
|
||||||
#### HU-COM-013 — Exportar reportes financieros
|
#### US-COM-013 — Export Financial Reports
|
||||||
* **Como:** Usuario Financiero
|
* **Role:** Financial User
|
||||||
* **Quiero:** Exportar reportes
|
* **Goal:** Export reports
|
||||||
* **Para:** Realizar análisis presupuestal y operativo.
|
* **Benefit:** Perform budget and operational analysis.
|
||||||
* **Criterios de Aceptación:**
|
* **Acceptance Criteria:**
|
||||||
* **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.
|
* **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.
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Exportación PDF, Exportación Excel, Reportes consolidados, Programación automática de reportes.
|
* 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
|
#### US-COM-014 — Manage Roles and Permissions
|
||||||
* **Como:** Administrador
|
* **Role:** Administrator
|
||||||
* **Quiero:** Gestionar roles y accesos
|
* **Goal:** Manage roles and accesses
|
||||||
* **Para:** Proteger información sensible.
|
* **Benefit:** Protect sensitive financial information.
|
||||||
* **Roles sugeridos:**
|
* **Suggested Roles:**
|
||||||
* Administrador, Director Comercial, Gerente Hotel, Líder Comercial, Analista Financiero, Consulta.
|
* Administrator, Commercial Director, Hotel Manager, Commercial Leader, Financial Analyst, Inquiry (Consulta).
|
||||||
* **Operaciones (Sub-features):**
|
* **Operations (Sub-features):**
|
||||||
* Roles, Permisos, Restricción por hotel, Restricción por región, Restricción por área.
|
* Roles, Permissions, Restriction by hotel, Restriction by region, Restriction by area.
|
||||||
|
|
|
||||||
179
docs/STYLE_GUIDE.md
Normal file
179
docs/STYLE_GUIDE.md
Normal 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%`).
|
||||||
Loading…
Reference in a new issue