diff --git a/docs/PHASE_6_IMPLEMENTATION.md b/docs/PHASE_6_IMPLEMENTATION.md new file mode 100644 index 0000000..0a7dc9c --- /dev/null +++ b/docs/PHASE_6_IMPLEMENTATION.md @@ -0,0 +1,159 @@ +# Phase 6 Implementation Plan: History, Auditing & Analytics + +**Variable Remuneration, Compensation, and Commissions System - Hoteles Estelar** + +--- + +This document defines the detailed technical specifications and deployment steps for Phase 6, covering commission history queries (US-COM-010), immutable audit log trails (US-COM-011), premium analytics dashboards (US-COM-012), and PDF/Excel financial report exporters (US-COM-013). + +--- + +## 1. Technical Stack & Additions + +* **Chart Library**: Integrate **`recharts`** (or `chart.js` + `react-chartjs-2`) as the charting library. It is fully compatible with React, Next.js, and TypeScript. All chart components will be scoped as client-side components (`"use client"`) to support SVG/Canvas interactive animations. +* **Styling**: Strictly adhere to [STYLE_GUIDE.md](file:///home/gabogg/Proyects/semillero-special-hotel/docs/STYLE_GUIDE.md). Apply Vanilla CSS Modules (`*.module.css`), utilizing CSS HSL variables from `globals.css` (e.g., `--primary`, `--card`, `--border`, `--background`) to support seamless light/dark theme switches. +* **Database & RLS**: All history and analytics database operations must execute using the `getPrisma(session)` transaction helper to automatically apply PostgreSQL Row-Level Security (RLS). +* **Internationalization**: All text labels, chart tooltips, tables, and audit logs must render dynamically in English or Spanish according to the user's active `useLocale()` context. + +--- + +## 2. Directory Layout & Routing + +The following new files will be constructed under the workspace directory: + +``` +src/ + ├── app/ + │ ├── history/ + │ │ ├── page.tsx # Colaborador historical ledger view + │ │ └── page.module.css # Scoped history layout styles + │ ├── dashboard/ + │ │ ├── page.tsx # Analytics dashboard layout + │ │ ├── page.module.css # Scoped dashboard dashboard grid + │ │ └── ChartComponents.tsx # Scoped client charts using Recharts + │ ├── admin/ + │ │ └── audit-logs/ + │ │ ├── page.tsx # Admin Audit log tracking view + │ │ └── page.module.css # Audit logs UI styling + │ └── api/ + │ ├── audit-logs/ + │ │ └── route.ts # Redacted audit logs fetch route + │ └── reports/ + │ └── export/ + │ ├── excel/ + │ │ └── route.ts # XLSX output streaming service + │ └── pdf/ + │ └── route.ts # Printable print-optimized layout +``` + +--- + +## 3. Detailed Feature Specifications + +### 3.1. Colaborador History Dashboard (US-COM-010) +Provides collaborators and managers with access to historical payments, goals, and calculations. + +* **Database Queries**: + - Filtered by `period` (YYYY-MM), `status` (APPROVED, REJECTED, PENDING), and `userId` (enforced automatically in database by user-context RLS session params). +* **UI/UX Design**: + - **Aesthetics**: Glassmorphic layout using `var(--card)` with a subtle blur backdrop, rounded corners (`var(--radius-lg)`), and smooth fade-in animations on hover. + - **Components**: + - Filter toolbar (select options for Period and Status). + - Settlement list displaying: Period, Target Goal, Sales Total, Commission, Clawback Adjustment, Total Payout, and Status. + - Expandable rows showing localized AI Audit Notes: `{item.aiAuditNotes[locale]}`. + - PDF download triggers using browser window printing sheets (`@media print`) optimized via CSS. + +### 3.2. Immutable Audit Log Trail System (US-COM-011) +Automates transaction audits and logs all security-critical mutations. + +* **Audit Triggers**: + - Place `tx.auditLog.create` inside prisma transactional operations in routes: + - `/api/plans` (Plan creation, edit, version increase) + - `/api/goals` (Quota setup updates) + - `/api/users` (Account additions / role changes) +* **Application Redaction Rule**: + - Implement a central audit logger utility that strips or masks credentials (such as password hashes, cookies, or database connection passwords) from the logged `previousValue` or `newValue` JSON structures. +* **Audit Logs Viewer (Admin-Only)**: + - Route: `/admin/audit-logs`. Blocks non-admin users with a `403 Forbidden` response. + - Features an interactive tabular view showing action timestamp, actor name, action verb, target table, and IP address. + - Selecting an entry reveals a side-by-side JSON diff details panel. +* **RLS Block**: + - Validate that database RLS triggers reject any attempts to update or delete rows on the `audit_logs` table. + +### 3.3. Premium Executive Dashboard (US-COM-012) +Provides executive analysis of paid commissions, quotas achievement, and cost trends. + +* **Access**: Restricted to `admin`, `director`, and `analyst` roles. +* **Metrics Widgets**: + - Total commissions paid, average goal achievement rate (progress circle), active budget utilization, and clawback adjustments. +* **Charts (Recharts Integration)**: + - **Line/Area Chart**: Monthly trends of commission payouts vs. budget cap, utilizing gradient fills with HSL transparency (`hsla(var(--primary-h), ..., 0.1)`). + - **Bar Chart**: Comparisons of total sales and achievements across active hotels (Cartagena, Medellin, Bogota). + - Charts must support responsive container scales (`ResponsiveContainer`) and localized tooltip values. + +### 3.4. Excel & PDF Consolidator Service (US-COM-013) +Consolidates metrics for financial department checks. + +* **Excel Exporter API**: `/api/reports/export/excel`. + - Uses the `xlsx` library to assemble and download multi-sheet spreadsheets containing summary tabs (summarized by region) and detailed sheets (sales and commission details). +* **PDF Exporter API**: `/api/reports/export/pdf`. + - Integrates printable stylesheet directives: + ```css + @media print { + body { + background: white; + color: black; + } + .noPrint { + display: none; + } + .pageBreak { + page-break-after: always; + } + } + ``` + - Enables exporting cleanly formatted records to PDF directly via standard browser print commands. + +--- + +## 4. Internationalization (i18n) Dictionary Additions + +Add the following keys to `src/lib/i18n/dictionaries/en.json` and `es.json`: + +* **`en.json`**: + ```json + { + "dashboard.title": "Compensation Analytics Dashboard", + "dashboard.total_paid": "Total Paid Commissions", + "dashboard.avg_achievement": "Avg Goal Achievement", + "dashboard.budget_cap": "Active Budget Cap", + "dashboard.trends": "Monthly Commission Trends", + "history.title": "My Commission History", + "history.audit_notes": "AI Audit Notes", + "audit.title": "System Audit Logs" + } + ``` +* **`es.json`**: + ```json + { + "dashboard.title": "Tablero de Análisis de Compensación", + "dashboard.total_paid": "Comisiones Totales Pagadas", + "dashboard.avg_achievement": "Promedio Logro de Metas", + "dashboard.budget_cap": "Límite de Presupuesto Activo", + "dashboard.trends": "Tendencias de Comisiones Mensuales", + "history.title": "Mi Historial de Comisiones", + "history.audit_notes": "Notas de Auditoría de IA", + "audit.title": "Registros de Auditoría del Sistema" + } + ``` + +--- + +## 5. Testing & Verification + +1. **Verify RLS Security**: + - Write integration assertions attempting to query history records under a different user session. Check that the database filters correctly and returns no foreign records. + - Run write-only tests attempting to run `DELETE` or `UPDATE` queries against the `AuditLog` table. Ensure the operations fail. +2. **Automated UI Testing (Puppeteer)**: + - Configure a headless script `prisma/test-phase6-ui.js` that logins as collaborator, visits `/history`, checks that the table renders data properly, and triggers language switches. + - Visits `/dashboard` as admin and verifies that the charts mount successfully.