feat: sync harness skills and reinforce system architecture/workstation docs
This commit is contained in:
parent
d4d5d080e7
commit
5ce1cc0585
9 changed files with 326 additions and 181 deletions
|
|
@ -1,12 +1,30 @@
|
||||||
---
|
---
|
||||||
name: integration-validation
|
name: integration-validation
|
||||||
description: "Manages Excel imports validation and n8n webhook routing setups."
|
description: "Manages Excel imports validation, zero-trust internal routing, and n8n webhook setups. Use this when importing sales, routing webhooks, configuring API endpoints, or troubleshooting 502/network issues."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Integration Validation
|
# Integration Validation
|
||||||
|
|
||||||
Defines rules for importing sales results and routing n8n webhooks.
|
Governs the validation of external file imports (e.g., Excel/CSV sales sheets) and the secure routing of n8n integration webhooks.
|
||||||
|
|
||||||
|
## Core Rationale
|
||||||
|
Ensuring data integrity at the system entry point prevents downstream calculation failures. Proper zero-trust routing isolates staging/test runs from production environments.
|
||||||
|
|
||||||
## Execution Rules
|
## Execution Rules
|
||||||
1. **Webhook Branching**: In test environments, route webhook payloads strictly through the `/webhook-test` path to target the dev sandbox.
|
|
||||||
2. **Idempotence Checks**: Prevent double-upload actions by verifying idempotency keys.
|
### 1. Webhook Isolation and Sandbox Branching
|
||||||
|
- **Branching Rule**: For all test runs and staging simulations, route webhook payloads strictly through the `/webhook-test` path instead of `/webhook`.
|
||||||
|
- **Target DB**: The `/webhook-test` endpoint must write only to the test database sandbox.
|
||||||
|
- **Why**: Prevents test data from contaminating real collaborator settlements and polluting production audit histories.
|
||||||
|
|
||||||
|
### 2. Zero-Trust Routing and Internal Hostnames
|
||||||
|
- **Container Name Routing**: Do not route requests via public IP or expose host ports unnecessarily. Connect via internal Docker hostnames behind the Caddy reverse proxy (e.g. `http://n8n:5678` or local reverse-proxied aliases).
|
||||||
|
- **Network Check**: If a `502 Bad Gateway` error occurs, verify that Caddy and the target service container share the same Docker network.
|
||||||
|
|
||||||
|
### 3. Idempotency & Double-Upload Prevention
|
||||||
|
- **Idempotency Key**: Every file upload or API payload must contain or generate a unique transaction/idempotency key.
|
||||||
|
- **Verification**: Query the database for the key before running the processing pipeline. If the key already exists, fail gracefully with a duplicate warning (e.g. "Duplicate import detected").
|
||||||
|
|
||||||
|
### 4. Layout Validation
|
||||||
|
- Ensure imported files have the correct column layout (Collaborator email/ID, Hotel, Amount, Date).
|
||||||
|
- Report validation errors formatted clearly so they can be rendered in the UI according to the user's active locale (en/es).
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,29 @@
|
||||||
---
|
---
|
||||||
name: plan-management
|
name: plan-management
|
||||||
description: "Handles compensation plan creation, versioning rules, and commercial goals parameters."
|
description: "Handles compensation plan creation, versioning rules, and commercial goals parameters. Use this when defining collaborator quotas, managing active/closed plans, or adjusting commercial targets."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Plan Management
|
# Plan Management
|
||||||
|
|
||||||
Defines rules for configuring plans, version controls, and quotas.
|
Provides rules and guardrails for configuring compensation plans, version control constraints, and collaborator goal mappings.
|
||||||
|
|
||||||
|
## Core Rationale
|
||||||
|
To maintain historical accuracy and prevent retroactive computation errors, compensation structures must never be updated in place once active. Changing rules mid-period without versioning destroys audit trails.
|
||||||
|
|
||||||
## Execution Rules
|
## Execution Rules
|
||||||
1. **Never edit an active plan in-place**: Modifying active items must close the active plan and save changes as a new version.
|
|
||||||
2. **Assign goals by period**: Ensure monthly and quarterly targets are isolated per collaborator.
|
### 1. Plan Versioning Constraints
|
||||||
|
- **Never Edit an Active Plan In-Place**: If a plan is marked as `ACTIVE` (or `ACTIVO`), any modification to its formulas, percentage brackets, or core rules must:
|
||||||
|
1. Close the active plan (set end date or mark status as `CLOSED` / `CERRADO`).
|
||||||
|
2. Create a new plan record with a incremented version number or new validity date range.
|
||||||
|
- **Why**: Retroactive recalculations rely on the exact state of the plan at the time of the sale. Modifying rules in-place invalidates prior settlement calculations.
|
||||||
|
|
||||||
|
### 2. Goals & Quotas Isolation
|
||||||
|
- **Period Isolation**: Assign commercial targets and quotas strictly by period (monthly or quarterly).
|
||||||
|
- **Collaborator Assignment**: Ensure quotas are mapped per collaborator and per hotel site (e.g., "Cartagena", "Bogota") to prevent cross-contamination.
|
||||||
|
|
||||||
|
### 3. Localized Keywords and i18n
|
||||||
|
- Support localized status strings and target types across database queries and UI forms:
|
||||||
|
- Plan statuses: `ACTIVE` / `ACTIVO`, `CLOSED` / `CERRADO`.
|
||||||
|
- Target types: `REVENUE` / `INGRESOS`, `NIGHTS` / `NOCHES`.
|
||||||
|
- Ensure schema updates preserve these exact value mappings, mapping them safely to the respective DB enums or text fields.
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,30 @@
|
||||||
---
|
---
|
||||||
name: reconciliation-auditing
|
name: reconciliation-auditing
|
||||||
description: "Checks row-level security boundaries, audits logs immutability, and reconciles PMS sales totals."
|
description: "Checks row-level security boundaries, audits logs immutability, and reconciles PMS sales totals. Use this when running security tests, validating database queries, or auditing log security."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Reconciliation & Auditing
|
# Reconciliation & Auditing
|
||||||
|
|
||||||
Defines rules for running data security checks and auditing logs.
|
Defines guidelines for validating row-level security (RLS), verifying system audit log immutability, and running compliance tests on calculations.
|
||||||
|
|
||||||
|
## Core Rationale
|
||||||
|
Financial systems must maintain zero-trust boundaries. Unauthorized data access or alteration of audit logs ruins regulatory compliance and system trustworthiness.
|
||||||
|
|
||||||
## Execution Rules
|
## Execution Rules
|
||||||
1. **RLS Verification**: Test database access filters using transaction user-context parameters.
|
|
||||||
2. **Audit Redactions**: Mask sensitive pricing or payroll outputs in logs.
|
### 1. Row-Level Security (RLS) Boundary Verification
|
||||||
3. **Log Immutability**: Ensure log rows are strictly append-only.
|
- **User-Context Checks**: Test database access filters by emulating collaborator queries. Validate that users can only fetch records belonging to their assigned hotel site (e.g., leaders in Cartagena cannot view Bogota records).
|
||||||
|
- **Test Assertion**: Execute automated queries using the collaborator's database role or session context and assert that 0 records are returned for other sites.
|
||||||
|
|
||||||
|
### 2. Audit Log Immutability
|
||||||
|
- **Append-Only Logs**: Ensure that all logs written to the system are strictly append-only.
|
||||||
|
- **Verification Rule**: Attempt to update or delete a log entry in a testing context. Assert that the operation is rejected (either by database triggers, Prisma hooks, or PostgreSQL permissions).
|
||||||
|
|
||||||
|
### 3. Bilingual JSON formatting Checks
|
||||||
|
- **Validation**: Inspect the `aiAuditNotes` and `flaggedReason` fields in calculation outputs.
|
||||||
|
- **Assertion**:
|
||||||
|
- The content MUST be a valid JSON object.
|
||||||
|
- The object MUST contain both `en` and `es` keys.
|
||||||
|
- The keys must have non-empty string values.
|
||||||
|
- **Example Assertion**: `expect(settlement.aiAuditNotes).toHaveProperty('en'); expect(settlement.aiAuditNotes).toHaveProperty('es');`
|
||||||
|
- **UI Rendering**: Verify that the Next.js UI component renders the correct translation matching the active context locale.
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,97 @@
|
||||||
---
|
---
|
||||||
name: remuneration-orchestrator
|
name: remuneration-orchestrator
|
||||||
description: "Coordinates the Variable Remuneration, Compensation, and Commissions workflow across subagents."
|
description: "Coordinates the Variable Remuneration, Compensation, and Commissions multi-agent team (Planner, Calculator, QA Auditor). Use this when executing or verifying commission calculations, setting up goals/quotas, validating plans, running delta check clawbacks, testing RLS security, or updating results. Use to re-run, modify, update, correct, check, or audit existing calculations and plan versions."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Remuneration Orchestrator
|
# Remuneration Orchestrator
|
||||||
|
|
||||||
Wires the multi-agent pipeline: Planner Agent -> Calculator Agent -> QA Auditor Agent.
|
Wires the multi-agent pipeline: Planner Agent -> Calculator Agent -> QA Auditor Agent to manage plans, execute settlements, and audit outputs.
|
||||||
|
|
||||||
## Orchestration Flow
|
## Execution Mode: Sequential Subagent Mode
|
||||||
1. **Initiate**: `planner-agent` verifies plan setups and goals.
|
|
||||||
2. **Calculate**: `calculator-agent` executes calculations and runs delta adjustment clawbacks.
|
## Subagent Team Configuration
|
||||||
3. **Verify**: `qa-auditor-agent` reviews the calculation outputs and runs RLS/immutability validation tests.
|
|
||||||
|
| Agent TypeName | Core Role | Assigned Skills | Intermediate Outputs |
|
||||||
|
|:---|:---|:---|:---|
|
||||||
|
| `planner-agent` | Plan & Goal Architect | `plan-management` | `_workspace/02_planner_plans.json` |
|
||||||
|
| `calculator-agent` | Calculation Engine | `settlement-calculation`, `integration-validation` | `_workspace/03_calculator_settlements.json` |
|
||||||
|
| `qa-auditor-agent` | Compliance & QA Auditor | `reconciliation-auditing` | `_workspace/04_qa_audit_report.json` |
|
||||||
|
|
||||||
|
## Workflow Phases
|
||||||
|
|
||||||
|
### Phase 0: Context Check (Incremental & Follow-up Support)
|
||||||
|
1. Verify if the `_workspace/` directory exists under the project root.
|
||||||
|
2. Determine execution mode:
|
||||||
|
- **No `_workspace/` folder**: Initial run. Proceed to Phase 1.
|
||||||
|
- **`_workspace/` exists + User requests partial edit/fix**: Partial re-run. Identify the failing or target agent, call it using `invoke_subagent` with the existing input/output files in the prompt, and overwrite only the target outputs.
|
||||||
|
- **`_workspace/` exists + User provides new raw data/plan**: Fresh run. Backup the current workspace to `_workspace_backup_<timestamp>/` and create a clean `_workspace/` folder.
|
||||||
|
3. For partial re-runs, ensure the subagent receives paths to previous outputs to merge changes correctly.
|
||||||
|
|
||||||
|
### Phase 1: Setup & Initialization
|
||||||
|
1. Parse the user's input request, target collaborators, plans, and period.
|
||||||
|
2. Ensure `_workspace/` is created and initialize `_workspace/00_input/`.
|
||||||
|
3. Save raw input parameters or JSON configurations to `_workspace/00_input/parameters.json`.
|
||||||
|
|
||||||
|
### Phase 2: Plan Validation & Goals Mapping
|
||||||
|
1. Invoke the `planner-agent` to check goals and plan statuses.
|
||||||
|
- **TypeName**: `planner-agent`
|
||||||
|
- **Role**: Plan Manager
|
||||||
|
- **Prompt**: "Read the inputs from `_workspace/00_input/parameters.json`. Verify the compensation plans, quotas, and goals. Ensure active plans are version-controlled and not modified in place. Write the validated configuration to `_workspace/02_planner_plans.json`."
|
||||||
|
2. Read the output of `planner-agent` to ensure no validation flags or unresolved conflicts remain.
|
||||||
|
|
||||||
|
### Phase 3: Settlement Execution & Retroactive Clawbacks
|
||||||
|
1. Invoke the `calculator-agent` to process formulas, run delta checks, and trigger n8n workflows.
|
||||||
|
- **TypeName**: `calculator-agent`
|
||||||
|
- **Role**: Commission Calculator
|
||||||
|
- **Prompt**: "Using the validated plans in `_workspace/02_planner_plans.json`, perform the settlement calculation. Verify historical sales for retroactive clawbacks (delta checks). Route tests through `/webhook-test` endpoints on the internal hostnames. Ensure all `aiAuditNotes` and `flaggedReason` strings are stored as bilingual `{ en, es }` JSON objects. Write outputs to `_workspace/03_calculator_settlements.json`."
|
||||||
|
2. Verify that settlements were successfully generated.
|
||||||
|
|
||||||
|
### Phase 4: QA Auditing & Compliance Checks
|
||||||
|
1. Invoke the `qa-auditor-agent` to run assertion checks and RLS validations.
|
||||||
|
- **TypeName**: `qa-auditor-agent`
|
||||||
|
- **Role**: QA Auditor
|
||||||
|
- **Prompt**: "Audit the calculation outputs in `_workspace/03_calculator_settlements.json`. Verify row-level security (RLS) constraints for the collaborators, ensure log immutability is respected, and assert that `aiAuditNotes` and `flaggedReason` are correctly formatted as bilingual `{ en, es }` JSON objects. Write your report to `_workspace/04_qa_audit_report.json`."
|
||||||
|
2. Read the audit report. If critical violations (e.g. invalid bilingual JSON, RLS failures) are found, request corrections from the respective agent.
|
||||||
|
|
||||||
|
### Phase 5: final Integration & Output Generation
|
||||||
|
1. Read the final QA audit report and the calculation outputs.
|
||||||
|
2. Compile and save the final settlement run summary to `docs/settlement_run_latest.md`.
|
||||||
|
3. Keep the `_workspace/` directory preserved for history/auditing.
|
||||||
|
4. Report the summary of the run to the user, highlighting calculations, adjusted clawbacks, and validation status.
|
||||||
|
|
||||||
|
## Data Flow Diagram
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
User([User Request]) --> P1[Phase 1: Setup]
|
||||||
|
P1 -->|Save input| RawFile[_workspace/00_input/parameters.json]
|
||||||
|
RawFile --> P2[Phase 2: planner-agent]
|
||||||
|
P2 -->|Validate plans| PlanFile[_workspace/02_planner_plans.json]
|
||||||
|
PlanFile --> P3[Phase 3: calculator-agent]
|
||||||
|
P3 -->|Run settlement & n8n| CalcFile[_workspace/03_calculator_settlements.json]
|
||||||
|
CalcFile --> P4[Phase 4: qa-auditor-agent]
|
||||||
|
P4 -->|Verify RLS & i18n JSON| QAFile[_workspace/04_qa_audit_report.json]
|
||||||
|
QAFile --> P5[Phase 5: Orchestrator Integration]
|
||||||
|
P5 -->|Write summary| FinalOut[docs/settlement_run_latest.md]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Handling Matrix
|
||||||
|
|
||||||
|
| Failure Mode | Resolution Strategy |
|
||||||
|
|:---|:---|
|
||||||
|
| Subagent execution error | Retry once. If failure persists, record the traceback, fallback to a safe null output, and flag the failure in the final report. |
|
||||||
|
| Non-bilingual `{ en, es }` notes | Re-invoke the calculator-agent to apply the translation chain and rewrite the fields as valid `{ en, es }` JSON. |
|
||||||
|
| RLS constraint breach | Immediately halt the pipeline, mark the run as FAILED, and notify the user with the trace details. |
|
||||||
|
| n8n webhook connection failure | Verify shared Docker network routing between Caddy and n8n, check internal hostnames, and retry with the correct endpoint. |
|
||||||
|
|
||||||
|
## Verification Test Scenarios
|
||||||
|
|
||||||
|
### Scenario 1: Standard Commission Run (Success)
|
||||||
|
1. **Input**: Quota/goals for collaborator "Juan Perez" with monthly sales data.
|
||||||
|
2. **Execution**: Planner validates goal, Calculator computes commission and translates notes to Spanish/English, QA Auditor verifies RLS rules and bilingual JSON.
|
||||||
|
3. **Expected Outcome**: `docs/settlement_run_latest.md` created, all tests pass, and database stores bilingual notes.
|
||||||
|
|
||||||
|
### Scenario 2: RLS Validation Failure (Error Fallback)
|
||||||
|
1. **Input**: Sales imports trying to cross-read records of another hotel site without appropriate permissions.
|
||||||
|
2. **Execution**: Planner passes layout, Calculator executes, but QA Auditor detects RLS violation during boundary checking.
|
||||||
|
3. **Expected Outcome**: Run halted. No settlements approved. Error logged in `_workspace/04_qa_audit_report.json`.
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,34 @@
|
||||||
---
|
---
|
||||||
name: settlement-calculation
|
name: settlement-calculation
|
||||||
description: "Executes automated commission calculations and processes retroactive delta/clawback adjustments."
|
description: "Executes automated commission calculations, processes retroactive delta/clawback adjustments, and translates notes. Use this when calculating settlements, running delta checks, or writing AI audit notes."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Settlement Calculation
|
# Settlement Calculation
|
||||||
|
|
||||||
Defines rules for running automated commission runs and retroactive audits.
|
Defines the mathematical and procedural rules for running automated commission calculations and processing retroactive adjustments.
|
||||||
|
|
||||||
|
## Core Rationale
|
||||||
|
Sales data can change retroactively (e.g., late cancellations, modified booking values). The settlement engine must dynamically detect changes in historical periods and reconcile them without modifying finalized records.
|
||||||
|
|
||||||
## Execution Rules
|
## Execution Rules
|
||||||
1. **Delta Checks**: Compare past closed calculations against PMS databases to generate adjustments (clawbacks).
|
|
||||||
2. **Idempotency keys**: Validate header tokens before saving settlement records.
|
### 1. Retroactive Delta & Clawback Calculations
|
||||||
|
- **Delta Check**: For the target collaborator and period, compare the previously calculated and finalized commissions against the current actual PMS sales records.
|
||||||
|
- **Adjustment Generation**:
|
||||||
|
- If the PMS value has decreased (e.g. refund/cancellation), calculate the difference and record a **negative adjustment (clawback)** in the current period.
|
||||||
|
- If the PMS value has increased, record a **positive adjustment**.
|
||||||
|
- **Never modify past finalized settlement records**; adjustments must be registered as new records in the active period.
|
||||||
|
|
||||||
|
### 2. Bilingual AI Audit Notes & i18n
|
||||||
|
- **Requirement**: `aiAuditNotes` and `flaggedReason` columns must be populated and stored as valid bilingual JSON objects matching the format:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"en": "English explanation of the calculation/flag.",
|
||||||
|
"es": "Explicación en español del cálculo/alerta."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- **Translation Chain**: Utilize the n8n translation LLM chain to translate dynamically generated audit notes.
|
||||||
|
- **Verification**: Ensure that the database schemas and fields can store this JSON structure correctly.
|
||||||
|
|
||||||
|
### 3. Idempotency Key Validation
|
||||||
|
- Before saving a settlement record, validate the idempotency key (header token/hash) to prevent duplicate transactions. If the transaction has already been processed, skip or throw a controlled exception.
|
||||||
|
|
|
||||||
|
|
@ -46,4 +46,5 @@ These instructions extend the baseline global `AGENTS.md` rules. When executing
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| 2026-06-11 | Initial scaffolding | All files | Initial team setup |
|
| 2026-06-11 | Initial scaffolding | All files | Initial team setup |
|
||||||
| 2026-06-12 | Implement i18n & bilingual AI audit notes | n8n, Prisma, E2E tests, agents config | Support multilingual UI rendering and LLM translations |
|
| 2026-06-12 | Implement i18n & bilingual AI audit notes | n8n, Prisma, E2E tests, agents config | Support multilingual UI rendering and LLM translations |
|
||||||
|
| 2026-06-12 | Synchronize harness skills | remuneration-plugin skills & orchestrator | Align skills with sequential orchestrator template, i18n bilingual JSON requirements, zero-trust hostnames, webhook branching, and RLS validation checks |
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,82 +4,67 @@
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
This document outlines the environment configurations (Development vs. Production), API keys, and recommended AI integration tools (like Model Context Protocol servers) designed to optimize this workspace for AI agents (such as Antigravity-cli / agy) and human developers alike.
|
This document outlines the environment configurations (Development vs. Production), active API keys, and recommended AI integration tools (like Model Context Protocol servers) designed to optimize this workspace for AI agents (such as Antigravity-cli / agy) and human developers alike.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Environment Configurations (.env Blueprints)
|
## 1. Environment Configurations (.env Blueprints)
|
||||||
|
|
||||||
The Next.js application separates environment secrets between local active development and production servers.
|
The Next.js application separates environment secrets between local active development, development containers, and production servers. All credentials reside in a centralized `.env` file at the project root.
|
||||||
|
|
||||||
### 1.1. Development Environment (`.env.development`)
|
### 1.1. Dual-Stack Configuration Layout (.env)
|
||||||
This file lives in the root directory during development. It configures connection strings to local/sandbox instances.
|
This file configs connection parameters for both production (`app-prod`) and development (`app-dev`) containers.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Database Setup
|
# Database Setup (Fallback / Local Development)
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Connection string pointing to your local development PostgreSQL instance.
|
DATABASE_URL="postgresql://special_hotel_user:SpecialHotel1235%2F%2A-%2B@pg.gaboggamer.online/special_hotel_dev?schema=public"
|
||||||
# Prisma uses this URL to run migrations and execute DB queries.
|
|
||||||
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/special_hotel_dev?schema=public"
|
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Next.js Application Settings
|
# Production Stack Environment Variables (for Docker Compose app-prod)
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# The host address of your local Next.js client (default dev port is 3000)
|
# Connection string pointing to the production PostgreSQL instance
|
||||||
NEXT_PUBLIC_APP_URL="http://localhost:3000"
|
DATABASE_URL_PROD="postgresql://special_hotel_user:SpecialHotel1235%2F%2A-%2B@pg.gaboggamer.online/special_hotel?schema=public"
|
||||||
|
|
||||||
# Secret token used by NextAuth / custom session helper to sign JWTs.
|
# Production domain resolved by the Caddy reverse proxy
|
||||||
# Generate a secure key locally using: openssl rand -base64 32
|
NEXT_PUBLIC_APP_URL="https://hotels.gaboggamer.online"
|
||||||
NEXTAUTH_SECRET="dev_secret_jwt_sign_key_change_me_locally"
|
|
||||||
|
# Secret token used to sign NextAuth / custom session JWTs in production
|
||||||
|
NEXTAUTH_SECRET="0qqPRY4NIbCEFag33Q6EB1ea7dUQR1J6Z8h4NogrgCg="
|
||||||
|
|
||||||
|
# Production n8n calculation webhook endpoint
|
||||||
|
N8N_WEBHOOK_URL="https://n8n.gaboggamer.online/webhook/calculate-commissions"
|
||||||
|
|
||||||
|
# Token to authorize and verify n8n webhook payload signatures in production
|
||||||
|
N8N_WEBHOOK_SECRET="Ecjb2s33tHJppNBDJ/DxXEjHWKow8bNWmsQrk1sQKyQ="
|
||||||
|
|
||||||
|
# Internal container networking URL for production app mapping
|
||||||
|
APP_PROD_INTERNAL_URL="http://special-hotel-prod:3000"
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# n8n Workflow Engine Integration
|
# Development Stack Environment Variables (for Docker Compose app-dev)
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Webhook URL pointing to your local n8n instance where calculations and
|
# Connection string pointing to the development PostgreSQL instance
|
||||||
# AI workflows are executed.
|
DATABASE_URL_DEV="postgresql://special_hotel_user:SpecialHotel1235%2F%2A-%2B@pg.gaboggamer.online/special_hotel_dev?schema=public"
|
||||||
N8N_WEBHOOK_URL="http://localhost:5678/webhook/calculate-commissions"
|
|
||||||
|
|
||||||
# Local authorization secret shared between Next.js and n8n.
|
# Dedicated connection string for the isolated test/sandbox database
|
||||||
# Incoming webhooks from n8n calling the Next.js API must provide this token
|
TEST_DATABASE_URL="postgresql://special_hotel_user:SpecialHotel1235%2F%2A-%2B@pg.gaboggamer.online/special_hotel_test?schema=public"
|
||||||
# in the 'x-n8n-signature' header.
|
|
||||||
N8N_WEBHOOK_SECRET="local_shared_signature_to_verify_n8n_callbacks"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
# Local host address for development
|
||||||
|
NEXT_PUBLIC_APP_URL_DEV="http://localhost:3001"
|
||||||
|
|
||||||
### 1.2. Production Environment (`.env.production`)
|
# JWT session signing key for development
|
||||||
Production values are configured inside the live environment (e.g. injected into the container via Dockge).
|
NEXTAUTH_SECRET_DEV="TdD2xx0rZYCGkYxFFB7y9Sm8L+HGyXaXInqB9lYLJsk="
|
||||||
|
|
||||||
```bash
|
# Sandbox n8n testing webhook endpoint
|
||||||
# -----------------------------------------------------------------------------
|
N8N_TEST_WEBHOOK_URL="https://n8n.gaboggamer.online/webhook-test/calculate-commissions"
|
||||||
# Database Setup
|
|
||||||
# -----------------------------------------------------------------------------
|
|
||||||
# Secure production database URL. Must be reachable only within the isolated
|
|
||||||
# network environment (e.g. via private container network aliases).
|
|
||||||
DATABASE_URL="postgresql://postgres:secure_db_prod_pass@postgres-vpn:5432/special_hotel?schema=public"
|
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# Signature token to authorize development webhook payloads
|
||||||
# Next.js Application Settings
|
N8N_WEBHOOK_SECRET_DEV="qUHuPqPjA65psdtwQU7zgp/DVkvd1xXk2WP/vzbnEdc="
|
||||||
# -----------------------------------------------------------------------------
|
|
||||||
# The public or VPN-locked domain resolved by Caddy
|
|
||||||
NEXT_PUBLIC_APP_URL="https://special-hotel.yourdomain.com"
|
|
||||||
|
|
||||||
# High-entropy random secret key for production JWT signatures.
|
# Internal container networking URL for development app mapping
|
||||||
NEXTAUTH_SECRET="prod_high_entropy_session_secret_key"
|
APP_DEV_INTERNAL_URL="http://special-hotel-dev:3000"
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
|
||||||
# n8n Workflow Engine Integration
|
|
||||||
# -----------------------------------------------------------------------------
|
|
||||||
# Production n8n calculation webhook endpoint (internally routed)
|
|
||||||
N8N_WEBHOOK_URL="http://n8n:5678/webhook/calculate-commissions"
|
|
||||||
|
|
||||||
# Optional application-level security secret.
|
|
||||||
# NOTE: In production, since Next.js and n8n share a private Docker container
|
|
||||||
# network, Caddy blocks all public access to /api/n8n/* endpoints.
|
|
||||||
# Because of this network-level isolation, token-based verification is optional
|
|
||||||
# but recommended as a defense-in-depth practice.
|
|
||||||
N8N_WEBHOOK_SECRET="prod_shared_signature_to_verify_n8n_callbacks"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
@ -90,7 +75,7 @@ To make this codebase highly friendly for the **Antigravity agent (`agy`)**, you
|
||||||
|
|
||||||
### 2.1. Recommended MCP Servers for agy
|
### 2.1. Recommended MCP Servers for agy
|
||||||
|
|
||||||
#### A. n8n MCP Server (Official Beta / Community)
|
#### A. n8n MCP Server (`n8n`)
|
||||||
Exposes tools to read, execute, and write workflows directly on the n8n canvas.
|
Exposes tools to read, execute, and write workflows directly on the n8n canvas.
|
||||||
* **Use Case**: Allows `agy` to trigger calculation runs, inspect failing nodes on the canvas, check webhook logs, and modify workflows dynamically.
|
* **Use Case**: Allows `agy` to trigger calculation runs, inspect failing nodes on the canvas, check webhook logs, and modify workflows dynamically.
|
||||||
* **Harness Registration**:
|
* **Harness Registration**:
|
||||||
|
|
@ -100,38 +85,37 @@ Exposes tools to read, execute, and write workflows directly on the n8n canvas.
|
||||||
"args": ["-y", "n8n-mcp"],
|
"args": ["-y", "n8n-mcp"],
|
||||||
"env": {
|
"env": {
|
||||||
"N8N_API_KEY": "your_n8n_api_key_here",
|
"N8N_API_KEY": "your_n8n_api_key_here",
|
||||||
"N8N_URL": "http://localhost:5678"
|
"N8N_URL": "https://n8n.gaboggamer.online"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### B. Prisma Postgres MCP Server (`@prisma/mcp`)
|
#### B. Prisma Postgres MCP Server (`prisma-postgres`)
|
||||||
Exposes tools allowing `agy` to interact with the database using type-safe schemas.
|
Exposes tools allowing `agy` to interact with the database using type-safe schemas.
|
||||||
* **Use Case**: Allows `agy` to run schema checks, dry-run validations, and automatically inspect database tables during development.
|
* **Use Case**: Allows `agy` to run schema checks, dry-run validations, and automatically inspect database tables during development.
|
||||||
* **Available Tools**: `ListDatabases`, `ExecuteSqlQuery`, `IntrospectSchema`, and `ExecuteRawSql`.
|
|
||||||
* **Harness Registration**:
|
* **Harness Registration**:
|
||||||
```json
|
```json
|
||||||
"prisma-postgres": {
|
"prisma-postgres": {
|
||||||
"command": "npx",
|
"command": "npx",
|
||||||
"args": ["-y", "@prisma/mcp"],
|
"args": ["-y", "@prisma/mcp"],
|
||||||
"env": {
|
"env": {
|
||||||
"DATABASE_URL": "postgresql://postgres:postgres@localhost:5432/special_hotel_dev?schema=public"
|
"DATABASE_URL": "postgresql://special_hotel_user:SpecialHotel1235%2F%2A-%2B@pg.gaboggamer.online/special_hotel_dev?schema=public"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### C. PostgreSQL MCP Server (`@modelcontextprotocol/server-postgres`)
|
#### C. PostgreSQL MCP Server (`postgres`)
|
||||||
Provides raw PostgreSQL connection and querying tools.
|
Provides raw PostgreSQL connection and querying tools.
|
||||||
* **Use Case**: Enables `agy` to query migration status, seed verification, and raw audit log verification directly.
|
* **Use Case**: Enables `agy` to query migration status, seed verification, and raw audit log verification directly.
|
||||||
* **Harness Registration**:
|
* **Harness Registration**:
|
||||||
```json
|
```json
|
||||||
"postgres": {
|
"postgres": {
|
||||||
"command": "npx",
|
"command": "npx",
|
||||||
"args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://postgres:postgres@localhost:5432/special_hotel_dev"]
|
"args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://special_hotel_user:SpecialHotel1235%2F%2A-%2B@pg.gaboggamer.online/special_hotel_dev"]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### D. Git MCP Server (`@modelcontextprotocol/server-git`)
|
#### D. Git MCP Server (`git`)
|
||||||
Provides local Git operations tools (clone, commit, diff, log, status).
|
Provides local Git operations tools (clone, commit, diff, log, status).
|
||||||
* **Use Case**: Allows `agy` to review local branches, examine diffs of modified code files, and make structured, micro-commits during development.
|
* **Use Case**: Allows `agy` to review local branches, examine diffs of modified code files, and make structured, micro-commits during development.
|
||||||
* **Harness Registration**:
|
* **Harness Registration**:
|
||||||
|
|
@ -142,7 +126,7 @@ Provides local Git operations tools (clone, commit, diff, log, status).
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### E. Puppeteer MCP Server (`@modelcontextprotocol/server-puppeteer`)
|
#### E. Puppeteer MCP Server (`puppeteer`)
|
||||||
Exposes browser automation tools (take screenshots, click, type, fill forms).
|
Exposes browser automation tools (take screenshots, click, type, fill forms).
|
||||||
* **Use Case**: Allows `agy` to start a headless browser, render our Next.js pages, and verify layout responsiveness and style details against the style guide without manual developer steps.
|
* **Use Case**: Allows `agy` to start a headless browser, render our Next.js pages, and verify layout responsiveness and style details against the style guide without manual developer steps.
|
||||||
* **Harness Registration**:
|
* **Harness Registration**:
|
||||||
|
|
@ -153,66 +137,40 @@ Exposes browser automation tools (take screenshots, click, type, fill forms).
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### F. Forgejo / Gitea MCP Server (`forgejo-mcp` / `gitea-mcp`)
|
|
||||||
Exposes tools allowing `agy` to interact directly with your Forgejo repository (creating and merging pull requests, reviewing code, creating issues) via API.
|
|
||||||
* **Use Case**: Enables `agy` to manage issues, automate code review tasks, verify pull request status, and merge pull requests directly using standard API endpoints.
|
|
||||||
* **Harness Registration**:
|
|
||||||
```json
|
|
||||||
"forgejo-mcp": {
|
|
||||||
"command": "npx",
|
|
||||||
"args": ["-y", "forgejo-mcp"],
|
|
||||||
"env": {
|
|
||||||
"FORGEJO_REMOTE_URL": "https://git.yourdomain.com",
|
|
||||||
"FORGEJO_AUTH_TOKEN": "your_forgejo_api_token_here"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Managing Pull Requests via CLI (Forgejo Client)
|
## 3. Testing Procedures & Webhook Testing Flow
|
||||||
|
|
||||||
To manage repositories, issues, and pull requests directly from your terminal (similar to GitHub CLI `gh`), you can use **`tea`**, the official Gitea CLI client. Since Forgejo is a fork of Gitea and shares the exact same REST API, `tea` is fully compatible out-of-the-box.
|
|
||||||
|
|
||||||
### 3.1. Installing tea on your workstation
|
|
||||||
For Linux systems, you can download the latest precompiled binary:
|
|
||||||
```bash
|
|
||||||
# Download and install the precompiled binary
|
|
||||||
curl -L -sS https://gitea.com/gitea/tea/releases/download/v0.9.2/tea-0.9.2-linux-amd64 -o /tmp/tea
|
|
||||||
sudo mv /tmp/tea /usr/local/bin/tea
|
|
||||||
sudo chmod +x /usr/local/bin/tea
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3.2. Authenticating tea with your Forgejo instance
|
|
||||||
Configure a login profile for your server:
|
|
||||||
```bash
|
|
||||||
tea login add \
|
|
||||||
--name forgejo \
|
|
||||||
--url https://git.yourdomain.com \
|
|
||||||
--token <YOUR_FORGEJO_PERSONAL_ACCESS_TOKEN>
|
|
||||||
```
|
|
||||||
*Note: You can generate a Personal Access Token in the Forgejo Web UI under Settings ➔ Applications.*
|
|
||||||
|
|
||||||
### 3.3. Standard PR commands
|
|
||||||
With `tea` configured, you can manage pull requests directly from the repository root:
|
|
||||||
* **List open PRs**: `tea pulls ls`
|
|
||||||
* **Checkout a PR locally**: `tea pulls checkout <PR_NUMBER>`
|
|
||||||
* **Create a new PR**: `tea pulls create --title "My PR" --base main --head my-feature`
|
|
||||||
* **Merge a PR**: `tea pulls merge <PR_NUMBER>`
|
|
||||||
* **Approve/Review a PR**: `tea pulls review <PR_NUMBER> --approve`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Testing Procedures & Webhook Testing Flow
|
|
||||||
|
|
||||||
Testing must occur in complete isolation from production data. We achieve this by splitting execution paths using dedicated test hooks in both Next.js and n8n.
|
Testing must occur in complete isolation from production data. We achieve this by splitting execution paths using dedicated test hooks in both Next.js and n8n.
|
||||||
|
|
||||||
### 4.1. Development & Test Variables Configuration
|
### 3.1. Testing Scripts Command List
|
||||||
During test executions (such as running Jest, Cypress, or integration suites), the application uses the following development-exclusive variables:
|
Run these commands from the repository root using `pnpm` (or `npm` / `yarn`):
|
||||||
* `TEST_DATABASE_URL`: Dedicated database connection URL for test schemas (e.g. `postgresql://.../special_hotel_test`). Migrations are run here independently.
|
* **Run Row-Level Security Tests**:
|
||||||
* `N8N_TEST_WEBHOOK_URL`: The specific path n8n exposes for test triggers.
|
```bash
|
||||||
|
pnpm run test:rls
|
||||||
|
```
|
||||||
|
Tests tenant read boundaries across admin, gerente, and colaborador roles, and verifies that update/delete actions on `audit_logs` are blocked.
|
||||||
|
* **Run Auth & API RLS Integration Tests**:
|
||||||
|
```bash
|
||||||
|
pnpm run test:auth-rls
|
||||||
|
```
|
||||||
|
Runs a Next.js instance on test port `3009` and asserts cookies, authorization blocks, and API-level data filtration.
|
||||||
|
* **Run UI End-to-End Tests**:
|
||||||
|
```bash
|
||||||
|
pnpm run test:ui
|
||||||
|
```
|
||||||
|
Compiles Next.js and runs automated Puppeteer scripts (`test-phase3-ui.js`, `test-phase4-ui.js`, `test-phase5-ui.js`) to verify pages, styles, translations, and modals.
|
||||||
|
* **Run n8n Webhook Integration Tests**:
|
||||||
|
```bash
|
||||||
|
pnpm run test:n8n
|
||||||
|
```
|
||||||
|
Fires sales validation and settlement calculation jobs directly at the n8n webhook test endpoint.
|
||||||
|
* **Run All Tests**:
|
||||||
|
```bash
|
||||||
|
pnpm run test
|
||||||
|
```
|
||||||
|
|
||||||
### 4.2. n8n Testing Webhook Routing
|
### 3.2. n8n Testing Webhook Routing
|
||||||
All calculations triggered by test suites route to n8n via `/webhook-test` path segments:
|
All calculations triggered by test suites route to n8n via `/webhook-test` path segments:
|
||||||
1. **Trigger**: Test suite invokes n8n via `POST ${process.env.N8N_TEST_WEBHOOK_URL}/calculate-commissions`.
|
1. **Trigger**: Test suite invokes n8n via `POST ${process.env.N8N_TEST_WEBHOOK_URL}/calculate-commissions`.
|
||||||
2. **n8n Path Branching**:
|
2. **n8n Path Branching**:
|
||||||
|
|
@ -220,15 +178,11 @@ All calculations triggered by test suites route to n8n via `/webhook-test` path
|
||||||
- **True**: The n8n workspace connects to the database utilizing `TEST_DATABASE_URL` credentials. It pulls test sales/goals data and pushes calculations back to the Next.js dev API.
|
- **True**: The n8n workspace connects to the database utilizing `TEST_DATABASE_URL` credentials. It pulls test sales/goals data and pushes calculations back to the Next.js dev API.
|
||||||
- **False**: Connects to the main `DATABASE_URL` for production processing.
|
- **False**: Connects to the main `DATABASE_URL` for production processing.
|
||||||
|
|
||||||
### 4.3. Running Integration Tests Locally
|
### 3.3. Manual Integration Setup
|
||||||
To run the full sandbox locally:
|
To sync and seed the testing database structure:
|
||||||
1. Spin up both databases: `docker compose up -d postgres-dev postgres-test`.
|
1. Spin up both databases.
|
||||||
2. Run database migrations on the test database:
|
2. Run database schema migrations on the test database:
|
||||||
```bash
|
```bash
|
||||||
DATABASE_URL=$TEST_DATABASE_URL npx prisma migrate deploy
|
pnpm run db:seed-test
|
||||||
```
|
```
|
||||||
3. Run the Next.js development server (which connects to the dev database by default, but switches API routing to test endpoints under integration scripts).
|
3. Run the development server or test suites.
|
||||||
4. Run testing script: `npm run test:integration`.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@
|
||||||
* **ORM**: Prisma ORM (providing type-safe database queries and automated schema migrations).
|
* **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).
|
* **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).
|
* **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**: Ready-to-use, community-proven **`@explita/prisma-audit-log`** Prisma Client Extension. It automatically intercepts database mutations (create, update, delete), tracks changes (old vs new state), handles sensitive field masking (e.g. passwords), and records logs into the `AuditLog` table. This approach is database-agnostic, requires no native OS dependencies, and runs purely inside the runtime.
|
* **Auditing**: Audit logs are explicitly recorded within transactions inside the Next.js API endpoints (`tx.auditLog.create`) utilizing the authenticated user session details. To enforce financial integrity and SOC 2/GDPR compliance, the database layer implements strict **Row-Level Security (RLS) policies** on the `audit_logs` table that permit only `INSERT` operations (making the logs strictly append-only) and block all `UPDATE` or `DELETE` mutations for all users, including system administrators. Sensitive inputs (like password hashes or detailed bulk data records) are redacted/masked at the application layer before serialization.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -20,15 +20,22 @@
|
||||||
|
|
||||||
The project is structured to run in any isolated Docker environment. All parameters are fed via environment variables to cleanly partition production and development configurations:
|
The project is structured to run in any isolated Docker environment. All parameters are fed via environment variables to cleanly partition production and development configurations:
|
||||||
|
|
||||||
### 2.1. Environment Variables
|
### 2.1. Environment Variables (.env Layout)
|
||||||
* **Core Variables (Both Env)**:
|
* **Production Stack Variables (app-prod)**:
|
||||||
* `DATABASE_URL`: Connection string for the active database (Production or Development).
|
* `DATABASE_URL_PROD`: Connection string for the production PostgreSQL database.
|
||||||
* `NEXT_PUBLIC_APP_URL`: The domain or local host path of the running application.
|
* `NEXT_PUBLIC_APP_URL`: The production public domain (`https://hotels.gaboggamer.online`).
|
||||||
* `NEXTAUTH_SECRET`: Secret key for JWT session validation.
|
* `NEXTAUTH_SECRET`: Secret token used to sign and verify session JWTs in production.
|
||||||
* **Development-Exclusive Test Variables**:
|
* `N8N_WEBHOOK_URL`: Webhook endpoint for live production calculation workflows (`https://n8n.gaboggamer.online/webhook/calculate-commissions`).
|
||||||
* `TEST_DATABASE_URL`: Connection string to the secondary sandbox/test database.
|
* `N8N_WEBHOOK_SECRET`: Signature token to verify n8n webhook payload authenticity.
|
||||||
* `N8N_TEST_WEBHOOK_URL`: The n8n testing webhook entry point. Used by development services and test runners.
|
* `APP_PROD_INTERNAL_URL`: Internal container URL for prod mapping (`http://special-hotel-prod:3000`).
|
||||||
* `N8N_WEBHOOK_SECRET`: Token to authorize and verify n8n webhook payload signatures locally.
|
* **Development & Test Stack Variables (app-dev)**:
|
||||||
|
* `DATABASE_URL_DEV`: Connection string for the development PostgreSQL database.
|
||||||
|
* `TEST_DATABASE_URL`: Dedicated connection string for the isolated test/sandbox database.
|
||||||
|
* `NEXT_PUBLIC_APP_URL_DEV`: Development URL (`http://localhost:3001`).
|
||||||
|
* `NEXTAUTH_SECRET_DEV`: JWT signature token for development sessions.
|
||||||
|
* `N8N_TEST_WEBHOOK_URL`: Sandbox webhook URL for development calculation testing (`https://n8n.gaboggamer.online/webhook-test/calculate-commissions`).
|
||||||
|
* `N8N_WEBHOOK_SECRET_DEV`: Signature token to authorize development webhook payloads.
|
||||||
|
* `APP_DEV_INTERNAL_URL`: Internal container URL for dev mapping (`http://special-hotel-dev:3000`).
|
||||||
|
|
||||||
### 2.2. Component Interaction:
|
### 2.2. Component Interaction:
|
||||||
```mermaid
|
```mermaid
|
||||||
|
|
@ -92,7 +99,7 @@ erDiagram
|
||||||
COMPENSATION_PLANS {
|
COMPENSATION_PLANS {
|
||||||
int id PK
|
int id PK
|
||||||
string name
|
string name
|
||||||
string code UK
|
string code
|
||||||
datetime validity_start
|
datetime validity_start
|
||||||
datetime validity_end
|
datetime validity_end
|
||||||
string type "PERCENTAGE | SCALE | CONDITIONAL | FIXED"
|
string type "PERCENTAGE | SCALE | CONDITIONAL | FIXED"
|
||||||
|
|
@ -137,6 +144,8 @@ erDiagram
|
||||||
string idempotency_key UK
|
string idempotency_key UK
|
||||||
string transaction_id
|
string transaction_id
|
||||||
int uploaded_by FK
|
int uploaded_by FK
|
||||||
|
boolean is_anomaly
|
||||||
|
json flagged_reason
|
||||||
datetime created_at
|
datetime created_at
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -158,6 +167,8 @@ erDiagram
|
||||||
string rejection_reason
|
string rejection_reason
|
||||||
int original_settlement_id FK "Self-references the settlement adjusted, if any"
|
int original_settlement_id FK "Self-references the settlement adjusted, if any"
|
||||||
string adjustment_notes
|
string adjustment_notes
|
||||||
|
boolean ai_audited
|
||||||
|
json ai_audit_notes
|
||||||
datetime created_at
|
datetime created_at
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -186,7 +197,7 @@ erDiagram
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 4. Workflows & n8n Integration Model
|
## 4. Workflows & n8n Integration Model
|
||||||
|
|
||||||
To achieve high modularity, testability, and adaptability, the system implements a **Thick Client (Next.js), Thin Coordinator (n8n)** architecture:
|
To achieve high modularity, testability, and adaptability, the system implements a **Thick Client (Next.js), Thin Coordinator (n8n)** architecture:
|
||||||
* **Zero Database Connections in n8n**: n8n must not connect directly to PostgreSQL. All data read/write mutations are handled by Next.js API endpoints.
|
* **Zero Database Connections in n8n**: n8n must not connect directly to PostgreSQL. All data read/write mutations are handled by Next.js API endpoints.
|
||||||
|
|
@ -223,7 +234,7 @@ To ensure complete isolation of production data, all n8n workflows follow a stri
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Security & Access Control Model (RBAC)
|
## 5. Security & Access Control Model (RBAC & RLS)
|
||||||
|
|
||||||
We define role-based access restrictions as follows:
|
We define role-based access restrictions as follows:
|
||||||
|
|
||||||
|
|
@ -234,7 +245,7 @@ We define role-based access restrictions as follows:
|
||||||
| **Gerente Hotel** | Reads data, sales, and settlements for their specific Hotel. | Restricted to `hotel_id`. |
|
| **Gerente Hotel** | Reads data, sales, and settlements for their specific Hotel. | Restricted to `hotel_id`. |
|
||||||
| **Líder Comercial** | Triggers simulations, views dashboards. Approves/Rejects settlements. | Restricted to their region/team. |
|
| **Líder Comercial** | Triggers simulations, views dashboards. Approves/Rejects settlements. | Restricted to their region/team. |
|
||||||
| **Analista Financiero** | Reviews calculations. Exports consolidated PDF/Excel reports. | Cannot approve. |
|
| **Analista Financiero** | Reviews calculations. Exports consolidated PDF/Excel reports. | Cannot approve. |
|
||||||
| **Consulta** | Read-only. | No mutations allowed. |
|
| **Consulta / Auditor** | Read-only. | No mutations allowed. |
|
||||||
| **Colaborador** | Consults own history & dashboard. | Restricted to `user_id`. |
|
| **Colaborador** | Consults own history & dashboard. | Restricted to `user_id`. |
|
||||||
|
|
||||||
### 5.1. PostgreSQL Row-Level Security (RLS) & Data Isolation
|
### 5.1. PostgreSQL Row-Level Security (RLS) & Data Isolation
|
||||||
|
|
@ -246,8 +257,7 @@ To ensure absolute segregation of sensitive compensation data, the database impl
|
||||||
* **Líderes**: Can select rows within their assigned regions or teams (`region_id = current_setting('app.current_region_id')`).
|
* **Líderes**: Can select rows within their assigned regions or teams (`region_id = current_setting('app.current_region_id')`).
|
||||||
* **Administradores / Analistas**: RLS is bypassed to allow system-wide computations and consolidated reporting.
|
* **Administradores / Analistas**: RLS is bypassed to allow system-wide computations and consolidated reporting.
|
||||||
* **Audit Trail Immutability**:
|
* **Audit Trail Immutability**:
|
||||||
* The `AUDIT_LOGS` table has RLS policies that prevent `UPDATE` or `DELETE` actions for all users, including administrators. It is strictly write-only (`INSERT` operations only).
|
* The `audit_logs` table has database RLS policies (`audit_logs_insert_policy` and `audit_logs_select_policy`) that only permit `INSERT` operations and explicitly block `UPDATE` and `DELETE` actions for all users, including administrators. It is strictly write-only.
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -256,18 +266,18 @@ To ensure absolute segregation of sensitive compensation data, the database impl
|
||||||
We design the containerized architecture to run two distinct instances of the application concurrently from the same codebase, ensuring clean division.
|
We design the containerized architecture to run two distinct instances of the application concurrently from the same codebase, ensuring clean division.
|
||||||
|
|
||||||
### 6.1. Service Configurations
|
### 6.1. Service Configurations
|
||||||
* **Production Container (`app-prod`)**:
|
* **Production Container (`app-prod` / `special-hotel-prod`)**:
|
||||||
* **Network Port**: Exposed on port `3000` (mapped via Caddy to `special-hotel.yourdomain.com`).
|
* **Network Port**: Exposed on port `3000` (mapped via Caddy to `hotels.gaboggamer.online`).
|
||||||
* **Database**: Bound to the production `DATABASE_URL`.
|
* **Database**: Bound to the production `DATABASE_URL_PROD`.
|
||||||
* **Logs**: Prefixed with `[PROD]` inside the container engine.
|
* **Logs**: Prefixed with `[PROD]` inside the container engine.
|
||||||
* **Development Container (`app-dev`)**:
|
* **Development Container (`app-dev` / `special-hotel-dev`)**:
|
||||||
* **Network Port**: Exposed on port `3001` (mapped via Caddy to `special-hotel-dev.yourdomain.com`).
|
* **Network Port**: Exposed on port `3001` (mapped via Caddy to `localhost:3001` or developmental paths).
|
||||||
* **Database**: Bound to `TEST_DATABASE_URL` (acting as its main `DATABASE_URL` for test isolated migrations).
|
* **Database**: Bound to `DATABASE_URL_DEV` (with integration testing executing queries on `TEST_DATABASE_URL`).
|
||||||
* **Logs**: Prefixed with `[DEV]` for easy debugging contrast.
|
* **Logs**: Prefixed with `[DEV]` for easy debugging contrast.
|
||||||
|
|
||||||
### 6.2. Graceful Dev Failure Model
|
### 6.2. Graceful Dev Failure Model
|
||||||
The development instance utilizes a validation startup hook. If any development-exclusive environment variables (like `TEST_DATABASE_URL`) are omitted:
|
The development instance utilizes a validation startup hook. If any development-exclusive environment variables (like `TEST_DATABASE_URL`) are omitted:
|
||||||
1. The `app-dev` container logs a clear notification: `[DEV] Missing required development variables. Gracefully shutting down development service.`
|
1. The `app-dev` container logs a clear notification: `[DEV] Required development-exclusive variables (TEST_DATABASE_URL, N8N_TEST_WEBHOOK_URL) are missing.`
|
||||||
2. The entrypoint script exits with **exit code 0**.
|
2. The entrypoint script exits with **exit code 0**.
|
||||||
3. Docker or the compose orchestrator registers the container as cleanly stopped (not crashed). The production stack is completely unaffected, avoiding restart-loop penalties or deployment failures.
|
3. Docker or the compose orchestrator registers the container as cleanly stopped (not crashed). The production stack is completely unaffected, avoiding restart-loop penalties or deployment failures.
|
||||||
|
|
||||||
|
|
@ -279,8 +289,9 @@ The internationalization architecture provides bilingual support (English and Sp
|
||||||
|
|
||||||
### 7.1. Client-Side Translation Context
|
### 7.1. Client-Side Translation Context
|
||||||
* **Scaffolding**: Static JSON dictionaries map UI strings under `src/lib/i18n/dictionaries/`.
|
* **Scaffolding**: Static JSON dictionaries map UI strings under `src/lib/i18n/dictionaries/`.
|
||||||
* **State Management**: A React Context provider (`LocaleProvider`) coordinates the selected locale across the client components, utilizing local storage for persistence.
|
* **State Management**: A React Context provider (`LocaleProvider`) coordinates the selected locale across client components, utilizing local storage for persistence.
|
||||||
* **Component Translation**: UI components call a lightweight `t(key)` translation hook, dynamically rendering headers, tables, validation warnings, and labels.
|
* **Component Translation**: UI components call a lightweight `t(key)` translation hook, dynamically rendering headers, tables, validation warnings, and labels.
|
||||||
|
* **Keyword Localization**: Core calculation states and types (such as `ACTIVE/ACTIVO`, `CLOSED/CERRADO`, `REVENUE/INGRESOS`, `NIGHTS/NOCHES`) are mapped at the dictionary level so views translate database enums to localized strings seamlessly.
|
||||||
|
|
||||||
### 7.2. Bilingual AI Audit Translation Flow
|
### 7.2. Bilingual AI Audit Translation Flow
|
||||||
To maintain semantic accuracy and structured parsing within the n8n pipelines, AI audits execute in English, followed by a dedicated translation stage:
|
To maintain semantic accuracy and structured parsing within the n8n pipelines, AI audits execute in English, followed by a dedicated translation stage:
|
||||||
|
|
@ -303,4 +314,3 @@ graph LR
|
||||||
```
|
```
|
||||||
These are stored in the database as PostgreSQL `JSONB` fields (`flaggedReason` on `SalesResult`, and `aiAuditNotes` on `Settlement`).
|
These are stored in the database as PostgreSQL `JSONB` fields (`flaggedReason` on `SalesResult`, and `aiAuditNotes` on `Settlement`).
|
||||||
* **Rendering**: The frontend page renders the string corresponding to the user's active locale: `item.aiAuditNotes[locale]`.
|
* **Rendering**: The frontend page renders the string corresponding to the user's active locale: `item.aiAuditNotes[locale]`.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,9 +6,11 @@
|
||||||
|
|
||||||
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).
|
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`)
|
## 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.
|
All colors, spacing, typography, transitions, and layout presets must be defined as CSS custom properties (variables) inside `src/app/globals.css`. Global variables are declared in HSL (Hue, Saturation, Lightness) format to allow dynamic opacity control using `alpha-value` mixing.
|
||||||
|
|
||||||
```css
|
```css
|
||||||
:root {
|
:root {
|
||||||
|
|
@ -98,16 +100,35 @@ All colors, spacing, typography, transitions, and layout presets must be defined
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Component Scoping with CSS Modules
|
## 2. Theme Consistency & Background Rules
|
||||||
|
|
||||||
|
To prevent background mismatching or flashing layout inconsistencies when moving between pages:
|
||||||
|
1. **Container Backgrounds**: Pages must use the radial gradient background that transitions smoothly across theme states:
|
||||||
|
```css
|
||||||
|
.container {
|
||||||
|
background: radial-gradient(circle at top right, hsla(var(--primary-h), var(--primary-s), var(--primary-l), 0.08), transparent 45%),
|
||||||
|
var(--background);
|
||||||
|
color: var(--foreground);
|
||||||
|
font-family: var(--font-sans);
|
||||||
|
transition: background var(--transition-slow);
|
||||||
|
padding-bottom: var(--space-12);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
2. **Context-Backed Authentication & Theme**: Fetching user profiles or auth tokens on page mount is handled by the central `UserProvider` context to avoid page rendering flashes.
|
||||||
|
3. **Typography**: System default fonts are forbidden. Font tokens (`var(--font-sans)`) must be used on the body and all wrapper components.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 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`).
|
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)
|
### 3.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:
|
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`
|
* Good: `.container`, `.card`, `.button`, `.badge`
|
||||||
* Avoid: `.button-container-outer`, `.btn-v2`
|
* Avoid: `.button-container-outer`, `.btn-v2`
|
||||||
|
|
||||||
### 2.2. CSS Modules Usage in React
|
### 3.2. Scoped Styling in React
|
||||||
```tsx
|
```tsx
|
||||||
import styles from './Button.module.css';
|
import styles from './Button.module.css';
|
||||||
|
|
||||||
|
|
@ -133,11 +154,11 @@ export function Button({ variant = 'primary', isActive, children }: ButtonProps)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Styling & Layout Guidelines
|
## 4. 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.
|
* **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)`).
|
* **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:
|
* **Responsive Design**: Follow a mobile-first media query approach. Breakpoints are coded as:
|
||||||
```css
|
```css
|
||||||
.container {
|
.container {
|
||||||
display: grid;
|
display: grid;
|
||||||
|
|
@ -160,7 +181,7 @@ export function Button({ variant = 'primary', isActive, children }: ButtonProps)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. UI Polish & Animations
|
## 5. UI Polish & Animations
|
||||||
|
|
||||||
To deliver a premium visual experience:
|
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`).
|
* **Micro-interactions**: Every interactive element (buttons, cards, inputs) must have a subtle hover effect using hardware-accelerated properties (`transform`, `opacity`, `background-color`).
|
||||||
|
|
@ -177,3 +198,4 @@ To deliver a premium visual experience:
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
* **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%`).
|
* **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%`).
|
||||||
|
* **Internationalization Integration**: Never hardcode text strings inside CSS files or class names. Labels must be fetched from the client translation dictionary (`t('key')`) to support bilingual layout rendering seamlessly.
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue