# Diagramas Mermaid

## Generacion de referencia individual

```mermaid
sequenceDiagram
  autonumber
  participant Sistema as Sistema comercial
  participant API as Plataforma API
  participant DB as Base de datos
  participant Openpay
  Sistema->>API: POST /api/v1/payment-references
  API->>API: Validar API Key, permisos, rate limit
  API->>DB: Buscar Idempotency-Key y external_reference
  alt Ya existe pendiente
    DB-->>API: Referencia existente
    API-->>Sistema: 200 referencia existente
  else Nueva referencia
    API->>Openpay: POST /charges method=store
    Openpay-->>API: charge + paynet reference
    API->>DB: Guardar referencia y evento
    API-->>Sistema: 201 referencia lista para imprimir
  end
```

## Layout masivo

```mermaid
flowchart TD
  A["Cliente envia JSON/CSV/XLSX"] --> B["Validar estructura"]
  B --> C["Crear payment_batch"]
  C --> D["Encolar items"]
  D --> E["Procesar item"]
  E --> F{"Item valido"}
  F -- "No" --> G["Guardar error por linea"]
  F -- "Si" --> H["Crear referencia Openpay"]
  H --> I["Guardar payment_reference"]
  G --> J{"Quedan items"}
  I --> J
  J -- "Si" --> E
  J -- "No" --> K["Actualizar lote: processed / partially_processed"]
```

## Webhook y callback

```mermaid
sequenceDiagram
  autonumber
  participant Openpay
  participant API
  participant DB
  participant Cliente
  Openpay->>API: POST /api/v1/webhooks/openpay
  API->>API: Validar firma/origen
  API->>DB: Guardar webhook_events y openpay_events
  API->>DB: Actualizar payment_references.status
  API->>DB: Insertar payment_status_history
  API->>Cliente: POST callback firmado
  alt Callback OK
    Cliente-->>API: 2xx
    API->>DB: callback_sent
  else Callback falla
    Cliente-->>API: 5xx/timeout
    API->>DB: callback_failed + callback_retries
  end
```

## Conciliacion automatica

```mermaid
flowchart TD
  A["Cron cada 15 minutos"] --> B["Buscar referencias pending"]
  B --> C["Consultar Openpay"]
  C --> D{"Estado o importe difiere"}
  D -- "No" --> E["Registrar reconciled"]
  D -- "Si" --> F["Actualizar estado local"]
  F --> G["Registrar diferencia"]
  G --> H["Enviar callback"]
  H --> I{"Callback OK"}
  I -- "Si" --> J["callback_sent"]
  I -- "No" --> K["callback_failed"]
```

## Multitenant

```mermaid
flowchart LR
  A["Municipio A"] --> K1["API Key A"]
  B["Municipio B"] --> K2["API Key B"]
  C["Organismo C"] --> K3["API Key C"]
  K1 --> API["API Gateway"]
  K2 --> API
  K3 --> API
  API --> T["Resolver client_id"]
  T --> D1["Datos aislados cliente A"]
  T --> D2["Datos aislados cliente B"]
  T --> D3["Datos aislados cliente C"]
```
