> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cucu.bo/llms.txt
> Use this file to discover all available pages before exploring further.

# Entrega al comprador

> Estado de la entrega de una factura por WhatsApp, Telegram y correo (delivery) y POST /api/v3/invoices/{id}/delivery/{channel}/retry para reintentar un canal.

Cada factura dice por qué canales le llegó al comprador y, si un canal falló, se puede reintentar.

## El bloque `delivery`

Viene en la respuesta de [`POST /invoices`](https://docs.cucu.bo/api/create-invoice) y en la consulta de una factura
([`GET /invoices/{id}`](https://docs.cucu.bo/api/get-invoice), por CUF, por `Idempotency-Key` y la herramienta MCP `obtenerFactura`).
No viene en los listados ni en los lotes. Las notas de crédito-débito y los documentos rechazados por el SIN no lo traen.

Siempre son tres elementos, en este orden: `whatsapp`, `telegram`, `email`.

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
"delivery": [
  { "channel": "whatsapp", "status": "FALLIDO", "reason": "template_not_configured",
    "to": "+591 ••• 7944", "at": "2026-11-20T15:04:05.120Z", "attempts": 1, "retryable": true },
  { "channel": "telegram", "status": "OMITIDO", "reason": "sin_dato", "attempts": 0, "retryable": false },
  { "channel": "email", "status": "ENTREGADO", "to": "a•••@ejemplo.com",
    "at": "2026-11-20T15:04:03.870Z", "attempts": 1, "retryable": false }
]
```

| Campo | Descripción |
| - | - |
| `channel` | `whatsapp`, `telegram` o `email` |
| `status` | Ver [estados](#estados) |
| `reason` | Por qué, en `FALLIDO` y `OMITIDO` (ver [motivos](#motivos)). Ausente en `ENTREGADO` |
| `to` | Destino enmascarado. Ausente si el comprador no dio el dato de ese canal |
| `at` | Último cambio de estado, en UTC. Ausente si todavía no hubo ningún intento |
| `attempts` | Intentos hechos contra el proveedor |
| `retryable` | `true`: el [reintento](#reintentar-un-canal) sin cuerpo lo envía ahora |
| `deliveredAt` | Cuándo le llegó al comprador, según el proveedor (UTC). Sólo WhatsApp. Ausente mientras no haya acuse |
| `readAt` | Cuándo lo leyó (UTC). Sólo WhatsApp, y sólo si el comprador tiene activas las confirmaciones de lectura |

La API nunca devuelve el teléfono, el correo ni el id de Telegram completos en este bloque.

### Estados

| `status` | Significado |
| - | - |
| `PENDIENTE` | La entrega está en cola. Recién emitida la factura, todos los canales con dato están así. Con `reason`, un intento falló y se reintenta solo |
| `ENVIANDO` | Hay un intento en curso |
| `ENTREGADO` | El proveedor aceptó el mensaje (WhatsApp, Telegram o el servidor de correo). En WhatsApp, `deliveredAt` y `readAt` dicen además si le llegó y si lo leyó |
| `FALLIDO` | No salió. Se puede reintentar |
| `OMITIDO` | No corresponde enviarlo por ese canal |

La entrega corre después de responder la emisión: consultá la factura unos segundos más tarde para ver el resultado.

### Recibido y leído (WhatsApp)

`deliveredAt` y `readAt` se actualizan cuando consultás la factura (`GET /invoices/{id}` u `obtenerFactura`). Para
mostrarlo en vivo, consultá cada 3 segundos mientras el canal esté `ENTREGADO` sin `readAt`, y dejá de hacerlo a los
pocos minutos. Si WhatsApp rechaza el mensaje después de aceptarlo (por ejemplo, el número no tiene WhatsApp), el
canal pasa a `FALLIDO` con `proveedor_<código>` y `retryable: true`.

### Motivos

| `reason` | `status` | Qué hacer |
| - | - | - |
| `sin_dato` | `OMITIDO` | El comprador no dio teléfono, id de Telegram o correo. Reintentá con `to` |
| `canal_deshabilitado` | `OMITIDO` | Tu empresa no entrega por ese canal. La entrega por chat la activa CUCU a pedido |
| `tenant_inactivo` | `OMITIDO` | La empresa está dada de baja |
| `anulada` | `OMITIDO` | La factura se anuló antes de entregarla |
| `destino_suprimido` | `OMITIDO` | El correo rebotó o el comprador se quejó: no se le escribe más. Reintentá con otro correo en `to` |
| `duplicado` | `OMITIDO` | Esa factura ya salió a ese destinatario |
| `sin_registro` | `OMITIDO` | Factura anterior a este registro: no se sabe cómo terminó su entrega |
| `cupo_tenant`, `cupo_destinatario`, `cupo_global` | `FALLIDO` | Se alcanzó un cupo de mensajes. Reintentá más tarde |
| `cupo_indisponible` | `FALLIDO` | No se pudo verificar el cupo. Reintentá más tarde |
| `template_not_configured`, `template_data_incomplete` | `FALLIDO` | WhatsApp no tiene la plantilla lista para tu remitente. Avisá a CUCU |
| `error_proveedor`, `http_<código>` | `FALLIDO` | El proveedor falló o no respondió. Reintentá |
| `proveedor_<código>` | `FALLIDO` | WhatsApp rechazó el mensaje después de aceptarlo (`proveedor_131026`: el número no tiene WhatsApp). Corregí el número y reintentá con `to` |
| `telegram_unlinked`, `chat_unavailable` | `FALLIDO` | El comprador cortó el chat con el bot. [Vinculalo de nuevo](#vincular-telegram) |
| `entrega_abandonada` | `FALLIDO` | La entrega automática agotó sus intentos. Reintentá |
| `bridge_apagado`, `sin_remitente`, `sin_documento` | `FALLIDO` | Falta configuración o el PDF no está listo. Reintentá; si se repite, avisá a CUCU |

La lista puede crecer: tratá un `reason` que no conozcas según su `status`.

## Reintentar un canal

`POST /api/v3/invoices/{id}/delivery/{channel}/retry`

Envía de nuevo la factura por ese canal y responde cómo quedó. Se puede cuando `retryable` es `true`, o cuando el canal
está `OMITIDO` por `sin_dato` o `destino_suprimido` y mandás otro destino en `to`.

### Path Parameters

| Parámetro | Tipo | Req | Descripción |
| - | - | - | - |
| `id` | string | Sí | UUID de la factura (de tu tenant; si no, `404`) |
| `channel` | string | Sí | `whatsapp`, `telegram` o `email` |

### Body (opcional)

| Campo | Tipo | Req | Descripción |
| - | - | - | - |
| `to` | string | No | Destino corregido. `whatsapp`: teléfono con código de país, sólo dígitos (`+59170000000`). `telegram`: id numérico del comprador. `email`: una sola dirección. Sin cuerpo, se usa el dato de la factura |

`to` vale para ese envío y no cambia la factura. Si el reintento con `to` vuelve a fallar, el siguiente tiene que
traer `to` otra vez.

### Reglas

* Un canal `ENTREGADO` responde `200` con su estado y no envía nada: repetir el pedido no repite el mensaje.
* De dos pedidos simultáneos sobre el mismo canal, uno envía y el otro recibe `409`.
* `PENDIENTE` y `ENVIANDO` responden `409` mientras la entrega está en curso. Un `ENVIANDO` sin cambios por 15 minutos pasa a `retryable: true`.
* Una factura anulada no se entrega (`409`).
* El reintento cuenta en los mismos cupos de mensajes que la entrega automática.

### Límites

| Cupo | Valor |
| - | - |
| Reintentos de una misma factura (suma sus canales) | 5 por hora |
| Reintentos totales del tenant | 60 por hora |

Superado cualquiera, `429` con `error.code = RATE_LIMITED` y `Retry-After`.

### Respuestas

| HTTP | `error.code` | Cuándo |
| - | - | - |
| `200` | — | El canal quedó `ENTREGADO` (o ya lo estaba) |
| `400` | `VALIDATION_ERROR` | `channel` desconocido, `to` con formato inválido, o hace falta `to` y no vino (`error.field`) |
| `404` | `NOT_FOUND` | Factura inexistente o de otro tenant |
| `409` | `CONFLICT` | El estado de la factura o del canal no admite el reintento |
| `422` | [`DELIVERY_FAILED`](https://docs.cucu.bo/errors#delivery_failed) | Se intentó y no salió; `data` trae el canal con su `reason` |
| `429` | `RATE_LIMITED` | Cupo de reintentos |
| `503` | `DOCUMENT_IN_PREPARATION` | El PDF se está generando; reintentá tras `Retry-After` |

```bash Reintentar theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://sandbox.cucu.bo/api/v3/invoices/a1b2c3d4-e5f6-7890-abcd-ef1234567890/delivery/whatsapp/retry \
  -H "X-API-Key: YOUR_API_KEY"
```

```bash Con destino corregido theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://sandbox.cucu.bo/api/v3/invoices/a1b2c3d4-e5f6-7890-abcd-ef1234567890/delivery/whatsapp/retry \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"to": "+59170000000"}'
```

```json 200 theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "success": true,
  "message": "Factura entregada por whatsapp",
  "data": {
    "channel": "whatsapp",
    "status": "ENTREGADO",
    "to": "+591 ••• 0000",
    "at": "2026-11-20T15:10:42.310Z",
    "attempts": 2,
    "retryable": false
  },
  "timestamp": "2026-11-20T11:10:42.315-04:00"
}
```

```json 422 theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "success": false,
  "message": "La factura no se entregó por whatsapp",
  "data": {
    "channel": "whatsapp",
    "status": "FALLIDO",
    "reason": "template_not_configured",
    "to": "+591 ••• 0000",
    "at": "2026-11-20T15:10:42.310Z",
    "attempts": 2,
    "retryable": true
  },
  "error": {
    "code": "DELIVERY_FAILED",
    "details": "template_not_configured"
  },
  "timestamp": "2026-11-20T11:10:42.315-04:00"
}
```

```json 409 theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "success": false,
  "message": "La entrega por whatsapp está en curso: espere a que termine",
  "error": { "code": "CONFLICT" },
  "timestamp": "2026-11-20T11:10:42.315-04:00"
}
```

## Vincular Telegram

Telegram no deja que un bot le escriba a quien no lo abrió. Para entregarle facturas por Telegram, el comprador
escanea un QR una sola vez. Tu empresa tiene que tener activa la entrega por Telegram (si no, `409`).

1. Pedí el enlace con una referencia tuya del comprador (el id de su ficha, sin datos personales).
2. Mostrá `deepLink` como QR. Es de un solo uso y vence en `expiresAt`.
3. Consultá cada 2 o 3 segundos hasta `linked`.
4. Guardá `telegramUserId` en tu cliente y mandalo como `clientTelegramUserId` en sus facturas. Para una factura ya
   emitida, [reintentá](#reintentar-un-canal) `telegram` con `{"to": "<telegramUserId>"}`.

```
POST   /api/v3/telegram/links          {"ref": "cliente:4821"}
GET    /api/v3/telegram/links?ref=cliente:4821
DELETE /api/v3/telegram/links?ref=cliente:4821
```

`ref`: hasta 120 caracteres entre letras, números y `: . _ -`.

```json 201 theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "success": true,
  "data": {
    "ref": "cliente:4821",
    "status": "pending",
    "deepLink": "https://t.me/cucuai_bot?start=v1_Zk3",
    "botUsername": "cucuai_bot",
    "expiresAt": "2026-11-20T11:15:00.000-04:00"
  }
}
```

```json 200 (vinculado) theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "success": true,
  "data": {
    "ref": "cliente:4821",
    "status": "linked",
    "telegramUserId": "829349454",
    "telegramUsername": "ana_bo",
    "phone": "+59170000000",
    "linkedAt": "2026-11-20T11:02:11.000-04:00"
  }
}
```

| `status` | Significado |
| - | - |
| `pending` | QR vigente, sin escanear |
| `linked` | Vinculado. `phone` viene si el comprador compartió su número desde Telegram |
| `unlinked` | Lo cortó el comprador (`/stop` en el bot) o tu empresa (`DELETE`) |
| `expired` | El QR venció sin usarse. Pedí otro |

| HTTP | `error.code` | Cuándo |
| - | - | - |
| `400` | `VALIDATION_ERROR` | Falta `ref` o tiene un formato inválido |
| `404` | `NOT_FOUND` | Nunca se pidió un vínculo para esa `ref` |
| `409` | `CONFLICT` | Tu empresa no entrega por Telegram |
| `503` | `CHANNEL_UNAVAILABLE` | Telegram no respondió. Reintentá en unos segundos (`Retry-After`) |

Por MCP: `vincularTelegram`, `consultarVinculoTelegram` y `desvincularTelegram`, con `ref` como único argumento.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.