---
name: settlement-calculation
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

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

### 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.
