# API PBX Voizend — Integración CRM (Olyas / OL&AS)

Base URL: `https://api.pbx.voizend.com`

Servicio aislado en `/var/www/pbx` (no modifica Gesthor ni softphones existentes).

## Autenticación

Enviar API Key en uno de estos encabezados:

- `X-Api-Key: <key>`
- `Authorization: Bearer <key>`

O en el body/query: `api_key`.

Tenant: `olyas`

## Click-to-Call

`POST /v1/call.php`

### Parámetros

| Campo | Obligatorio | Descripción |
|-------|-------------|-------------|
| `tenant` | sí | `olyas` |
| `to` / `tel` | sí | Teléfono destino (9XXXXXXXX, 51..., etc.) |
| `anexo` **o** `agent` | sí | Anexo `1562001`… o usuario `asesorolyas01` |
| `mode` | no | `mask` \| `rotate` \| `auto` (default auto→rotate) |
| `department` | no | `aacc` (mask), `ventas` / `cobranzas` (rotate) |
| `cid` | no | Forzar Caller ID |
| `ref` | no | ID lead/CRM para trazabilidad |

### Respuesta OK

```json
{
  "ok": true,
  "call_id": "c2c_1562001_20260814221500_ab12cd34",
  "anexo": "1562001",
  "to": "51999888777",
  "ani": "905332131",
  "mode": "rotate",
  "department": "ventas",
  "recording": true,
  "queued_at": "2026-08-14 22:15:00"
}
```

### Flujo

1. La central **suena el anexo del asesor** (softphone registrado).
2. Al contestar, marca al cliente.
3. El cliente ve el **Caller ID** enmascarado o rotativo.
4. La llamada queda **grabada** (mismo macro `rec-out` de la PBX).

## Enmascarado vs Rotativo

- **AACC / mask:** siempre el mismo número (`cid.mask` / department `aacc`).
- **Ventas / Cobranzas / rotate:** rota sobre `/etc/asterisk/anis/ani562.txt` (pool Olyas).

## Anexos Olyas (existentes, no se cruzan con otros clientes)

| Agent           | Anexo   |
|-----------------|---------|
| asesorolyas01   | 1562001 |
| asesorolyas02   | 1562002 |
| asesorolyas03   | 1562003 |
| asesorolyas04   | 1562004 |
| olyas (admin)   | 1562999 |

Prefijo Telcore: `07645` — IDU: `562` — contexto API: `api-c2c-562` (aparte de `out-562` del softphone).

## Ejemplos

### cURL ventas (rotativo)

```bash
curl -X POST "https://api.pbx.voizend.com/v1/call.php" \
  -H "X-Api-Key: TU_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"tenant":"olyas","agent":"asesorolyas01","to":"999888777","department":"ventas","ref":"lead-3180"}'
```

### Botón web (JS)

```javascript
async function llamarLead(telefono, agente) {
  const r = await fetch('https://api.pbx.voizend.com/v1/call.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'TU_API_KEY'
    },
    body: JSON.stringify({
      tenant: 'olyas',
      agent: agente,
      to: telefono,
      department: 'ventas',
      mode: 'rotate'
    })
  });
  return r.json();
}
```

### PHP (CRM)

```php
$ch = curl_init('https://api.pbx.voizend.com/v1/call.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Content-Type: application/json',
  'X-Api-Key: TU_API_KEY'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
  'tenant' => 'olyas',
  'anexo' => '1562001',
  'to' => $telefono,
  'department' => 'cobranzas',
  'mode' => 'rotate',
  'ref' => $idLead
)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($ch);
```

## Estado

`GET /v1/status.php?tenant=olyas&call_id=c2c_...`

## Health

`GET /v1/health.php`

## Prueba recomendada

1. Softphone del asesor registrado (anexo 156200x).
2. Llamar health.
3. POST call a un celular de prueba.
4. Verificar que suena el softphone, luego el destino, y que el CID mostrado es el esperado.

## Seguridad

- No publicar la API Key en frontends públicos sin proxy.
- Restringir por IP en Apache si el CRM tiene IP fija (opcional).
- Rotar `api_key` en `/var/www/pbx/config/tenants.json` cuando haga falta.
